Это мой код Swift, я хочу отправить данные на устройство BLE с WRITEVALUE, но характеристики всегда равны нулю. Не могли бы вы мне помочь, пожалуйста? спасибо!
импорт CoreBluetooth
импорт UIKit
импорт AVFoundation
Класс ViewController: UIViewController, CBPeripheralDelegate, UITableViewDelegate, UITableViewDataSource, CBCentralManagerDelegate {
var selectedPeripheral: CBPeripheral?
var centralManager: CBCentralManager?
var peripherals = Array<CBPeripheral>()
var vibrationCharacteristic: CBCharacteristic?
@IBOutlet weak var menuPpal: UIStackView!
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.tableView.delegate = self
self.tableView.dataSource = self
self.title = "List BT"
let rightBarButtonItem = UIBarButtonItem.init(image: UIImage(named: "menu"), style: .done, target: self, action: #selector(ViewController.optionMenu))
self.navigationItem.rightBarButtonItem = rightBarButtonItem
menuPpal.isHidden = true
centralManager = CBCentralManager(delegate: self, queue: nil, options: nil)
}
func myRouteChangeSelector(){
let currentRoute = AVAudioSession.sharedInstance().currentRoute
for route in currentRoute.outputs {
// print("PortType \(route.portType), Description \(route.portName), Id \(route.uid)")
// peripherals.append(route)
}
}
@IBAction func optionMenu(sender: AnyObject) {
self.menuPpal.isHidden = !self.menuPpal.isHidden
}
@IBAction func muestraDispositivos(){
self.myRouteChangeSelector()
DispatchQueue.global(qos: .background).async {
// Background Thread
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
override func viewWillAppear(_ animated: Bool) {
// do something like alert the user that ble is not on
let refreshAlert = UIAlertController(title: "Importante", message: "Vincule bluetooth para un funcionamiento completo", preferredStyle: UIAlertController.Style.alert)
refreshAlert.addAction(UIAlertAction(title: "CONFIRMAR", style: .default, handler: { (action: UIAlertAction!) in
self.openBluetooth()
}))
refreshAlert.addAction(UIAlertAction(title: "CANCELAR", style: .cancel, handler: { (action: UIAlertAction!) in
print("Handle Cancel Logic here")
}))
present(refreshAlert, animated: true, completion: nil)
myRouteChangeSelector()
DispatchQueue.global(qos: .background).async {
// Background Thread
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
func centralManagerDidUpdateState(_ central: CBCentralManager) {
if (central.state == .poweredOn){
centralManager!.scanForPeripherals(withServices: nil, options:nil)
}
else {
self.centralManager?.scanForPeripherals(withServices: nil, options: nil)
// do something like alert the user that ble is not on
let refreshAlert = UIAlertController(title: "Importante", message: "Vincule bluetooth para un funcionamiento completo", preferredStyle: UIAlertController.Style.alert)
refreshAlert.addAction(UIAlertAction(title: "CONFIRMAR", style: .default, handler: { (action: UIAlertAction!) in
self.openBluetooth()
}))
refreshAlert.addAction(UIAlertAction(title: "CANCELAR", style: .cancel, handler: { (action: UIAlertAction!) in
print("Handle Cancel Logic here")
}))
present(refreshAlert, animated: true, completion: nil)
}
}
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
peripherals.append(peripheral)
print("Peripheral: \(peripheral)")
tableView.reloadData()
}
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
print("Successfully connected to \(peripheral.identifier.uuidString)")
}
// Invoked when you write data to a characteristic’s value.
public func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) {
print("Peripheral did write characteristic value for " + characteristic.uuid.uuidString)
}
func openBluetooth(){
if let url = URL(string: "App-Prefs:root=Bluetooth") {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return peripherals.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:UITableViewCell = self.tableView.dequeueReusableCell(withIdentifier: "cell")! as UITableViewCell
let peripheral = peripherals[indexPath.row]
cell.textLabel?.text = peripheral.name
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
// print("Pulsado: " + String(indexPath.row))
self.tableView.deselectRow(at: indexPath, animated: true)
selectedPeripheral = peripherals[indexPath.row]
let audioSession = AVAudioSession.sharedInstance()
DispatchQueue.main.async(){
self.centralManager!.connect(self.selectedPeripheral!, options: nil)
let textToSend: String = "10"
let data = textToSend.data(using: String.Encoding.utf8)
print(self.selectedPeripheral)
self.selectedPeripheral?.writeValue(data!, for: foundCharacteristic, type: CBCharacteristicWriteType.withResponse)
}
self.performSegue(withIdentifier: "irMando", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "irMando" {
if let destinationVC = segue.destination as? Mando {
print("Ha seleccionado: " + (selectedPeripheral?.name)!)
destinationVC.perifericoElegido = selectedPeripheral
}
}
}
}