连接两个BLE外设的流程是什么样的?

时间:2016-01-22 11:53:47

标签: ios swift core-bluetooth

我在论坛上一直在阅读很多帖子,我看到了很多与我的案例相关的帖子。但是我仍然没有找到我想要的清晰度。

我想连接到两个CBPeripherals并将数据写入其中。根据我的阅读,我认为在连接第二个设备之前,我必须断开当前的外围设备。好吧,假设我要在其中一个外设上写命令,然后我想向另一个写另一个命令,我是否必须断开与当前外设的连接?如果我断开连接到另一个,前一个命令是否仍然有效? iOS上最好的做法是什么?

1 个答案:

答案 0 :(得分:2)

我的蓝牙朋友,首先,如果您想发送这两个消息,则无需断开当前的外围设备以连接另一个外围设备。但是许多应用程序将连接设备(CBPeripheral)的数量限制为5-10,因为超过5-10个连接设备可能会自发丢失,我对它有点了解(我只使用4个设备)。例如:

[[RKCentralManager sharedManager] scanForPeripheralsWithServices:nil options:@{CBCentralManagerScanOptionAllowDuplicatesKey:@NO}  onUpdated:^(RKPeripheral *peripheral)
{
  //first of all u should start a scan

  [[RKCentralManager sharedManager] connectPeripheral: peripheral options:nil onFinished:^(RKPeripheral * connectedperipheral, NSError *error) 
     {
      //after u can connect to Peripheral immediately

         [connectedperipheral discoverServices:nil onFinish:^(NSError *error) 
         {
           // services - a collection of data and associated behaviors for accomplishing a function or feature of a device

              [connectedperipheral discoverCharacteristics:nil forService: [connectedperipheral.services lastObject] onFinish:^(CBService *service, NSError *error) 
              {
                //after u should take a characteristic - Represents a service's characteristic
                CBCharacteristic * characteristic = service.characteristics[0];

                //and at last u can write value in characteristic in which you are going to write down something
                 NSData * data = [NSData  dataWithHexString: newstring];
                 CBCharacteristicWriteType type = CBCharacteristicWriteWithoutResponse;
                 [connectedperipheral writeValue:data forCharacteristic:characteristic type:type onFinish:nil];

              }];

         }];

     }];

}];

为蓝牙设备发送消息的近似方案,不必对方法进行投资,可以在行动中分发。

您不必担心连接和发送数据  对于多个设备,因为它适用于CBCentralManager,如果你正确使用它。

CBCentralManager对象用于管理已发现或连接的远程外围设备(由CBPeripheral对象表示),包括扫描,发现和连接广告外围设备。

您可以立即连接某些设备并向其发送消息,一切正常。 如果您有疑问,请尝试回答。

这是一个很好的例子,你可以看到它的工作原理:https://github.com/ruiking/ble

关于设备的最大数量https://stackoverflow.com/a/17282862/4912496

相关问题