ios – SWIFT – BLE通讯

ios – SWIFT – BLE通讯,第1张

概述我有一个SWIFT应用程序,必须通过蓝牙LowEnergy模块向我的Arduino发送一个值! 我已经正确完成了搜索和连接部分,但我无法发送和接收任何数据. 这是我的代码,用于获取可用的BLE设备列表,并将所有这些放在表格视图中,然后在应用程序提供的单元格中单击以将设备与它们连接! 所有这一切都很完美,但我不知道从应用程序到BLE发送一个“a”字符,并从arduino回复给app! import 我有一个SWIFT应用程序,必须通过蓝牙LowEnergy模块向我的Arduino发送一个值!

我已经正确完成了搜索和连接部分,但我无法发送和接收任何数据.

这是我的代码,用于获取可用的BLE设备列表,并将所有这些放在表格视图中,然后在应用程序提供的单元格中单击以将设备与它们连接!

所有这一切都很完美,但我不知道从应用程序到BLE发送一个“a”字符,并从arduino回复给app!

import UIKit    import CoreBluetoothclass BluetoothList: UItableVIEwController,CBCentralManagerDelegate,CBPeripheralDelegate {    var ListValue = [Lista]()    var Blue: CBCentralManager!    var conn: CBPeripheral!    var a: String!    var char: CBCharacteristic!    func centralManager(central: CBCentralManager,dIDdiscoverPeripheral peripheral: CBPeripheral,advertisementData: [String : AnyObject],RSSI: NSNumber) {        if (peripheral.name == a){            self.conn = peripheral            self.conn.delegate = self            Blue.stopScan()            Blue.connectPeripheral(self.conn,options: nil)            self.performSegueWithIDentifIEr("ConnectionSegue",sender: nil)        }        else{            ListValue = [                Lista(name: peripheral.name!,RSS: RSSI.stringValue)            ]            self.tableVIEw.reloadData()        }    }    func centralManager(central: CBCentralManager,dIDConnectPeripheral peripheral: CBPeripheral) {        peripheral.delegate = self        peripheral.discoverServices(nil)    }    func peripheral(peripheral: CBPeripheral,dIDdiscoverServices error: NSError?) {        if let servicePeripheral = peripheral.services! as [CBService]!{            for service in servicePeripheral{                peripheral.discovercharacteristics(nil,forService: service)            }        }    }    func peripheral(peripheral: CBPeripheral,dIDdiscovercharacteristicsForService service: CBService,error: NSError?) {        if let characterarray = service.characteristics! as [CBCharacteristic]!{            for cc in characterarray {                if(cc.UUID.UUIDString == "FF05"){                    print("OKOK")                    peripheral.readValueForCharacteristic(cc)                }            }        }    }    func peripheral(peripheral: CBPeripheral,dIDUpdateValueForCharacteristic characteristic: CBCharacteristic,error: NSError?) {        if (characteristic.UUID.UUIDString == "FF05"){            let value = UnsafePointer<Int>((characteristic.value?.bytes.memory)!)            print("\(value)")        }    }    func centralManagerDIDUpdateState(central: CBCentralManager){        switch(central.state){        case .PoweredOn:            Blue.scanForperipheralsWithServices(nil,options:nil)            print("Bluetooth is powered ON")        case .PoweredOff:            print("Bluetooth is powered OFF")        case .resetting:            print("Bluetooth is resetting")        case .Unauthorized:            print("Bluetooth is unauthorized")        case .UnkNown:            print("Bluetooth is unkNown")        case .Unsupported:            print("Bluetooth is not supported")        }    }    overrIDe func vIEwDIDLoad() {        super.vIEwDIDLoad()        Blue = CBCentralManager(delegate: self,queue: nil)    }    overrIDe func tableVIEw(tableVIEw: UItableVIEw,dIDSelectRowAtIndexPath indexPath: NSIndexPath) {        let currentCell = tableVIEw.cellForRowAtIndexPath(tableVIEw.indexPathForSelectedRow!)! as UItableVIEwCell        a = currentCell.textLabel?.text        Blue = CBCentralManager(delegate: self,queue: nil)    }    overrIDe func numberOfSectionsIntableVIEw(tableVIEw: UItableVIEw) -> Int {        return 1    }    @IBAction func Reload_BTN(sender: AnyObject) {        self.tableVIEw.reloadData()    }    overrIDe func tableVIEw(tableVIEw: UItableVIEw,numberOfRowsInSection section: Int) -> Int {        return self.ListValue.count    }    overrIDe func dIDReceiveMemoryWarning() {        super.dIDReceiveMemoryWarning()    }    overrIDe func tableVIEw(tableVIEw: UItableVIEw,cellForRowAtIndexPath indexPath: NSIndexPath) -> UItableVIEwCell {        let cella = self.tableVIEw.dequeueReusableCellWithIDentifIEr("Cella",forIndexPath: indexPath)        let Lista = self.ListValue[indexPath.row]        cella.textLabel?.text = Lista.name        cella.accessoryType = UItableVIEwCellAccessoryType.disclosureIndicator        return cella    }
解决方法 以下代码适用于Swift 3(XCode 8 Beta 6).这是一个使用标准UUID用于串行端口的示例,例如某些商业模块上的串行端口.因此,服务和特征的声明应如下所示:

private let UuIDSerialService = "6E400001-B5A3-F393-E0A9-E50E24DCCA9E"private let UuIDTx =            "6E400002-B5A3-F393-E0A9-E50E24DCCA9E"private let UuIDRx =            "6E400003-B5A3-F393-E0A9-E50E24DCCA9E"

然后你的委托给dIDdiscoverCharacteristic的方法可以是这样的:

public func peripheral(_ peripheral: CBPeripheral,dIDdiscovercharacteristicsFor service: CBService,error: Error?){    if let characteristics = service.characteristics {        for characteristic in characteristics {            // Tx:            if characteristic.uuID == CBUUID(string: UuIDTx) {                print("Tx char found: \(characteristic.uuID)")                txCharacteristic = characteristic            }            // Rx:            if characteristic.uuID == CBUUID(string: UuIDRx) {                rxCharacteristic = characteristic                if let rxCharacteristic = rxCharacteristic {                    print("Rx char found: \(characteristic.uuID)")                    serialPortPeripheral?.setNotifyValue(true,for: rxCharacteristic)                }            }        }    }}

对于写入Tx,类似下面的工作,其中value是[UInt8]:

let data = NSData(bytes: value,length: value.count)serialPortPeripheral?.writeValue(data as Data,for: txCharacteristic,type: CBCharacteristicWriteType.withResponse)

读?

public func peripheral(_ peripheral: CBPeripheral,dIDUpdateValueFor characteristic: CBCharacteristic,error: Error?) {    let rxData = characteristic.value    if let rxData = rxData {        let numberOfBytes = rxData.count        var rxByteArray = [UInt8](repeating: 0,count: numberOfBytes)        (rxData as NSData).getBytes(&rxByteArray,length: numberOfBytes)        print(rxByteArray)    }}

最后,如果你不知道或者你不确定你的BLE设备的服务和特性,你可以寻找一个名为“lightBlue”的免费iOS应用程序.它会发现一个设备,如果你连接它,它将列出所有服务和特征.请注意,当lightBlue连接到您的设备时,您的应用程序将无法访问BLE硬件.

总结

以上是内存溢出为你收集整理的ios – SWIFT – BLE通讯全部内容,希望文章能够帮你解决ios – SWIFT – BLE通讯所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1072917.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-26
下一篇 2022-05-26

发表评论

登录后才能评论

评论列表(0条)

保存