藍牙連接以及協(xié)議數(shù)據(jù)解析

1.聲明屬性以及引入相關(guān)庫

NSMutableArray *pers;//這個必須有,用于記錄搜索到的設(shè)備,沒有導(dǎo)致連接不上

manager = [[CBCentralManager alloc]initWithDelegate:self queue:dispatch_get_main_queue()];


2.代理方法

-(void)centralManagerDidUpdateState:(CBCentralManager *)central{

switch (central.state) {

case CBCentralManagerStateUnknown:

NSLog(@">>>CBCentralManagerStateUnknown");

break;

case CBCentralManagerStateResetting:

NSLog(@">>>CBCentralManagerStateResetting");

break;

case CBCentralManagerStateUnsupported:

NSLog(@">>>CBCentralManagerStateUnsupported");

break;

case CBCentralManagerStateUnauthorized:

NSLog(@">>>CBCentralManagerStateUnauthorized");

break;

case CBCentralManagerStatePoweredOff:

NSLog(@">>>CBCentralManagerStatePoweredOff");

break;

case CBCentralManagerStatePoweredOn:{

NSLog(@">>>CBCentralManagerStatePoweredOn");

//開始掃描周圍的外設(shè)

/*

第一個參數(shù)nil就是掃描周圍所有的外設(shè),掃描到外設(shè)后會進入

- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI;

*/

//? ? ? ? ? ? NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber? numberWithBool:YES], CBCentralManagerScanOptionAllowDuplicatesKey, nil];

[manager scanForPeripheralsWithServices:nil options:nil];

hudView.hidden=NO;

hudView.contentLab.text=@"開始掃描設(shè)備";

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

hudView.hidden=YES;

});

[manager scanForPeripheralsWithServices:nil options:nil];

break;

}

default:

break;

}

}

//掃描到設(shè)備會進入方法

-(void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI{

NSLog(@"當掃描到設(shè)備:%@",peripheral.name);

//? ? [peripherals addObject:peripheral];

//? ? [tableview reloadData];

//接下來可以連接設(shè)備

// 這個是我的設(shè)備名,根據(jù)實際情況,修改

if ([peripheral.name hasPrefix:@"ABG"]){

/*

一個主設(shè)備最多能連7個外設(shè),每個外設(shè)最多只能給一個主設(shè)備連接,連接成功,失敗,斷開會進入各自的委托

- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral;//連接外設(shè)成功的委托

- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error;//外設(shè)連接失敗的委托

- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error;//斷開外設(shè)的委托

*/

//找到的設(shè)備必須持有它,否則CBCentralManager中也不會保存peripheral,那么CBPeripheralDelegate中的方法也不會被調(diào)用!!

manager.delegate=self;

[pers addObject:peripheral];

self.per=peripheral;

//連接設(shè)備

[manager connectPeripheral:peripheral options:nil];

hudView.hidden=NO;

hudView.contentLab.text=[NSString stringWithFormat:@"掃描到設(shè)備%@,并開始連接",peripheral.name];

}

}

//連接到Peripherals-成功

- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral

{

NSLog(@">>>連接到名稱為(%@)的設(shè)備-成功",peripheral.name);

//設(shè)置的peripheral委托CBPeripheralDelegate

//@interface ViewController : UIViewController

[peripheral setDelegate:self];

//掃描外設(shè)Services,成功后會進入方法:-(void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{

[peripheral discoverServices:nil];

//? ? self.nameLab.text=peripheral.name;

//? ? self.contactStateLab.text=@"鏈接中";

hudView.hidden=NO;

hudView.contentLab.text=[NSString stringWithFormat:@"鏈接設(shè)備%@成功,",peripheral.name];

}

//連接到Peripherals-失敗

-(void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error

{

NSLog(@">>>連接到名稱為(%@)的設(shè)備-失敗,原因:%@",[peripheral name],[error localizedDescription]);

//自定義的mbprogress

hudView.hidden=NO;

hudView.contentLab.text=[NSString stringWithFormat:@"鏈接設(shè)備%@失敗,",peripheral.name];

}

//Peripherals斷開連接

- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error{

NSLog(@">>>外設(shè)連接斷開連接 %@: %@\n", [peripheral name], [error localizedDescription]);

//? ? self.contactStateLab.text=@"鏈接斷開";

//這句話確保了能保持連接,斷了重新連接

[manager connectPeripheral:peripheral options:nil];

hudView.contentLab.text=[NSString stringWithFormat:@"設(shè)備%@鏈接斷開",peripheral.name];

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

hudView.hidden=YES;

});

}

//掃描到Services

