现在已经有几年时间,Microchip发布了具有私有MLDP配置文件的RN4020 BT LE芯片。然而,尽管他们在Apple App Store中拥有iOS应用程序,但仍然没有可用的公共可用iOS示例源代码。有没有人有任何工作代码并愿意分享/发布它?
谢谢!
添
答案 0 :(得分:4)
我有一些工作代码。我会在这里给出一些片段。在第一个符合我们CBCentralManagerDelegate
的ViewController中:
var cbc : CBCentralManager? = nil
override func viewDidLoad() {
super.viewDidLoad()
cbc = CBCentralManager(delegate: self, queue: nil)
}
触摸按钮开始扫描外围设备
@IBAction func scan(_ sender: Any) {
cbc?.scanForPeripherals(withServices: nil, options: nil)
}
找到每个外围设备的将调用以下代理成员
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
// store peripherals here to let select user one
NSLog("name=%@", peripheral.name ?? "unnamed")
}
我们将外围设备存储在字典中,并使用表格视图向用户显示其名称。如果用户选择外围设备,我们会尝试连接到
@IBAction func connect(_ sender: Any) {
// selectedPeripheral set by selection from the table view
cbc?.connect(selectedPeripheral!, options: nil)
}
成功连接将导致调用以下委托方法:
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
performSegue(withIdentifier: "ConnectPeriph", sender: self)
}
导致第二个ViewController负责连接状态。此ViewController符合CBPeripheralDelegate
协议并声明以下变量:
var periph : CBPeripheral! // selected peripheral
var dataChar : CBCharacteristic? // characteristic for data transfer
let mchpPrivateService : CBUUID = CBUUID(string: "00035B03-58E6-07DD-021A-08123A000300")
let mchpDataPrivateChar : CBUUID = CBUUID(string: "00035B03-58E6-07DD-021A-08123A000301")
连接后的第一个动作是发现外围设备提供的服务:
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
periph.delegate = self
periph.discoverServices(nil)
}
这导致调用此委托方法:
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
if let e = error {
NSLog("Error %@", e.localizedDescription)
}
else if let services = peripheral.services {
for s in services {
NSLog("Service=%@", s.uuid.uuidString)
if s.uuid.isEqual(mchpPrivateService) {
peripheral.discoverCharacteristics(nil, for: s)
}
}
}
}
反过来导致发现特征:
func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
NSLog("characteristics for service %@", service.uuid.uuidString)
if let characteristics = service.characteristics {
for c in characteristics {
if c.uuid.isEqual(mchpDataPrivateChar) {
peripheral.setNotifyValue(true, for: c)
dataChar = c
}
}
}
}
我们感兴趣的唯一特征是使用uuid mchpDataPrivateChar
。通知请求导致调用:
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
NSLog("update value for %@", characteristic.uuid)
if let d = characteristic.value {
var s : String = String()
for b in d {
s.append(Character(UnicodeScalar(b)))
}
NSLog("received \(d.count) bytes: \(s)")
}
}
完成了iOS端的接收器。发送字节通过以下方式完成:
@IBAction func sendClicked(_ sender: Any) {
if let d = dataChar, let s=sendEdit.text {
let buffer : [UInt8] = Array(s.utf8)
let data : Data = Data(buffer)
periph.writeValue(data, for: d, type: .withResponse)
}
}