#import <UIKit/UIKit.h> @interface ViewController : UIViewController @end #import "ViewController.h" #import <CoreBluetooth/CoreBluetooth.h> @interface ViewController ()<CBCentralManagerDelegate,CBPeripheralDelegate> @property BOOL cbReady; @property (nonatomic,assign) float batteryValue; @property (nonatomic,strong) CBCentralManager *manager;// @property (nonatomic,strong) CBPeripheral *peripheral;// @property (nonatomic,strong) CBCharacteristic *writeCharacteristic; @property (nonatomic,strong) NSMutableArray *nDevices; @property (nonatomic,strong) NSMutableArray *nServices; @property (nonatomic,strong) NSMutableArray *nCharacteristics; @property (nonatomic,strong)UIActivityIndicatorView *activity;//轉菊花 @property (nonatomic,strong)UILabel *peripheralName; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; self.manager = [[CBCentralManager alloc]initWithDelegate:self queue:nil]; _cbReady = false; [self.view addSubview:self.peripheralName]; _nDevices = [[NSMutableArray alloc]init]; _nServices = [[NSMutableArray alloc]init]; _nCharacteristics = [[NSMutableArray alloc]init]; _activity = [[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(100, 50, 50, 50)]; _activity.backgroundColor = [UIColor orangeColor]; [self.view addSubview:_activity]; } #pragma mark UI -(UILabel*)peripheralName{ if (!_peripheralName){ _peripheralName = [[UILabel alloc]init]; _peripheralName.frame = CGRectMake(100, 150, 200, 100); _peripheralName.backgroundColor = [UIColor orangeColor]; _peripheralName.text = @"顯示鏈接設備名"; } return _peripheralName; } #pragma mark print log -(void)updatelog:(NSString *)str { NSLog(@"%@",str); } #pragma mark bluetooth delegate -(void)centralManagerDidUpdateState:(CBCentralManager *)central{ switch (central.state) { case CBCentralManagerStatePoweredOn: [self updatelog:@"藍牙已打開,請掃描外設"]; [_activity startAnimating]; [_manager scanForPeripheralsWithServices:nil options:nil];// break; case CBCentralManagerStatePoweredOff: [self updatelog:@"藍牙沒有打開,請先打開藍牙"]; break; default: break; } } -(void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *,id> *)advertisementData RSSI:(NSNumber *)RSSI{ [self updatelog:[NSString stringWithFormat:@"已發現設備 %@ peripheral:\n 設備名稱%@ rssi:%@ ",peripheral,peripheral.name,RSSI]]; _peripheral = peripheral; //鏈接外設 [_manager connectPeripheral:_peripheral options:nil]; _peripheralName.text = _peripheral.name; BOOL replace = NO; for (int i = 0; i<_nDevices.count; i++) { CBPeripheral *p = [_nDevices objectAtIndex:i]; if ([p isEqual:peripheral]){ [_nDevices replaceObjectAtIndex:i withObject:peripheral]; replace = YES; } } if (!replace){ [_nDevices addObject:peripheral]; _peripheralName.text = _peripheral.name; } if ([_peripheral.name isEqualToString:@"B-ME31-354221"]){ [self.manager stopScan]; [_activity stopAnimating]; } } //success 鏈接外設成功,開始發現服務 -(void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral{ [self.peripheral setDelegate:self]; [self.peripheral discoverServices:nil]; } //fail -(void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error{ NSLog(@"%@",error); } //deprecated //-(void)peripheralDidUpdateRSSI:(CBPeripheral *)peripheral error:(NSError *)error{ // //} // -(void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{ [self updatelog:@"發現服務"]; int i = 0; for (CBService * s in peripheral.services){ [self.nServices addObject:s]; } //49535343-FE7D-4AE5-8FA9-9FAFD205E455 for (CBService *s in peripheral.services){ i++; [peripheral discoverCharacteristics:nil forService:s]; if ([s.UUID isEqual:[CBUUID UUIDWithString:@"49535343-FE7D-4AE5-8FA9-9FAFD205E455"]]){ BOOL replace = NO; for (int i=0;i<_nDevices.count;i++){ CBPeripheral *p = [_nDevices objectAtIndex:i]; if ([p isEqual:peripheral]){ [_nDevices replaceObjectAtIndex:i withObject:peripheral]; replace = YES; } } if (!replace){ [_nDevices addObject:peripheral]; _peripheralName.text = peripheral.name; } } } } //已搜索到的Characteristics -(void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error{ [self updatelog:@"發現特徵服務"]; for (CBCharacteristic *c in service.characteristics){ [self updatelog:[NSString stringWithFormat:@"UUID:%@ UUIDString:%@,data%@",c.UUID,c.UUID.UUIDString,c.UUID.data]]; if ([c.UUID isEqual:[CBUUID UUIDWithString:@"2A23"]]) { _writeCharacteristic = c; } if ([c.UUID isEqual:[CBUUID UUIDWithString:@"2A29"]]) { [_peripheral readValueForCharacteristic:c]; [_peripheral setNotifyValue:YES forCharacteristic:c]; } if ([c.UUID isEqual:[CBUUID UUIDWithString:@"2A24"]]) { [_peripheral readValueForCharacteristic:c]; } if ([c.UUID isEqual:[CBUUID UUIDWithString:@"2A25"]]) { [_peripheral readValueForCharacteristic:c]; [_peripheral setNotifyValue:YES forCharacteristic:c]; } if ([c.UUID isEqual:[CBUUID UUIDWithString:@"2A2A"]]) { [_peripheral readRSSI]; } [_nCharacteristics addObject:c]; //log // 2016-06-17 14:24:30.722 BlueToothDemo[27905:17730659] UUID:System ID UUIDString:2A23,data<2a23> // 2016-06-17 14:24:30.723 BlueToothDemo[27905:17730659] UUID:Manufacturer Name String UUIDString:2A29,data<2a29> // 2016-06-17 14:24:30.723 BlueToothDemo[27905:17730659] UUID:Model Number String UUIDString:2A24,data<2a24> // 2016-06-17 14:24:30.723 BlueToothDemo[27905:17730659] UUID:Serial Number String UUIDString:2A25,data<2a25> // 2016-06-17 14:24:30.723 BlueToothDemo[27905:17730659] UUID:Firmware Revision String UUIDString:2A26,data<2a26> // 2016-06-17 14:24:30.723 BlueToothDemo[27905:17730659] UUID:Hardware Revision String UUIDString:2A27,data<2a27> // 2016-06-17 14:24:30.724 BlueToothDemo[27905:17730659] UUID:Software Revision String UUIDString:2A28,data<2a28> // 2016-06-17 14:24:30.724 BlueToothDemo[27905:17730659] UUID:IEEE Regulatory Certification UUIDString:2A2A,data<2a2a> // 2016-06-17 14:24:30.871 BlueToothDemo[27905:17730659] 發現特徵服務 // 2016-06-17 14:24:30.871 BlueToothDemo[27905:17730659] UUID:49535343-6DAA-4D02-ABF6-19569ACA69FE UUIDString:49535343-6DAA-4D02-ABF6-19569ACA69FE,data<49535343 6daa4d02 abf61956 9aca69fe> // 2016-06-17 14:24:30.871 BlueToothDemo[27905:17730659] UUID:49535343-ACA3-481C-91EC-D85E28A60318 UUIDString:49535343-ACA3-481C-91EC-D85E28A60318,data<49535343 aca3481c 91ecd85e 28a60318> // 2016-06-17 14:24:30.872 BlueToothDemo[27905:17730659] UUID:49535343-8841-43F4-A8D4-ECBE34729BB3 UUIDString:49535343-8841-43F4-A8D4-ECBE34729BB3,data<49535343 884143f4 a8d4ecbe 34729bb3> // 2016-06-17 14:24:30.872 BlueToothDemo[27905:17730659] UUID:49535343-1E4D-4BD9-BA61-23C647249616 UUIDString:49535343-1E4D-4BD9-BA61-23C647249616,data<49535343 1e4d4bd9 ba6123c6 47249616> } } //斷開與設備鏈接 -(void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error{ [self updatelog:[NSString stringWithFormat:@"已斷開與設備%@鏈接",peripheral.name]]; UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"" message:[NSString stringWithFormat:@"已斷開與設備%@鏈接",peripheral.name] preferredStyle:UIAlertControllerStyleAlert]; UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"從新鏈接" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) { [_manager connectPeripheral:_peripheral options:nil]; }]; UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler:nil]; [alertController addAction:cancelAction]; [alertController addAction:okAction]; [self presentViewController:alertController animated:YES completion:nil]; } //獲取外設發來的數據 -(void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{ [self updatelog:[NSString stringWithFormat:@"%@",characteristic]]; NSData *data = characteristic.value; Byte *resultByte = (Byte *)[data bytes]; NSLog(@"%s %ld",resultByte,[data length]);//Ampak 5 , 6210B 5 , £F 6 } @end
參考文章:http://doc.okbase.net/kw-ios/archive/94529.htmlhtml
http://blog.csdn.net/dolacmeng/article/details/46457487ios
http://www.jianshu.com/p/84b5b834b942atom
http://www.jianshu.com/p/0bc96af31f10.net