GVKun编程网logo

IOS 与 OSX BLE:实例化 CBCentralManager - 为 iOS 编码

2

对于IOS与OSXBLE:实例化CBCentralManager-为iOS编码感兴趣的读者,本文将提供您所需要的所有信息,并且为您提供关于AndroidBLEApp只能订阅1个BLE设备的特性通知、A

对于IOS 与 OSX BLE:实例化 CBCentralManager - 为 iOS 编码感兴趣的读者,本文将提供您所需要的所有信息,并且为您提供关于Android BLE App 只能订阅 1 个 BLE 设备的特性通知、Android BLE:连接和订阅 2 个 BLE 外围设备的特征通知、BLE 设备在通过 iOS 上的免提配置文件呼叫时断开连接,原因为 722 步骤系统诊断日志、bleManager.startDeviceScan 不适用于 iOS react-native-ble-plx的宝贵知识。

本文目录一览:

IOS 与 OSX BLE:实例化 CBCentralManager - 为 iOS 编码

IOS 与 OSX BLE:实例化 CBCentralManager - 为 iOS 编码

如何解决IOS 与 OSX BLE:实例化 CBCentralManager - 为 iOS 编码

我正在学习 iOS 与 OSX BLE。
我注意到我无法在 iOS 中实例化 CBCentralManager 因为:

[CoreBluetooth] xpc connection invalid
Unsupported

与通过 OSX 相比,因为 iOS 平台没有“应用沙盒”特性,我可以在其中设置为 BLE 使用。

这是我的 iOS 代码:

import SwiftUI

struct ContentView: View {
    @Observedobject var bleManager = BLEManager()

    var body: some View {
        ZStack {
            Color("Background")
            Text("Hello")
        }
    }
}

class BLEManager: NSObject,ObservableObject,CBCentralManagerDelegate {
    var centralManager: CBCentralManager!

    override init() {
        super.init()
        centralManager = CBCentralManager(delegate: self,queue: nil)
    }

    public func centralManagerDidUpdateState(_ central: CBCentralManager) {
        switch central.state {
        case .poweredOn:
            print("power is on")

        case .resetting:
            print("Resetting")
        case .unsupported:
            print("Unsupported")
        case .unauthorized:
            print("UnAuthorized")
        case .unkNown:
            print("UnKNown")
        case .poweredOff:
            print("Powered OFF")
        @unkNown default:
            print("**** Default ****")
        }
    }
}

这是必需的 .plist 条目:

enter image description here

我知道 iPhone 可以是 BLE 中心或外围设备。

简单问题:如何为真正的 iOS CBCentralMaster 编码?

我只是在这里采取一些小步骤:为外围检测编码。
...然后从那里继续。

解决方法

您是在模拟器上运行(不受支持)而不是在设备上运行?

,

查看主要的 Core Bluetooth 文档:

如果它的 Info.plist 不包含它需要访问的数据类型的使用说明键,你的应用就会崩溃。要访问 iOS 13 或之后链接的应用程序上的核心蓝牙 API,请包含 NSBluetoothAlwaysUsageDescription 键。在 iOS 12 及更早版本中,包含 NSBluetoothPeripheralUsageDescription 以访问蓝牙外设数据。

Android BLE App 只能订阅 1 个 BLE 设备的特性通知

Android BLE App 只能订阅 1 个 BLE 设备的特性通知

如何解决Android BLE App 只能订阅 1 个 BLE 设备的特性通知

我是 Android 新手。我正在尝试从 2 个 BLE 设备订阅特征通知。现在,我的应用程序只能从第一个设备接收 BLE 数据。 我知道 BLE 是串行通信,所以我必须等到 onDescriptorWrite() 回调被调用,然后才能为第二个设备启用通知。我们每次只能有 1 个 GATT 操作。 我的问题是:

  1. 如何修改onDescriptorWrite()Thread.sleep() 延迟方法没有帮助。

  2. 有些人提到使用队列来添加/删除某些东西?

    1. public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic,boolean enabled,int device) {
    2. if (mBluetoothAdapter == null || mBluetoothGatt == null || mBluetoothGatt1 == null) {
    3. Log.e(TAG,"BluetoothAdapter not initialized");
    4. return;
    5. }
    6. if(device == 0) {
    7. mBluetoothGatt.setCharacteristicNotification(characteristic,enabled);
    8. BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUID.fromString(SampleGattAttributes.CLIENT_CHaraCTERISTIC_CONfig));
    9. descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
    10. mBluetoothGatt.writeDescriptor(descriptor);
    11. try {
    12. Thread.sleep(100);
    13. } catch (InterruptedException e) {
    14. e.printstacktrace();
    15. }
    16. Log.e(TAG,"Device #0 is done for notification!");
    17. }
    18. else if(device == 1){
    19. mBluetoothGatt1.setCharacteristicNotification(characteristic,"Device #1 is done for notification!");
    20. }

    }

    1. private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
    2. @Override
    3. public void onConnectionStateChange(BluetoothGatt gatt,int status,int newState) {
    4. String intentAction;
    5. if (newState == BluetoothProfile.STATE_CONNECTED) {
    6. intentAction = ACTION_GATT_CONNECTED;
    7. mConnectionState = STATE_CONNECTED;
    8. broadcastUpdate(intentAction);
    9. Log.e(TAG,"Connected to GATT server #0.");
    10. // Attempts to discover services after successful connection.
    11. Log.e(TAG,"Attempting to start service discovery #0:" + mBluetoothGatt.discoverServices());
    12. } else if (newState == BluetoothProfile.STATE_disCONNECTED) {
    13. intentAction = ACTION_GATT_disCONNECTED;
    14. mConnectionState = STATE_disCONNECTED;
    15. Log.e(TAG,"disconnected from GATT server #0.");
    16. broadcastUpdate(intentAction);
    17. }
    18. }
    19. @Override
    20. public void onServicesdiscovered(BluetoothGatt gatt,int status) {
    21. if (status == BluetoothGatt.GATT_SUCCESS) {
    22. broadcastUpdate(ACTION_GATT_SERVICES_disCOVERED);
    23. } else {
    24. Log.e(TAG,"onServicesdiscovered received: " + status);
    25. }
    26. }
    27. @Override
    28. public void onCharacteristicRead(BluetoothGatt gatt,BluetoothGattCharacteristic characteristic,int status) {
    29. if (status == BluetoothGatt.GATT_SUCCESS) {
    30. broadcastUpdate(ACTION_DATA_AVAILABLE,characteristic,0);
    31. }
    32. try {
    33. Thread.sleep(700);
    34. }catch(InterruptedException ex) {
    35. Thread.currentThread().interrupt();
    36. }
    37. Log.e(TAG,"onCHAR READ");
    38. }
    39. @Override
    40. public void onCharacteristicChanged(BluetoothGatt gatt,BluetoothGattCharacteristic characteristic) {
    41. broadcastUpdate(ACTION_DATA_AVAILABLE,0);
    42. try {
    43. Thread.sleep(700);
    44. }catch(InterruptedException ex) {
    45. Thread.currentThread().interrupt();
    46. }
    47. Log.e(TAG,"onCharacteristicChanged #0 = ACTION_DATA_AVAILABLE,Done! ");
    48. }
    49. @Override
    50. public void onDescriptorWrite(BluetoothGatt gatt,BluetoothGattDescriptor descriptor,int status) {
    51. super.onDescriptorWrite(gatt,descriptor,status);
    52. // Do something here ????????????
    53. // Thread.sleep() delay method doesn''t help
    54. try {
    55. Thread.sleep(700);
    56. }catch(InterruptedException ex) {
    57. Thread.currentThread().interrupt();
    58. }
    59. Log.e(TAG,"onDescriptorWrite #0,Done! ");
    60. }

    };

解决方法

  1. mBluetoothGatt1.setCharacteristicNotification(characteristic,enabled);
  2. BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUID.fromString(SampleGattAttributes.CLIENT_CHARACTERISTIC_CONFIG));
  3. descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
  4. mBluetoothGatt.writeDescriptor(descriptor);

我认为应该是:

  1. mBluetoothGatt1.setCharacteristicNotification(characteristic,enabled);
  2. BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUID.fromString(SampleGattAttributes.CLIENT_CHARACTERISTIC_CONFIG));
  3. descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
  4. mBluetoothGatt1.writeDescriptor(descriptor);

Android BLE:连接和订阅 2 个 BLE 外围设备的特征通知

Android BLE:连接和订阅 2 个 BLE 外围设备的特征通知

如何解决Android BLE:连接和订阅 2 个 BLE 外围设备的特征通知

我使用了两个 BLE 外围传感器和 1 个手机(中央)。每个 BLE 外围设备都运行良好(单独测试)。

我遵循了 BluetoothLeGatt> 示例。我的手机是HUAWEI Mate 10,使用Android 10版本,支持BLE 4.2。

在我的 Android BLE 应用程序中,按下第一页上的连接按钮后,应用程序将自动连接到名称为“BC805M BLE ADC1”和“BC805M BLE ADC2”的 2 个 BLE 设备。

该应用程序似乎可以成功连接 2 个 BLE 设备。但是,没有收到数据(订阅特征通知失败)。 BluetoothGattCallback.onCharacteristicChanged() 方法永远不会被触发。因此,该操作永远不会变为“ACTION_DATA_AVAILABLE”。

BLE App screenshot 1

BLE App screenshot 2

