2016-03-04 130 views
4

我有一個SWIFT應用程序必須通過Bluetooth LowEnergy模塊將值發送給我的Arduino!SWIFT - BLE通信

我已經正確地完成了搜索和連接部分,但我無法發送和接收任何數據。

這裏是我的代碼,以獲得可用的BLE設備列表,並將所有這些都放在表格視圖中,然後點擊應用程序提供的單元格以連接設備!

這一切都很完美,但我不知道從應用程序發送「A」字符到BLE,並從arduino迴應應用程序!

import UIKit 
    import CoreBluetooth 


class 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 
    } 
+1

您需要知道您的arduino使用哪種特性來接收數據,然後您只需將字節寫入該特性。 – Paulw11

+0

那麼,我怎麼找到它? –

+0

如果你能夠在錯誤的地方編輯我的代碼,我會很高興,因爲我知道我必須知道我的BLE模塊的特性,並且我知道我可以將它放入CBCharacteristic變量(或類似的東西)但我不知道我在哪裏可以得到這種類型的價值!非常感謝 –

回答

4

以下代碼適用於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,有點像以下作品,其中價值是[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連接到您的設備時,obvoiusly您的應用程序將無法訪問BLE硬件。