LEONBLManager.m 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. //
  2. // LEONBLManager.m
  3. // Unity-iPhone
  4. //
  5. // Created by Leon on 2021/4/23.
  6. #import "LEONBLManager.h"
  7. //CBCentralManagerDelegate 蓝牙外设回调代理
  8. //CBPeripheralDelegate 蓝牙链接后的数据回调代理
  9. @interface LEONBLManager()<CBCentralManagerDelegate,CBPeripheralDelegate>
  10. @property (strong, nonatomic)CBCentralManager * centralManager;/**< 蓝牙中心管理器 */
  11. @end
  12. @implementation LEONBLManager
  13. #pragma mark --------------------------------------- public methon ==>> 单例
  14. static LEONBLManager * instance;
  15. //[[self alloc] init] 类方法使用self时,self代表类本身即Class
  16. //类方法中不能访问“属性”和“实例变量”,只能访问“类”对象
  17. +(instancetype)sharedInstance{
  18. // NSLog(@"LEONBLManager === 1");
  19. return [[self alloc] init];
  20. }
  21. //初始化一个对象的时候,[[Class alloc] init],其实是做了两件事。
  22. //alloc 给对象分配内存空间,init是对对象的初始化,包括设置成员变量初值这些工作。
  23. //而给对象分配空间,除了alloc方法之外,还有另一个方法: allocWithZone.
  24. //使用alloc方法初始化一个类的实例的时候,默认是调用了allocWithZone的方法。为了保持单例类实例的唯一性,需要覆盖所有会生成新的实例的方法,如果初始化这个单例类的时候不走[[Class alloc] init] ,而是直接 allocWithZone, 那么这个单例就不再是单例了,所以必须把这个方法也堵上。
  25. + (instancetype)allocWithZone:(struct _NSZone *)zone{
  26. // NSLog(@"LEONBLManager === 2");
  27. static dispatch_once_t onceToken;
  28. dispatch_once(&onceToken, ^{
  29. instance = [super allocWithZone:zone];
  30. });
  31. return instance;
  32. }
  33. //实例对象能访问“属性”和“实例变量”
  34. - (instancetype)init{
  35. // NSLog(@"LEONBLManager === 3");
  36. static dispatch_once_t onceToken;
  37. dispatch_once(&onceToken, ^{
  38. instance = [super init];
  39. [self initCBCentralManager];
  40. });
  41. return instance;
  42. }
  43. /**
  44. 初始外设管理类
  45. */
  46. -(void)initCBCentralManager{
  47. //蓝牙没打开时alert提示框
  48. NSDictionary *options = @{CBCentralManagerOptionShowPowerAlertKey:@(YES)};
  49. self.centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:dispatch_get_main_queue() options:options];
  50. }
  51. #pragma mark ---------------- public methon ==>> 外部 操作蓝牙外设
  52. /**
  53. 开始扫描蓝牙外设
  54. @param serviceUUIDs 一个CBUUID对象表示要扫描的服务。
  55. @param options 一个可选的字典,指定扫描选项
  56. */
  57. - (void)scanForPeripheralsWithServices:(nullable NSArray<CBUUID *> *)serviceUUIDs options:(nullable NSDictionary<NSString *, id> *)options{
  58. [self.centralManager scanForPeripheralsWithServices:serviceUUIDs options:options];
  59. NSLog(@"开始扫描外设");
  60. }
  61. /**
  62. 停止扫描蓝牙外设
  63. */
  64. - (void)stopScan{
  65. [self.centralManager stopScan];
  66. NSLog(@"停止扫描外设");
  67. }
  68. /**
  69. 外部主动断开蓝牙链接
  70. @param peripheral 待链接的CBPeripheral对象
  71. @param options 一个可选的字典,指定连接行为选项
  72. */
  73. - (void)connectPeripheral:(CBPeripheral *)peripheral options:(nullable NSDictionary<NSString *, id> *)options{
  74. if (peripheral==self.peripheral){
  75. [self.centralManager connectPeripheral:self.peripheral options:options];
  76. NSLog(@"主设备 主动连接蓝牙外设 = %@ %p %p",self.peripheral.name,self.peripheral,peripheral);
  77. }else if (peripheral==self.vicePeripheral){
  78. [self.centralManager connectPeripheral:self.vicePeripheral options:options];
  79. NSLog(@"副设备 主动连接蓝牙外设 = %@ %p %p",self.vicePeripheral.name,self.vicePeripheral,peripheral);
  80. }
  81. }
  82. /**
  83. 外部主动断开蓝牙链接
  84. @param peripheral 待断开的CBPeripheral对象
  85. */
  86. - (void)cancelPeripheralConnection{
  87. if (self.peripheral!=nil){
  88. [self.centralManager cancelPeripheralConnection:self.peripheral];
  89. NSLog(@"主动断开蓝牙链接 = %@",self.peripheral.name);
  90. // self.peripheral = nil;
  91. }else if (self.vicePeripheral!=nil){
  92. [self.centralManager cancelPeripheralConnection:self.vicePeripheral];
  93. NSLog(@"主动断开蓝牙链接 = %@",self.vicePeripheral.name);
  94. // self.vicePeripheral = nil;
  95. }
  96. }
  97. #pragma mark -------------- public methon ==>> 外部 操作蓝牙数据
  98. /**
  99. 主动向蓝牙写入数据
  100. @param data 数据流
  101. @param characteristic 可以写入的特征
  102. @param type 写入数据的类型
  103. */
  104. - (void)writeValue:(NSData *)data forCharacteristic:(CBCharacteristic *)characteristic writeType:(CBCharacteristicWriteType)writeType deviceType:(DEVICE_TYPE)deviceType{
  105. if (deviceType==DEVICETYPE_MAIN){
  106. [self.peripheral writeValue:data forCharacteristic:characteristic type:writeType];
  107. }else if (deviceType==DEVICETYPE_VICE){
  108. [self.vicePeripheral writeValue:data forCharacteristic:characteristic type:writeType];
  109. }
  110. }
  111. #pragma mark =================================== CentralManagerDelegate 代理回调
  112. //返回蓝牙状态
  113. - (void)centralManagerDidUpdateState:(CBCentralManager *)central{
  114. // NSLog(@"蓝牙状态更新 = %ld",(long)central.state);
  115. if (central!=nil){
  116. if (_stateUpdateBlock){
  117. _stateUpdateBlock(central);
  118. }
  119. }
  120. }
  121. //扫描发现蓝牙设备
  122. - (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *, id> *)advertisementData RSSI:(NSNumber *)RSSI{
  123. if (_discoverPeripheralBlock){
  124. //过滤无效外设
  125. if (peripheral.name.length>=1){
  126. // NSLog(@"扫描发现蓝牙外设 = %@",peripheral.name);
  127. _discoverPeripheralBlock(central, peripheral, advertisementData, RSSI);
  128. }
  129. }
  130. }
  131. //蓝牙链接成功
  132. - (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral{
  133. if (_successfulBlock){
  134. _successfulBlock(peripheral);
  135. }
  136. if (peripheral == self.peripheral){
  137. NSLog(@"主设备 查找 %@ 的服务",peripheral.name);
  138. //声明蓝牙delegate
  139. self.peripheral.delegate = self;
  140. //serviceUUIDs传nil表示去获取连接到的蓝牙的所有服务
  141. [self.peripheral discoverServices:nil];
  142. }else if (peripheral == self.vicePeripheral){
  143. NSLog(@"副设备 查找 %@ 的服务",peripheral.name);
  144. //声明蓝牙delegate
  145. self.vicePeripheral.delegate = self;
  146. //serviceUUIDs传nil表示去获取连接到的蓝牙的所有服务
  147. [self.vicePeripheral discoverServices:nil];
  148. }
  149. }
  150. //蓝牙链接失败
  151. - (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(nullable NSError *)error{
  152. if (_connectFailureBlock){
  153. _connectFailureBlock(error);
  154. }
  155. if (peripheral == self.peripheral){
  156. NSLog(@"主设备 蓝牙外设链接失败 = %@",peripheral.name);
  157. }else if (peripheral == self.vicePeripheral){
  158. NSLog(@"副设备 蓝牙外设链接失败 = %@",peripheral.name);
  159. }
  160. }
  161. //丢失蓝牙链接
  162. - (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(nullable NSError *)error{
  163. if (_disConnectBlock){
  164. _disConnectBlock(peripheral,error);
  165. }
  166. if (peripheral == self.peripheral){
  167. NSLog(@"主设备 蓝牙外设丢失链接 = %@",peripheral.name);
  168. }else if (peripheral == self.vicePeripheral){
  169. NSLog(@"副设备 蓝牙外设丢失链接 = %@",peripheral.name);
  170. }
  171. }
  172. #pragma mark =================================== PeripheralDelegate 代理回调
  173. //发现服务的回调
  174. - (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(nullable NSError *)error{
  175. if (_discoveredServicesBlock){
  176. _discoveredServicesBlock(peripheral,peripheral.services,error);
  177. }
  178. if (peripheral == self.peripheral){
  179. NSLog(@"主设备 查找 %@ 的特征",peripheral.name);
  180. }else if (peripheral == self.vicePeripheral){
  181. NSLog(@"主设备 查找 %@ 的特征",peripheral.name);
  182. }
  183. //扫描所有的特征
  184. for (CBService *service in peripheral.services){
  185. [peripheral discoverCharacteristics:nil forService:service];
  186. }
  187. }
  188. //发现特征的回调
  189. - (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(nullable NSError *)error{
  190. // NSLog(@"发现所有服务+特征的值 %p %p %p",self.peripheral,self.vicePeripheral,peripheral);
  191. if (_discoverCharacteristicsBlock){
  192. if (peripheral==self.peripheral){
  193. _discoverCharacteristicsBlock(peripheral,service,service.characteristics,error);
  194. NSLog(@"主设备 发现 %@ 服务+特征",peripheral.name);
  195. }else if (peripheral == self.vicePeripheral){
  196. _discoverCharacteristicsBlock(peripheral,service,service.characteristics,error);
  197. NSLog(@"副设备 发现 %@ 服务+特征",peripheral.name);
  198. }
  199. }
  200. }
  201. //收到数据的回调
  202. - (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{
  203. if (_readValueForCharacteristicBlock){
  204. NSData *data = characteristic.value;
  205. if (peripheral==self.peripheral){
  206. _readValueForCharacteristicBlock(self.peripheral,characteristic,data,error,DEVICETYPE_MAIN);
  207. // NSLog(@"收到主设备 %@ 推送的报文 %@",peripheral.name,data);
  208. }else if (peripheral == self.vicePeripheral){
  209. _readValueForCharacteristicBlock(self.vicePeripheral,characteristic,data,error,DEVICETYPE_VICE);
  210. // NSLog(@"收到副设备 %@ 推送的报文 %@",peripheral.name,data);
  211. }
  212. }
  213. }
  214. //写入数据的回调
  215. - (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(nullable NSError *)error{
  216. if (_writeToCharacteristicBlock){
  217. if (peripheral==self.peripheral){
  218. _writeToCharacteristicBlock(self.peripheral,characteristic,error,DEVICETYPE_MAIN);
  219. // NSLog(@"收到主设备 %@ 的response",peripheral.name);
  220. }else if (peripheral == self.vicePeripheral){
  221. _writeToCharacteristicBlock(self.vicePeripheral,characteristic,error,DEVICETYPE_VICE);
  222. // NSLog(@"收到附设备 %@ 的response",peripheral.name);
  223. }
  224. }
  225. }
  226. @end