Bluetooth的使用(以app为中心设备)

第一:现在项目中导入CoreBluetooth.framework框架。

第二:蓝牙的使用。

在使用的类中导入#import<CoreBluetooth/CoreBluetooth.h>

步骤:

<1>.首先创建和初始化中心设备CBCentralManager。

dispatch_queue_t centralQueue = dispatch_queue_create("定义线程的名字", DISPATCH_QUEUE_SERIAL);

bluetoothManager = [[CBCentralManager alloc] initWithDelegate:self queue:centralQueue];

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

NSLog(@"[ScanTableViewController] [centralManagerDidUpdateState] state === %ld", (long)central.state);

if (central.state == CBCentralManagerStatePoweredOn) {

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

} else {

NSLog(@"蓝牙没有正常打开");

}

}

<2>.对外围设备进行扫描,显示到扫描结果的页面,并且对蓝牙进行连接。

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

dispatch_async(dispatch_get_main_queue(), ^{

// Add the sensor to the list and reload deta set

ScannedPeripheral* sensor = [ScannedPeripheral initWithPeripheral:peripheral rssi:RSSI.intValue isPeripheralConnected:NO];

if (![peripherals containsObject:sensor]) {

[peripherals addObject:sensor];

} else {

sensor = [peripherals objectAtIndex:[peripherals indexOfObject:sensor]];

sensor.RSSI = RSSI.intValue;

}

});

//然后反应到相应的View中


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

dispatch_async(dispatch_get_main_queue(), ^{

NSLog(@"[ScanTableViewController] [didConnectPeripheral]");

isConnectingOneDevice = NO;

[timer invalidate];

CachedBLEDevice* device = [CachedBLEDevice defaultInstance];

if ([[DBRecorder getFMDBDeviceParameters] count]) {

[DBRecorder deleteFMDBDevice:device.mDeviceIdentifier];

}

device.mDeviceName = [peripheral name];

device.mDeviceIdentifier = [[peripheral identifier] UUIDString];

device.mAlertEnabled = false;

device.mRangeAlertEnabled = true;

device.mRangeType = RANGE_ALERT_OUT;

device.mRangeValue = RANGE_ALERT_FAR;

device.mDisconnectEnabled = true;

device.mRingtoneEnabled = true;

device.mVibrationEnabled = true;

device.mConnectionState = CONNECTION_STATE_CONNECTED;

[device setDevicePeripheral:peripheral];

NSLog(@"保存到数据库中的值:%@", [device getDevicePeripheral]);

[device persistData:1];

iSmartWatchConfiguration *configuration = [iSmartWatchConfiguration sharedConfiguration];

configuration.software.paired = YES;

[configuration save];

if (nil != connectingCell) {

[connectingCell showIndicator:NO];

}

MainTabBarViewController *mainTVC = [[MainTabBarViewController alloc] init];

[self.navigationController presentViewController:mainTVC animated:YES completion:NULL];

});


<3>.对已经连接的设备发现服务。

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

