溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

iOS藍牙開發(fā)數(shù)據(jù)實時傳輸

發(fā)布時間:2020-09-21 01:35:06 來源:腳本之家 閱讀:240 作者:畫個大餅 欄目:移動開發(fā)

隨著iOS項目開發(fā)  很多app需要通過藍牙與設(shè)備連接

藍牙開發(fā)注意:

先定義中心設(shè)備和外圍設(shè)備以及遵守藍牙協(xié)議

@interface ViewController()<CBCentralManagerDelegate,CBPeripheralDelegate>
@property (strong, nonatomic) CBCentralManager *manager;
@property (nonatomic, strong) CBPeripheral *peripheral;
 
@property (nonatomic, weak)NSTimer * connentTimer;
 
@end

再實現(xiàn)delegate方法

1.判斷藍牙狀態(tài),如成功則掃描指定UUID設(shè)備(如不指定UUID,則無法后臺持續(xù)連接)
2.當發(fā)現(xiàn)指定設(shè)備后,連接該設(shè)備
3.當連接指定外圍設(shè)備成功,編寫定時器,每秒讀取1次RSSI
4.當監(jiān)聽到失去和外圍設(shè)備連接,重新建立連接
5.當讀取到RSSI值,打印出它的值

//藍牙狀態(tài)
- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
  NSString * state = nil;
  switch ([central state])
  {
    case CBCentralManagerStateUnsupported:
      state = @"The platform/hardware doesn't support Bluetooth Low Energy.";
      break;
   //應(yīng)用程序沒有被授權(quán)使用藍牙
    case CBCentralManagerStateUnauthorized:
      state = @"The app is not authorized to use Bluetooth Low Energy.";
      break;
       //尚未打開藍牙
    case CBCentralManagerStatePoweredOff:
      state = @"Bluetooth is currently powered off.";
      break;
       //連接成功
    case CBCentralManagerStatePoweredOn:
      [self.manager scanForPeripheralsWithServices:nil options:nil];
      state = @"work";
      break;
    case CBCentralManagerStateUnknown:
    default:
      ;
  }
  
  NSLog(@"Central manager state: %@", state);
}
//查找設(shè)備
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
{
   //每個藍牙設(shè)備有自己唯一的標識符,根據(jù)標識符確認自己要連接的設(shè)備
  if ([peripheral.identifier isEqual:self.peripheral.identifier])
  {
    self.peripheral = peripheral;
    //數(shù)據(jù)連接定時器
    self.connentTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(connentPeripheral) userInfo:@"timer" repeats:YES];
    [self.connentTimer fire];
  }
}
 
- (void)connentPeripheral {
  //連接外設(shè)
  self.manager.delegate = self;
  [self.manager connectPeripheral:_peripheral options:[NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:CBConnectPeripheralOptionNotifyOnDisconnectionKey]];
 
}
 
//連接成功后調(diào)用
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
  NSLog(@"Did connect to peripheral: %@,%@", peripheral,peripheral.name);
  [peripheral setDelegate:self]; //查找服務(wù)
  [peripheral discoverServices:nil];
  [self.connentTimer invalidate];
  //監(jiān)測設(shè)備是否斷開了
//  [self createWorkDataSourceWithTimeInterval:1];
}
//當監(jiān)聽到失去和外圍設(shè)備連接,重新建立連接
//這個方法是必須實現(xiàn)的,因為藍牙會中斷連接,正好觸發(fā)這個方法重建連接。重建連接可能造成數(shù)秒后才能讀取到RSSI。
 
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
  [self.manager connectPeripheral:peripheral options:nil];
}
 
- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
  NSLog(@"%@",error.description);
}
 
//返回的藍牙服務(wù)通知通過代理實現(xiàn)
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
{
  if (error)
  {
    NSLog(@"Discovered services for %@ with error: %@", peripheral.name, [error localizedDescription]);
    return;
  }
  for (CBService *service in peripheral.services)
  {
//    NSLog(@"Service found with UUID: %@", service.UUID.UUIDString);
    //發(fā)現(xiàn)服務(wù)
    if ([service.UUID isEqual:[CBUUID UUIDWithString:@"180D"]])//heart rate
    {
      //在一個服務(wù)中尋找特征值
      [peripheral discoverCharacteristics:nil forService:service];
    }
  }
}
 
//返回的藍牙特征值通知通過代理實現(xiàn)
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
{
  if (error)
  {
    NSLog(@"Discovered characteristics for %@ with error: %@", service.UUID, [error localizedDescription]);
    return;
  }
  for (CBCharacteristic * characteristic in service.characteristics)
  {
    NSLog(@"characteristic:%@",characteristic);
    if( [characteristic.UUID isEqual:[CBUUID UUIDWithString:@"2A37"]])
    {
      
      [self notification:service.UUID characteristicUUID:characteristic.UUID peripheral:peripheral on:YES];
//      [self.peripheral setNotifyValue:YES forCharacteristic:characteristic];
    }
  }
}
 
//處理藍牙發(fā)過來的數(shù)據(jù)
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
 
}
 
-(void) notification:(CBUUID *) serviceUUID characteristicUUID:(CBUUID *)characteristicUUID peripheral:(CBPeripheral *)p on:(BOOL)on
{
  CBService *service = [self getServiceFromUUID:serviceUUID p:p];
  if (!service)
  {
    //    if (p.UUID == NULL) return; // zach ios6 addedche
    //    NSLog(@"Could not find service with UUID on peripheral with UUID \n");
    return;
  }
  CBCharacteristic *characteristic = [self getCharacteristicFromUUID:characteristicUUID service:service];
  if (!characteristic)
  {
    //    if (p.UUID == NULL) return; // zach ios6 added
    //    NSLog(@"Could not find characteristic with UUID on service with UUID on peripheral with UUID\n");
    return;
  }
  [p setNotifyValue:on forCharacteristic:characteristic];
  
}
 
-(CBService *) getServiceFromUUID:(CBUUID *)UUID p:(CBPeripheral *)p
{
  
  for (CBService* s in p.services)
  {
    if ([s.UUID isEqual:UUID]) return s;
  }
  return nil; //Service not found on this peripheral
}
-(CBCharacteristic *) getCharacteristicFromUUID:(CBUUID *)UUID service:(CBService*)service {
  
  for (CBCharacteristic* c in service.characteristics)
  {
    if ([c.UUID isEqual:UUID]) return c;
  }
  return nil; //Characteristic not found on this service
}

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持億速云。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI