Andorid/IOS 蓝牙开发总结

IOS 蓝牙开发

1 首先增加库依赖 CoreBluetooth    general-> Linked Frameworks and lib
2 权限info.plist 申明权限,Bluetooth Peripheral Usage
需要2个后台模式,app communicates usering COreBluetooth 
app shares data using CoreBluetooth
3 库底下主要的几个类
CBCentral  CBCentralManager     中心
CBPeripheral  CBPeripheralManager  外设
CBService SBCharacteristic  CBDescriptor  CBUUID 服务 特征 描述 UUID 
4 流程:
(中心,外设,服务,特征)
-> 【中心】初始化 -> 中心扫描外设 -> 中心连接外设 
-> 【外设】搜索【服务】 
-> 【外设】搜索【服务的特征 】
-> 【外设】读特征的【特征值】
-> 【外设】发现特征的【特征描述】
-> 【外设】写数据到指定【特征】
-> 【特征】 character.properties 属性,有可读,可写,可写无返回,广播,通知等几种类型

A 初始化中心 init CBCentralManager,设置代理, 在回调  centralManagerDidUpdateState 中判断蓝牙是否可用
B 中心搜索外设centerManager  scanForPeripheralsWithServices ,在回调 didDiscoverPeripheral 中发现设备(有多个外设,回调返回多次)
C 定时几秒后调用 中心停止搜索 centerManager  stopScan
D 中心连接外设 centerManager  connectPeripheral: perip  连接其中一个外设, 在回调 didConnectPeripheral 确认已经连接上
E 已连接上的外设搜索服务  peripheral  discoverServices:   在回调 didDiscoverServices  发现服务(有多个服务,回调返回多次)
E 发现的服务对象搜索特征,service.peripheral discoverCharacteristics , 在回调 didDiscoverCharateristicsForService 发现特征
F 外设读特征 periphera readValueForCharacteristic , 在回调 didUpdateValueForCharacteristic 中获取特征值value
H 外设读特征描述 discoverDescriptorsForCharacteristic  ,在回调 didDiscoverDescriptorsForCharacteristic  发现特征描述
I 外设写特征 peripheral writeValue:data forCharacteristic:writeChara   写数据到有写属性的特征中

注意:
1 推荐IOS 蓝牙调试工具 lightBlue, 可做为中心,可建立虚拟外设
2 读写特征传递的value 是NSData 类型,注意定义好编码,lightBlue默认是 十六进制,可改为UTF-8
然后就可以自由传 中英文了(IOS 一次传送有大小限制, 听说最大60个字节?)
3 发现的外设,有connectable = 0的,不可连接的外设,可自行过滤
4 连接以后容易断线,再次从步骤 D connectPeripheral 即可

————————————————————————————
Android 蓝牙待续
目前用的是 https://github.com/dingjikerbo/Android-BluetoothKit
这个封装的库 kit 
 

猜你喜欢

转载自blog.csdn.net/qq_42022061/article/details/88825165