Как создать массив байтов для отправки на устройство BLE и получить от него ответ? - PullRequest
0 голосов
/ 30 сентября 2018

Есть замок, который открывается через Bluetooth.Перед началом работы с блокировкой необходимо отправить набор байтов, в ответ на которые устройство должно вернуть ключ.Вот инструкция для составления набора байтов: https://www.dropbox.com/s/z0nsoccz8or4kkf/Omni_OGB1_LOCK_Permenant_connection_smart_lock_Air_Interface_Protocol_V01_03_1%20%281%29.pdf?dl=0

На основе данных из таблицы значений, необходимых для получения ключа, был получен массив таких значений:

FE 43 11 22 19 8A 60 65 7E 5C 46 41 8B F7 4D

Подпишитесь на уведомление и напишите этот набор.Но после того, как не получено никакого уведомления при чтении всех uuid, вы получите пустые массивы

Вопросы:

1) сделать массив байтов для правильной отправки?

2) мне сделатьподписаться на изменения Правильно?

3) Правильно ли мы читаем значения, чтобы получить ответы или ключ от устройства?

4) Как получить ответ из замка и вытащитьключ?

5) Как связаться с этим устройством?

Код класса:

class ViewController: UIViewController, CBCentralManagerDelegate, CBPeripheralDelegate {
    var manager: CBCentralManager!
    var lock: CBPeripheral!
    var characteristicNot: CBCharacteristic!

    override func viewDidLoad() {
        super.viewDidLoad()
        manager = CBCentralManager(delegate: self, queue: nil)
    }

    // Ищем устройство
    func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
        if let name = peripheral.name {
            if name == "LOCK" {
                lock = peripheral
                lock.delegate = self
                manager.stopScan()
                manager.connect(lock, options: nil)
            }
        }
    }

    // Произошло подключение
    func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
        peripheral.delegate = self
        peripheral.discoverServices(nil)
    }

    // Ищем сервисы
    func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
        if let servicePeripheral = peripheral.services as [CBService]? {
            for service in servicePeripheral {
                peripheral.discoverCharacteristics(nil, for: service)
            }
        }
    }
    // Находим сервис
    func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {

        if let characterArray = service.characteristics as [CBCharacteristic]? {

            for characteristic in characterArray {

                if characteristic.uuid.uuidString == "00002902-0000-1000-8000-00805F9B34FB" {
                    print("00002902-0000-1000-8000-00805f9b34fb")
                }

                if characteristic.uuid.uuidString == "0783B03E-8535-B5A0-7140-A304D2495CB8" {
                    characteristicNot = characteristic
                    if characteristic.properties.contains(.read) {
                        print("\(characteristic.uuid): properties contains .read")
                    }

                    if characteristic.properties.contains(.notify) {
                        print("\(characteristic.uuid): properties contains .notify")
                    }

                    peripheral.discoverDescriptors(for: characteristic)
                    peripheral.setNotifyValue(true, for: characteristic)

                    print("-------------------------")
                }

                if characteristic.uuid.uuidString == "0783B03E-8535-B5A0-7140-A304D2495CBA" {
                    if characteristic.properties.contains(.read) {
                        print("\(characteristic.uuid): properties contains .read")
                    }

                    if characteristic.properties.contains(.writeWithoutResponse) {
                        print("\(characteristic.uuid): properties contains .writeWithoutResponse")
                    }

                    let data:[UInt8] = [0xFE, 0x43, 0x11, 0x22, 0x19, 0x8A, 0x60, 0x65, 0x7E, 0x5C, 0x46, 0x41, 0x8B, 0xF7, 0x4D]
                    let writeData =  Data(bytes: data)

                    peripheral.writeValue(writeData, for: characteristic, type: CBCharacteristicWriteType.withoutResponse)

                    peripheral.readValue(for: characteristic)
                    peripheral.readValue(for: characteristicNot)
                    peripheral.setNotifyValue(true, for: characteristicNot)

                    print("-------------------------")
                }

                if characteristic.uuid.uuidString == "0783B03E-8535-B5A0-7140-A304D2495CB9" {
                    if characteristic.properties.contains(.read) {
                        print("\(characteristic.uuid): properties contains .read")
                    }

                    if characteristic.properties.contains(.notify) {
                        print("\(characteristic.uuid): properties contains .notify")
                    }

                    if characteristic.properties.contains(.writeWithoutResponse) {
                        print("\(characteristic.uuid): properties contains .writeWithoutResponse")
                    }

                    print("-------------------------")
                }
            }
        }
    }

    func peripheral(_ peripheral: CBPeripheral, didDiscoverDescriptorsFor characteristic: CBCharacteristic, error: Error?) {
        if let descriptorsArray = characteristic.descriptors as [CBDescriptor]? {
            for descriptor in descriptorsArray {
                print(descriptor)
            }
        }
    }
    // Читаем значения сервиса
    func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
        print("didUpdateValueFor characteristic", characteristic.uuid.uuidString)
        print("didUpdateValueFor characteristic value", characteristic.value)
        print("didUpdateValueFor characteristic error", error)

        if let characteristicData = characteristic.value {
            let byteArray = [UInt8](characteristicData)

            //let firstBitValue = byteArray[0] & 0x01
            print(byteArray)
        }

        print("-------------------------")
    }

    func peripheral(_ peripheral: CBPeripheral, didUpdateNotificationStateFor characteristic: CBCharacteristic, error: Error?) {
        print("didUpdateNotificationStateFor characteristic", characteristic.uuid.uuidString)
        print("didUpdateNotificationStateFor characteristic value", characteristic.value)
        print("didUpdateNotificationStateFor characteristic error", error)
        print("didUpdateNotificationStateFor characteristic descriptors", characteristic.descriptors)
        print("-------------------------")
    }

    func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) {
        print("didWriteValueFor characteristic", characteristic.uuid.uuidString)
        print("didWriteValueFor characteristic", characteristic.value)
        print("didWriteValueFor characteristic", error?.localizedDescription)
        print("-------------------------")
    }

    func peripheral(_ peripheral: CBPeripheral, didWriteValueFor descriptor: CBDescriptor, error: Error?) {
        print("didWriteValueFor descriptor")
    }

    func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor descriptor: CBDescriptor, error: Error?) {
         print("didUpdateValueFor descriptor")
    }


    func centralManagerDidUpdateState(_ central: CBCentralManager) {
        var consoleLog = ""

        switch central.state {
        case .poweredOff:
            consoleLog = "BLE is powered off"
        case .poweredOn:
            consoleLog = "BLE is poweredOn"
            manager.scanForPeripherals(withServices: nil, options: nil)
        case .resetting:
            consoleLog = "BLE is resetting"
        case .unauthorized:
            consoleLog = "BLE is unauthorized"
        case .unknown:
            consoleLog = "BLE is unknown"
        case .unsupported:
            consoleLog = "BLE is unsupported"
        default:
            consoleLog = "default"
        }
    }
}
...