我知道 BLE 通信是串行的。有些人建议在 BluetoothGattCallback() 中使用“onDescriptorWrite()”。但是,我不完全了解如何做到这一点。我在这里附上了我的 Android Studio 项目。如果有人能找到问题,我们将不胜感激。

  1. public class DeviceControlActivity extends Activity {
  2. private final static String TAG = DeviceControlActivity.class.getSimpleName();
  3. public static final String EXTRAS_DEVICE_NAME = "DEVICE_NAME";
  4. public static final String EXTRAS_DEVICE_ADDRESS = "DEVICE_ADDRESS";
  5. public static final String NUMBER_OF_DEVICE = "NUMBER OF DEVICE";
  6. public static final String EXTRAS_DEVICE_NAME_1 = "DEVICE_NAME1";
  7. public static final String EXTRAS_DEVICE_ADDRESS_1 = "DEVICE_ADDRESS1";
  8. public static final String NUMBER_OF_DEVICE_1 = "NUMBER OF DEVICE1";
  9. private TextView mConnectionState;
  10. private TextView mdatafield;
  11. private TextView mThumb;
  12. private TextView mIndex;
  13. private TextView mThumb1;
  14. private TextView mIndex1;
  15. private String mDeviceName;
  16. private String mDeviceAddress;
  17. private String mDeviceName1;
  18. private String mDeviceAddress1;
  19. private int DEVICE_NUMBER;
  20. private int DEVICE_NUMBER1;
  21. private int TOTAL_DEVICE;
  22. private BluetoothLeService mBluetoothLeService;
  23. private ArrayList<ArrayList<BluetoothGattCharacteristic>> mGattcharacteristics =
  24. new ArrayList<ArrayList<BluetoothGattCharacteristic>>();
  25. private ArrayList<ArrayList<BluetoothGattCharacteristic>> mGattcharacteristics1 =
  26. new ArrayList<ArrayList<BluetoothGattCharacteristic>>();
  27. private boolean mConnected = false;
  28. private BluetoothGattCharacteristic mNotifyCharacteristic;
  29. private BluetoothGattCharacteristic mNotifyCharacteristic1;
  30. private final String ServiceUUID = "6e400001-b5a3-f393-e0a9-e50e24dcca9e";
  31. private final String CharUUID = "6e400003-b5a3-f393-e0a9-e50e24dcca9e";
  32. private final String LIST_NAME = "NAME";
  33. private final String LIST_UUID = "UUID";
  34. // Code to manage Service lifecycle.
  35. private final ServiceConnection mServiceConnection = new ServiceConnection() {
  36. @Override
  37. public void onServiceConnected(ComponentName componentName,IBinder service) {
  38. Log.d(TAG,"Service Connected Called");
  39. mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
  40. if (!mBluetoothLeService.initialize()) {
  41. finish();
  42. }
  43. mBluetoothLeService.connect(mDeviceAddress,0);
  44. mBluetoothLeService.connect(mDeviceAddress1,1);
  45. }
  46. @Override
  47. public void onServicedisconnected(ComponentName componentName) {
  48. Log.d(TAG,"Service disConnected Called");
  49. mBluetoothLeService = null;
  50. }
  51. };
  52. private final broadcastReceiver mGattUpdateReceiver = new broadcastReceiver() {
  53. @Override
  54. public void onReceive(Context context,Intent intent) {
  55. final String action = intent.getAction();
  56. if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
  57. mConnected = true;
  58. updateConnectionState(R.string.connected);
  59. invalidateOptionsMenu();
  60. Log.e(TAG,"ACTION_GATT_CONNECTED ");
  61. } else if (BluetoothLeService.ACTION_GATT_disCONNECTED.equals(action)) {
  62. Log.e(TAG,"WHEN IS ACTION GATT disCONNECTED");
  63. mConnected = false;
  64. updateConnectionState(R.string.disconnected);
  65. invalidateOptionsMenu();
  66. Log.e(TAG,"ACTION_GATT_disCONNECTED ");
  67. clearUI();
  68. } else if (BluetoothLeService.ACTION_GATT_SERVICES_disCOVERED.equals(action)) {
  69. Log.e(TAG,"ACTION_GATT_SERVICE_disCOVERED ");
  70. updateGattServices(mBluetoothLeService.getSupportedGattServices(0),0);
  71. try {
  72. Thread.sleep(700);
  73. }catch(InterruptedException ex) {
  74. Thread.currentThread().interrupt();
  75. }
  76. Log.e(TAG,"getSupportedGattServices() is done for device #0");
  77. updateGattServices(mBluetoothLeService.getSupportedGattServices(1),1);
  78. try {
  79. Thread.sleep(700);
  80. }catch(InterruptedException ex) {
  81. Thread.currentThread().interrupt();
  82. }
  83. Log.e(TAG,"getSupportedGattServices() is done for device #1");
  84. updateDATA();
  85. } else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
  86. Log.d(TAG,"ACTION_DATA_AVAILABLE ");
  87. mBluetoothLeService.readCharacteristic(mNotifyCharacteristic,0);
  88. displayData(intent.getStringExtra(BluetoothLeService.EXTRA_DATA),0);
  89. mBluetoothLeService.readCharacteristic(mNotifyCharacteristic1,1);
  90. displayData(intent.getStringExtra(BluetoothLeService.EXTRA_DATA1),1);
  91. }
  92. }
  93. };
  94. private final boolean updateDATA(){
  95. int servicePos = 0;
  96. int charPos = 0;
  97. if(mGattcharacteristics!=null&&mGattcharacteristics.size()!=0){
  98. final BluetoothGattCharacteristic characteristic = mGattcharacteristics.get(servicePos).get(charPos);
  99. final int charPro = characteristic.getProperties();
  100. if((charPro|BluetoothGattCharacteristic.PROPERTY_READ)>0){
  101. if(mNotifyCharacteristic!= null){
  102. mBluetoothLeService.setCharacteristicNotification(mNotifyCharacteristic,false,0);
  103. }
  104. }
  105. mBluetoothLeService.readCharacteristic(characteristic,0);
  106. if ((charPro | BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) {
  107. Log.d(TAG,"PROPER_NOTIFY > 0");
  108. Log.d(TAG," ");
  109. }
  110. return true;
  111. }
  112. return false;
  113. }
  114. private void clearUI() {
  115. mdatafield.setText(R.string.no_data);
  116. }
  117. @Override
  118. public void onCreate(Bundle savedInstanceState) {
  119. Log.e(TAG,"2.2 onCreate() starts! ");
  120. super.onCreate(savedInstanceState);
  121. setContentView(R.layout.gatt_services_characteristics);
  122. final Intent intent = getIntent();
  123. mDeviceName = intent.getStringExtra(EXTRAS_DEVICE_NAME);
  124. mDeviceAddress = intent.getStringExtra(EXTRAS_DEVICE_ADDRESS);
  125. mDeviceName1 = intent.getStringExtra(EXTRAS_DEVICE_NAME_1);
  126. mDeviceAddress1=intent.getStringExtra(EXTRAS_DEVICE_ADDRESS_1);
  127. DEVICE_NUMBER=intent.getIntExtra(NUMBER_OF_DEVICE,0);
  128. DEVICE_NUMBER1=intent.getIntExtra(NUMBER_OF_DEVICE_1,0);
  129. ((TextView) findViewById(R.id.device_address)).setText(mDeviceAddress+" AND "+mDeviceAddress1);
  130. mConnectionState = (TextView) findViewById(R.id.connection_state);
  131. mdatafield = (TextView) findViewById(R.id.data_value);
  132. mThumb = (TextView) findViewById(R.id.Thumb);
  133. mIndex = (TextView) findViewById(R.id.Index);
  134. mThumb1 = (TextView) findViewById(R.id.Thumb1);
  135. mIndex1 = (TextView) findViewById(R.id.Index1);
  136. Log.d(TAG,"MY DEVICE NAME "+mDeviceName);
  137. Log.d(TAG,"MY DEVICE ADDRESS "+mDeviceAddress);
  138. Log.d(TAG,"MY DEVICE NUMBER "+DEVICE_NUMBER);
  139. Log.d(TAG,"MY DEVICE NAME1 "+mDeviceName1);
  140. Log.d(TAG,"MY DEVICE ADDRESS1 "+mDeviceAddress1);
  141. Log.d(TAG,"MY DEVICE NUMBER1 "+DEVICE_NUMBER1);
  142. getActionBar().setTitle(mDeviceName+" "+mDeviceName1);
  143. getActionBar().setdisplayHomeAsUpEnabled(true);
  144. Intent gattServiceIntent = new Intent(this,BluetoothLeService.class);
  145. bindService(gattServiceIntent,mServiceConnection,BIND_AUTO_CREATE);
  146. }
  147. @Override
  148. protected void onResume() {
  149. Log.e(TAG,"2.2 onResume is Called");
  150. super.onResume();
  151. registerReceiver(mGattUpdateReceiver,makeGattUpdateIntentFilter());
  152. if (mBluetoothLeService != null) {
  153. boolean result = mBluetoothLeService.connect(mDeviceAddress,0);
  154. boolean result1 = mBluetoothLeService.connect(mDeviceAddress1,1);
  155. Log.d(TAG,"Connect request result = " + result+" "+result1);
  156. }
  157. }
  158. @Override
  159. protected void onPause() {
  160. Log.d(TAG,"onPause is called");
  161. super.onPause();
  162. unregisterReceiver(mGattUpdateReceiver);
  163. }
  164. @Override
  165. protected void onDestroy() {
  166. Log.d(TAG,"onDestroy is Called");
  167. super.onDestroy();
  168. unbindService(mServiceConnection);
  169. mBluetoothLeService = null;
  170. }
  171. @Override
  172. public boolean onCreateOptionsMenu(Menu menu) {
  173. getMenuInflater().inflate(R.menu.gatt_services,menu);
  174. if (mConnected) {
  175. menu.findItem(R.id.menu_connect).setVisible(false);
  176. menu.findItem(R.id.menu_disconnect).setVisible(true);
  177. } else {
  178. menu.findItem(R.id.menu_connect).setVisible(true);
  179. menu.findItem(R.id.menu_disconnect).setVisible(false);
  180. }
  181. return true;
  182. }
  183. @Override
  184. public boolean onoptionsItemSelected(MenuItem item) {
  185. switch(item.getItemId()) {
  186. case R.id.menu_connect:
  187. mBluetoothLeService.connect(mDeviceAddress,0);
  188. mBluetoothLeService.connect(mDeviceAddress1,1);
  189. return true;
  190. case R.id.menu_disconnect:
  191. Log.d(TAG,"FirsT DEVICE"+DEVICE_NUMBER);
  192. mBluetoothLeService.disconnect();
  193. return true;
  194. case android.R.id.home:
  195. Log.d(TAG,"HOME IS pressed");
  196. onBackpressed();
  197. return true;
  198. }
  199. return super.onoptionsItemSelected(item);
  200. }
  201. private void updateConnectionState(final int resourceId) {
  202. runOnUiThread(new Runnable() {
  203. @Override
  204. public void run() {
  205. mConnectionState.setText(resourceId);
  206. }
  207. });
  208. }
  209. private void displayData(String data,int device) {
  210. if (data != null && device ==0) {
  211. mThumb1.setText(data.substring(1,4));
  212. mIndex1.setText(data.substring(5,8));
  213. }
  214. else if(data != null && device == 1) {
  215. mThumb.setText(data.substring(1,4));
  216. mIndex.setText(data.substring(5,8));
  217. }
  218. }
  219. private void updateGattServices(List<BluetoothGattService> gattServices,int device) {
  220. if (gattServices == null) return;
  221. String uuid = null;
  222. String unkNownServiceString = getResources().getString(R.string.unkNown_service);
  223. String unkNownCharaString = getResources().getString(R.string.unkNown_characteristic);
  224. ArrayList<HashMap<String,String>> gattServiceData = new ArrayList<HashMap<String,String>>();
  225. if(device ==0) {
  226. mGattcharacteristics = new ArrayList<ArrayList<BluetoothGattCharacteristic>>();
  227. Log.e(TAG,"mGattcharacteristics is created for device #0");
  228. }
  229. else if(device ==1) {
  230. mGattcharacteristics1 = new ArrayList<ArrayList<BluetoothGattCharacteristic>>();
  231. Log.e(TAG,"mGattcharacteristics is created for device #1");
  232. }
  233. int i=0;
  234. int j=0;
  235. // Loops through available GATT Services.
  236. Log.e(TAG,"Start For Loop");
  237. for (BluetoothGattService gattService : gattServices) {
  238. Log.e(TAG,"Service index = " + i);
  239. HashMap<String,String> currentServiceData = new HashMap<String,String>();
  240. uuid = gattService.getUuid().toString();
  241. if(uuid.equals(ServiceUUID)) {
  242. Log.e(TAG,"Selected Service index = " + i);
  243. currentServiceData.put(LIST_NAME,SampleGattAttributes.lookup(uuid,unkNownServiceString));
  244. currentServiceData.put(LIST_UUID,"");
  245. gattServiceData.add(currentServiceData);
  246. ArrayList<HashMap<String,String>> gattCharacteristicGroupData = new ArrayList<HashMap<String,String>>();
  247. List<BluetoothGattCharacteristic> gattcharacteristics = gattService.getcharacteristics();
  248. ArrayList<BluetoothGattCharacteristic> charas = new ArrayList<BluetoothGattCharacteristic>();
  249. // Loops through available characteristics.
  250. for (BluetoothGattCharacteristic gattCharacteristic : gattcharacteristics) {
  251. Log.e(TAG,"Characteristic index = " + j);
  252. charas.add(gattCharacteristic);
  253. HashMap<String,String> currentCharaData = new HashMap<String,String>();
  254. uuid = gattCharacteristic.getUuid().toString();
  255. if(uuid.equals(CharUUID)) {
  256. Log.e(TAG,"Selected Characteristic index = " + j);
  257. currentCharaData.put(
  258. LIST_NAME,unkNownCharaString));
  259. currentCharaData.put(LIST_UUID,"");
  260. gattCharacteristicGroupData.add(currentCharaData);
  261. if(device ==0){
  262. mNotifyCharacteristic=gattCharacteristic;
  263. }
  264. else if(device ==1){
  265. mNotifyCharacteristic1=gattCharacteristic;
  266. }
  267. }
  268. j = j +1;
  269. }
  270. if(device ==0){
  271. mGattcharacteristics.add(charas);
  272. }
  273. else if(device ==1){
  274. mGattcharacteristics1.add(charas);
  275. }
  276. }
  277. i = i + 1 ;
  278. }
  279. }
  280. private static IntentFilter makeGattUpdateIntentFilter() {
  281. final IntentFilter intentFilter = new IntentFilter();
  282. intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED);
  283. intentFilter.addAction(BluetoothLeService.ACTION_GATT_disCONNECTED);
  284. intentFilter.addAction(BluetoothLeService.ACTION_GATT_SERVICES_disCOVERED);
  285. intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE);
  286. return intentFilter;
  287. }

}

  1. public class BluetoothLeService extends Service {
  2. private final static String TAG = BluetoothLeService.class.getSimpleName();
  3. private BluetoothManager mBluetoothManager;
  4. private BluetoothAdapter mBluetoothAdapter;
  5. private String mBluetoothDeviceAddress;
  6. private String mBluetoothDeviceAddress1;
  7. private BluetoothGatt mBluetoothGatt;
  8. private BluetoothGatt mBluetoothGatt1;
  9. private int mConnectionState = STATE_disCONNECTED;
  10. private static final int STATE_disCONNECTED = 0;
  11. private static final int STATE_CONNECTING = 1;
  12. private static final int STATE_CONNECTED = 2;
  13. public final static String ACTION_GATT_CONNECTED =
  14. "com.example.bluetooth.le.ACTION_GATT_CONNECTED";
  15. public final static String ACTION_GATT_disCONNECTED =
  16. "com.example.bluetooth.le.ACTION_GATT_disCONNECTED";
  17. public final static String ACTION_GATT_SERVICES_disCOVERED =
  18. "com.example.bluetooth.le.ACTION_GATT_SERVICES_disCOVERED";
  19. public final static String ACTION_DATA_AVAILABLE =
  20. "com.example.bluetooth.le.ACTION_DATA_AVAILABLE";
  21. public final static String EXTRA_DATA =
  22. "com.example.bluetooth.le.EXTRA_DATA";
  23. public final static String EXTRA_DATA1 =
  24. "com.example.bluetooth.le.EXTRA_DATA1";
  25. public final static UUID ServiceUUID2 = UUID.fromString("6e400001-b5a3-f393-e0a9-e50e24dcca9e");
  26. public final static UUID CharUUID2 = UUID.fromString("6e400003-b5a3-f393-e0a9-e50e24dcca9e");
  27. // Implements callback methods for GATT events that the app cares about. For example,// connection change and services discovered.
  28. private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
  29. @Override
  30. public void onConnectionStateChange(BluetoothGatt gatt,int status,int newState) {
  31. String intentAction;
  32. if (newState == BluetoothProfile.STATE_CONNECTED) {
  33. intentAction = ACTION_GATT_CONNECTED;
  34. mConnectionState = STATE_CONNECTED;
  35. broadcastUpdate(intentAction);
  36. Log.e(TAG,"Connected to GATT server.");
  37. // Attempts to discover services after successful connection.
  38. Log.e(TAG,"Attempting to start service discovery:" + mBluetoothGatt.discoverServices());
  39. } else if (newState == BluetoothProfile.STATE_disCONNECTED) {
  40. intentAction = ACTION_GATT_disCONNECTED;
  41. mConnectionState = STATE_disCONNECTED;
  42. Log.e(TAG,"disconnected from GATT server.");
  43. broadcastUpdate(intentAction);
  44. }
  45. }
  46. @Override
  47. public void onServicesdiscovered(BluetoothGatt gatt,int status) {
  48. if (status == BluetoothGatt.GATT_SUCCESS) {
  49. broadcastUpdate(ACTION_GATT_SERVICES_disCOVERED);
  50. } else {
  51. Log.e(TAG,"onServicesdiscovered received: " + status);
  52. }
  53. }
  54. @Override
  55. public void onCharacteristicRead(BluetoothGatt gatt,BluetoothGattCharacteristic characteristic,int status) {
  56. if (status == BluetoothGatt.GATT_SUCCESS) {
  57. broadcastUpdate(ACTION_DATA_AVAILABLE,characteristic,0);
  58. }
  59. Log.e(TAG,"onCHAR READ");
  60. }
  61. @Override
  62. public void onCharacteristicChanged(BluetoothGatt gatt,BluetoothGattCharacteristic characteristic) {
  63. broadcastUpdate(ACTION_DATA_AVAILABLE,0);
  64. Log.e(TAG,"onCharacteristicChanged #0 = ACTION_DATA_AVAILABLE,Done! ");
  65. }
  66. @Override
  67. public void onDescriptorWrite(BluetoothGatt gatt,BluetoothGattDescriptor descriptor,int status) {
  68. super.onDescriptorWrite(gatt,descriptor,status);
  69. Log.e(TAG,"onDescriptorWrite #0,Done! ");
  70. }
  71. };
  72. private final BluetoothGattCallback mGattCallback1 = new BluetoothGattCallback() {
  73. @Override
  74. public void onConnectionStateChange(BluetoothGatt gatt,"Connected to GATT server.");
  75. Log.e(TAG,"Attempting to start service discovery:" +
  76. mBluetoothGatt1.discoverServices());
  77. } else if (newState == BluetoothProfile.STATE_disCONNECTED) {
  78. intentAction = ACTION_GATT_disCONNECTED;
  79. mConnectionState = STATE_disCONNECTED;
  80. Log.e(TAG,1);
  81. }
  82. Log.e(TAG,"onCHAR READ in callback 1");
  83. }
  84. @Override
  85. public void onCharacteristicChanged(BluetoothGatt gatt,1);
  86. Log.e(TAG,int status) {
  87. Log.e(TAG,"onDescriptorWrite starts");
  88. if (descriptor.getUuid().equals(SampleGattAttributes.CLIENT_CHaraCTERISTIC_CONfig)) {
  89. BluetoothGattCharacteristic characteristic = gatt
  90. .getService(ServiceUUID2)
  91. .getCharacteristic(CharUUID2);
  92. gatt.readCharacteristic(characteristic);
  93. }
  94. Log.e(TAG,"onDescriptorWrite #1,Done!");
  95. }
  96. };
  97. private void broadcastUpdate(final String action) {
  98. final Intent intent = new Intent(action);
  99. sendbroadcast(intent);
  100. }
  101. private void broadcastUpdate(final String action,final BluetoothGattCharacteristic characteristic,int device) {
  102. final Intent intent = new Intent(action);
  103. final byte[] data = characteristic.getValue();
  104. if (data != null && data.length > 0&&device ==0) {
  105. final StringBuilder stringBuilder = new StringBuilder(data.length);
  106. for(byte byteChar : data)
  107. stringBuilder.append(String.format("%02X ",byteChar));
  108. String DATA = stringBuilder.toString();
  109. Log.d(TAG,"MY DATA IN HEX " + DATA);
  110. String DecData =HexAsciiConverter.HexAscii2Decimal(DATA);
  111. Log.d(TAG,"MY DATA IN DECIMAL "+ DecData);
  112. intent.putExtra(EXTRA_DATA," " + DecData);
  113. }
  114. else if( data != null && data.length > 0 && device ==1 ){
  115. final StringBuilder stringBuilder = new StringBuilder(data.length);
  116. for(byte byteChar : data)
  117. stringBuilder.append(String.format("%02X ","MY DATA IN DECIMAL "+ DecData);
  118. intent.putExtra(EXTRA_DATA1," " + DecData);
  119. }
  120. sendbroadcast(intent);
  121. }
  122. public class LocalBinder extends Binder {
  123. BluetoothLeService getService() {
  124. return BluetoothLeService.this;
  125. }
  126. }
  127. @Override
  128. public IBinder onBind(Intent intent) {
  129. return mBinder;
  130. }
  131. @Override
  132. public boolean onUnbind(Intent intent) {
  133. close();
  134. return super.onUnbind(intent);
  135. }
  136. private final IBinder mBinder = new LocalBinder();
  137. public boolean initialize() {
  138. // For API level 18 and above,get a reference to BluetoothAdapter through
  139. // BluetoothManager.
  140. if (mBluetoothManager == null) {
  141. mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUetoOTH_SERVICE);
  142. if (mBluetoothManager == null) {
  143. Log.e(TAG,"Unable to initialize BluetoothManager.");
  144. return false;
  145. }
  146. }
  147. mBluetoothAdapter = mBluetoothManager.getAdapter();
  148. if (mBluetoothAdapter == null) {
  149. Log.e(TAG,"Unable to obtain a BluetoothAdapter.");
  150. return false;
  151. }
  152. return true;
  153. }
  154. public boolean connect(final String address,int devicenum) {
  155. if (mBluetoothAdapter == null || address == null) {
  156. Log.e(TAG,"BluetoothAdapter not initialized or unspecified address.");
  157. return false;
  158. }
  159. // PrevIoUsly connected device. Try to reconnect.
  160. if ((mBluetoothDeviceAddress != null && address.equals(mBluetoothDeviceAddress))
  161. || (mBluetoothDeviceAddress1!=null && address.equals(mBluetoothDeviceAddress1))) {
  162. Log.e(TAG,"Trying to use an existing mBluetoothGatt for connection.");
  163. if (devicenum==0&&mBluetoothGatt.connect()) {
  164. mConnectionState = STATE_CONNECTING;
  165. return true;
  166. }
  167. else if(devicenum==1 && mBluetoothGatt1.connect()) {
  168. mConnectionState = STATE_CONNECTING;
  169. return true;
  170. }
  171. else{
  172. return false;
  173. }
  174. }
  175. final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
  176. if (device == null) {
  177. Log.e(TAG,"Device not found. Unable to connect.");
  178. return false;
  179. }
  180. if(devicenum==0){
  181. mBluetoothGatt1 = device.connectGatt(this,mGattCallback);
  182. mBluetoothDeviceAddress= address;
  183. mConnectionState = STATE_CONNECTING;
  184. Log.e(TAG,"GATT CALLBACK #0 ! "+address);
  185. }
  186. else if(devicenum ==1){
  187. mBluetoothGatt = device.connectGatt(this,mGattCallback1);
  188. mBluetoothDeviceAddress1=address;
  189. mConnectionState = STATE_CONNECTING;
  190. Log.e(TAG,"GATT CALLBACK #1 ! "+address);
  191. }
  192. Log.e(TAG,"Trying to create a new connection.");
  193. return true;
  194. }
  195. public void disconnect() {
  196. if (mBluetoothAdapter == null || mBluetoothGatt == null) {
  197. Log.e(TAG,"BluetoothAdapter not initialized");
  198. return;
  199. }
  200. mBluetoothGatt.disconnect();
  201. if(mBluetoothGatt1!=null){
  202. mBluetoothGatt1.disconnect();
  203. }
  204. }
  205. public void close() {
  206. if (mBluetoothGatt == null) {
  207. return;
  208. }
  209. mBluetoothGatt.close();
  210. mBluetoothGatt1.close();
  211. mBluetoothGatt1 = null;
  212. mBluetoothGatt = null;
  213. }
  214. public void readCharacteristic(BluetoothGattCharacteristic characteristic,int device) {
  215. if (mBluetoothAdapter == null || mBluetoothGatt == null) {
  216. Log.e(TAG,"BluetoothAdapter not initialized");
  217. return;
  218. }
  219. if (device == 0) {
  220. mBluetoothGatt.readCharacteristic(characteristic);
  221. }
  222. else if(device ==1){
  223. mBluetoothGatt1.readCharacteristic(characteristic);
  224. }
  225. }
  226. public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic,boolean enabled,"BluetoothAdapter not initialized");
  227. return;
  228. }
  229. if(device == 0) {
  230. mBluetoothGatt.setCharacteristicNotification(characteristic,enabled);
  231. BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUID.fromString(SampleGattAttributes.CLIENT_CHaraCTERISTIC_CONfig));
  232. descriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
  233. mBluetoothGatt.writeDescriptor(descriptor);
  234. try {
  235. Thread.sleep(100);
  236. } catch (InterruptedException e) {
  237. e.printstacktrace();
  238. }
  239. Log.e(TAG,"Device #0 is done for notification!");
  240. }
  241. else if(device == 1){
  242. mBluetoothGatt1.setCharacteristicNotification(characteristic,"Device #1 is done for notification!");
  243. }
  244. }
  245. public List<BluetoothGattService> getSupportedGattServices(int device) {
  246. if (mBluetoothGatt == null) return null;
  247. if(device ==0) {
  248. return mBluetoothGatt.getServices();
  249. }
  250. else {
  251. return mBluetoothGatt1.getServices();
  252. }
  253. }

}

