iOS蓝牙开发数据实时传输
随着iOS项目开发 很多app需要通过蓝牙与设备连接
蓝牙开发注意:
先定义中心设备和外围设备以及遵守蓝牙协议
@interfaceViewController()@property(strong,nonatomic)CBCentralManager*manager; @property(nonatomic,strong)CBPeripheral*peripheral; @property(nonatomic,weak)NSTimer*connentTimer; @end
再实现delegate方法
1.判断蓝牙状态,如成功则扫描指定UUID设备(如不指定UUID,则无法后台持续连接)
2.当发现指定设备后,连接该设备
3.当连接指定外围设备成功,编写定时器,每秒读取1次RSSI
4.当监听到失去和外围设备连接,重新建立连接
5.当读取到RSSI值,打印出它的值
//蓝牙状态
-(void)centralManagerDidUpdateState:(CBCentralManager*)central
{
NSString*state=nil;
switch([centralstate])
{
caseCBCentralManagerStateUnsupported:
state=@"Theplatform/hardwaredoesn'tsupportBluetoothLowEnergy.";
break;
//应用程序没有被授权使用蓝牙
caseCBCentralManagerStateUnauthorized:
state=@"TheappisnotauthorizedtouseBluetoothLowEnergy.";
break;
//尚未打开蓝牙
caseCBCentralManagerStatePoweredOff:
state=@"Bluetoothiscurrentlypoweredoff.";
break;
//连接成功
caseCBCentralManagerStatePoweredOn:
[self.managerscanForPeripheralsWithServices:niloptions:nil];
state=@"work";
break;
caseCBCentralManagerStateUnknown:
default:
;
}
NSLog(@"Centralmanagerstate:%@",state);
}
//查找设备
-(void)centralManager:(CBCentralManager*)centraldidDiscoverPeripheral:(CBPeripheral*)peripheraladvertisementData:(NSDictionary*)advertisementDataRSSI:(NSNumber*)RSSI
{
//每个蓝牙设备有自己唯一的标识符,根据标识符确认自己要连接的设备
if([peripheral.identifierisEqual:self.peripheral.identifier])
{
self.peripheral=peripheral;
//数据连接定时器
self.connentTimer=[NSTimerscheduledTimerWithTimeInterval:1target:selfselector:@selector(connentPeripheral)userInfo:@"timer"repeats:YES];
[self.connentTimerfire];
}
}
-(void)connentPeripheral{
//连接外设
self.manager.delegate=self;
[self.managerconnectPeripheral:_peripheraloptions:[NSDictionarydictionaryWithObject:[NSNumbernumberWithBool:YES]forKey:CBConnectPeripheralOptionNotifyOnDisconnectionKey]];
}
//连接成功后调用
-(void)centralManager:(CBCentralManager*)centraldidConnectPeripheral:(CBPeripheral*)peripheral
{
NSLog(@"Didconnecttoperipheral:%@,%@",peripheral,peripheral.name);
[peripheralsetDelegate:self];//查找服务
[peripheraldiscoverServices:nil];
[self.connentTimerinvalidate];
//监测设备是否断开了
//[selfcreateWorkDataSourceWithTimeInterval:1];
}
//当监听到失去和外围设备连接,重新建立连接
//这个方法是必须实现的,因为蓝牙会中断连接,正好触发这个方法重建连接。重建连接可能造成数秒后才能读取到RSSI。
-(void)centralManager:(CBCentralManager*)centraldidDisconnectPeripheral:(CBPeripheral*)peripheralerror:(NSError*)error
{
[self.managerconnectPeripheral:peripheraloptions:nil];
}
-(void)centralManager:(CBCentralManager*)centraldidFailToConnectPeripheral:(CBPeripheral*)peripheralerror:(NSError*)error
{
NSLog(@"%@",error.description);
}
//返回的蓝牙服务通知通过代理实现
-(void)peripheral:(CBPeripheral*)peripheraldidDiscoverServices:(NSError*)error
{
if(error)
{
NSLog(@"Discoveredservicesfor%@witherror:%@",peripheral.name,[errorlocalizedDescription]);
return;
}
for(CBService*serviceinperipheral.services)
{
//NSLog(@"ServicefoundwithUUID:%@",service.UUID.UUIDString);
//发现服务
if([service.UUIDisEqual:[CBUUIDUUIDWithString:@"180D"]])//heartrate
{
//在一个服务中寻找特征值
[peripheraldiscoverCharacteristics:nilforService:service];
}
}
}
//返回的蓝牙特征值通知通过代理实现
-(void)peripheral:(CBPeripheral*)peripheraldidDiscoverCharacteristicsForService:(CBService*)serviceerror:(NSError*)error
{
if(error)
{
NSLog(@"Discoveredcharacteristicsfor%@witherror:%@",service.UUID,[errorlocalizedDescription]);
return;
}
for(CBCharacteristic*characteristicinservice.characteristics)
{
NSLog(@"characteristic:%@",characteristic);
if([characteristic.UUIDisEqual:[CBUUIDUUIDWithString:@"2A37"]])
{
[selfnotification:service.UUIDcharacteristicUUID:characteristic.UUIDperipheral:peripheralon:YES];
//[self.peripheralsetNotifyValue:YESforCharacteristic:characteristic];
}
}
}
//处理蓝牙发过来的数据
-(void)peripheral:(CBPeripheral*)peripheraldidUpdateValueForCharacteristic:(CBCharacteristic*)characteristicerror:(NSError*)error
{
}
-(void)notification:(CBUUID*)serviceUUIDcharacteristicUUID:(CBUUID*)characteristicUUIDperipheral:(CBPeripheral*)pon:(BOOL)on
{
CBService*service=[selfgetServiceFromUUID:serviceUUIDp:p];
if(!service)
{
//if(p.UUID==NULL)return;//zachios6addedche
//NSLog(@"CouldnotfindservicewithUUIDonperipheralwithUUID\n");
return;
}
CBCharacteristic*characteristic=[selfgetCharacteristicFromUUID:characteristicUUIDservice:service];
if(!characteristic)
{
//if(p.UUID==NULL)return;//zachios6added
//NSLog(@"CouldnotfindcharacteristicwithUUIDonservicewithUUIDonperipheralwithUUID\n");
return;
}
[psetNotifyValue:onforCharacteristic:characteristic];
}
-(CBService*)getServiceFromUUID:(CBUUID*)UUIDp:(CBPeripheral*)p
{
for(CBService*sinp.services)
{
if([s.UUIDisEqual:UUID])returns;
}
returnnil;//Servicenotfoundonthisperipheral
}
-(CBCharacteristic*)getCharacteristicFromUUID:(CBUUID*)UUIDservice:(CBService*)service{
for(CBCharacteristic*cinservice.characteristics)
{
if([c.UUIDisEqual:UUID])returnc;
}
returnnil;//Characteristicnotfoundonthisservice
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。