Bluetooth的使用(以app為中心設(shè)備)

第一:現(xiàn)在項(xiàng)目中導(dǎo)入CoreBluetooth.framework框架绵脯。

第二:藍(lán)牙的使用。

在使用的類中導(dǎo)入#import<CoreBluetooth/CoreBluetooth.h>

步驟:

<1>.首先創(chuàng)建和初始化中心設(shè)備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(@"藍(lán)牙沒有正常打開");

}

}

<2>.對外圍設(shè)備進(jìn)行掃描蛆挫,顯示到掃描結(jié)果的頁面,并且對藍(lán)牙進(jìn)行連接妙黍。

- (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;

}

});

//然后反應(yīng)到相應(yīng)的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(@"保存到數(shù)據(jù)庫中的值:%@", [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>.對已經(jīng)連接的設(shè)備發(fā)現(xiàn)服務(wù)悴侵。

- (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>.對服務(wù)進(jìn)行UUID判斷,發(fā)現(xiàn)相應(yīng)的特征拭嫁。

-(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>.對發(fā)現(xiàn)的特征進(jìn)行判斷可免,進(jìn)行讀取操作。

- (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(@"手表收到的十六進(jìn)制的數(shù)據(jù):%@", hexStr);


<6>.對讀取到的數(shù)據(jù)進(jìn)行數(shù)據(jù)處理做粤。

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(@"手表收到的十六進(jìn)制的數(shù)據(jù):%@", hexStr);

}

第三:與手表或者其他藍(lán)牙設(shè)備進(jìn)行通信巴元。

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(@"除去校驗(yàn)值的值:%@, 校驗(yàn)值:%@", 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(@"創(chuàng)建的文件名:%@", 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(@"保存文件路徑的數(shù)組:%@", 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(@"每次寫入文件的數(shù)-------:%@", [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");

//獲取到多少個(gè)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:@"正在解析數(shù)據(jù)"];

[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]];

}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市驮宴,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌呕缭,老刑警劉巖堵泽,帶你破解...
    沈念sama閱讀 217,907評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異恢总,居然都是意外死亡迎罗,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,987評論 3 395
  • 文/潘曉璐 我一進(jìn)店門片仿,熙熙樓的掌柜王于貴愁眉苦臉地迎上來纹安,“玉大人,你說我怎么就攤上這事∠崞瘢” “怎么了光督?”我有些...
    開封第一講書人閱讀 164,298評論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長塔粒。 經(jīng)常有香客問我结借,道長,這世上最難降的妖魔是什么卒茬? 我笑而不...
    開封第一講書人閱讀 58,586評論 1 293
  • 正文 為了忘掉前任船老,我火速辦了婚禮,結(jié)果婚禮上圃酵,老公的妹妹穿的比我還像新娘柳畔。我一直安慰自己,他們只是感情好郭赐,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,633評論 6 392
  • 文/花漫 我一把揭開白布薪韩。 她就那樣靜靜地躺著,像睡著了一般堪置。 火紅的嫁衣襯著肌膚如雪躬存。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,488評論 1 302
  • 那天舀锨,我揣著相機(jī)與錄音岭洲,去河邊找鬼。 笑死坎匿,一個(gè)胖子當(dāng)著我的面吹牛盾剩,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播替蔬,決...
    沈念sama閱讀 40,275評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼告私,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了承桥?” 一聲冷哼從身側(cè)響起驻粟,我...
    開封第一講書人閱讀 39,176評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎凶异,沒想到半個(gè)月后蜀撑,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,619評論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡剩彬,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,819評論 3 336
  • 正文 我和宋清朗相戀三年酷麦,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片喉恋。...
    茶點(diǎn)故事閱讀 39,932評論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡沃饶,死狀恐怖母廷,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情糊肤,我是刑警寧澤琴昆,帶...
    沈念sama閱讀 35,655評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站轩褐,受9級特大地震影響椎咧,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜把介,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,265評論 3 329
  • 文/蒙蒙 一勤讽、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧拗踢,春花似錦脚牍、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,871評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至君纫,卻和暖如春驯遇,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背蓄髓。 一陣腳步聲響...
    開封第一講書人閱讀 32,994評論 1 269
  • 我被黑心中介騙來泰國打工叉庐, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人会喝。 一個(gè)月前我還...
    沈念sama閱讀 48,095評論 3 370
  • 正文 我出身青樓陡叠,卻偏偏與公主長得像,于是被迫代替她去往敵國和親肢执。 傳聞我的和親對象是個(gè)殘疾皇子枉阵,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,884評論 2 354

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