简体   繁体   中英

Getting response from BLE device

I'm quite new to working with bluetooth devices. So far everything works perfect. But there's an issue I don't know how to deal with. I have a led lamp device where I can change everything from color to speed, flashing, fading and so on. Now I want to read the current device state (is the device turned on or off for example). I have a document for the device which says:

Query: a) Send order:【0XEF】+【0X01】+【0X77】 b) Controller response: 【0X66】+【8bit device name(0x14)】+【8bit swtich on /off】+【8bit mode value】+【8bit run/pause state】+【8bit speed value】+【8bit red data】+【8bit green data】+【8bit blue data】+【8bit warm while】+【8bit version number】+【0X99】

How do I get the controller response? The didWriteValueFor function just returns me wether or not the write call was successful.

If characteristic supports notifying you can turn of notyfying with that line:

peripheral.setNotifyValue(true, for: characteristic)

It's very important to set delegate for peripheral with that characteristic to proper file, in my case it was:

peripheral.delegate = self

After that when something will change, peripheral will fire this method in your code:

func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
    //data is in characteristic.value
}

If your characteristic does not support notyfying you can try to write data to peripheral with response type set to .withReponse like that:

peripheral.writeValue(data, for: characteristic, type: .withResponse)

Remember to set peripheral delegate too, after that peripheral will fire this method after every successful write:

    //write response
    func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) {
        //data is in characteristic.value
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM