藍牙實現(xiàn)方案
之前項目有用到藍牙,這里記錄一下藍牙的一些簡單使用.
iOS提供了4個用于實現(xiàn)藍牙連接的方案:
1. ExternalAccessory.framework
提供了配件鏈接iOS的通道,可用于第三方藍牙設備交互(藍牙設備必須需要蘋果MFI認證,比較麻煩)
2.MultipeerConnectivity.framework
iOS7引入的多點連接,只能用于Apple設備,可在較近的距離基于藍牙和WIFI發(fā)現(xiàn)和連接實現(xiàn)進場通信,有點和AirDrop類似,不過AirDrop必須同時打開WiFi和藍牙,而且要保持較近的距離 ( 其過程相當于A放出廣播,B用于搜索,B搜到之后向A發(fā)邀請,請求建立連接,A接受之后向B發(fā)送一個會話,建立連接)
MCPeerID *_peerID = [[MCPeerID alloc] initWithDisplayName:[UIDevice currentDevice].name];//給設備自定義個名字
MCSession *_session = [[MCSession alloc] initWithPeer:_peerID];//創(chuàng)建會話
_session.delegate = self;//遵守<MCSessionDelegate>協(xié)議
MCAdvertiserAssistant *_advertiser = [[MCAdvertiserAssistant alloc] initWithServiceType:@"chat-files"
discoveryInfo:nil
session:_session];
//初始化廣播服務,serviceType是類型標識符,通過文本描述來讓瀏覽器發(fā)現(xiàn)廣播者,只有相同的serviceType才能相互連接(要求1-15個字符,只能包含ASCII小寫字母,數(shù)字和連字符)
[_advertiser start]; //開始廣播 stop關閉廣播
MCBrowserViewController *_browser = [[MCBrowserViewController alloc] initWithServiceType:@"chat-files"session:_session]; // 創(chuàng)建視圖瀏覽器
_browser.delegate = self; //遵守<MCBrowserViewControllerDelegate>協(xié)議
[self presentViewController: _browser animated:YES completion:nil]; //彈出視窗
//<MCBrowserViewControllerDelegate>
-(void)browserViewControllerDidFinish:(MCBrowserViewController *)browserViewController{//完成
[_browser dismissViewControllerAnimated:YES completion:nil];
}
-(void)browserViewControllerWasCancelled:(MCBrowserViewController *)browserViewController{//取消
[_browser dismissViewControllerAnimated:YES completion:nil];
}
//瀏覽器提供連接功能 ,等連接之后就根據(jù)情況實現(xiàn)<MCSessionDelegate>方法
-(void)session:(MCSession *)session peer:(MCPeerID *)peerID didChangeState:(MCSessionState)state{
//新的連接發(fā)生時,會被調(diào)用 state狀態(tài)如下:
//MCSessionStateNotConnected, // Not connected to the session.
// MCSessionStateConnecting, // Peer is connecting to the session.
// MCSessionStateConnected
}
-(void)session:(MCSession *)session didReceiveData:(NSData *)data fromPeer:(MCPeerID *)peerID{
//接受數(shù)據(jù)
}
-(void)session:(MCSession *)session didStartReceivingResourceWithName:(NSString *)resourceName fromPeer:(MCPeerID *)peerID withProgress:(NSProgress *)progress{
//開始接受資源
}
-(void)session:(MCSession *)session didFinishReceivingResourceWithName:(NSString *)resourceName fromPeer:(MCPeerID *)peerID atURL:(NSURL *)localURL withError:(NSError *)error{
//結(jié)束接收資源
}
-(void)session:(MCSession *)session didReceiveStream:(NSInputStream *)stream withName:(NSString *)streamName fromPeer:(MCPeerID *)peerID{
//接收流
}
[_session sendData: dataToSend toPeers:_session.connectedPeers withMode:MCSessionSendDataReliable error:&error]; //發(fā)送數(shù)據(jù)給所有連接的設備
連接流程圖.png
3.GameKit.framework
用于Apple設備之間的連接,更多用于游戲方面,從iOS7廢棄.此方案可以增加對等連接,無需連接到互聯(lián)網(wǎng)
GKPeerPickerController *gpp = [[GKPeerPickerController alloc] init];//創(chuàng)建查找設備控制器
gpp.connectionTypesMask = GKPeerPickerConnectionTypeNearby | GKPeerPickerConnectionTypeOnline;
//nearby指藍牙 online指WIFI
gpp.delegate = self; // 遵守<GKPeerPickerControllerDelegate>協(xié)議
[gpp show];//彈出控制器
//<GKPeerPickerControllerDelegate>協(xié)議
- (void)peerPickerController:(GKPeerPickerController *)picker didConnectPeer:(NSString *)peerID toSession:(GKSession *)session
{
//設備連接成功后調(diào)用方法
[self.session setDataReceiveHandler:self withContext:nil]; // 設置數(shù)據(jù)接受者
[picker dismiss]; // 退出查找設備的控制器
}
- (void) receiveData:(NSData *)data fromPeer:(NSString *)peer inSession: (GKSession *)session context:(void *)context
{
//接收數(shù)據(jù)的時候會調(diào)用該方法
}
[self.session sendDataToAllPeers: data withDataMode:GKSendDataReliable error:nil];//發(fā)送數(shù)據(jù)
[self.session sendData:data toPeers: peers withDataMode:GKSendDataReliable error:nil];//往指定peer發(fā)送數(shù)據(jù)
4.CoreBluetooth.framework (藍牙4.0)
以低功耗著稱,可用于第三方藍牙設備交互,對硬件上是有一定要求的柬脸,iPhone 4S及以后的設備,第三代iPad及以后的設備是支持這一標準的
核心結(jié)構(gòu)圖如下
CoreBluetooth結(jié)構(gòu)圖.png
每個藍牙設備必有一個或多個Service ,一個Service有若干個Characteristic,它們都是用UUID來唯一識別
@property(nonatomic,strong)CBCentralManager *_mgr;//中央管理者
//初始化中央管理者
_mgr = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
//遵守<CBCentralManagerDelegate>協(xié)議
- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
//狀態(tài)發(fā)生改變的時候會執(zhí)行該方法(藍牙4.0沒有打開變成打開狀態(tài)就會調(diào)用該方法)
switch (central.state) {
case CBCentralManagerStatePoweredOn:
NSLog(@"打開西乖,可用");
//掃描周圍的藍牙 options參數(shù) 允許中央設備多次收到曾經(jīng)監(jiān)聽到的設備的消息
[_mgr scanForPeripheralsWithServices:nil options:@{CBCentralManagerScanOptionAllowDuplicatesKey:@(NO)}];
break;
case CBCentralManagerStatePoweredOff:
NSLog(@"可用,未打開");
break;
case CBCentralManagerStateUnsupported:
NSLog(@"SDK不支持");
break;
case CBCentralManagerStateUnauthorized:
NSLog(@"程序未授權(quán)");
break;
case CBCentralManagerStateResetting:
NSLog(@"CBCentralManagerStateResetting");
break;
case CBCentralManagerStateUnknown:
NSLog(@"CBCentralManagerStateUnknown");
break;
}
//搜索到藍牙設備之后調(diào)用
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
{
//一次返回一個設備信息 RSSI為信號強度宋梧,可以將信息放入數(shù)組中
//peripheral.identifier.UUIDString 藍牙設備的唯一標識
}
//連接設備
[self.mgr connectPeripheral:peripheral options:@{CBConnectPeripheralOptionNotifyOnDisconnectionKey:@(YES)}];
[self.manager stopScan];//停止掃描外設
//連接外圍設備之后調(diào)用
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
// 1.掃描所有的服務
// serviceUUIDs:指定要掃描該外圍設備的哪些服務(傳nil,掃描所有的服務)
[peripheral discoverServices:nil];
// 2.設置代理芜茵,為了后面查詢外設的服務和外設的特性
//<CBPeripheralDelegate>協(xié)議
peripheral.delegate = self;
}
- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(nullable NSError *)error
{
//連接失敗調(diào)用
NSLog(@"didFailToConnectPeripheral");
}
//遵循<CBPeripheralDelegate>協(xié)議
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
{
//發(fā)現(xiàn)外圍設備的服務
for (CBService *serivce in peripheral.services) {
if ([serivce.UUID.UUIDString isEqualToString:@"123456"]) {
// characteristicUUIDs : 可以指定想要掃描的特征(傳nil,掃描所有的特征)
[peripheral discoverCharacteristics:nil forService:serivce];
}
}
}
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
{
//發(fā)現(xiàn)服務后硫狞,當掃描到服務的特征時調(diào)用
for (CBCharacteristic *characteristic in service.characteristics) {
if ([characteristic.UUID.UUIDString isEqualToString:@"456"]) {
// 拿到特征,和外圍設備進行交互
CBCharacteristicProperties proper = characteristic.properties;
if (proper & CBCharacteristicPropertyBroadcast){} //廣播特性
if (proper & CBCharacteristicPropertyRead){
//讀特性
[peripheral readValueForCharacteristic:characteristic];
}
if (proper & CBCharacteristicPropertyWriteWithoutResponse){
//寫特性不需要響應烛卧,可以保存特征以便后續(xù)寫數(shù)據(jù)
}
if (properties & CBCharacteristicPropertyWrite) {
//如果具備寫入值的特性,這個應該會有一些響應
}
if (properties & CBCharacteristicPropertyNotify) {
//如果具備通知的特性
[peripheral setNotifyValue:YES forCharacteristic:character];
}
}
}
}
//通知代理
- (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(nonnull CBCharacteristic *)characteristic error:(nullable NSError *)error
{
CBCharacteristicProperties properties = characteristic.properties;
if (properties & CBCharacteristicPropertyRead) {
//如果具備讀特性验辞,即可以讀取特性的value
[peripheral readValueForCharacteristic:characteristic];
}
}
//讀取特性中的值調(diào)用
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
NSData *data = characteristic.value;
if (data.length <= 0) {
return;
}
NSString *info = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}
//往設備寫數(shù)據(jù)
[peripheral writeValue: data forCharacteristic: chatacter type:CBCharacteristicWriteWithoutResponse];
//取消與設備連接
[self.manager cancelPeripheralConnection:peripheral];
//斷開連接的代理
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(nullable NSError *)error;