instancesRespondToSelector:@selector(registerUserNotificationSettings:)]) {

NSLog(@"[RecordController] [didDiscoverServices]");

if (!error) {

NSLog(@"services discovered %lu",(unsigned long)[peripheral.services count] );

for (CBService *service in peripheral.services) {

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

if ([service.UUID isEqual:batteryServiceUUID]) {

NSLog(@"Battery service found");

[self.recordPeripheral discoverCharacteristics:nil forService:service];

} else if ([service.UUID isEqual:dogpServiceUUID]) {

NSLog(@"Dogp service found");

kisfinishFile = 0;

[self.recordPeripheral discoverCharacteristics:nil forService:service];

} else if ([service.UUID isEqual:proximityLinkLossServiceUUID]) {

NSLog(@"Linkloss service is found");

[self.recordPeripheral discoverCharacteristics:nil forService:service];

}

else if ([service.UUID isEqual:proximityImmediateAlertServiceUUID]) {

NSLog(@"Immidiate Alert service is found");

[self.recordPeripheral discoverCharacteristics:nil forService:service];

}

}

} else {

NSLog(@"error in discovering services on device: %@", self.recordPeripheral.name);

}


<4>.对服务进行UUID判断,发现相应的特征。

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

if (!error) {

if ([service.UUID isEqual:dogpServiceUUID]) {

for (CBCharacteristic *characteristic in service.characteristics) {

if ([characteristic.UUID isEqual:dogpReadCharacteristicUUID]) {

NSLog(@"Dogp service read characteristic is found");

[self.recordPeripheral setNotifyValue:YES forCharacteristic:characteristic];

}

if ([characteristic.UUID isEqual:dogpWriteCharacteristicUUID]) {

NSLog(@"Dogp service write characteristic is found");

dogpWriteCharacteristic = characteristic;

}

}


<5>.对发现的特征进行判断,进行读取操作。

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

if ([characteristic.UUID isEqual:dogpReadCharacteristicUUID]) {

NSLog(@"获取到读的UUID:%@, ---%@",characteristic.UUID, characteristic.value);

NSString *content = [[NSString alloc] initWithData:characteristic.value encoding:NSUTF8StringEncoding];

NSLog(@"%s", characteristic.value.bytes);

NSLog(@"----> dogp content === %@", content);

if ([content isEqualToString:@"ios indication"]) {

[self.recordPeripheral readValueForCharacteristic:characteristic];

dogpReadCharacteristic = characteristic;

return;

}else{

NSString *hexStr = [self convertDataToHexStr:characteristic.value];

NSLog(@"手表收到的十六进制的数据:%@", hexStr);


<6>.对读取到的数据进行数据处理。

if ([characteristic.UUID isEqual:dogpReadCharacteristicUUID]) {

NSLog(@"获取到读的UUID:%@, ---%@",characteristic.UUID, characteristic.value);

NSString *content = [[NSString alloc] initWithData:characteristic.value encoding:NSUTF8StringEncoding];

NSLog(@"%s", characteristic.value.bytes);

NSLog(@"----> dogp content === %@", content);

if ([content isEqualToString:@"ios indication"]) {

[self.recordPeripheral readValueForCharacteristic:characteristic];

dogpReadCharacteristic = characteristic;

return;

}else{

NSString *hexStr = [self convertDataToHexStr:characteristic.value];

NSLog(@"手表收到的十六进制的数据:%@", hexStr);

}

第三:与手表或者其他蓝牙设备进行通信。

NSInteger length = [hexStr length];

NSString *contentOfDataStr = [hexStr substringWithRange:NSMakeRange(0, length-2)];

NSString *checkStr = [hexStr substringWithRange:NSMakeRange(length-2, 2)];

//check len of data

NSLog(@"除去校验值的值:%@, 校验值:%@", contentOfDataStr, checkStr);

NSString *getCheckSum = [self checkTheString:contentOfDataStr];

NSString *comToLenStr = [hexStr substringWithRange:NSMakeRange(2, 14)];

NSString *splitCommdStr = @"";

NSFileManager *fileManager = [NSFileManager defaultManager];

//check the code

if ([[checkStr uppercaseString] isEqualToString:getCheckSum]) {

NSLog(@"check checkSum is right");

NSString *data_typeStr = [hexStr substringWithRange:NSMakeRange(10, 2)];

if ([data_typeStr isEqualToString:@"00"]) {

//The name of file

NSString *fileName = [hexStr substringWithRange:NSMakeRange(20, hexStr.length - 22)];

NSLog(@"创建的文件名:%@", fileName);

data_number = 0;

//判断文件是否存在

filePath = [self createFile:fileName type:@"1"];

NSMutableArray *dataArray = [[NSUserDefaults standardUserDefaults] objectForKey:@"fitName"];

NSString *compare_fileName = [NSString stringWithFormat:@"FIT_%@.fit", fileName];

[dataArray addObject:@"1"];

NSLog(@"保存文件路径的数组:%@", dataArray);

NSLog(@"文件路径:%@", compare_fileName);

if (([dataArray containsObject:compare_fileName] && dataArray != NULL) || ([filePath isEqualToString:@""])) {

kisStat = @"02";

}else{

NSString *tempFile = [self createFile:[fileName stringByAppendingString:@"0"] type:@"0"];

if ([tempFile isEqualToString:@""]) {

[fileManager removeItemAtPath:tempPath error:nil];

kisStat = @"01";

}else{

tempPath = tempFile;

[fileManager createFileAtPath:tempPath contents:nil attributes:nil];

kisStat = @"00";

}

}

}else if ([data_typeStr isEqualToString:@"01"]){

//insert data into Local file

if ([self checkLenOfData:hexStr]) {

NSLog(@"data len is right");

kisStat = @"00";

data_number += 1;

NSInteger lengOfhex = hexStr.length;

NSString *dataStr = [hexStr substringWithRange:NSMakeRange(20, lengOfhex-22)];

NSLog(@"每次写入文件的数-------:%@", [dataStr uppercaseString]);

[self insertData:dataStr toFile:tempPath];

}else{

NSLog(@"data len is wrong");

kisStat = @"01";

}

}else if ([data_typeStr isEqualToString:@"02"]){

//check infomation

NSString *fileNumberStr = [hexStr substringWithRange:NSMakeRange(20, 4)];

if ([self checkInformation:[fileNumberStr uppercaseString]]){

NSLog(@"check successful");

NSString *sizeOffileStr = [hexStr substringWithRange:NSMakeRange(24, 8)];

long localLength = [self getCacheFileSize:tempPath];

long watch_length = [self getNumberOfString:[sizeOffileStr uppercaseString]];

NSLog(@"localLength:%ld, -----watch_length:%ld", localLength, watch_length);

if (localLength == watch_length) {

BOOL isChange = [fileManager moveItemAtPath:tempPath toPath:filePath error:nil];

NSLog(@"%d", isChange);

NSLog(@"temp文件大小:%ld-----file文件大小:%ld", [self getCacheFileSize:tempPath], [self getCacheFileSize:filePath]);

if (isChange) {

[fileManager removeItemAtPath:tempPath error:nil];

}else{

NSLog(@"isChange fail");

}

NSLog(@"size of file is right");

kisStat = @"00";

}else{

NSLog(@"size of file is wrong");

kisStat = @"01";

}

}else{

NSLog(@"check fail");

kisStat = @"01";

}

}else if ([data_typeStr isEqualToString:@"03"]){

//sync end

kisfinishFile = 1;

NSString *statStr = [hexStr substringWithRange:NSMakeRange(20, 2)];

if ([statStr isEqualToString:@"01"]) {

[fileManager removeItemAtPath:tempPath error:nil];

}

NSLog(@"parse file");

//获取到多少个fit文件

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentDiectory = [paths objectAtIndex:0];

NSString *appDirectory = [documentDiectory stringByAppendingPathComponent:@"rftech-smartwatch-fit"];

NSArray *fileArray = [fileManager subpathsAtPath:appDirectory];

NSLog(@"同步获取到的fit文件%@", fileArray);

CustomAlertWindow *customAlertWindow = [CustomAlertWindow shareCustomAlertWindow];

if (fileArray.count != 0) {

[customAlertWindow setNotes:@"正在解析数据"];

[customAlertWindow show];

[self pareQueueManagercustom:customAlertWindow andFileManager:fileManager andFileArray:fileArray andAppDirectory:appDirectory];

}else{

[customAlertWindow dismiss];

}

}

}else{

NSLog(@"check checkSum is wrong");

kisStat = @"01";

}

if (kisfinishFile == 0) {

splitCommdStr = [self getCommandStr:comToLenStr andStat:kisStat];

NSLog(@"split of CommdStr:%@", splitCommdStr);

[self replyFit:[self convertHexStrToData:splitCommdStr]];

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 214,837评论 6 496
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,551评论 3 389
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 160,417评论 0 350
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,448评论 1 288
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,524评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,554评论 1 293
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,569评论 3 414
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,316评论 0 270
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,766评论 1 307
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,077评论 2 330
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,240评论 1 343
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,912评论 5 338
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,560评论 3 322
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,176评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,425评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,114评论 2 366
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,114评论 2 352

推荐阅读更多精彩内容