writeValue BLE不起作用(特征为零)

时间:2019-01-15 19:59:59

标签: swift bluetooth-lowenergy

这是我的Swift代码,我想使用WRITEVALUE将数据发送到BLE设备,但特性始终保持不变。请问你能帮帮我吗?谢谢!

导入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
        }
    }
}

}

1 个答案:

答案 0 :(得分:0)

这是我用于通过BLE服务器将应用程序与esp32链接的代码

请注意,我在ios APP中定义了两个常量CHARACTERISTIC_UUID_TX和CHARACTERISTIC_UUID_RX,它们与BLE服务器中定义的两个常量匹配。

希望它能提供帮助

       import UIKit
        import CoreBluetooth


        let CHARACTERISTIC_UUID_TX = "C0DE0002-FEED-F00D-C0FF-EEB3D05EBEEF"
        let CHARACTERISTIC_UUID_RX = "C0DE0003-FEED-F00D-C0FF-EEB3D05EBEEF"
        class Bluetooth: NSObject,  CBCentralManagerDelegate, CBPeripheralDelegate      {



        public func shutdown() {
            writeValue(tx: false, message: "shutdown")
            writeValue(tx: true, message: "shutdown")
        }

        public func tapGreen() {
            writeValue(tx: false, message: "vert")
            writeValue(tx: true, message: "vert")
        }

         public func tapBlue() {
            writeValue(tx: false, message: "bleu")
            writeValue(tx: true, message: "bleu")
        }

        public func tapRed() {
            writeValue(tx: false, message: "rouge")
            writeValue(tx: true, message: "rouge")
        }


        weak var btdelegate: BluetoothDelegate?
        var manager : CBCentralManager!
        var myBluetoothPeripheral : CBPeripheral!
        var myCharacteristicRX : CBCharacteristic!
        var myCharacteristicTX : CBCharacteristic!
        var isMyPeripheralConected = false

        override init() {
            super.init()
        }

        func setup(bt: BluetoothDelegate) {
            self.btdelegate = bt
            manager = CBCentralManager(delegate: self, queue: .main)
        }


        func centralManagerDidUpdateState(_ central: CBCentralManager) {

            var msg = ""

            switch central.state {

            case .poweredOff:
                msg = "Bluetooth is Off"
            case .poweredOn:
                msg = "Bluetooth is On"
                manager.scanForPeripherals(withServices: nil, options: nil)
            case .unsupported:
                msg = "Not Supported"
            default:
                msg = ""

            }

            print("STATE: " + msg)

        }

        func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {

            print("Name: \(peripheral.name)") //print the names of all peripherals connected.

            //you are going to use the name here down here ⇩

            if peripheral.name == "ThejEcho" { //if is it my peripheral, then connect

                self.myBluetoothPeripheral = peripheral     //save peripheral
                self.myBluetoothPeripheral.delegate = self

                manager.stopScan()                          //stop scanning for peripherals
                manager.connect(myBluetoothPeripheral, options: nil) //connect to my peripheral

            }
        }

        func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
            isMyPeripheralConected = true //when connected change to true
            peripheral.delegate = self
            peripheral.discoverServices(nil)

        }

        func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
            isMyPeripheralConected = false //and to falso when disconnected
        }


        func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {

            if let servicePeripheral = peripheral.services as [CBService]! { //get the services of the perifereal

                for service in servicePeripheral {

                    //Then look for the characteristics of the services

                    peripheral.discoverCharacteristics([CBUUID(string: CHARACTERISTIC_UUID_TX), CBUUID(string: CHARACTERISTIC_UUID_RX)], for: service)

                }

            }
        }

        func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {

            if let characterArray = service.characteristics {

                for characteristic in characterArray {
                    print("--------------------------------------------")
                    print("Characteristic UUID: \(characteristic.uuid)")
                    print("Characteristic isNotifying: \(characteristic.isNotifying)")
                    print("Characteristic properties: \(characteristic.properties)")
                    print("Characteristic descriptors: \(characteristic.descriptors)")
                    print("Characteristic value: \(characteristic.value)")
                }

                for cc in characterArray {

                    print(cc.uuid.uuidString)

                    if(cc.uuid.uuidString == CHARACTERISTIC_UUID_TX) {
                        myCharacteristicTX = cc //saved it to send data in another function.
                        peripheral.readValue(for: cc)

                    }
                    if (cc.uuid.uuidString == CHARACTERISTIC_UUID_RX) {
                        myCharacteristicRX = cc
                        peripheral.readValue(for: cc)
                    }
                }
            }

            self.btdelegate?.connect()

        }

        func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {


            if(characteristic.uuid.uuidString == CHARACTERISTIC_UUID_TX) {
                myCharacteristicTX = characteristic //saved it to send data in another function.
                //             writeValue(tx: true)
            }
            if (characteristic.uuid.uuidString == CHARACTERISTIC_UUID_RX) {
                myCharacteristicRX = characteristic
                //             writeValue(tx: false)
            }

            guard let data = characteristic.value else {
                print("ERROR DATA")
                return
            }


            var dataString = String(data: data, encoding: String.Encoding.utf8)


        }


        //if you want to send an string you can use this function.
        func writeValue(tx : Bool, message: String) {

            if isMyPeripheralConected { //check if myPeripheral is connected to send data

                let dataToSend: Data = message.data(using: String.Encoding.utf8)!


                if (!tx) {
                    myBluetoothPeripheral.writeValue(dataToSend, for: myCharacteristicRX, type: CBCharacteristicWriteType.withResponse)    //Writing the data to the peripheral



                } else {
                    myBluetoothPeripheral.writeValue(dataToSend, for: myCharacteristicTX, type: CBCharacteristicWriteType.withResponse)




                }
            } else {
                print("Not connected")
            }
        }
    }