enter image description here

enter image description here

BLE 设备在通过 iOS 上的免提配置文件呼叫时断开连接,原因为 722 步骤系统诊断日志

BLE 设备在通过 iOS 上的免提配置文件呼叫时断开连接,原因为 722 步骤系统诊断日志

如何解决BLE 设备在通过 iOS 上的免提配置文件呼叫时断开连接,原因为 722 步骤系统诊断日志

我们开发了自己的 BLE 设备并连接到 iPhone。我们发现通过 HFP 进行并行呼叫时,它会在 2 到 3 分钟后断开连接的问题。 (例如:使用汽车音响系统、信息娱乐 HUD 等)。

有谁知道 722 代表什么状态。我们如何解决这个问题? 谢谢。

步骤

  1. iPhone 连接到 Our Device(在后台模式下持续收集数据。)
  2. iPhone 连接到 Car Audio Systems
  3. iPhone 使用 IM 应用(通过 HFP)拨打电话。
  4. 2 ~ 3 分钟后,iPhoneOur Device 之间的连接因722 原因断开。

系统诊断日志

default 2021-02-09 17:04:57.813721 +0800    bluetoothd  Server.LE.Connection    LE Link disconnected for handle 0x14c804720 address <private> with reason 722 encryptionPending 0
default 2021-02-09 17:04:57.813774 +0800    bluetoothd  Server.LE.Connection    LE ConnManager disconnection complete reason 722 address=<private> localRole=Master
default 2021-02-09 17:04:57.816296 +0800    bluetoothd  Stack.GATT   _GATT_LE_disconnectedCB on handle 0x000000014C804720 with reason  STATUS 722
default 2021-02-09 17:04:57.816977 +0800    bluetoothd  Server.LE   Device "E2278A91-B7B6-2122-696C-BE887487C8D7" set last connected time to 1612890297
default 2021-02-09 17:04:57.820707 +0800    bluetoothd  Stack.CL     Removing peer ID 0 for handle 0x000000014C804720
default 2021-02-09 17:04:57.820869 +0800    bluetoothd  Stack.HCI    Releasing LE connection 0x0041
default 2021-02-09 17:04:57.822551 +0800    bluetoothd  Server.LE.Connection    Device "E2278A91-B7B6-2122-696C-BE887487C8D7" does not require low latency
default 2021-02-09 17:04:57.822580 +0800    bluetoothd  Server.LE.Connection    Found link-ready device calling disconnection notification
default 2021-02-09 17:04:57.822582 +0800    bluetoothd  Server.LE.Connection    disconnected from device "E2278A91-B7B6-2122-696C-BE887487C8D7" successfully (locally-initiated)
default 2021-02-09 17:04:57.822585 +0800    bluetoothd  Server.LE.Connection    linkReady:1 disconnectDevice:0 localRole:0 reason:722 result:0
default 2021-02-09 17:04:57.824928 +0800    bluetoothd  Server.LE.Security  Removing temporary security keys for device <private>