-(void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{

//? NSLog(@">>>掃描到服務(wù):%@",peripheral.services);

if (error)

{

NSLog(@">>>Discovered services for %@ with error: %@", peripheral.name, [error localizedDescription]);

return;

}

for (CBService *service in peripheral.services) {

NSLog(@"%@",service.UUID);

//掃描每個service的Characteristics,掃描到后會進入方法: -(void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error

/這個1808是我的設(shè)備的入口,需根據(jù)實際改變

if ([service.UUID.UUIDString isEqualToString:@"1808"]) {

[peripheral discoverCharacteristics:nil forService:service];

}

//? ? ? ? if ([service.UUID.UUIDString isEqualToString:@"180A"]) {

//? ? ? ? ? ? [peripheral discoverCharacteristics:nil forService:service];

//? ? ? ? }

//? ? ? ? if ([service.UUID.UUIDString isEqualToString:@"180F"]) {

//? ? ? ? ? ? [peripheral discoverCharacteristics:nil forService:service];

//? ? ? ? }

}

}

//掃描到Characteristics

-(void) peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error{

NSString *name=[NSString stringWithFormat:@"發(fā)現(xiàn)特征的服務(wù):%@ (%@)",service.UUID.data ,service.UUID];

NSLog(@"%@",name);

for (CBCharacteristic *c in service.characteristics) {

//? ? ? ? [self updateLog:[NSString stringWithFormat:@"特征 UUID: %@ (%@)",c.UUID.data,c.UUID]];

NSLog(@"%@",c.UUID);

//? ? ? ? if ([c.UUID isEqual:[CBUUID UUIDWithString:@"FF01"]]) {

////? ? ? ? ? ? _writeCharacteristic = c;

//? ? ? ? }

//

if ([c.UUID isEqual:[CBUUID UUIDWithString:@"FFF4"]]) {

chara=c;

[peripheral readValueForCharacteristic:c];

[peripheral setNotifyValue:YES forCharacteristic:c];

}

//? ? ? ? if ([c.UUID isEqual:[CBUUID UUIDWithString:@"FF04"]]) {

//? ? ? ? ? ? [peripheral readValueForCharacteristic:c];

//? ? ? ? }

//

//? ? ? ? if ([c.UUID isEqual:[CBUUID UUIDWithString:@"FF05"]]) {

//? ? ? ? ? ? [peripheral readValueForCharacteristic:c];

//? ? ? ? ? ? [peripheral setNotifyValue:YES forCharacteristic:c];

//? ? ? ? }

//

//? ? ? ? if ([c.UUID isEqual:[CBUUID UUIDWithString:@"FFA1"]]) {

//? ? ? ? ? ? [peripheral readRSSI];

//? ? ? ? }

//? ? ? ? [_nCharacteristics addObject:c];

}

}

-(void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{

//打印出characteristic的UUID和值

//!注意,value的類型是NSData,具體開發(fā)時,會根據(jù)外設(shè)協(xié)議制定的方式去解析數(shù)據(jù)

//該藍牙協(xié)議是返回數(shù)值是ascii碼

//? ? NSLog(@"characteristic uuid:%@? value:%@",characteristic.UUID,characteristic.value);

//? ? NSData * data = characteristic.value;

//? ? //將接收到的十六進制數(shù)據(jù) 轉(zhuǎn)成 十六進制字符串

//? ? Byte *byte? ? = (Byte *)[data bytes];

//? ? // 取出其中用用的兩位

//? ? Byte b[]? ? ? = {byte[1],byte[2]};

//? ? // 在轉(zhuǎn)化成NSData

//? ? NSData *adata = [[NSData alloc] initWithBytes:b length:sizeof(b)];

//? ? NSLog(@"adata = %@", adata);

//? ? // 轉(zhuǎn)化成字符串

//? ? NSString *str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];

//? ? NSLog(@"%@",str);

NSData * data = characteristic.value;

Byte * resultByte = (Byte *)[data bytes];

//

for(int i=0;i<[data length];i++){

printf("testByteFF02[%d] = %d\n",i,resultByte[i]);

//? ? ? ? NSString *string = [NSString stringWithFormat:@"%c",resultByte[i]];

//? ? ? ? printf("testByteFF02[%d] = %@\n",i,string);

if (resultByte[3]==0x00&&resultByte[4]==0x00&&resultByte[5]==0x00&&resultByte[6]==0x01) {

NSLog(@"停止測試");

hudView.hidden=NO;

hudView.contentLab.text=@"停止測量";

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

hudView.hidden=YES;

});

}

if (resultByte[7]==0xcf) {

NSLog(@"停止測試");

hudView.hidden=NO;

hudView.contentLab.text=@"停止測量";

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

hudView.hidden=YES;

});

}

int asc=resultByte[i];

if (asc==0xfe) {

int num;

if (resultByte[2]==0) {

num=resultByte[1];

}else{

num=resultByte[2];

}

NSString *aString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

NSLog(@"測量中,當前值:%d",num);

if(num!=254){

hudView.hidden=NO;

hudView.contentLab.text=[NSString stringWithFormat:@"當前測量值%d",num];

}

//? ? ? ? ? ? self.textview.text=[NSString stringWithFormat:@"測量中,當前值:%d",num];

}

if (asc==0xfd) {

//? ? ? ? ? ? Byte? byte1=resultByte[2];

//? ? ? ? ? ? int num1=[self hBytesToInt:];

[manager cancelPeripheralConnection:peripheral];

UInt16 asc1=resultByte[3];

UInt16 asc2=resultByte[4];

NSString *str= [NSString stringWithFormat:@"%c%c",asc2,asc1];

NSString *num= [NSString stringWithFormat:@"%ld",strtoul([str UTF8String],0,16)];

//? ? ? ? ? ? NSLog(@"測量結(jié)束,收縮壓%@",str);

NSLog(@"測量結(jié)束,收縮壓%@",num);

UInt16 asc3=resultByte[5];

UInt16 asc4=resultByte[6];

NSString *str2= [NSString stringWithFormat:@"%c%c",asc4,asc3];

NSString *num2= [NSString stringWithFormat:@"%ld",strtoul([str2 UTF8String],0,16)];

//? ? ? ? ? ? NSLog(@"測量結(jié)束,收縮壓%@",str);

NSLog(@"測量結(jié)束,舒張壓%@",num2);

UInt16 asc5=resultByte[7];

UInt16 asc6=resultByte[8];

NSString *str3= [NSString stringWithFormat:@"%c%c",asc6,asc5];

NSString *num3= [NSString stringWithFormat:@"%ld",strtoul([str3 UTF8String],0,16)];

//? ? ? ? ? ? NSLog(@"測量結(jié)束,收縮壓%@",str);

if ([num isEqualToString:@"0"]||[num2 isEqualToString:@"0"]||[num3 isEqualToString:@"0"]) {

hudView.hidden=NO;

hudView.contentLab.text=@"測量異常";

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

hudView.hidden=YES;

});

return;

}

if ([num isEqualToString:hasGaoya]&&[num2 isEqualToString:hasDiya]&&[num3 isEqualToString:hasXinglu]) {

return;

}else{

hasGaoya=num;

hasDiya=num2;

hasXinglu=num3;

hudView.hidden=NO;

hudView.contentLab.text=[NSString stringWithFormat:@"測量結(jié)束,高壓:%@;低壓:%@,心率:%@",num,num2,num3];

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

hudView.hidden=YES;

});

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];

HomeBloodSCell *bloodScell=[mytab cellForRowAtIndexPath:indexPath];

bloodScell.gaoyaLab.text=num;

bloodScell.diyaLab.text=num2;

bloodScell.xingluLab.text=num3;

NSLog(@"測量結(jié)束,心率%@",num3);

SelfDataModel *selfdata=[SelfDataModel returnModelBySelectFMDB];

NSDate *date=[NSDate date];

NSDateFormatter *form=[[NSDateFormatter alloc]init];

[form setDateFormat:@"YYYY-MM-dd HH:mm:ss"];

NSString *datestr=[form stringFromDate:date ];

NSString *url=[[HJInterfaceManager sharedInstance]uploadXueya];

NSMutableDictionary *mdic=[[NSMutableDictionary alloc]init];

mdic[@"userId"]=selfdata.idNum;

mdic[@"dbp"]=num2;

mdic[@"sbp"]=num;

mdic[@"pulse"]=num3;

mdic[@"measureTime"]=datestr;

[HJHttpManager PostRequestWithUrl:url param:mdic finish:^(NSData *data) {

NSDictionary *dic=(NSDictionary *)data;

if([dic[@"status"] isEqualToString:@"S"]){

[MBProgressHUD showSuccess:@"數(shù)據(jù)上傳成功"];

HomeBloodSCell *cell=[mytab cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];

NSString *str=dic[@"value"][@"measurements"];

cell.statusLab.text=str;

if ([str isEqualToString:@"偏低"]) {

cell.statusLab.textColor=[UIColor colorWithHexString:@"2aa764"];

//? ? ? ? self.pointImage.transform=CGAffineTransformMakeRotation(M_PI/6);

}

if ([str isEqualToString:@"理想"]) {

cell.statusLab.textColor=[UIColor colorWithHexString:@"62c342"];

cell.statusImage.transform=CGAffineTransformMakeRotation(M_PI/2-M_PI/6);

}

if ([str isEqualToString:@"正常"]) {

cell.statusLab.textColor=[UIColor colorWithHexString:@"c9e93c"];

cell.statusImage.transform=CGAffineTransformMakeRotation(M_PI/6*5-M_PI/6);

}

if ([str isEqualToString:@"輕度"]) {

cell.statusLab.textColor=[UIColor colorWithHexString:@"ffc102"];

cell.statusImage.transform=CGAffineTransformMakeRotation(M_PI/6*7-M_PI/6);

}

if ([str isEqualToString:@"中度"]) {

cell.statusLab.textColor=[UIColor colorWithHexString:@"f78758"];

cell.statusImage.transform=CGAffineTransformMakeRotation(M_PI/2*3-M_PI/6);

}

if ([str isEqualToString:@"偏高"]) {

cell.statusLab.textColor=[UIColor colorWithHexString:@"e74c3c"];

cell.statusImage.transform=CGAffineTransformMakeRotation(M_PI/6*11-M_PI/6);

}

}else{

[MBProgressHUD showError:dic[@"message"]];

}

CDLog(@"請求成功");

} failed:^(NSError *error) {

[MBProgressHUD showError:@"請求失敗"];

}];

}

//? ? ? ? ? ? self.textview.text=[NSString stringWithFormat:@"測量結(jié)束,收縮壓%@\n\n測量結(jié)束,舒張壓%@\n\n測量結(jié)束,心率%@",num,num2,num3];

}

}

//? ? NSString *productNumber = [reciveString substringWithRange:NSMakeRange(7, 17)];

//? ? [productDefault setObject:productNumber forKey:@"productNumber"];

//? ? [productDefault synchronize];

}

//中心讀取外設(shè)實時數(shù)據(jù)

- (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {

if (error) {

NSLog(@"Error changing notification state: %@", error.localizedDescription);

}

// Notification has started

if (characteristic.isNotifying) {

NSString *reciveString = [NSString stringWithFormat:@"%@", [self hexadecimalString:characteristic.value]];

NSUserDefaults *productDefault = [NSUserDefaults standardUserDefaults];

//? ? NSString *productNumber = [reciveString substringWithRange:NSMakeRange(7, 17)];

[peripheral readValueForCharacteristic:characteristic];

} else { // Notification has stopped

// so disconnect from the peripheral

NSLog(@"Notification stopped on %@.? Disconnecting", characteristic);

//? ? ? ? [self updateLog:[NSString stringWithFormat:@"Notification stopped on %@.? Disconnecting", characteristic]];

[manager cancelPeripheralConnection:peripheral];

}

}

//搜索到Characteristic的Descriptors

-(void)peripheral:(CBPeripheral *)peripheral didDiscoverDescriptorsForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{

//打印出Characteristic和他的Descriptors

NSLog(@"characteristic uuid:%@",characteristic.UUID);

for (CBDescriptor *d in characteristic.descriptors) {

NSLog(@"Descriptor uuid:%@",d.UUID);

}

}

//獲取到Descriptors的值

-(void)peripheral:(CBPeripheral *)peripheral didUpdateValueForDescriptor:(CBDescriptor *)descriptor error:(NSError *)error{

//打印出DescriptorsUUID 和value

//這個descriptor都是對于characteristic的描述,一般都是字符串,所以這里我們轉(zhuǎn)換成字符串去解析

NSLog(@"characteristic uuid:%@? value:%@",[NSString stringWithFormat:@"%@",descriptor.UUID],descriptor.value);

}

#pragma mark 寫數(shù)據(jù)后回調(diào)

- (void)peripheral:(CBPeripheral *)peripheral

didWriteValueForCharacteristic:(CBCharacteristic *)characteristic

error:(NSError *)error {

if (error) {

NSLog(@"Error writing characteristic value: %@",

[error localizedDescription]);

return;

}

NSLog(@"寫入%@成功",characteristic);

[peripheral readValueForCharacteristic:characteristic];

}

//向設(shè)備寫入數(shù)據(jù)讓其停止

-(IBAction)stopBtnDown:(id)sender{

//? ? char byte[] = {0xFD,0xFD,0xFB,0xFB,0x05,0x0C,0x0D,0x0A};

Byte byte[] = {0XFD,0XFD,0XFB,0XFB,0X05,0X0C,0X0D,0X0A};

NSData * data = [NSData dataWithBytes:byte length:8];

[self.per writeValue:data forCharacteristic:chara type:CBCharacteristicWriteWithResponse];

//? ? NSString *str=@"[0xFD,0xFD,0xFB,0xFB,0x05,0x0C,0x0D,0x0A]";

//? ? NSData *data=[str dataUsingEncoding:NSUTF8StringEncoding];

//? ? [self.per writeValue:data forCharacteristic:chara type:CBCharacteristicWriteWithResponse];

}

-(IBAction)showList:(id)sender{

Byte byte[] = {0xFD,0xFD,0x07,0x07,0x07,0x07,0x0D,0x0A};

NSData * data = [NSData dataWithBytes:byte length:8];

[self.per writeValue:data forCharacteristic:chara type:CBCharacteristicWriteWithResponse];

}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容