SWIFT - BLE通信
问题描述:
我有一个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
}
答
以下代码适用于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硬件。
您需要知道您的arduino使用哪种特性来接收数据,然后您只需将字节写入该特性。 – Paulw11
那么,我怎么找到它? –
如果你能够在错误的地方编辑我的代码,我会很高兴,因为我知道我必须知道我的BLE模块的特性,并且我知道我可以将它放入CBCharacteristic变量(或类似的东西)但我不知道我在哪里可以得到这种类型的价值!非常感谢 –