蓝牙连接,实时数据传输

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


蓝牙连接,实时数据传输_第1张图片

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

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


#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

你可能感兴趣的:(蓝牙连接,实时数据传输)