IOS蓝牙4.0(BLE)开发二编码实战
来源:互联网 发布:爱淘宝怎么删除 编辑:程序博客网 时间:2024/05/29 07:45
1.首先导入蓝牙框架,然后
#import <CoreBluetooth/CoreBluetooth.h>
二、编码步骤,首先定义一些宏,这是你要连接的蓝牙芯片(外设,不同芯片不一样)的服务与特征的UUID了,你的硬件工程师会给你相应的说明文档的。同时还声明了一些属性,方便接下来的使用:
开发步骤
- 建立中心管家
// 1. 创建中心管家,并且设置代理self.cmgr = [[CBCentralManager alloc]initWithDelegate:self queue:nil];
- 扫描外设(discover)
// 2. 在代理方法中扫描外部设备 /** * scanForPeripheralsWithServices :如果传入指定的数组,那么就只会扫描数组中对应ID的设备 * 如果传入nil,那么就是扫描所有可以发现的设备 * 扫描完外部设备就会通知CBCentralManager的代理 */ - (void)centralManagerDidUpdateState:(CBCentralManager *)central{ if ([central state] == CBCentralManagerStatePoweredOn) { [self.cmgr scanForPeripheralsWithServices:nil options:nil]; }}
/** * 发现外部设备,每发现一个就会调用这个方法 * 所以可以使用一个数组来存储每次扫描完成的数组 */- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *,id> *)advertisementData RSSI:(NSNumber *)RSSI{ // 有可能会导致重复添加扫描到的外设 // 所以需要先判断数组中是否包含这个外设 if(![self.peripherals containsObject:peripheral]){ [self.peripherals addObject:peripheral]; }}
- 连接外设
/** * 模拟开始连接方法 */- (void)start{ // 3. 连接外设 for (CBPeripheral *ppl in self.peripherals) { // 扫描外设的服务 // 这个操作应该交给外设的代理方法来做 // 设置代理 ppl.delegate = self; [self.cmgr connectPeripheral:ppl options:nil]; }}
扫描外设中的服务和特征
服务和特征的关系
每个蓝牙4.0的设备都是通过服务和特征来展示自己的,一个设备必然包含一个或多个服务,每个服务下面又包含若干个特征。
/** * 连接外设成功调用 */- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral{ // 查找外设服务 [peripheral discoverServices:nil];}
/** * 发现服务就会调用代理方法 * * @param peripheral 外设 */- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{ // 扫描到设备的所有服务 NSArray *services = peripheral.services; // 根据服务再次扫描每个服务对应的特征 for (CBService *ses in services) { [peripheral discoverCharacteristics:nil forService:ses]; }}
- 与外设做数据交互
- 在指定的特征下做相应的操作
/** * 发现服务对应的特征 */- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error{ // 服务对应的特征 NSArray *ctcs = service.characteristics; // 遍历所有的特征 for (CBCharacteristic *character in ctcs) { // 根据特征的唯一标示过滤 if ([character.UUID.UUIDString isEqualToString:@"XMG"]) { NSLog(@"可以吃饭了"); } }}
- 断开连接
/** * 断开连接 */- (void)stop{ // 断开所有连接上的外设 for (CBPeripheral *per in self.peripherals) { [self.cmgr cancelPeripheralConnection:per]; }}
阅读全文
0 0
- IOS蓝牙4.0(BLE)开发二编码实战
- iOS蓝牙4.0(BLE)-开发
- iOS蓝牙4.0(BLE)-开发
- iOS:蓝牙BLE 4.0 开发
- iOS蓝牙Ble开发
- ios开发蓝牙 BLE
- iOS蓝牙BLE开发
- iOS开发之蓝牙4.0 BLE开发
- iOS开发之蓝牙4.0 -- BLE开发
- IOS蓝牙4.0(BLE)开发一基本概念
- 蓝牙BLE开发基础教程 android5.0 蓝牙4.0 透传 Android Studio(二)
- Android 蓝牙开发(二)Ble 开发(android4.3)
- Android 蓝牙开发【二】BLE开发 (Android4.3)
- android 蓝牙4.0(BLE)开发
- Android 蓝牙4.0 Ble开发(一)
- 三步走--低功耗蓝牙BLE开发实战
- iOS开发 之 可穿戴设备 蓝牙4.0 BLE 开发
- iOS开发 之 可穿戴设备 蓝牙4.0 BLE 开发
- http请求常见状态码说明
- python+opencv安装
- PYTHON3.6+PYCHARM 爬虫
- MySQL存储引擎
- ⑧ NDK学习之C语言枚举
- IOS蓝牙4.0(BLE)开发二编码实战
- Hibernate入门
- 11.4模拟赛感言
- 快速学习 Spring Boot 技术栈
- 解忧程序员,你遇到的坎儿,它懂
- 正则
- Mysql 服务无法启动 服务没有报告任何错误
- ⑨ NDK学习之C语言IO
- shder总结四