【问题标题】:iOS/Objective-C: BLE in Peripheral mode doesn't workiOS/Objective-C:外设模式下的 BLE 不起作用
【发布时间】:2017-08-02 00:38:58
【问题描述】:

我正在尝试在 CentralPeripheral 模式下启动 BLE。为了简单起见,现在使用硬编码变量。
我想我已经根据文档实现了一切。

我可以使用 Android 智能手机检查外设模式是否正常工作(api-19,不支持外设模式)。例如,当我使用 MyBeacon 应用程序时,iPhone 会正确显示。

但是当我在我的应用程序中运行此代码时它没有显示:

这里是.h

#import <RCTBridgeModule.h>
#import <RCTEventEmitter.h>
@import CoreBluetooth;
@import QuartzCore;

@interface BTManager : RCTEventEmitter <RCTBridgeModule, CBCentralManagerDelegate, CBPeripheralManagerDelegate, CBPeripheralDelegate>

@property (nonatomic, strong) CBCentralManager *centralManager;
@property (nonatomic, strong) CBPeripheralManager *peripheralManager;
@property (nonatomic, strong) CBMutableCharacteristic *transferCharacteristic;

@end

还有.m

#import "BTManager.h"

@implementation BTManager

RCT_EXPORT_MODULE();

- (NSArray<NSString *> *)supportedEvents
{
  return @[@"BTManagerDeviceFound", @"BTManagerStatus"];
}

- (void)viewDidLoad
{
  CBCentralManager *centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
  self.centralManager = centralManager;
  CBPeripheralManager *peripheralManager = [[CBPeripheralManager alloc] initWithDelegate:self queue:nil];
  self.peripheralManager = peripheralManager;
}

RCT_EXPORT_METHOD(start:(NSDictionary *)options)
{

  [self.centralManager scanForPeripheralsWithServices:nil options:nil];

  self.transferCharacteristic = [[CBMutableCharacteristic alloc] initWithType:[CBUUID UUIDWithString:@"EB6727C4-F184-497A-A656-76B0CDAC633A"] properties:CBCharacteristicPropertyRead value:nil permissions:CBAttributePermissionsReadable];

  CBMutableService *transferService = [[CBMutableService alloc] initWithType:[CBUUID UUIDWithString:@"EB6727C4-F184-497A-A656-76B0CDAC633A"] primary:YES];

  transferService.characteristics = @[self.transferCharacteristic];

  [self.peripheralManager addService:transferService];

  [self.peripheralManager startAdvertising:@{ CBAdvertisementDataServiceUUIDsKey : @[[CBUUID UUIDWithString:@"FB694B90-F49E-4597-8306-171BBA78F846"]] }];

  NSLog(@"Started");
}

- (void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral {
  // log peripheralManager state
  NSLog(@"peripheralManagerDidUpdateState peripheral %@", peripheral);
}

- (void)peripheralManager:(CBPeripheralManager *)peripheral didAddService:(CBService *)service error:(NSError *)error
{
  // log centralManager state
  NSLog(@"peripheralManager didAddService peripheral %@", peripheral);
  NSLog(@"peripheralManager didAddService service %@", service);
  NSLog(@"peripheralManager didAddService error %@", error);
}

- (void)peripheralManagerDidStartAdvertising:(CBPeripheralManager *)peripheral error:(NSError *)error
{
  NSLog(@"peripheralManagerDidStartAdvertising peripheral %@", peripheral);
  NSLog(@"peripheralManagerDidStartAdvertising error %@", error);
}

- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
{
  [self sendEventWithName:@"BTManagerDeviceFound" body:advertisementData];
}

- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
  NSLog(@"centralManagerDidUpdateState central %@", central);
}

RCT_EXPORT_METHOD(stop:(NSDictionary *)options)
{
  // remove all related processes, send event to js
  [self sendEventWithName:@"BTManagerStatus" body:@"details here"];
  //  [self.myCentralManager stopScan];
}

@end

除了NSLog(@"Started");之外,上面的事件监听器都没有被触发

我有这个建议:

在相关主题上,确保创建和执行 BTManager 的任何代码都允许对象存在足够长的时间以执行蓝牙操作。如果它超出范围或被垃圾收集,您将遇到同样的问题。

我不知道如何检查这是不是真的。

另外,this tutorial 正在使用这种方法:

- (void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral {
    if (peripheral.state != CBPeripheralManagerStatePoweredOn) {
        return;
    }

    if (peripheral.state == CBPeripheralManagerStatePoweredOn) {
        self.transferCharacteristic = [[CBMutableCharacteristic alloc] initWithType:[CBUUID UUIDWithString:TRANSFER_CHARACTERISTIC_UUID] properties:CBCharacteristicPropertyNotify value:nil permissions:CBAttributePermissionsReadable];

        CBMutableService *transferService = [[CBMutableService alloc] initWithType:[CBUUID UUIDWithString:TRANSFER_SERVICE_UUID] primary:YES];

        transferService.characteristics = @[_transferCharacteristic];

        [_peripheralManager addService:transferService];
    }
}

...但docs 不包含与此CBPeripheralManagerStatePoweredOn 相关的任何内容。这篇文章已有 4 年的历史了,所以它现在可能甚至不相关。

哦,是的,而且我对objective-c几乎不熟悉,所以那里的错误可能很简单。

感谢您阅读到这里 :)

更新 1

显然,viewDidLoad 从未被启动。因此,正如@LarsBlumberg 建议的那样,我将代码从它移到了start 方法,并将代码从start 移到了...DidUpdateStates 方法中。

#import "BTManager.h"
#import <React/RCTLog.h>

@implementation BTManager

RCT_EXPORT_MODULE();

- (NSArray<NSString *> *)supportedEvents
{
  return @[@"BTManagerDeviceFound", @"BTManagerStatus"];
}

RCT_EXPORT_METHOD(start:(NSDictionary *)options)
{
  RCTLogInfo(@"Start?");
  CBCentralManager *centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil options:@{CBCentralManagerOptionShowPowerAlertKey: @(YES)}];
  self.centralManager = centralManager;
  CBPeripheralManager *peripheralManager = [[CBPeripheralManager alloc] initWithDelegate:self queue:nil];
  self.peripheralManager = peripheralManager;
  RCTLogInfo(@"Started");
}

- (void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral {
  // log peripheralManager state
  RCTLogInfo(@"peripheralManagerDidUpdateState peripheral %ld", (long)peripheral.state);
  if (peripheral.state != CBPeripheralManagerStatePoweredOn) {
    RCTLogInfo(@"Peripheral is not powered on");
    return;
  }
  self.transferCharacteristic = [[CBMutableCharacteristic alloc] initWithType:[CBUUID UUIDWithString:@"EB6727C4-F184-497A-A656-76B0CDAC633A"] properties:CBCharacteristicPropertyRead value:nil permissions:CBAttributePermissionsReadable];

  CBMutableService *transferService = [[CBMutableService alloc] initWithType:[CBUUID UUIDWithString:@"EB6727C4-F184-497A-A656-76B0CDAC633A"] primary:YES];

  transferService.characteristics = @[self.transferCharacteristic];

  [peripheral addService:transferService];

  NSDictionary *advertisingData = @{CBAdvertisementDataLocalNameKey : @"yphone", CBAdvertisementDataServiceUUIDsKey : @[[CBUUID UUIDWithString:@"EBA38950-0D9B-4DBA-B0DF-BC7196DD44FC"]]};
  [peripheral startAdvertising:advertisingData];
}

- (void)peripheralManager:(CBPeripheralManager *)peripheral didAddService:(CBService *)service error:(NSError *)error
{
  // log centralManager state
  RCTLogInfo(@"peripheralManager didAddService peripheral %@", peripheral);
  RCTLogInfo(@"peripheralManager didAddService service %@", service);
  RCTLogInfo(@"peripheralManager didAddService error %@", error);
}

- (void)peripheralManagerDidStartAdvertising:(CBPeripheralManager *)peripheral error:(NSError *)error
{
  RCTLogInfo(@"peripheralManagerDidStartAdvertising peripheral %@", peripheral);
  RCTLogInfo(@"peripheralManagerDidStartAdvertising error %@", error);
}

- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
{
  [self sendEventWithName:@"BTManagerDeviceFound" body:advertisementData];
}

- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
  RCTLogInfo(@"centralManagerDidUpdateState central %ld", (long)central.state);
  // if (central.state == CBCentralManagerStatePoweredOff) {
  //   UIAlertView *alert = [[UIAlertView alloc] initWithTitle: @"Error" message: @"Please turn on Bluetooth in Settings" delegate: nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; 
  //   [alert show]; 
  // }
  if (central.state != CBCentralManagerStatePoweredOn) {
    RCTLogInfo(@"Central is not powered on");
    return;
  }
  [central scanForPeripheralsWithServices:nil options:nil];
}

RCT_EXPORT_METHOD(stop:(NSDictionary *)options)
{
  // remove all related processes, send event to js
  [self sendEventWithName:@"BTManagerStatus" body:@"details here"];
  //  [self.myCentralManager stopScan];
}

@end

现在一切正常,直到状态更新。 central.stateperipheral.state 返回 4,而 CB...ManagerStatePoweredOn 等于 5。我如何使它等于5?应用程序正在请求访问 bt,但 iphone 未启用它。手动启用后,一切似乎都运行良好。

【问题讨论】:

    标签: ios objective-c bluetooth react-native bluetooth-lowenergy


    【解决方案1】:

    您可能太早将服务transferService 添加到外围管理器,并且您也可能太早开始广告。

    您必须等待直到peripheralManagerDidUpdateState 报告您的外设管理器的状态已达到CBPeripheralManagerStatePoweredOn

    也就是说,您可以将代码从 RCT_EXPORT_METHOD(start:(NSDictionary *)options) 移动到空的 peripheralManagerDidUpdateState 实现中。

    或者,如果您只想将服务添加到您的 peripheralManager,然后在有人调用您的 start 方法时开始做广告(看起来您正在创建 React Native 绑定?),请确保 self.peripheralManager.stateCBPeripheralManagerStatePoweredOn 在您的 start 方法中。但是,这需要start(您的 React Native JS 代码)的调用者不要过早调用此方法。

    RCT_EXPORT_METHOD(start:(NSDictionary *)options)
    {
      NSLog(@"Start?");
      if (self.peripheralManager.state != CBPeripheralManagerStatePoweredOn) {
          NSLog(@"Peripheral is not powered on");
          return;
      }
      if (self.centralManager.state != CBCentralManagerStatePoweredOn) {
          NSLog(@"Central is not powered on");
          return;
      }
      NSLog(@"OK, peripheral and central are both powered on");
      [self.centralManager scanForPeripheralsWithServices:nil options:nil];
    
      self.transferCharacteristic = [[CBMutableCharacteristic alloc] initWithType:[CBUUID UUIDWithString:@"EB6727C4-F184-497A-A656-76B0CDAC633A"] properties:CBCharacteristicPropertyRead value:nil permissions:CBAttributePermissionsReadable];
    
      CBMutableService *transferService = [[CBMutableService alloc] initWithType:[CBUUID UUIDWithString:@"EB6727C4-F184-497A-A656-76B0CDAC633A"] primary:YES];
    
      transferService.characteristics = @[self.transferCharacteristic];
    
      [self.peripheralManager addService:transferService];
    
      [self.peripheralManager startAdvertising:@{ CBAdvertisementDataServiceUUIDsKey : @[[CBUUID UUIDWithString:@"FB694B90-F49E-4597-8306-171BBA78F846"]] }];
    
      NSLog(@"Started");
    }
    

    同样,如果您的 centralManager 处于“开机”状态,您只能开始扫描外围设备。

    【讨论】:

      【解决方案2】:

      显然,在 iOS 中无法以编程方式打开蓝牙,而且目前无法以编程方式进行配对。

      但是,我们可以通过如下 RCT_EXPORT_METHOD(start:(NSDictionary *)options) 方法中的警报提示用户打开蓝牙。

      if(peripheralManager.state < CBPeripheralManagerStatePoweredOn){
      {
           //Show alert to user to turn on the Bluetooth and it will go to 
             peripheralManagerDidUpdateState when user turn it on.
      }
      else
      {
           //You can continue setting up the data.
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-12-30
        • 1970-01-01
        • 2014-11-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多