bleManager.startDeviceScan 不适用于 iOS react-native-ble-plx

bleManager.startDeviceScan 不适用于 iOS react-native-ble-plx

如何解决bleManager.startDeviceScan 不适用于 iOS react-native-ble-plx

我正在尝试使用 react-native-ble-plx 将网关与 React 本机应用程序配对。 下面的源代码在 Android 中运行良好,而在 iOS 中,bleManager.startDeviceScan() 不会被触发。这一步之后什么都没有发生。

非常感谢任何帮助!

源代码:

  1. const connectBLE = () => {
  2. const subscription = bleManager.onStateChange(async (state) => {
  3. if (state === ''PoweredOn'') {
  4. subscription.remove();
  5. scanAndConnect();
  6. }
  7. };
  8. }
  9. const scanAndConnect = () => {
  10. bleManager.startDeviceScan(null,null,async (error,device) => {
  11. if (error) {
  12. showToast(error,''error'');
  13. console.log(''Handle error - scanning will be stopped automatically'');
  14. return;
  15. }
  16. console.log(''Devices'');
  17. console.log(device.name);
  18. // Check if it is a device you are looking for based on device name
  19. if (device.name === "BLE_0006") {
  20. // Stop scanning as we have found the device.
  21. bleManager.stopDeviceScan();
  22. // Establish Device connection.
  23. device
  24. .connect()
  25. .then((deviceData) => {
  26. /** Show Toast on Device disconnect */
  27. bleManager.onDevicedisconnected(
  28. deviceData.id,(connectionError,connectionData) => {
  29. if (connectionError) {
  30. console.log(connectionError);
  31. }
  32. console.log(''Device is disconnected'');
  33. console.log(connectionData);
  34. },);
  35. /** discover All Services and characteristics */
  36. return device.discoverAllServicesAndcharacteristics();
  37. })
  38. .then(async (deviceObject) => {
  39. console.log(''deviceObject'');
  40. console.log(deviceObject);
  41. /** Subscribe for the Readable service */
  42. device.monitorCharacteristicForService(
  43. Enum.bleConnectionInfo.customServiceUUID,Enum.bleConnectionInfo.readCharacteristicUUID,(error,characteristic) => {
  44. if (error) {
  45. console.log(''Error in monitorCharacteristicForService'');
  46. console.log(error.message);
  47. return;
  48. }
  49. console.log(characteristic.uuid,characteristic.value);
  50. ]);
  51. },);
  52. })
  53. .catch((error) => {
  54. console.warn(error);
  55. showToast(error,''error'');
  56. });
  57. }
  58. });
  59. }

解决方法

这可能对某人有帮助!

通过将 bleManager() 初始化移到功能组件之外解决了该问题。

关于IOS 与 OSX BLE:实例化 CBCentralManager - 为 iOS 编码的介绍现已完结,谢谢您的耐心阅读,如果想了解更多关于Android BLE App 只能订阅 1 个 BLE 设备的特性通知、Android BLE:连接和订阅 2 个 BLE 外围设备的特征通知、BLE 设备在通过 iOS 上的免提配置文件呼叫时断开连接,原因为 722 步骤系统诊断日志、bleManager.startDeviceScan 不适用于 iOS react-native-ble-plx的相关知识,请在本站寻找。

本文标签: