蓝牙连接,实时数据传输

菜鸟 本人再做一个项目,一个 类似血糖仪的 设备,需要通过蓝牙实时传输测量的值然后根据数值变化 去改变界面的值和波形图,本来查找了 很多demo,第三方框架,都是只能发现是设备但是拿不到实时变化的值把本菜鸟一顿愁啊,然后各种找资料 ,外文网站 啊 ,最后 通过使用<babybluetooth>的框架,并且修改了 部分代码,拿到实时变化的值,


主要是 修改图中读取数值的方式即可,这个特别重要!!!!!

接下来是修改的 核心类里面的代码 :


#import"BabyCentralManager.h"

#import"BabyCallback.h"

@implementationBabyCentralManager

#define currChannel [babySpeaker callbackOnCurrChannel]

- (instancetype)init {

self= [superinit];

if(self) {

#if__IPHONE_OS_VERSION_MIN_REQUIRED > __IPHONE_6_0

NSDictionary*options = [NSDictionarydictionaryWithObjectsAndKeys:

//蓝牙power没打开时alert提示框

[NSNumbernumberWithBool:YES],CBCentralManagerOptionShowPowerAlertKey,

//重设centralManager恢复的IdentifierKey

@"babyBluetoothRestore",CBCentralManagerOptionRestoreIdentifierKey,

nil];

#else

NSDictionary *options =nil;

#endif

NSArray*backgroundModes = [[[NSBundlemainBundle]infoDictionary]objectForKey:@"UIBackgroundModes"];

if([backgroundModescontainsObject:@"bluetooth-central"]) {

//后台模式

centralManager= [[CBCentralManageralloc]initWithDelegate:selfqueue:niloptions:options];

}

else{

//非后台模式

centralManager= [[CBCentralManageralloc]initWithDelegate:selfqueue:nil];

}

//pocket

pocket= [[NSMutableDictionaryalloc]init];

connectedPeripherals= [[NSMutableArrayalloc]init];

discoverPeripherals= [[NSMutableArrayalloc]init];

reConnectPeripherals= [[NSMutableArrayalloc]init];

}

returnself;

}

#pragma mark -接收到通知

//扫描Peripherals

- (void)scanPeripherals {

[centralManagerscanForPeripheralsWithServices:[currChannelbabyOptions].scanForPeripheralsWithServicesoptions:[currChannelbabyOptions].scanForPeripheralsWithOptions];

}

//连接Peripherals

- (void)connectToPeripheral:(CBPeripheral*)peripheral{

[centralManagerconnectPeripheral:peripheraloptions:[currChannelbabyOptions].connectPeripheralWithOptions];

}

//断开设备连接

- (void)cancelPeripheralConnection:(CBPeripheral*)peripheral {

[centralManagercancelPeripheralConnection:peripheral];

}

//断开所有已连接的设备

- (void)cancelAllPeripheralsConnection {

for(inti=0;i

[centralManagercancelPeripheralConnection:connectedPeripherals[i]];

}

}

//停止扫描

- (void)cancelScan {

[centralManagerstopScan];

//停止扫描callback

if([currChannelblockOnCancelScan]) {

[currChannelblockOnCancelScan](centralManager);

}

}

#pragma mark - CBCentralManagerDelegate委托方法

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

//发送通知

[[NSNotificationCenterdefaultCenter]postNotificationName:BabyNotificationAtCentralManagerDidUpdateStateobject:@{@"central":central}];

switch(central.state) {

caseCBCentralManagerStateUnknown:

BabyLog(@">>>CBCentralManagerStateUnknown");

break;

caseCBCentralManagerStateResetting:

BabyLog(@">>>CBCentralManagerStateResetting");

break;

caseCBCentralManagerStateUnsupported:

BabyLog(@">>>CBCentralManagerStateUnsupported");

break;

caseCBCentralManagerStateUnauthorized:

BabyLog(@">>>CBCentralManagerStateUnauthorized");

break;

caseCBCentralManagerStatePoweredOff:

BabyLog(@">>>CBCentralManagerStatePoweredOff");

break;

caseCBCentralManagerStatePoweredOn:

BabyLog(@">>>CBCentralManagerStatePoweredOn");

[[NSNotificationCenterdefaultCenter]postNotificationName:BabyNotificationAtCentralManagerEnableobject:@{@"central":central}];

break;

default:

break;

}

//状态改变callback

if([currChannelblockOnCentralManagerDidUpdateState]) {

[currChannelblockOnCentralManagerDidUpdateState](central);

}

}

- (void)centralManager:(CBCentralManager*)central willRestoreState:(NSDictionary*)dict {

}

//扫描到Peripherals

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

//日志

//BabyLog(@"当扫描到设备:%@",peripheral.name);

[selfaddDiscoverPeripheral:peripheral];

//发出通知

[[NSNotificationCenterdefaultCenter]postNotificationName:BabyNotificationAtDidDiscoverPeripheral

object:@{@"central":central,@"peripheral":peripheral,@"advertisementData":advertisementData,@"RSSI":RSSI}];

//扫描到设备callback

if([currChannelfilterOnDiscoverPeripherals]) {

if([currChannelfilterOnDiscoverPeripherals](peripheral.name,advertisementData,RSSI)) {

if([currChannelblockOnDiscoverPeripherals]) {

[[babySpeakercallbackOnCurrChannel]blockOnDiscoverPeripherals](central,peripheral,advertisementData,RSSI);

}

}

}

//处理连接设备

if(needConnectPeripheral) {

if([currChannelfilterOnconnectToPeripherals](peripheral.name,advertisementData,RSSI)) {

[centralManagerconnectPeripheral:peripheraloptions:[currChannelbabyOptions].connectPeripheralWithOptions];

//开一个定时器监控连接超时的情况

connectTimer= [NSTimerscheduledTimerWithTimeInterval:5.0ftarget:selfselector:@selector(disconnect:)userInfo:peripheralrepeats:NO];

}

}

}

//停止扫描

- (void)disconnect:(id)sender {

[centralManagerstopScan];

}

//连接到Peripherals-成功

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

//发出通知

[[NSNotificationCenterdefaultCenter]postNotificationName:BabyNotificationAtDidConnectPeripheral

object:@{@"central":central,@"peripheral":peripheral}];

//设置委托

[peripheralsetDelegate:self];

//BabyLog(@">>>连接到名称为(%@)的设备-成功",peripheral.name);

[connectTimerinvalidate];//停止时钟

[selfaddPeripheral:peripheral];

//执行回叫

//扫描到设备callback

if([currChannelblockOnConnectedPeripheral]) {

[currChannelblockOnConnectedPeripheral](central,peripheral);

}

//扫描外设的服务

if(needDiscoverServices) {

[peripheraldiscoverServices:[currChannelbabyOptions].discoverWithServices];

//discoverIncludedServices

}

}

//连接到Peripherals-失败

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

//发出通知

[[NSNotificationCenterdefaultCenter]postNotificationName:BabyNotificationAtDidFailToConnectPeripheral

object:@{@"central":central,@"peripheral":peripheral,@"error":error?error:@""}];

//BabyLog(@">>>连接到名称为(%@)的设备-失败,原因:%@",[peripheral name],[error localizedDescription]);

if([currChannelblockOnFailToConnect]) {

[currChannelblockOnFailToConnect](central,peripheral,error);

}

}

//Peripherals断开连接

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

//发出通知

[[NSNotificationCenterdefaultCenter]postNotificationName:BabyNotificationAtDidDisconnectPeripheral

object:@{@"central":central,@"peripheral":peripheral,@"error":error?error:@""}];

//BabyLog(@">>>外设连接断开连接%@: %@\n", [peripheral name], [error localizedDescription]);

if(error)

{

BabyLog(@">>> didDisconnectPeripheral for %@ with error: %@", peripheral.name, [error localizedDescription]);

}

[selfdeletePeripheral:peripheral];

if([currChannelblockOnDisconnect]) {

[currChannelblockOnDisconnect](central,peripheral,error);

}

//判断是否全部链接都已经段开,调用blockOnCancelAllPeripheralsConnection委托

if([selffindConnectedPeripherals].count==0) {

//停止扫描callback

if([currChannelblockOnCancelAllPeripheralsConnection]) {

[currChannelblockOnCancelAllPeripheralsConnection](centralManager);

}

//BabyLog(@">>> stopConnectAllPerihperals");

}

//检查并重新连接需要重连的设备

if([reConnectPeripheralscontainsObject:peripheral]) {

[selfconnectToPeripheral:peripheral];

}

}

//扫描到服务

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

//发出通知

[[NSNotificationCenterdefaultCenter]postNotificationName:BabyNotificationAtDidDiscoverServices

object:@{@"peripheral":peripheral,@"error":error?error:@""}];

//BabyLog(@">>>扫描到服务:%@",peripheral.services);

if(error) {

BabyLog(@">>>didDiscoverServices for %@ with error: %@", peripheral.name, [error localizedDescription]);

}

//回叫block

if([currChannelblockOnDiscoverServices]) {

[currChannelblockOnDiscoverServices](peripheral,error);

}

//discover characteristics

if(needDiscoverCharacteristics) {

for(CBService*serviceinperipheral.services) {

[peripheraldiscoverCharacteristics:[currChannelbabyOptions].discoverWithCharacteristicsforService:service];

}

}

}

//发现服务的Characteristics

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

//发出通知

[[NSNotificationCenterdefaultCenter]postNotificationName:BabyNotificationAtDidDiscoverCharacteristicsForService

object:@{@"peripheral":peripheral,@"service":service,@"error":error?error:@""}];

if(error) {

BabyLog(@"error didDiscoverCharacteristicsForService for %@ with error: %@", service.UUID, [error localizedDescription]);

//return;

}

//回叫block

if([currChannelblockOnDiscoverCharacteristics]) {

[currChannelblockOnDiscoverCharacteristics](peripheral,service,error);

}

//如果需要更新Characteristic的值

if(needReadValueForCharacteristic) {

for(CBCharacteristic*characteristicinservice.characteristics) {

//[peripheral readValueForCharacteristic:characteristic];

[peripheralsetNotifyValue:YESforCharacteristic:characteristic];

//判断读写权限

//if (characteristic.properties & CBCharacteristicPropertyRead ) {

//[peripheral readValueForCharacteristic:characteristic];

//}

}

}

//如果搜索Characteristic的Descriptors

if(needDiscoverDescriptorsForCharacteristic) {

for(CBCharacteristic*characteristicinservice.characteristics) {

[peripheraldiscoverDescriptorsForCharacteristic:characteristic];

}

}

}

//读取Characteristics的值

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

//发出通知

[[NSNotificationCenterdefaultCenter]postNotificationName:BabyNotificationAtDidUpdateValueForCharacteristic

object:@{@"peripheral":peripheral,@"characteristic":characteristic,@"error":error?error:@""}];

if(error) {

BabyLog(@"error didUpdateValueForCharacteristic %@ with error: %@", characteristic.UUID, [error localizedDescription]);

//return;

}

//查找字段订阅

if([babySpeakernotifyCallback:characteristic]) {

[babySpeakernotifyCallback:characteristic](peripheral,characteristic,error);

return;

}

//回叫block

if([currChannelblockOnReadValueForCharacteristic]) {

[currChannelblockOnReadValueForCharacteristic](peripheral,characteristic,error);

}

}

//发现Characteristics的Descriptors

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

if(error) {

BabyLog(@"error Discovered DescriptorsForCharacteristic for %@ with error: %@", characteristic.UUID, [error localizedDescription]);

//return;

}

//回叫block

if([currChannelblockOnDiscoverDescriptorsForCharacteristic]) {

[currChannelblockOnDiscoverDescriptorsForCharacteristic](peripheral,characteristic,error);

}

//如果需要更新Characteristic的Descriptors

if(needReadValueForDescriptors) {

for(CBDescriptor*dincharacteristic.descriptors) {

[peripheralreadValueForDescriptor:d];

}

}

//执行一次的方法

if(oneReadValueForDescriptors) {

for(CBDescriptor*dincharacteristic.descriptors) {

[peripheralreadValueForDescriptor:d];

}

oneReadValueForDescriptors=NO;

}

}

//读取Characteristics的Descriptors的值

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

if(error) {

BabyLog(@"error didUpdateValueForDescriptorfor %@ with error: %@", descriptor.UUID, [error localizedDescription]);

//return;

}

//回叫block

if([currChannelblockOnReadValueForDescriptors]) {

[currChannelblockOnReadValueForDescriptors](peripheral,descriptor,error);

}

}

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

[[NSNotificationCenterdefaultCenter]postNotificationName:BabyNotificationAtDidWriteValueForCharacteristicobject:@{@"characteristic":characteristic,@"error":error?error:@""}];

//BabyLog(@">>>didWriteValueForCharacteristic");

//BabyLog(@">>>uuid:%@,new value:%@",characteristic.UUID,characteristic.value);

if([currChannelblockOnDidWriteValueForCharacteristic]) {

[currChannelblockOnDidWriteValueForCharacteristic](characteristic,error);

}

}

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

//BabyLog(@">>>didWriteValueForCharacteristic");

//BabyLog(@">>>uuid:%@,new value:%@",descriptor.UUID,descriptor.value);

if([currChannelblockOnDidWriteValueForDescriptor]) {

[currChannelblockOnDidWriteValueForDescriptor](descriptor,error);

}

}

#pragma mark--------------数据状态改变-------------

//characteristic.isNotifying状态改变

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

[peripheralreadValueForCharacteristic:characteristic];

[[NSNotificationCenterdefaultCenter]postNotificationName:BabyNotificationAtDidUpdateNotificationStateForCharacteristicobject:@{@"characteristic":characteristic,@"error":error?error:@""}];

BabyLog(@">>>didUpdateNotificationStateForCharacteristic");

BabyLog(@">>>uuid:%@,isNotifying:%@",characteristic.UUID,characteristic.isNotifying?@"isNotifying":@"Notifying");

if([currChannelblockOnDidUpdateNotificationStateForCharacteristic]) {

[currChannelblockOnDidUpdateNotificationStateForCharacteristic](characteristic,error);

}

}

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

if([currChannelblockOnDidDiscoverIncludedServicesForService]) {

[currChannelblockOnDidDiscoverIncludedServicesForService](service,error);

}

}

# if__IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_8_0

- (void)peripheralDidUpdateRSSI:(CBPeripheral*)peripheral error:(nullableNSError*)error {

[[NSNotificationCenterdefaultCenter]postNotificationName:BabyNotificationAtDidReadRSSIobject:@{@"peripheral":peripheral,@"RSSI":peripheral.RSSI,@"error":error?error:@""}];

BabyLog(@">>>peripheralDidUpdateRSSI -> RSSI:%@",peripheral.RSSI);

if([currChannelblockOnDidReadRSSI]) {

[currChannelblockOnDidReadRSSI](peripheral.RSSI,error);

}

}

#else

- (void)peripheral:(CBPeripheral *)peripheral didReadRSSI:(NSNumber *)RSSI error:(NSError *)error {

[[NSNotificationCenter defaultCenter]postNotificationName:BabyNotificationAtDidReadRSSI object:@{@"peripheral":peripheral,@"RSSI":RSSI,@"error":error?error:@""}];

BabyLog(@">>>peripheralDidUpdateRSSI -> RSSI:%@",RSSI);

if([currChannel blockOnDidReadRSSI]) {

[currChannel blockOnDidReadRSSI](RSSI,error);

}

}

#endif

- (void)peripheralDidUpdateName:(CBPeripheral*)peripheral {

if([currChannelblockOnDidUpdateName]) {

[currChannelblockOnDidUpdateName](peripheral);

}

}

- (void)peripheral:(CBPeripheral*)peripheral didModifyServices:(NSArray*)invalidatedServices {

if([currChannelblockOnDidModifyServices]) {

[currChannelblockOnDidModifyServices](peripheral,invalidatedServices);

}

}

/**

sometimes ever,sometimes never.相聚有时,后会无期

this is center with peripheral's story

**/

//sometimes ever:添加断开重连接的设备

-(void)sometimes_ever:(CBPeripheral*)peripheral {

if(![reConnectPeripheralscontainsObject:peripheral]) {

[reConnectPeripheralsaddObject:peripheral];

}

}

//sometimes never:删除需要重连接的设备

-(void)sometimes_never:(CBPeripheral*)peripheral {

[reConnectPeripheralsremoveObject:peripheral];

}

#pragma mark -私有方法

#pragma mark -设备list管理

- (void)addDiscoverPeripheral:(CBPeripheral*)peripheral{

if(![discoverPeripheralscontainsObject:peripheral]) {

[discoverPeripheralsaddObject:peripheral];

}

}

- (void)addPeripheral:(CBPeripheral*)peripheral {

if(![connectedPeripheralscontainsObject:peripheral]) {

[connectedPeripheralsaddObject:peripheral];

}

}

- (void)deletePeripheral:(CBPeripheral*)peripheral{

[connectedPeripheralsremoveObject:peripheral];

}

- (CBPeripheral*)findConnectedPeripheral:(NSString*)peripheralName {

for(CBPeripheral*pinconnectedPeripherals) {

if([p.nameisEqualToString:peripheralName]) {

returnp;

}

}

returnnil;

}

- (NSArray*)findConnectedPeripherals{

returnconnectedPeripherals;

}

@end

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

推荐阅读更多精彩内容