BabyBluetoothSwift.m 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078
  1. /*
  2. 切换连接
  3. 断开上一个连接
  4. */
  5. //传数据所用标识g
  6. /*
  7. 发一条标记一条。
  8. 发一条 隔一段时间发一条
  9. 隔一段时间发一条
  10. */
  11. #define ReceiveData @"RECEIVEDATA"
  12. #define DataTag @"DataTag"
  13. #import "BabyBluetoothSwift.h"
  14. #import <CoreBluetooth/CoreBluetooth.h>
  15. //#import "VMUserInfoPlist.h"
  16. #import "NSData+CRC16.h"
  17. #import "NSString+WithCRCModbus.h"
  18. #import "SolarBT-Swift.h"
  19. @interface BabyBluetoothSwift() {
  20. BabyBluetooth *baby;//蓝牙单例
  21. NSMutableData* mUartRecvData;//接收到的数据
  22. NSLock *dataLock;//线程锁
  23. NSString *gUartMessageType;//消息类型
  24. NSMutableArray *dataDictionary;//传进来的消息类型
  25. NSMutableData *allrecevedata;
  26. NSMutableData *_loopallrecevedata;
  27. NSMutableDictionary *recciveDataDictionary;//接收到的消息类型
  28. BOOL isLoop;//是否是循环的
  29. BOOL isUpdateFirmware;//是否更新固件
  30. }
  31. @property (nonatomic,assign) BOOL reConnectedToRead;
  32. //@property (nullable,strong) NSMutableArray *connectArray
  33. //写入特征
  34. @property (nonatomic,strong)CBCharacteristic *writeCharacteristic;
  35. //密码特征
  36. @property (nonatomic,strong)CBCharacteristic *passwordCharacteristic;
  37. //复位特征
  38. @property (nonatomic,strong)CBCharacteristic *restoreCharacteristic;
  39. @property (nonatomic,copy) void (^CompleteHandle)(NSString *reacive);
  40. @property (nonatomic,copy) void (^CompleteHandle2)(NSDictionary *reaciveDic);
  41. @property (nonatomic,copy) void (^loopCompleteHandle)(NSString *reacive);
  42. @property (nonatomic,copy) void (^loopCompleteHandle2)(NSDictionary *reaciveDic);
  43. @property (nonatomic,copy) void (^connectCompletHandle)(CBPeripheral *peripheral, BOOL isSuccess);
  44. @property (nonatomic,copy) void (^StartWriteCallback)(void);
  45. @end
  46. //写入服务的UUID
  47. const static NSString* writeServerUUIDString = @"FFF0";
  48. //读取服务的UUID
  49. const static NSString* readServerUUIDString = @"FFD0";
  50. //参数设置服务的UUID
  51. const static NSString* setServerUUIDString = @"FF50";
  52. //密码服务的UUID
  53. const static NSString* passwordServerUUIDString = @"FF80";
  54. //写入特征的UUID
  55. const static NSString* writeCharacteristicUUIDString = @"FFD1";
  56. //读取特征的UUID
  57. const static NSString* readCharacterosticUUIDString = @"FFF1";
  58. //修改名称 uuid
  59. const static NSString* writeNameCharacteristicUUIDString = @"FF51";
  60. //复位模块
  61. const static NSString* restoreSystermCharacteristicUUIDString = @"FF54";
  62. //设置密码特征值
  63. const static NSString* writePasswordCharacteristicUUIDString = @"FF81";
  64. //通知密码特征值
  65. const static NSString* notityPasswordCharacteristicUUIDString = @"FF82";
  66. @implementation BabyBluetoothSwift
  67. static BOOL isReadChFound = false;//是否读?
  68. static BOOL isWriteCHFound = false;//是否写?
  69. _Bool isAutoConnect = true;//是否自动连接
  70. _Bool mCMDConnect = false;//CMD是否连接
  71. _Bool connected = false;//连接
  72. bool isFirstStart = true;//是否是第一次开始
  73. _Bool isStartWrite = true;//为真代表可以写入
  74. NSTimer *timer;
  75. //单例模式
  76. + (instancetype)shareInstance {
  77. static BabyBluetoothSwift *share = nil;
  78. static dispatch_once_t oneToken;
  79. dispatch_once(&oneToken, ^{
  80. share = [[BabyBluetoothSwift alloc]init];
  81. });
  82. return share;
  83. }
  84. //初始化蓝牙并设置代理
  85. - (instancetype)init {
  86. self = [super init];
  87. if (self) {
  88. baby = [BabyBluetooth shareBabyBluetooth];
  89. _peripherals = [[NSMutableArray alloc]init];
  90. mUartRecvData = [NSMutableData data];
  91. allrecevedata = [NSMutableData data];
  92. dataLock = [[NSLock alloc] init];
  93. recciveDataDictionary = [NSMutableDictionary dictionary];
  94. // self.newRead = false;
  95. isUpdateFirmware = false;
  96. self.reConnectedToRead = false ;
  97. ;
  98. [self babyDelegate];
  99. }
  100. return self;
  101. }
  102. -(BOOL)canWrite{
  103. return isWriteCHFound;
  104. }
  105. -(BOOL) isConnected {
  106. return connected;
  107. }
  108. -(void)autoConnect {
  109. [baby retrievePeripheralWithUUIDString:@""];
  110. }
  111. -(void)scanForPeripherals {
  112. baby.scanForPeripherals().begin();
  113. }
  114. -(void)cancelScan{
  115. baby.cancelScan;
  116. }
  117. -(void)reconnectPeripheralWithName:(NSString *)name{
  118. for (id peripherial in _peripherals) {
  119. if([((CBPeripheral *)peripherial).name isEqualToString:name]) {
  120. _currPeripheral = (CBPeripheral *)peripherial;
  121. NSLog(@"");
  122. baby.having(_currPeripheral).connectToPeripherals().discoverServices().discoverCharacteristics().begin();
  123. NSLog(@"重新连接 - %@",_currPeripheral);
  124. mCMDConnect = true;
  125. [baby cancelScan];
  126. }
  127. }
  128. [_peripherals removeAllObjects];
  129. }
  130. //判断是否存在设备
  131. -(BOOL)peripheralExitsAtPeripheralName:(NSString *)peripheralName{
  132. for (id peripherial in _peripherals) {
  133. if([((CBPeripheral *)peripherial).name isEqualToString:peripheralName]) {
  134. NSLog(@"存在设备 ---%@",peripheralName);
  135. return YES;
  136. }
  137. }
  138. return NO;
  139. }
  140. -(void)connectPeripheralWithName:(NSString *)name {
  141. [NSThread sleepForTimeInterval:0.5];
  142. NSLog(@"当前设备数组 - %@",_peripherals);
  143. for (id peripherial in _peripherals) {
  144. if([((CBPeripheral *)peripherial).name isEqualToString:name]) {
  145. _currPeripheral = (CBPeripheral *)peripherial;
  146. NSLog(@"---- %@",_currPeripheral);
  147. baby.having(_currPeripheral).connectToPeripherals().discoverServices().discoverCharacteristics().begin();
  148. mCMDConnect = true;
  149. [baby cancelScan];
  150. }
  151. }
  152. [_peripherals removeAllObjects];
  153. }
  154. -(void)connectPeripheralWithName:(NSString *)name connectCompletionHandler:(void (^)(CBPeripheral *, BOOL))connectCompletionHandler startWriteDataCallback:(void (^)(void))startWriteDataCallback{
  155. self.reConnectedToRead = true;
  156. isLoop = false;
  157. __weak BabyBluetoothSwift *weakSelf = self;
  158. self.StartWriteCallback = startWriteDataCallback;
  159. // .创建一个数目为1的信号量,用于“卡”for循环,等上次循环结束在执行下一次的for循环
  160. dispatch_semaphore_t sema = dispatch_semaphore_create(1);
  161. // 开始执行for循环,让信号量-1,这样下次操作须等信号量>=0才会继续,否则下次操作将永久停止
  162. long result = dispatch_semaphore_wait(sema, 15 * NSEC_PER_SEC);
  163. printf("连接 --- 信号量等待中\n");
  164. if (result == 0) {
  165. //返回0时可以安全的执行进行排他控制的处理,该处理结束后,通过dispath)semaphore_signal 函数Dispath Semphore 的计数值加1
  166. [self asynConnectPeripheralWithName:name connectCompletionHandler:^(CBPeripheral *perhpheral, BOOL isSuccess) {
  167. connectCompletionHandler(perhpheral,isSuccess);
  168. dispatch_semaphore_signal(sema);
  169. }];
  170. } else {
  171. /* 说明semaphore的值等于0.此时timeout指定d时间内函数处于线程阻塞*/
  172. for (id peripherial in weakSelf.peripherals) {
  173. if([((CBPeripheral *)peripherial).name isEqualToString:name]) {
  174. connectCompletionHandler(peripherial,false);
  175. }
  176. }
  177. }
  178. }
  179. -(void)connectPeripheralWithName:(NSString *)name connectCompletionHandler:(void (^)(CBPeripheral *, BOOL))connectCompletionHandler{
  180. __weak BabyBluetoothSwift *weakSelf = self;
  181. // .创建一个数目为1的信号量,用于“卡”for循环,等上次循环结束在执行下一次的for循环
  182. dispatch_semaphore_t sema = dispatch_semaphore_create(1);
  183. // 开始执行for循环,让信号量-1,这样下次操作须等信号量>=0才会继续,否则下次操作将永久停止
  184. long result = dispatch_semaphore_wait(sema, 15 * NSEC_PER_SEC);
  185. printf("连接 --- 信号量等待中\n");
  186. if (result == 0) {
  187. //返回0时可以安全的执行进行排他控制的处理,该处理结束后,通过dispath)semaphore_signal 函数Dispath Semphore 的计数值加1
  188. [self asynConnectPeripheralWithName:name connectCompletionHandler:^(CBPeripheral *perhpheral, BOOL isSuccess) {
  189. connectCompletionHandler(perhpheral,isSuccess);
  190. dispatch_semaphore_signal(sema);
  191. }];
  192. } else {
  193. /* 说明semaphore的值等于0.此时timeout指定d时间内函数处于线程阻塞*/
  194. for (id peripherial in weakSelf.peripherals) {
  195. if([((CBPeripheral *)peripherial).name isEqualToString:name]) {
  196. connectCompletionHandler(peripherial,false);
  197. }
  198. }
  199. }
  200. }
  201. -(void)asynConnectPeripheralWithName:(NSString *)name connectCompletionHandler:(void (^)(CBPeripheral *, BOOL))connectCompletionHandler{
  202. self.connectCompletHandle = connectCompletionHandler;
  203. [NSThread sleepForTimeInterval:0.5];
  204. NSLog(@"当前设备数组 - %@",_peripherals);
  205. for (id peripherial in _peripherals) {
  206. if([((CBPeripheral *)peripherial).name isEqualToString:name]) {
  207. _currPeripheral = (CBPeripheral *)peripherial;
  208. NSLog(@"开始连接 ---- %@",_currPeripheral);
  209. baby.having(_currPeripheral).connectToPeripherals().discoverServices().discoverCharacteristics().begin();
  210. // [self WaitPostConnect:15];
  211. mCMDConnect = true;
  212. [baby cancelScan];
  213. }
  214. }
  215. [_peripherals removeAllObjects];
  216. }
  217. - (BOOL)WaitPostConnect:(int)timerout{
  218. while( timerout >0)
  219. {
  220. usleep(1000);
  221. timerout--;
  222. NSLog(@"当前设备 --- %@ --- %d",self.currPeripheral,timerout);
  223. }
  224. if(timerout <= 0)
  225. {
  226. NSLog(@"false and timeout is %d", timerout);
  227. return false;
  228. }
  229. NSLog(@"true and timeout is %d", timerout);
  230. return true;
  231. }
  232. //断开连接
  233. -(void)disconnectPeripheralWithName:(NSString *)name{
  234. NSLog(@"断开设备");
  235. for (id peripherial in _peripherals) {
  236. if([((CBPeripheral *)peripherial).name isEqualToString:name]) {
  237. mCMDConnect = false;
  238. [baby cancelPeripheralConnection:peripherial];
  239. NSLog(@"断开设备++++++==");
  240. }
  241. }
  242. }
  243. -(void)cancelAllPeripheralsConnection {
  244. if (_currPeripheral == nil) {
  245. return;
  246. }
  247. mCMDConnect = false;
  248. [baby cancelAllPeripheralsConnection];
  249. }
  250. -(BOOL) crcCheck:(NSData *) data {
  251. [dataLock lock];
  252. [mUartRecvData appendData:data];
  253. [dataLock unlock];
  254. return YES;
  255. }
  256. -(void) ClearRecvFifo {
  257. [dataLock lock];
  258. [mUartRecvData setLength:0];
  259. [dataLock unlock];
  260. }
  261. -(BOOL) WaitPostMessage:(int) timerout {
  262. while(![self PostRecvMessage] && timerout >0)
  263. {
  264. usleep(1000);
  265. timerout--;
  266. }
  267. if(timerout <= 0)
  268. {
  269. NSLog(@"false and timeout is %d", timerout);
  270. return false;
  271. }
  272. NSLog(@"true and timeout is %d", timerout);
  273. return true;
  274. }
  275. -(void) StartLoopRecvOneMessage:(int) timeout {
  276. __weak BabyBluetoothSwift *weakSelf = self;
  277. dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
  278. dispatch_async(queue, ^{
  279. [weakSelf WaitPostMessage:timeout];
  280. });
  281. }
  282. /**
  283. 获取接收到的通知信息
  284. @param msg 通知信息
  285. */
  286. -(void) OnRecvMessage:(NSData *) msg {
  287. [dataLock lock];
  288. [mUartRecvData appendData:msg];
  289. [dataLock unlock];
  290. }
  291. /**
  292. 发送接收到的信息
  293. @return 是否成功?
  294. */
  295. -(BOOL) PostRecvMessage {
  296. // if(mUartRecvData == nil)
  297. // [dataLock unlock];
  298. // return false;
  299. // if(![ModbusData dataCrcCheck:mUartRecvData])
  300. // {
  301. // // [dataLock unlock];
  302. // return false;
  303. // }
  304. // if ([mUartRecvData length] == 0) {
  305. //
  306. // return false;
  307. // }
  308. //
  309. // [dataLock lock];
  310. // Uart_UserInfo *info = [[Uart_UserInfo alloc] init];
  311. // info.type = [[NSNumber alloc] initWithInteger:gUartMessageType];
  312. // info.data = mUartRecvData;
  313. // [[NSNotificationCenter defaultCenter] postNotificationName:kBabyBluetoothNotificationUartDataRecieve object:info];
  314. // NSLog(@"收到蓝牙完整数据: %@", mUartRecvData);
  315. // [ModbusData print:[[NSString alloc] initWithFormat:@"RecvData: %@", mUartRecvData]];
  316. // // [self ClearRecvFifo];
  317. // [dataLock unlock];
  318. return true;
  319. }
  320. -(void)setPasswordCharacterNotify:(CBCharacteristic *) ch {
  321. NSLog(@"设置密码通知 --- ");
  322. // __weak typeof(self) weakSelf = self;
  323. NSMutableData *_allrecevedata;
  324. // 设置通知
  325. [baby notify:_currPeripheral characteristic:ch block:^(CBPeripheral *peripheral, CBCharacteristic *characteristics, NSError *error) {
  326. NSData *data = characteristics.value;
  327. [self OnRecvMessage:data];
  328. [_allrecevedata appendData:data];
  329. NSLog(@"收到蓝牙完整数据 ========: %@", _allrecevedata);
  330. }];
  331. }
  332. -(void) setReadCharacterNotify3:(CBCharacteristic *) ch {
  333. __weak typeof(self) weakSelf = self;
  334. // 设置通知
  335. [baby notify:_currPeripheral characteristic:ch block:^(CBPeripheral *peripheral, CBCharacteristic *characteristics, NSError *error) {
  336. NSData *data = characteristics.value;
  337. [self OnRecvMessage:data];
  338. [_loopallrecevedata appendData:data];
  339. //
  340. if (_loopallrecevedata.length > 4) {
  341. NSLog(@"setReadCharacterNotify3 ----%@",_loopallrecevedata);
  342. NSString *str1 = [NSString stringWithFormat:@"%@",[_loopallrecevedata subdataWithRange:NSMakeRange(0, _loopallrecevedata.length-2)]];
  343. NSString *str2 = [NSString stringWithFormat:@"%@",[_loopallrecevedata subdataWithRange:NSMakeRange(
  344. _loopallrecevedata.length-2,2)]];
  345. str2 = [str2 substringWithRange:NSMakeRange(1, str2.length-2)];
  346. NSString *ssss = [NSString stringWithFormat:@"%@",[str1 substringWithRange:NSMakeRange(1, str1.length-2)]];
  347. ssss = [ssss stringByReplacingOccurrencesOfString:@" " withString:@""];
  348. NSString *crcbuss = [ssss withCrc16Modbus];
  349. NSString *res = [crcbuss substringWithRange:NSMakeRange(crcbuss.length-4, 4)];
  350. NSLog(@"res -- %@ str2 ---%@",res,str2);
  351. if ([res isEqualToString:str2]) {
  352. NSLog(@"收到蓝牙完整数据========: %@", allrecevedata);
  353. NSString *datastr = [NSString stringWithFormat:@"%@",_loopallrecevedata];
  354. self.loopCompleteHandle(datastr);
  355. _loopallrecevedata = nil;
  356. }
  357. }
  358. }];
  359. }
  360. -(void) setReadCharacterNotify2:(CBCharacteristic *) ch {
  361. NSLog(@"返回控制器数3");
  362. __weak typeof(self) weakSelf = self;
  363. // 设置通知
  364. [baby notify:_currPeripheral characteristic:ch block:^(CBPeripheral *peripheral, CBCharacteristic *characteristics, NSError *error) {
  365. NSLog(@"返回控制器数据4");
  366. NSData *data = characteristics.value;
  367. [self OnRecvMessage:data];
  368. [allrecevedata appendData:data];
  369. //
  370. if (allrecevedata.length > 4) {
  371. // NSLog(@"setReadCharacterNotify2!!! ----%@",[self convertDataToHexStr:allrecevedata]);
  372. //NSString *str1 = [NSString stringWithFormat:@"%@",[allrecevedata subdataWithRange:NSMakeRange(0, allrecevedata.length-2)]];
  373. // NSLog(@"str1 -- %@",);
  374. NSData *data1 = [allrecevedata subdataWithRange:NSMakeRange(0, allrecevedata.length-2)];
  375. NSString *str2 = [self convertDataToHexStr:[allrecevedata subdataWithRange:NSMakeRange(allrecevedata.length-2,2)]];
  376. // ssss = [ssss stringByReplacingOccurrencesOfString:@" " withString:@""];
  377. NSString *str1 = [self convertDataToHexStr:allrecevedata];
  378. // NSLog(@"str1 - %@",str1);
  379. NSString *ssss = [str1 substringWithRange:NSMakeRange(0, str1.length-4)];
  380. //NSLog(@"ssss - %@",ssss);
  381. NSString *crcbuss = [ssss withCrc16Modbus];
  382. // NSLog(@"crcbuss - %@",crcbuss);
  383. NSString *res = [crcbuss substringWithRange:NSMakeRange(crcbuss.length-4, 4)];
  384. // NSLog(@"res -- %@ str2 ---%@",res,str2);
  385. if ([res isEqualToString:str2]) {
  386. NSLog(@"收到蓝牙完整数据========: %@", allrecevedata);
  387. // NSString *datastr = [NSString stringWithFormat:@"%@",allrecevedata];
  388. NSString *datastr = [NSString stringWithFormat:@"<%@>",[self convertDataToHexStr:allrecevedata]];
  389. self.CompleteHandle(datastr);
  390. // NSLog(@"datastr - %@ ",datastr);
  391. allrecevedata = nil;
  392. }
  393. }
  394. }];
  395. }
  396. - (NSString *)convertDataToHexStr:(NSData *)data
  397. {
  398. if (!data || [data length] == 0) {
  399. return @"";
  400. }
  401. NSMutableString *string = [[NSMutableString alloc] initWithCapacity:[data length]];
  402. [data enumerateByteRangesUsingBlock:^(const void *bytes, NSRange byteRange, BOOL *stop) {
  403. unsigned char *dataBytes = (unsigned char*)bytes;
  404. for (NSInteger i = 0; i < byteRange.length; i++) {
  405. NSString *hexStr = [NSString stringWithFormat:@"%x", (dataBytes[i]) & 0xff];
  406. if ([hexStr length] == 2) {
  407. [string appendString:hexStr];
  408. } else {
  409. [string appendFormat:@"0%@", hexStr];
  410. }
  411. }
  412. }];
  413. return string;
  414. }
  415. /**
  416. 设置读特征的通知 欢迎来到深圳市云之声科技有限公司
  417. @param ch 特征
  418. */
  419. -(void) setReadCharacterNotify:(CBCharacteristic *) ch {
  420. NSLog(@"返回控制器数据5");
  421. __weak typeof(self) weakSelf = self;
  422. // 设置通知
  423. [baby notify:_currPeripheral characteristic:ch block:^(CBPeripheral *peripheral, CBCharacteristic *characteristics, NSError *error) {
  424. NSData *data = characteristics.value;
  425. NSLog(@"返回控制器数据= %@ ",data);
  426. [self OnRecvMessage:data];
  427. [_loopallrecevedata appendData:data];
  428. NSLog(@"返回控制器数据= %@ ",_loopallrecevedata);
  429. if (_loopallrecevedata.length > 4) {
  430. NSString *str1 = [NSString stringWithFormat:@"%@",[_loopallrecevedata subdataWithRange:NSMakeRange(0, _loopallrecevedata.length-2)]];
  431. NSString *str2 = [NSString stringWithFormat:@"%@",[_loopallrecevedata subdataWithRange:NSMakeRange(
  432. _loopallrecevedata.length-2,2)]];
  433. str2 = [str2 substringWithRange:NSMakeRange(1, str2.length-2)];
  434. NSString *ssss = [NSString stringWithFormat:@"%@",[str1 substringWithRange:NSMakeRange(1, str1.length-2)]];
  435. ssss = [ssss stringByReplacingOccurrencesOfString:@" " withString:@""];
  436. NSString *crcbuss = [ssss withCrc16Modbus];
  437. NSString *res = [crcbuss substringWithRange:NSMakeRange(crcbuss.length-4, 4)];
  438. if ([res isEqualToString:str2]) {
  439. [[NSNotificationCenter defaultCenter] postNotificationName:kBabyBluetoothNotificationUartDataRecieve object:nil];
  440. isStartWrite = true;
  441. NSLog(@"收到蓝牙完整数据========: %@", allrecevedata);
  442. NSString *allrecevedataStr = [NSString stringWithFormat:@"%@",_loopallrecevedata];
  443. [recciveDataDictionary setObject:_loopallrecevedata forKey:ReceiveData];
  444. [recciveDataDictionary setObject:allrecevedataStr forKey:ReceiveData];
  445. if (weakSelf.testBlock) {
  446. weakSelf.testBlock(recciveDataDictionary);
  447. }
  448. if (weakSelf.testBlock2) {
  449. weakSelf.testBlock2(recciveDataDictionary);
  450. }
  451. /*
  452. let dataTagValue : String = deviceData?.value(forKey: DataTag) as! String
  453. if dataTagValue == "FF0300490010"
  454. */
  455. NSString *dataTag = [recciveDataDictionary valueForKey:DataTag];
  456. if ([dataTag isEqualToString:@"FF0300490010"]) {
  457. if (weakSelf.updateNameBlock) {
  458. weakSelf.updateNameBlock(recciveDataDictionary);
  459. }
  460. }
  461. //清除历史记录
  462. //FF06DF050001 FF7900000001
  463. if ([dataTag isEqualToString:@"FF06DF050001"] || [dataTag isEqualToString:@"FF7900000001"] ) {
  464. if (weakSelf.clearHistoryDataBlock) {
  465. weakSelf.clearHistoryDataBlock(recciveDataDictionary);
  466. }
  467. }
  468. // let arr = ["FF7800000001"]
  469. // let arr = ["FF06DF010001"] 恢复出厂设置
  470. if ([dataTag isEqualToString:@"FF7800000001"] || [dataTag isEqualToString:@"FF06DF020001"] ) {
  471. if (weakSelf.resetBlock) {
  472. weakSelf.resetBlock(recciveDataDictionary);
  473. }
  474. }
  475. }
  476. }
  477. }];
  478. }
  479. -(void)firmwareUpdateReadCharacterNotify:(CBCharacteristic *) ch {
  480. __weak typeof(self) weakSelf = self;
  481. // 设置通知
  482. [baby notify:_currPeripheral characteristic:ch block:^(CBPeripheral *peripheral, CBCharacteristic *characteristics, NSError *error) {
  483. NSData *data = characteristics.value;
  484. [self OnRecvMessage:data];
  485. NSString *dataStr = [NSString stringWithFormat:@"%@",data];
  486. NSLog(@"收到的数据为 --%@",dataStr);
  487. }];
  488. }
  489. - (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
  490. {
  491. NSLog(@"%s, line = %d", __FUNCTION__, __LINE__);
  492. // if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:@"FFF1"]]) {
  493. NSLog(@"获取蓝牙最新值%@",characteristic.value);
  494. // }else {
  495. // NSLog(@"失败");
  496. // }
  497. }
  498. - (void)actions {
  499. for (int i = 0; i < dataDictionary.count; i++) {
  500. if (dataDictionary.count > 0) {
  501. // 循环数组
  502. if (isStartWrite && self.isConnected) {
  503. NSData *data = [[[dataDictionary[i] objectForKey:DataTag] withCrc16Modbus] toNSData];
  504. NSLog(@"发送完整aaaaaa %@",data);
  505. // 1.创建串行队列
  506. dispatch_queue_t queue = dispatch_queue_create("UUUUU", DISPATCH_QUEUE_SERIAL);
  507. // 2.将任务加到队列当中
  508. dispatch_async(dispatch_get_main_queue(), ^{
  509. dispatch_async(queue, ^{
  510. _loopallrecevedata = [NSMutableData dataWithLength:0];
  511. // 写入操作
  512. [recciveDataDictionary removeAllObjects];
  513. NSLog(@"写入特征值 >>>>>>>>>>>>>>>.writeCharacteristic ---- %@",self.writeCharacteristic);
  514. if (self.writeCharacteristic != nil) {
  515. [self.currPeripheral writeValue:data forCharacteristic:self.writeCharacteristic type:CBCharacteristicWriteWithoutResponse];
  516. }
  517. [recciveDataDictionary setObject:[dataDictionary[i] valueForKey:DataTag] forKey:DataTag];
  518. NSLog(@"recciveDataDictionary = %@",recciveDataDictionary);
  519. [dataDictionary removeObjectAtIndex:i];
  520. });
  521. });
  522. isStartWrite = false;
  523. }
  524. }else {
  525. [timer invalidate];
  526. }
  527. }
  528. }
  529. -(void) writeData1:(NSMutableArray *)type{
  530. NSLog(@"写数据 ---%@",type);
  531. // isLoop = true;
  532. //在这里执行事件
  533. dataDictionary = type;
  534. timer = [NSTimer scheduledTimerWithTimeInterval:0.3 target:self selector:@selector(actions) userInfo:nil repeats:YES];
  535. }
  536. -(NSString *)getCurrentTime{
  537. NSDate *date = [NSDate date];
  538. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  539. [formatter setDateStyle:NSDateFormatterMediumStyle];
  540. [formatter setTimeStyle:NSDateFormatterShortStyle];
  541. [formatter setDateFormat:@"YYYYMMddhhmmss"];
  542. NSString *DateTime = [formatter stringFromDate:date];
  543. NSLog(@"%@============年-月-日 时:分:秒=====================",DateTime);
  544. return DateTime;
  545. }
  546. //写固件更新
  547. -(void)updateFirmwareData:(NSString *)data{
  548. if (self.isConnected) {
  549. isUpdateFirmware = true;
  550. NSData *cmd = [[data withCrc16Modbus] toNSData];
  551. [NSThread sleepForTimeInterval:0.05];
  552. if (self.currPeripheral != nil && self.writeCharacteristic != nil) {
  553. NSLog(@"writeData --发送的指令数据---- %@ ",data);
  554. [self.currPeripheral writeValue:cmd forCharacteristic:self.writeCharacteristic type:CBCharacteristicWriteWithoutResponse];
  555. }
  556. }
  557. }
  558. //循环写入
  559. -(void)loopWriteDataWite:(NSArray *)dataArr type:(NSString *)type completionHandler:(void (^)(NSDictionary *))completionHandler{
  560. if (self.isConnected) {
  561. __block BOOL isFinish = false;
  562. __block NSMutableDictionary *reaciveData = [NSMutableDictionary dictionary];
  563. NSString *queueName = [NSString stringWithFormat:@"serialQueue%@%@",type,[self getCurrentTime]];
  564. // 1.创建一个串行队列,保证for循环依次执行
  565. dispatch_queue_t serialQueue = dispatch_queue_create("serialQueue", DISPATCH_QUEUE_SERIAL);
  566. // 2.异步执行任务
  567. dispatch_async(serialQueue, ^{
  568. // 3.创建一个数目为1的信号量,用于“卡”for循环,等上次循环结束在执行下一次的for循环
  569. dispatch_semaphore_t sema = dispatch_semaphore_create(1);
  570. for (int i = 0 ; i < dataArr.count; i++) {
  571. isLoop = true;
  572. // 开始执行for循环,让信号量-1,这样下次操作须等信号量>=0才会继续,否则下次操作将永久停止
  573. dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
  574. printf("信号量等待中\n");
  575. NSLog(@"任务%d:%@",i,[NSThread currentThread]);
  576. NSString *dataStr = dataArr[i];
  577. [self writeData:dataStr completionHandler:^(NSString * result) {
  578. NSLog(@"结果 ---%@",dataStr);
  579. [NSThread sleepForTimeInterval:0.1];
  580. reaciveData[dataStr] = result;
  581. if (i == dataArr.count - 1) { //当执行到最后一个时 则跳出
  582. NSLog(@"完成了所有任务");
  583. dispatch_async(dispatch_get_main_queue(), ^{
  584. completionHandler(reaciveData);
  585. });
  586. }
  587. dispatch_semaphore_signal(sema);
  588. }];
  589. }
  590. });
  591. }
  592. }
  593. -(void)_loopWriteDataWite:(NSArray *)dataArr type:(NSString *)type completionHandler:(void (^)(NSDictionary *))completionHandler{
  594. if (self.isConnected) {
  595. for (int i = 0 ; i < dataArr.count; i++) {
  596. }
  597. }
  598. }
  599. -(void)writeData2222:(NSArray *)dataArr completionHandler:(void (^)(NSDictionary *))completionHandler{
  600. if ([self isConnected] == true) {
  601. __block BOOL isFinish = false;
  602. __block NSMutableDictionary *reaciveData = [NSMutableDictionary dictionary];
  603. // 1.创建一个串行队列,保证for循环依次执行
  604. dispatch_queue_t serialQueue = dispatch_queue_create("serialQueue", DISPATCH_QUEUE_SERIAL);
  605. // 2.异步执行任务
  606. dispatch_async(serialQueue, ^{
  607. // 3.创建一个数目为1的信号量,用于“卡”for循环,等上次循环结束在执行下一次的for循环
  608. dispatch_semaphore_t sema = dispatch_semaphore_create(1);
  609. for (int i = 0 ; i < dataArr.count; i++) {
  610. isLoop == false;
  611. // 开始执行for循环,让信号量-1,这样下次操作须等信号量>=0才会继续,否则下次操作将永久停止
  612. dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
  613. printf("信号量等待中\n");
  614. NSLog(@"任务%d:%@",i,[NSThread currentThread]);
  615. NSString *dataStr = dataArr[i];
  616. [self writeData:dataStr completionHandler:^(NSString * result) {
  617. NSLog(@"结果 ---%@",dataStr);
  618. [NSThread sleepForTimeInterval:0.1];
  619. reaciveData[dataStr] = result;
  620. allrecevedata = nil;
  621. if (i == dataArr.count - 1) { //当执行到最后一个时 则跳出
  622. NSLog(@"完成了所有任务");
  623. dispatch_async(dispatch_get_main_queue(), ^{
  624. completionHandler(reaciveData);
  625. });
  626. }
  627. dispatch_semaphore_signal(sema);
  628. }];
  629. }
  630. });
  631. }
  632. }
  633. - (void)loopWriteData:(NSString *)dataStr completionHandler:(void (^)(NSString *))completionHandler{
  634. [NSThread sleepForTimeInterval:0.05];
  635. // self.newRead = true;
  636. if (self.isConnected) {
  637. _loopallrecevedata = [NSMutableData dataWithLength:0];
  638. self.loopCompleteHandle = completionHandler;
  639. //
  640. NSData *data = [[dataStr withCrc16Modbus] toNSData];
  641. [NSThread sleepForTimeInterval:0.05];
  642. if (self.currPeripheral != nil && self.writeCharacteristic != nil) {
  643. NSLog(@"看看loopWriteData --发送的指令数据---- %@ ---- characteristic = %@",data,self.writeCharacteristic.UUID.UUIDString);
  644. [self.currPeripheral writeValue:data forCharacteristic:self.writeCharacteristic type:CBCharacteristicWriteWithoutResponse];
  645. }
  646. }
  647. }
  648. - (void)writeData:(NSString *)dataStr completionHandler:(void (^)(NSString *))completionHandler{
  649. // self.newRead = true;
  650. if (self.isConnected) {
  651. allrecevedata = [NSMutableData dataWithLength:0];
  652. self.CompleteHandle = completionHandler;
  653. //
  654. NSData *data = [[dataStr withCrc16Modbus] toNSData];
  655. if (self.currPeripheral != nil && self.writeCharacteristic != nil) {
  656. NSLog(@"看看1writeData --发送的指令数据---- %@ ---- characteristic = %@",data,self.writeCharacteristic.UUID.UUIDString);
  657. [self.currPeripheral writeValue:data forCharacteristic:self.writeCharacteristic type:CBCharacteristicWriteWithoutResponse];
  658. }
  659. }
  660. }
  661. - (void)writePasswordData:(NSString *)data{
  662. if (self.isConnected) {
  663. NSLog(@"特征值FF81");
  664. //转为ASCII
  665. NSData *dataAT = [data dataUsingEncoding:NSASCIIStringEncoding];
  666. [NSThread sleepForTimeInterval:0.05];
  667. if (self.currPeripheral != nil && self.passwordCharacteristic != nil) {
  668. NSLog(@"发送的指令数据---- %@ ---- characteristic = %@",dataAT,self.passwordCharacteristic.UUID.UUIDString);
  669. [self.currPeripheral writeValue:dataAT forCharacteristic:self.passwordCharacteristic type:CBCharacteristicWriteWithoutResponse];
  670. }
  671. [NSThread sleepForTimeInterval:0.05];
  672. }
  673. }
  674. - (void)writeRestoreSystemData:(NSString *)data{
  675. if (self.isConnected) {
  676. NSLog(@"特征值 FF54");
  677. //转为ASCII
  678. NSData *dataAT = [data toNSData];
  679. [NSThread sleepForTimeInterval:0.05];
  680. if (self.currPeripheral != nil && self.restoreCharacteristic != nil) {
  681. [self.currPeripheral writeValue:dataAT forCharacteristic:self.restoreCharacteristic type:CBCharacteristicWriteWithoutResponse];
  682. }
  683. [NSThread sleepForTimeInterval:0.05];
  684. }
  685. }
  686. -(void) writeData:(NSString *)type withData:(NSData *) data {
  687. if (self.isConnected) {
  688. gUartMessageType = type;
  689. [NSThread sleepForTimeInterval:0.05];
  690. if (self.currPeripheral != nil && self.writeCharacteristic != nil) {
  691. [self.currPeripheral writeValue:data forCharacteristic:self.writeCharacteristic type:CBCharacteristicWriteWithoutResponse];
  692. }
  693. [NSThread sleepForTimeInterval:0.05];
  694. }else {
  695. //[MBProgressHUD showInfoMessage:NSLocalizedString(@"can_not_connect_device_info", nil)];
  696. }
  697. }
  698. -(void)babyDelegate{
  699. __weak typeof(self) weakSelf = self;
  700. // 连接回调
  701. [baby setBlockOnCentralManagerDidUpdateState:^(CBCentralManager *central) {
  702. if (weakSelf.centralBlock) {
  703. weakSelf.centralBlock(central);
  704. }
  705. NSLog(@"读取状态回调 -- %ld",central.state);
  706. if (central.state == CBManagerStatePoweredOn) {
  707. // [SVProgressHUD showInfoWithStatus:@"设备打开成功,开始扫描设备"];
  708. }
  709. }];
  710. //设置扫描到设备的委托
  711. [baby setBlockOnConnected:^(CBCentralManager *central, CBPeripheral *peripheral) {
  712. weakSelf.currPeripheral = nil;
  713. NSLog(@"UUID -- %@",peripheral.identifier);
  714. NSLog(@"已经连接蓝牙 %@", [peripheral name]);
  715. weakSelf.currPeripheral = peripheral;
  716. connected = true;
  717. // NSLog(@"连接状态--- %d isconcect %d",connected,[self isConnected]);
  718. weakSelf.connectCompletHandle(peripheral, true);
  719. [[NSNotificationCenter defaultCenter] postNotificationName:kBabyBluetoothNotificationServiceStatus object:[[NSNumber alloc] initWithInteger:BabyBluetooth_ConnectedStatus]];
  720. }];
  721. //设置连接失败代理
  722. [baby setBlockOnFailToConnect:^(CBCentralManager *central, CBPeripheral *peripheral, NSError *error) {
  723. NSLog(@"连接失败%@",peripheral.name);
  724. connected = false;
  725. weakSelf.connectCompletHandle(peripheral, false);
  726. }];
  727. // 断开蓝牙的回调
  728. __block BabyBluetooth *weakBaby = baby;
  729. [baby setBlockOnDisconnect:^(CBCentralManager *central, CBPeripheral *peripheral, NSError *error) {
  730. isReadChFound = false;
  731. isWriteCHFound = false;
  732. if (mCMDConnect == true) {
  733. // 添加断开自动重连的外设
  734. } else {
  735. // 删除断开自动重连的外设
  736. }
  737. connected = false;
  738. NSLog(@"已经断开蓝牙 %@", [peripheral name]);
  739. // 设置通知的蓝牙服务状态为断开连接状态
  740. [[NSNotificationCenter defaultCenter] postNotificationName:kBabyBluetoothNotificationServiceStatus object:[[NSNumber alloc] initWithInteger:BabyBluetooth_DisConnectedStatus]];
  741. NSDictionary *periDict = @{@"peripheral":[peripheral name] };
  742. // [[NSNotificationCenter defaultCenter]postNotificationName:kBabyBluetoothNotificationDeviceWasDisconect object:nil];
  743. [[NSNotificationCenter defaultCenter]postNotificationName:kBabyBluetoothNotificationDeviceWasDisconect object:nil userInfo:periDict];
  744. }];
  745. //设置 Characteristics 过滤值
  746. [baby setBlockOnDiscoverToPeripherals:^(CBCentralManager *central, CBPeripheral *peripheral, NSDictionary *advertisementData, NSNumber *RSSI) {
  747. NSLog(@"搜索到了设备:%@ --- uuid - %@ ",peripheral.name,peripheral.identifier.UUIDString);
  748. // [[weakSelf peripherals] addObject:peripheral];
  749. // 如果搜索到的外设不在数组中
  750. if (![weakSelf.peripherals containsObject:peripheral]) {
  751. // 添加到外设数组中
  752. [weakSelf.peripherals addObject:peripheral];
  753. // 设置通知的搜索结果状态为nil
  754. [[NSNotificationCenter defaultCenter] postNotificationName:kBabyBluetoothNotificationScanResult object:nil];
  755. }
  756. NSString *uuidString = [[NSUserDefaults standardUserDefaults] objectForKey:@"periheralUUID"];
  757. if (uuidString != nil && isFirstStart) {
  758. if ([[[NSUUID alloc] initWithUUIDString:uuidString] isEqual:peripheral.identifier]) {
  759. // [baby retrievePeripheralWithUUIDString:uuidString];
  760. weakBaby.having(peripheral).connectToPeripherals().discoverServices().discoverCharacteristics().begin();
  761. _currPeripheral = peripheral;
  762. mCMDConnect = true;
  763. isFirstStart = false;
  764. [weakBaby cancelScan];
  765. }
  766. }
  767. }];
  768. //设置发现设备的Services的委托
  769. [baby setBlockOnDiscoverServices:^(CBPeripheral *peripheral, NSError *error) {
  770. for (CBService *service in peripheral.services) {
  771. NSLog(@"搜索到服务:%@",service.UUID.UUIDString);
  772. if (weakSelf.DiscoverServicesBlock != nil) {
  773. weakSelf.DiscoverServicesBlock(service.UUID.UUIDString);
  774. }
  775. }
  776. //找到cell并修改detaisText
  777. }];
  778. //设置发现设service的Characteristics的委托
  779. [baby setBlockOnDiscoverCharacteristics:^(CBPeripheral *peripheral, CBService *service, NSError *error) {
  780. NSLog(@"===service name:%@",service.UUID);
  781. for (CBCharacteristic *c in service.characteristics) {
  782. NSLog(@"charateristic name is :%@",c.UUID);
  783. if ([c.UUID isEqual:[CBUUID UUIDWithString:writeCharacteristicUUIDString]]) {
  784. NSLog(@"writeCharacteristicUUIDString");
  785. isWriteCHFound = true;
  786. weakSelf.writeCharacteristic = c;
  787. if (weakSelf.StartWriteCallback != nil) {
  788. NSLog(@"开始读写");
  789. weakSelf.StartWriteCallback();
  790. }
  791. if (c == nil) {
  792. NSLog(@"FFF1不存在 ");
  793. }else{
  794. NSLog(@"FFF1 --存在 --%@ ", weakSelf.writeCharacteristic.UUID);
  795. }
  796. }
  797. if ([c.UUID isEqual:[CBUUID UUIDWithString:readCharacterosticUUIDString]]) {
  798. NSLog(@"返回控制器数据0");
  799. isReadChFound = true;
  800. if (isLoop == false || weakSelf.reConnectedToRead == true) {
  801. [weakSelf setReadCharacterNotify2:c];
  802. NSLog(@"返回控制器数据1");
  803. } else if (isLoop == true){
  804. NSLog(@"返回控制器数据2");
  805. [weakSelf setReadCharacterNotify:c];
  806. }
  807. //更新固件返回
  808. if (isUpdateFirmware == true) {
  809. [weakSelf firmwareUpdateReadCharacterNotify:c];
  810. }
  811. // [weakSelf setReadCharacterNotify:c];
  812. connected = true;
  813. }
  814. //发送
  815. //通知
  816. if ([c.UUID isEqual:[CBUUID UUIDWithString:writePasswordCharacteristicUUIDString]]) {
  817. weakSelf.passwordCharacteristic = c ;
  818. }
  819. //通知
  820. if ([c.UUID isEqual:[CBUUID UUIDWithString:notityPasswordCharacteristicUUIDString]]) {
  821. [weakSelf setPasswordCharacterNotify:c];
  822. }
  823. if ([c.UUID isEqual:[CBUUID UUIDWithString:restoreSystermCharacteristicUUIDString]]) {
  824. weakSelf.restoreCharacteristic = c;
  825. }
  826. }
  827. // 可读可写
  828. if (isReadChFound && isWriteCHFound) {
  829. [[NSNotificationCenter defaultCenter] postNotificationName:kBabyBluetoothNotificationServiceStatus object:[[NSNumber alloc] initWithInteger:BabyBluetooth_ReadyToSendCMDStatus]];
  830. }
  831. }];
  832. //设置读取characteristics的委托
  833. [baby setBlockOnReadValueForCharacteristic:^(CBPeripheral *peripheral, CBCharacteristic *characteristics, NSError *error) {
  834. NSLog(@"characteristic name:%@ value is:%@",characteristics.UUID,characteristics.value);
  835. }];
  836. //设置发现characteristics的descriptors的委托
  837. [baby setBlockOnDiscoverDescriptorsForCharacteristic:^(CBPeripheral *peripheral, CBCharacteristic *characteristic, NSError *error) {
  838. NSLog(@"===characteristic name:%@",characteristic.service.UUID);
  839. for (CBDescriptor *d in characteristic.descriptors) {
  840. NSLog(@"CBDescriptor name is :%@",d.UUID);
  841. }
  842. }];
  843. //设置读取Descriptor的委托
  844. [baby setBlockOnReadValueForDescriptors:^(CBPeripheral *peripheral, CBDescriptor *descriptor, NSError *error) {
  845. NSLog(@"Descriptor name:%@ value is:%@",descriptor.characteristic.UUID, descriptor.value);
  846. mCMDConnect = true;
  847. }];
  848. //设置查找设备的过滤器
  849. [baby setFilterOnDiscoverPeripherals:^BOOL(NSString *peripheralName, NSDictionary *advertisementData, NSNumber *RSSI) {
  850. //最常用的场景是查找某一个前缀开头的设备 非空字符串
  851. if (![peripheralName hasPrefix:@""] && peripheralName != nil) {
  852. NSLog(@"搜索到的设备 %@",peripheralName);
  853. NSLog(@"广播数据 -- %@",advertisementData);
  854. return YES;
  855. }
  856. //设置查找规则是名称大于0 , the search rule is peripheral.name length > 0
  857. if (peripheralName.length >0) {
  858. return YES;
  859. }
  860. return NO;
  861. }];
  862. [baby setBlockOnCancelAllPeripheralsConnectionBlock:^(CBCentralManager *centralManager) {
  863. NSLog(@"setBlockOnCancelAllPeripheralsConnectionBlock");
  864. connected = NO;
  865. }];
  866. [baby setBlockOnCancelScanBlock:^(CBCentralManager *centralManager) {
  867. NSLog(@"setBlockOnCancelScanBlock");
  868. }];
  869. //示例:
  870. //扫描选项->CBCentralManagerScanOptionAllowDuplicatesKey:忽略同一个Peripheral端的多个发现事件被聚合成一个发现事件
  871. NSDictionary *scanForPeripheralsWithOptions = @{CBCentralManagerScanOptionAllowDuplicatesKey:@YES,CBCentralManagerOptionShowPowerAlertKey:@YES};
  872. NSArray *uuidServices = @[[CBUUID UUIDWithString:readServerUUIDString],
  873. [CBUUID UUIDWithString:writeServerUUIDString],
  874. [CBUUID UUIDWithString:passwordServerUUIDString],
  875. [CBUUID UUIDWithString:setServerUUIDString],];
  876. //连接设备->
  877. [baby setBabyOptionsWithScanForPeripheralsWithOptions:scanForPeripheralsWithOptions
  878. connectPeripheralWithOptions:nil
  879. scanForPeripheralsWithServices:nil
  880. discoverWithServices:nil
  881. discoverWithCharacteristics:nil];
  882. }
  883. @end
  884. /*
  885. 切换设备
  886. 断开当前设备 ----> 搜索设备----> 连接
  887. */