From 5f0fe5a9c6cd8e94d7430e677ad8aa5f0d06f7c8 Mon Sep 17 00:00:00 2001 From: Jo Alley Date: Tue, 7 Feb 2023 15:27:01 +1000 Subject: [PATCH 001/439] Updating Android code to allow multiple callbacks for each peripheral event type --- .../src/main/java/it/innove/Peripheral.java | 212 +++++++++++------- 1 file changed, 126 insertions(+), 86 deletions(-) diff --git a/android/src/main/java/it/innove/Peripheral.java b/android/src/main/java/it/innove/Peripheral.java index 1273704..13f9ea8 100644 --- a/android/src/main/java/it/innove/Peripheral.java +++ b/android/src/main/java/it/innove/Peripheral.java @@ -27,6 +27,7 @@ import java.lang.reflect.Method; import java.util.ArrayList; +import java.util.LinkedList; import java.util.Map; import java.util.Arrays; import java.util.Iterator; @@ -58,13 +59,13 @@ public class Peripheral extends BluetoothGattCallback { private BluetoothGatt gatt; - private Callback connectCallback; - private Callback retrieveServicesCallback; - private Callback readCallback; - private Callback readRSSICallback; - private Callback writeCallback; - private Callback registerNotifyCallback; - private Callback requestMTUCallback; + private LinkedList connectCallbacks = new LinkedList<>(); + private LinkedList retrieveServicesCallbacks = new LinkedList<>(); + private LinkedList readCallbacks = new LinkedList<>(); + private LinkedList readRSSICallbacks = new LinkedList<>(); + private LinkedList writeCallbacks = new LinkedList<>(); + private LinkedList registerNotifyCallbacks = new LinkedList<>(); + private LinkedList requestMTUCallbacks = new LinkedList<>(); private final Queue commandQueue = new ConcurrentLinkedQueue<>(); private final Handler mainHandler = new Handler(Looper.getMainLooper()); @@ -107,7 +108,7 @@ public void connect(final Callback callback, Activity activity) { mainHandler.post(() -> { if (!connected) { BluetoothDevice device = getDevice(); - this.connectCallback = callback; + this.connectCallbacks.addLast(callback); this.connecting = true; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { Log.d(BleManager.LOG_TAG, " Is Or Greater than M $mBluetoothDevice"); @@ -140,7 +141,10 @@ public void connect(final Callback callback, Activity activity) { public void disconnect(final Callback callback, final boolean force) { mainHandler.post(() -> { - connectCallback = null; + connectCallbacks.forEach( + (connectCallback) -> connectCallback.invoke("Disconnect called before connect callback invoked") + ); + connectCallbacks.clear(); connected = false; clearBuffers(); commandQueue.clear(); @@ -274,11 +278,11 @@ public BluetoothDevice getDevice() { public void onServicesDiscovered(BluetoothGatt gatt, int status) { super.onServicesDiscovered(gatt, status); mainHandler.post(() -> { - if (retrieveServicesCallback != null) { - WritableMap map = this.asWritableMap(gatt); - retrieveServicesCallback.invoke(null, map); - retrieveServicesCallback = null; - } + WritableMap map = this.asWritableMap(gatt); + retrieveServicesCallbacks.forEach( + (retrieveServicesCallback) -> retrieveServicesCallback.invoke(null, map) + ); + retrieveServicesCallbacks.clear(); completedCommand(); }); } @@ -316,11 +320,9 @@ public void run() { sendConnectionEvent(device, "BleManagerConnectPeripheral", status); - if (connectCallback != null) { - Log.d(BleManager.LOG_TAG, "Connected to: " + device.getAddress()); - connectCallback.invoke(); - connectCallback = null; - } + Log.d(BleManager.LOG_TAG, "Connected to: " + device.getAddress()); + connectCallbacks.forEach((connectCallback) -> connectCallback.invoke()); + connectCallbacks.clear(); } else if (newState == BluetoothProfile.STATE_DISCONNECTED || status != BluetoothGatt.GATT_SUCCESS) { @@ -329,30 +331,36 @@ public void run() { discoverServicesRunnable = null; } - List callbacks = Arrays.asList(writeCallback, retrieveServicesCallback, readRSSICallback, - readCallback, registerNotifyCallback, requestMTUCallback); - for (Callback currentCallback : callbacks) { - if (currentCallback != null) { - try { - currentCallback.invoke("Device disconnected"); - } catch (Exception e) { - e.printStackTrace(); - } } - } - if (connectCallback != null) { - connectCallback.invoke("Connection error"); - connectCallback = null; - } - writeCallback = null; + writeCallbacks.forEach((writeCallback) -> writeCallback.invoke("Device disconnected")); + writeCallbacks.clear(); + + retrieveServicesCallbacks.forEach( + (retrieveServicesCallback) -> retrieveServicesCallback.invoke("Device disconnected") + ); + retrieveServicesCallbacks.clear(); + + readRSSICallbacks.forEach((readRSSICallback) -> readRSSICallback.invoke("Device disconnected")); + readRSSICallbacks.clear(); + + registerNotifyCallbacks.forEach( + (registerNotifyCallback) -> registerNotifyCallback.invoke("Device disconnected") + ); + registerNotifyCallbacks.clear(); + + requestMTUCallbacks.forEach( + (requestMTUCallback) -> requestMTUCallback.invoke("Device disconnected") + ); + requestMTUCallbacks.clear(); + + readCallbacks.forEach((readCallback) -> readCallback.invoke("Device disconnected")); + readCallbacks.clear(); + + connectCallbacks.forEach((connectCallback) -> connectCallback.invoke("Connection error")); + connectCallbacks.clear(); + writeQueue.clear(); - readCallback = null; - retrieveServicesCallback = null; - readRSSICallback = null; - registerNotifyCallback = null; - requestMTUCallback = null; commandQueue.clear(); commandQueueBusy = false; - connectCallback = null; connected = false; clearBuffers(); commandQueue.clear(); @@ -430,12 +438,21 @@ public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic if (status == GATT_AUTH_FAIL || status == GATT_INSUFFICIENT_AUTHENTICATION) { Log.d(BleManager.LOG_TAG, "Read needs bonding"); } - readCallback.invoke("Error reading " + characteristic.getUuid() + " status=" + status, null); - readCallback = null; - } else if (readCallback != null) { + + readCallbacks.forEach( + (readCallback) -> readCallback.invoke( + "Error reading " + characteristic.getUuid() + " status=" + status, + null + ) + ); + readCallbacks.clear(); + } else if (!readCallbacks.isEmpty()) { final byte[] dataValue = copyOf(characteristic.getValue()); - readCallback.invoke(null, BleManager.bytesToWritableArray(dataValue)); - readCallback = null; + + readCallbacks.forEach( + (readCallback) -> readCallback.invoke(null, BleManager.bytesToWritableArray(dataValue)) + ); + readCallbacks.clear(); } completedCommand(); }); @@ -450,18 +467,24 @@ public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristi if (writeQueue.size() > 0) { byte[] data = writeQueue.get(0); writeQueue.remove(0); - doWrite(characteristic, data, writeCallback); + doWrite(characteristic, data, null); } else if (status != BluetoothGatt.GATT_SUCCESS) { if (status == GATT_AUTH_FAIL || status == GATT_INSUFFICIENT_AUTHENTICATION) { Log.d(BleManager.LOG_TAG, "Write needs bonding"); // *not* doing completedCommand() return; } - writeCallback.invoke( "Error writing " + characteristic.getUuid() + " status=" + status, null); - writeCallback = null; - } else if (writeCallback != null) { - writeCallback.invoke(); - writeCallback = null; + writeCallbacks.forEach( + (writeCallback) -> + writeCallback.invoke("Error writing " + characteristic.getUuid() + " status=" + status, null) + ); + writeCallbacks.clear(); + } else if (!writeCallbacks.isEmpty()) { + writeCallbacks.forEach( + (writeCallback) -> + writeCallback.invoke() + ); + writeCallbacks.clear(); } completedCommand(); }); @@ -470,16 +493,19 @@ public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristi @Override public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) { mainHandler.post(() -> { - if (registerNotifyCallback != null) { + if (!registerNotifyCallbacks.isEmpty()) { if (status == BluetoothGatt.GATT_SUCCESS) { - registerNotifyCallback.invoke(); + registerNotifyCallbacks.forEach((registerNotifyCallback) -> registerNotifyCallback.invoke()); Log.d(BleManager.LOG_TAG, "onDescriptorWrite success"); } else { - registerNotifyCallback.invoke("Error writing descriptor status=" + status, null); + registerNotifyCallbacks.forEach( + (registerNotifyCallback) -> + registerNotifyCallback.invoke("Error writing descriptor status=" + status, null) + ); Log.e(BleManager.LOG_TAG, "Error writing descriptor status=" + status); } - registerNotifyCallback = null; + registerNotifyCallbacks.clear(); } else { Log.e(BleManager.LOG_TAG, "onDescriptorWrite with no callback"); } @@ -493,15 +519,17 @@ public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) { super.onReadRemoteRssi(gatt, rssi, status); mainHandler.post(() -> { - if (readRSSICallback != null) { + if (!readRSSICallbacks.isEmpty()) { if (status == BluetoothGatt.GATT_SUCCESS) { updateRssi(rssi); - readRSSICallback.invoke(null, rssi); + readRSSICallbacks.forEach((readRSSICallback) -> readRSSICallback.invoke(null, rssi)); } else { - readRSSICallback.invoke("Error reading RSSI status=" + status, null); + readRSSICallbacks.forEach( + (readRSSICallback) -> readRSSICallback.invoke("Error reading RSSI status=" + status, null) + ); } - readRSSICallback = null; + readRSSICallbacks.clear(); } completedCommand(); @@ -562,22 +590,24 @@ private void setNotify(UUID serviceUUID, UUID characteristicUUID, final Boolean return; } final byte[] finalValue = notify ? value : BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE; - final Callback finalCallback = callback; boolean result = false; try { result = gatt.setCharacteristicNotification(characteristic, notify); // Then write to descriptor descriptor.setValue(finalValue); - registerNotifyCallback = finalCallback; + registerNotifyCallbacks.addLast(callback); result &= gatt.writeDescriptor(descriptor); } catch(Exception e) { Log.d(BleManager.LOG_TAG, "Exception in setNotify", e); } if (! result) { - callback.invoke( "writeDescriptor failed for descriptor: " + descriptor.getUuid(), null); - registerNotifyCallback = null; + registerNotifyCallbacks.forEach( + (registerNotifyCallback) -> + registerNotifyCallback.invoke("writeDescriptor failed for descriptor: " + descriptor.getUuid(), null) + ); + registerNotifyCallbacks.clear(); completedCommand(); } } @@ -662,13 +692,12 @@ public void read(UUID serviceUUID, UUID characteristicUUID, final Callback callb return; } - readCallback = callback; + this.readCallbacks.addLast(callback); if (!gatt.readCharacteristic(characteristic)) { - callback.invoke("Read failed", null); - readCallback = null; + readCallbacks.forEach((readCallback) -> readCallback.invoke("Read failed", null)); + readCallbacks.clear(); completedCommand(); } - }); } @@ -744,10 +773,12 @@ public void readRSSI(final Callback callback) { completedCommand(); return; } else { - readRSSICallback = callback; + readRSSICallbacks.addLast(callback); if (!gatt.readRemoteRssi()) { - callback.invoke("Read RSSI failed", null); - readRSSICallback = null; + readRSSICallbacks.forEach( + (readRSSICallback) -> readRSSICallback.invoke("Read RSSI failed", null) + ); + readRSSICallbacks.clear(); completedCommand(); } } @@ -786,7 +817,7 @@ public void retrieveServices(Callback callback) { completedCommand(); return; } else { - this.retrieveServicesCallback = callback; + this.retrieveServicesCallbacks.addLast(callback); gatt.discoverServices(); } }); @@ -824,16 +855,18 @@ public boolean doWrite(final BluetoothGattCharacteristic characteristic, byte[] @Override public void run() { characteristic.setValue(copyOfData); - if (characteristic.getWriteType() == BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT) - writeCallback = callback; - else - writeCallback = null; + if ( + characteristic.getWriteType() == BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT + && callback != null + ) { + writeCallbacks.addLast(callback); + } if (!gatt.writeCharacteristic(characteristic)) { // write without response, caller will handle the callback - if (writeCallback != null) { - writeCallback.invoke("Write failed", writeCallback); - writeCallback = null; - } + writeCallbacks.forEach( + (writeCallback) -> writeCallback.invoke("Write failed", writeCallback) + ); + writeCallbacks.clear(); completedCommand(); } } @@ -957,10 +990,12 @@ public void requestMTU(int mtu, Callback callback) { } if (Build.VERSION.SDK_INT >= LOLLIPOP) { - requestMTUCallback = callback; + requestMTUCallbacks.addLast(callback); if (!gatt.requestMtu(mtu)) { - requestMTUCallback.invoke("Request MTU failed", null); - requestMTUCallback = null; + requestMTUCallbacks.forEach( + (requestMTUCallback) -> requestMTUCallback.invoke("Request MTU failed", null) + ); + requestMTUCallbacks.clear(); completedCommand(); } } else { @@ -974,14 +1009,19 @@ public void requestMTU(int mtu, Callback callback) { public void onMtuChanged(BluetoothGatt gatt, int mtu, int status) { super.onMtuChanged(gatt, mtu, status); mainHandler.post(() -> { - if (requestMTUCallback != null) { + if (!requestMTUCallbacks.isEmpty()) { if (status == BluetoothGatt.GATT_SUCCESS) { - requestMTUCallback.invoke(null, mtu); + requestMTUCallbacks.forEach( + (requestMTUCallback) -> requestMTUCallback.invoke(null, mtu) + ); } else { - requestMTUCallback.invoke("Error requesting MTU status = " + status, null); + requestMTUCallbacks.forEach( + (requestMTUCallback) -> + requestMTUCallback.invoke("Error requesting MTU status = " + status, null) + ); } - requestMTUCallback = null; + requestMTUCallbacks.clear(); } completedCommand(); From 3d9e7eb515d8c1ffb408057dcf5e5fc22cee6de9 Mon Sep 17 00:00:00 2001 From: Jo Alley Date: Wed, 8 Feb 2023 09:08:31 +1000 Subject: [PATCH 002/439] Updating iOS code to allow multiple callbacks for each peripheral event type --- ios/BleManager.m | 162 +++++++++++++++++++---------------------------- 1 file changed, 65 insertions(+), 97 deletions(-) diff --git a/ios/BleManager.m b/ios/BleManager.m index 87122ec..f507dc0 100644 --- a/ios/BleManager.m +++ b/ios/BleManager.m @@ -82,21 +82,17 @@ +(BOOL)requiresMainQueueSetup - (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error { NSString *key = [self keyForPeripheral: peripheral andCharacteristic:characteristic]; - RCTResponseSenderBlock readCallback = [readCallbacks objectForKey:key]; if (error) { NSLog(@"Error %@ :%@", characteristic.UUID, error); - if (readCallback != NULL) { - readCallback(@[error, [NSNull null]]); - [readCallbacks removeObjectForKey:key]; - } + [self invokeAndClearDictionary:readCallbacks withKey:key usingParameters:@[error, [NSNull null]]]; return; } NSLog(@"Read value [%@]: (%lu) %@", characteristic.UUID, [characteristic.value length], characteristic.value); - - if (readCallback != NULL) { - readCallback(@[[NSNull null], ([characteristic.value length] > 0) ? [characteristic.value toArray] : [NSNull null]]); - [readCallbacks removeObjectForKey:key]; + + NSMutableArray* peripheralReadCallbacks = [readCallbacks objectForKey:key]; + if (peripheralReadCallbacks != NULL) { + [self invokeAndClearDictionary:readCallbacks withKey:key usingParameters:@[[NSNull null], ([characteristic.value length] > 0) ? [characteristic.value toArray] : [NSNull null]]]; } else { if (hasListeners) { [self sendEventWithName:@"BleManagerDidUpdateValueForCharacteristic" body:@{@"peripheral": peripheral.uuidAsString, @"characteristic":characteristic.UUID.UUIDString, @"service":characteristic.service.UUID.UUIDString, @"value": ([characteristic.value length] > 0) ? [characteristic.value toArray] : [NSNull null]}]; @@ -118,27 +114,25 @@ - (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForChara NSString *key = [self keyForPeripheral: peripheral andCharacteristic:characteristic]; if (characteristic.isNotifying) { - RCTResponseSenderBlock notificationCallback = [notificationCallbacks objectForKey:key]; - if (notificationCallback != nil) { + NSMutableArray* peripheralNotificationCallbacks = [notificationCallbacks objectForKey:key]; + if (peripheralNotificationCallbacks != nil) { if (error) { - notificationCallback(@[error]); + [self invokeAndClearDictionary:notificationCallbacks withKey:key usingParameters:@[error]]; } else { NSLog(@"Notification began on %@", characteristic.UUID); - notificationCallback(@[]); + [self invokeAndClearDictionary:notificationCallbacks withKey:key usingParameters:@[]]; } - [notificationCallbacks removeObjectForKey:key]; } } else { // Notification has stopped - RCTResponseSenderBlock stopNotificationCallback = [stopNotificationCallbacks objectForKey:key]; - if (stopNotificationCallback != nil) { + NSMutableArray* peripheralStopNotificationCallbacks = [stopNotificationCallbacks objectForKey:key]; + if (peripheralStopNotificationCallbacks != nil) { if (error) { - stopNotificationCallback(@[error]); + [self invokeAndClearDictionary:stopNotificationCallbacks withKey:key usingParameters:@[error]]; } else { NSLog(@"Notification ended on %@", characteristic.UUID); - stopNotificationCallback(@[]); + [self invokeAndClearDictionary:stopNotificationCallbacks withKey:key usingParameters:@[]]; } - [stopNotificationCallbacks removeObjectForKey:key]; } } if (hasListeners) { @@ -435,8 +429,8 @@ - (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeri } if (peripheral) { NSLog(@"Connecting to peripheral with UUID : %@", peripheralUUID); - - [connectCallbacks setObject:callback forKey:[peripheral uuidAsString]]; + + [self insertCallback:callback intoDictionary:connectCallbacks withKey:[peripheral uuidAsString]]; [manager connectPeripheral:peripheral options:nil]; } else { @@ -486,12 +480,8 @@ - (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(C { NSString *errorStr = [NSString stringWithFormat:@"Peripheral connection failure: %@. (%@)", peripheral, [error localizedDescription]]; NSLog(@"%@", errorStr); - RCTResponseSenderBlock connectCallback = [connectCallbacks valueForKey:[peripheral uuidAsString]]; - - if (connectCallback) { - connectCallback(@[errorStr]); - [connectCallbacks removeObjectForKey:[peripheral uuidAsString]]; - } + + [self invokeAndClearDictionary:connectCallbacks withKey:[peripheral uuidAsString] usingParameters:@[errorStr]]; } RCT_EXPORT_METHOD(write:(NSString *)deviceUUID serviceUUID:(NSString*)serviceUUID characteristicUUID:(NSString*)characteristicUUID message:(NSArray*)message maxByteSize:(NSInteger)maxByteSize callback:(nonnull RCTResponseSenderBlock)callback) @@ -518,8 +508,8 @@ - (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(C CBCharacteristic *characteristic = [context characteristic]; NSString *key = [self keyForPeripheral: peripheral andCharacteristic:characteristic]; - [writeCallbacks setObject:callback forKey:key]; - + [self insertCallback:callback intoDictionary:writeCallbacks withKey:key]; + RCTLogInfo(@"Message to write(%lu): %@ ", (unsigned long)[dataMessage length], [dataMessage hexadecimalString]); if ([dataMessage length] > maxByteSize){ int dataLength = (int)dataMessage.length; @@ -606,7 +596,7 @@ - (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(C CBCharacteristic *characteristic = [context characteristic]; NSString *key = [self keyForPeripheral: peripheral andCharacteristic:characteristic]; - [readCallbacks setObject:callback forKey:key]; + [self insertCallback:callback intoDictionary:readCallbacks withKey:key]; [peripheral readValueForCharacteristic:characteristic]; // callback sends value } @@ -620,7 +610,7 @@ - (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(C CBPeripheral *peripheral = [self findPeripheralByUUID:deviceUUID]; if (peripheral && peripheral.state == CBPeripheralStateConnected) { - [readRSSICallbacks setObject:callback forKey:[peripheral uuidAsString]]; + [self insertCallback:callback intoDictionary:readRSSICallbacks withKey:[peripheral uuidAsString]]; [peripheral readRSSI]; } else { callback(@[@"Peripheral not found or not connected"]); @@ -635,7 +625,7 @@ - (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(C CBPeripheral *peripheral = [self findPeripheralByUUID:deviceUUID]; if (peripheral && peripheral.state == CBPeripheralStateConnected) { - [retrieveServicesCallbacks setObject:callback forKey:[peripheral uuidAsString]]; + [self insertCallback:callback intoDictionary:retrieveServicesCallbacks withKey:[peripheral uuidAsString]]; NSMutableArray *uuids = [NSMutableArray new]; for ( NSString *string in services ) { @@ -665,7 +655,7 @@ - (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(C CBCharacteristic *characteristic = [context characteristic]; NSString *key = [self keyForPeripheral: peripheral andCharacteristic:characteristic]; - [notificationCallbacks setObject: callback forKey: key]; + [self insertCallback:callback intoDictionary:notificationCallbacks withKey:key]; [peripheral setNotifyValue:YES forCharacteristic:characteristic]; } @@ -684,7 +674,7 @@ - (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(C if ([characteristic isNotifying]){ NSString *key = [self keyForPeripheral: peripheral andCharacteristic:characteristic]; - [stopNotificationCallbacks setObject: callback forKey: key]; + [self insertCallback:callback intoDictionary:stopNotificationCallbacks withKey:key]; [peripheral setNotifyValue:NO forCharacteristic:characteristic]; NSLog(@"Characteristic stopped notifying"); } else { @@ -730,17 +720,15 @@ - (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CB NSLog(@"didWrite"); NSString *key = [self keyForPeripheral: peripheral andCharacteristic:characteristic]; - RCTResponseSenderBlock writeCallback = [writeCallbacks objectForKey:key]; + NSMutableArray* peripheralWriteCallbacks = [writeCallbacks objectForKey:key]; - if (writeCallback) { + if (peripheralWriteCallbacks) { if (error) { NSLog(@"%@", error); - [writeCallbacks removeObjectForKey:key]; - writeCallback(@[error.localizedDescription]); + [self invokeAndClearDictionary:writeCallbacks withKey:key usingParameters:@[error.localizedDescription]]; } else { if ([writeQueue count] == 0) { - [writeCallbacks removeObjectForKey:key]; - writeCallback(@[]); + [self invokeAndClearDictionary:writeCallbacks withKey:key usingParameters:@[]]; }else{ // Remove and write the queud message NSData *message = [writeQueue objectAtIndex:0]; @@ -750,18 +738,14 @@ - (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CB } } - + } - (void)peripheral:(CBPeripheral*)peripheral didReadRSSI:(NSNumber*)rssi error:(NSError*)error { NSLog(@"didReadRSSI %@", rssi); NSString *key = [peripheral uuidAsString]; - RCTResponseSenderBlock readRSSICallback = [readRSSICallbacks objectForKey: key]; - if (readRSSICallback) { - readRSSICallback(@[[NSNull null], [NSNumber numberWithInteger:[rssi integerValue]]]); - [readRSSICallbacks removeObjectForKey:key]; - } + [self invokeAndClearDictionary:readRSSICallbacks withKey:key usingParameters:@[[NSNull null], [NSNumber numberWithInteger:[rssi integerValue]]]]; } @@ -776,14 +760,9 @@ - (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPerip dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.002 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void){ // didFailToConnectPeripheral should have been called already if not connected by now - - RCTResponseSenderBlock connectCallback = [connectCallbacks valueForKey:[peripheral uuidAsString]]; - - if (connectCallback) { - connectCallback(@[[NSNull null], [peripheral asDictionary]]); - [connectCallbacks removeObjectForKey:[peripheral uuidAsString]]; - } - + + [self invokeAndClearDictionary:self->connectCallbacks withKey:[peripheral uuidAsString] usingParameters:@[[NSNull null], [peripheral asDictionary]]]; + if (hasListeners) { [self sendEventWithName:@"BleManagerConnectPeripheral" body:@{@"peripheral": [peripheral uuidAsString]}]; } @@ -802,66 +781,36 @@ - (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPe NSString *peripheralUUIDString = [peripheral uuidAsString]; NSString *errorStr = [NSString stringWithFormat:@"Peripheral did disconnect: %@", peripheralUUIDString]; - - RCTResponseSenderBlock connectCallback = [connectCallbacks valueForKey:peripheralUUIDString]; - if (connectCallback) { - connectCallback(@[errorStr]); - [connectCallbacks removeObjectForKey:peripheralUUIDString]; - } - - RCTResponseSenderBlock readRSSICallback = [readRSSICallbacks valueForKey:peripheralUUIDString]; - if (readRSSICallback) { - readRSSICallback(@[errorStr]); - [readRSSICallbacks removeObjectForKey:peripheralUUIDString]; - } - - RCTResponseSenderBlock retrieveServicesCallback = [retrieveServicesCallbacks valueForKey:peripheralUUIDString]; - if (retrieveServicesCallback) { - retrieveServicesCallback(@[errorStr]); - [retrieveServicesCallbacks removeObjectForKey:peripheralUUIDString]; - } + + [self invokeAndClearDictionary:connectCallbacks withKey:peripheralUUIDString usingParameters:@[errorStr]]; + [self invokeAndClearDictionary:readRSSICallbacks withKey:peripheralUUIDString usingParameters:@[errorStr]]; + [self invokeAndClearDictionary:retrieveServicesCallbacks withKey:peripheralUUIDString usingParameters:@[errorStr]]; NSArray* ourReadCallbacks = readCallbacks.allKeys; for (id key in ourReadCallbacks) { if ([key hasPrefix:peripheralUUIDString]) { - RCTResponseSenderBlock callback = [readCallbacks objectForKey:key]; - if (callback) { - callback(@[errorStr]); - [readCallbacks removeObjectForKey:key]; - } + [self invokeAndClearDictionary:readCallbacks withKey:key usingParameters:@[errorStr]]; } } NSArray* ourWriteCallbacks = writeCallbacks.allKeys; for (id key in ourWriteCallbacks) { if ([key hasPrefix:peripheralUUIDString]) { - RCTResponseSenderBlock callback = [writeCallbacks objectForKey:key]; - if (callback) { - callback(@[errorStr]); - [writeCallbacks removeObjectForKey:key]; - } + [self invokeAndClearDictionary:writeCallbacks withKey:key usingParameters:@[errorStr]]; } } NSArray* ourNotificationCallbacks = notificationCallbacks.allKeys; for (id key in ourNotificationCallbacks) { if ([key hasPrefix:peripheralUUIDString]) { - RCTResponseSenderBlock callback = [notificationCallbacks objectForKey:key]; - if (callback) { - callback(@[errorStr]); - [notificationCallbacks removeObjectForKey:key]; - } + [self invokeAndClearDictionary:notificationCallbacks withKey:key usingParameters:@[errorStr]]; } } NSArray* ourStopNotificationsCallbacks = stopNotificationCallbacks.allKeys; for (id key in ourStopNotificationsCallbacks) { if ([key hasPrefix:peripheralUUIDString]) { - RCTResponseSenderBlock callback = [stopNotificationCallbacks objectForKey:key]; - if (callback) { - callback(@[errorStr]); - [stopNotificationCallbacks removeObjectForKey:key]; - } + [self invokeAndClearDictionary:stopNotificationCallbacks withKey:key usingParameters:@[errorStr]]; } } @@ -908,11 +857,7 @@ - (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForServi if ([latch count] == 0) { // Call success callback for connect - RCTResponseSenderBlock retrieveServiceCallback = [retrieveServicesCallbacks valueForKey:peripheralUUIDString]; - if (retrieveServiceCallback) { - retrieveServiceCallback(@[[NSNull null], [peripheral asDictionary]]); - [retrieveServicesCallbacks removeObjectForKey:peripheralUUIDString]; - } + [self invokeAndClearDictionary:retrieveServicesCallbacks withKey:peripheralUUIDString usingParameters:@[[NSNull null], [peripheral asDictionary]]]; [retrieveServicesLatches removeObjectForKey:peripheralUUIDString]; } } @@ -1048,4 +993,27 @@ +(BleManager *)getInstance return _instance; } +-(void) insertCallback:(nonnull RCTResponseSenderBlock)callback intoDictionary:(NSMutableDictionary *)dictionary withKey:(NSString *)key +{ + NSMutableArray* peripheralCallbacks = [dictionary objectForKey:key]; + if (!peripheralCallbacks) { + peripheralCallbacks = [NSMutableArray array]; + [dictionary setObject:peripheralCallbacks forKey:key]; + } + + [peripheralCallbacks addObject:callback]; +} + +-(void) invokeAndClearDictionary:(NSMutableDictionary *)dictionary withKey:(NSString *)key usingParameters:(NSArray *)parameters +{ + NSMutableArray* peripheralCallbacks = [dictionary objectForKey:key]; + if (peripheralCallbacks) { + for (RCTResponseSenderBlock callback in peripheralCallbacks) { + callback(parameters); + } + + [dictionary removeObjectForKey:key]; + } +} + @end From bd4e5dff8fa749bc95dcf668cc1fb4d3e0f2e44f Mon Sep 17 00:00:00 2001 From: Marco Sinigaglia Date: Fri, 10 Feb 2023 09:36:17 +0100 Subject: [PATCH 003/439] Update README.md --- README.md | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index a5ff738..07d6964 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,13 @@ [![npm downloads](https://img.shields.io/npm/dm/react-native-ble-manager.svg?style=flat)](https://www.npmjs.com/package/react-native-ble-manager) [![GitHub issues](https://img.shields.io/github/issues/innoveit/react-native-ble-manager.svg?style=flat)](https://github.com/innoveit/react-native-ble-manager/issues) -This is a porting of https://github.com/don/cordova-plugin-ble-central project to React Native. +A React Native Bluetooth Low Energy library. + +Originally inspired by https://github.com/don/cordova-plugin-ble-central. + +## Introduction + +The library is a simple connection with the OS APIs, the BLE stack should be standard but often has different behaviors based on the device used, the operating system and the BLE chip it connects to. Before opening an issue verify that the problem is really the library. ## Requirements From f8532f654063b96624aff40aebdd5c89306ace34 Mon Sep 17 00:00:00 2001 From: Rob McLean Date: Sat, 11 Feb 2023 18:34:22 -0700 Subject: [PATCH 004/439] removing previous example --- example/.babelrc | 8 - example/.buckconfig | 6 - example/.eslintrc.js | 4 - example/.flowconfig | 73 -- example/.gitattributes | 1 - example/.gitignore | 59 -- example/.prettierrc.js | 6 - example/.watchmanconfig | 1 - example/App.js | 302 ------ example/__tests__/App-test.js | 14 - example/android/app/BUCK | 55 - example/android/app/build.gradle | 221 ---- example/android/app/build_defs.bzl | 19 - example/android/app/debug.keystore | Bin 2257 -> 0 bytes example/android/app/proguard-rules.pro | 10 - .../android/app/src/debug/AndroidManifest.xml | 8 - .../java/com/example/ReactNativeFlipper.java | 72 -- .../android/app/src/main/AndroidManifest.xml | 31 - .../main/java/com/example/MainActivity.java | 15 - .../java/com/example/MainApplication.java | 80 -- .../src/main/res/mipmap-hdpi/ic_launcher.png | Bin 3056 -> 0 bytes .../res/mipmap-hdpi/ic_launcher_round.png | Bin 5024 -> 0 bytes .../src/main/res/mipmap-mdpi/ic_launcher.png | Bin 2096 -> 0 bytes .../res/mipmap-mdpi/ic_launcher_round.png | Bin 2858 -> 0 bytes .../src/main/res/mipmap-xhdpi/ic_launcher.png | Bin 4569 -> 0 bytes .../res/mipmap-xhdpi/ic_launcher_round.png | Bin 7098 -> 0 bytes .../main/res/mipmap-xxhdpi/ic_launcher.png | Bin 6464 -> 0 bytes .../res/mipmap-xxhdpi/ic_launcher_round.png | Bin 10676 -> 0 bytes .../main/res/mipmap-xxxhdpi/ic_launcher.png | Bin 9250 -> 0 bytes .../res/mipmap-xxxhdpi/ic_launcher_round.png | Bin 15523 -> 0 bytes .../app/src/main/res/values/strings.xml | 3 - .../app/src/main/res/values/styles.xml | 9 - example/android/build.gradle | 37 - example/android/gradle.properties | 29 - example/android/settings.gradle | 3 - example/app.json | 4 - example/index.js | 9 - example/ios/Podfile | 43 - example/ios/Podfile.lock | 410 -------- example/ios/example-tvOS/Info.plist | 53 - example/ios/example-tvOSTests/Info.plist | 24 - example/ios/example.xcodeproj/project.pbxproj | 964 ------------------ .../contents.xcworkspacedata | 7 - .../xcshareddata/IDEWorkspaceChecks.plist | 8 - .../xcschemes/example-tvOS.xcscheme | 88 -- .../xcshareddata/xcschemes/example.xcscheme | 88 -- .../contents.xcworkspacedata | 10 - .../xcshareddata/IDEWorkspaceChecks.plist | 8 - example/ios/example/AppDelegate.h | 8 - example/ios/example/AppDelegate.m | 58 -- .../AppIcon.appiconset/Contents.json | 53 - .../ios/example/Images.xcassets/Contents.json | 6 - example/ios/example/Info.plist | 59 -- example/ios/example/LaunchScreen.storyboard | 58 -- example/ios/example/main.m | 9 - example/ios/exampleTests/Info.plist | 24 - example/ios/exampleTests/exampleTests.m | 65 -- example/metro.config.js | 34 - example/package.json | 31 - 59 files changed, 3187 deletions(-) delete mode 100644 example/.babelrc delete mode 100644 example/.buckconfig delete mode 100644 example/.eslintrc.js delete mode 100644 example/.flowconfig delete mode 100644 example/.gitattributes delete mode 100644 example/.gitignore delete mode 100644 example/.prettierrc.js delete mode 100644 example/.watchmanconfig delete mode 100644 example/App.js delete mode 100644 example/__tests__/App-test.js delete mode 100644 example/android/app/BUCK delete mode 100644 example/android/app/build.gradle delete mode 100644 example/android/app/build_defs.bzl delete mode 100644 example/android/app/debug.keystore delete mode 100644 example/android/app/proguard-rules.pro delete mode 100644 example/android/app/src/debug/AndroidManifest.xml delete mode 100644 example/android/app/src/debug/java/com/example/ReactNativeFlipper.java delete mode 100644 example/android/app/src/main/AndroidManifest.xml delete mode 100644 example/android/app/src/main/java/com/example/MainActivity.java delete mode 100644 example/android/app/src/main/java/com/example/MainApplication.java delete mode 100644 example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png delete mode 100644 example/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png delete mode 100644 example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png delete mode 100644 example/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png delete mode 100644 example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png delete mode 100644 example/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png delete mode 100644 example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png delete mode 100644 example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png delete mode 100644 example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png delete mode 100644 example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png delete mode 100644 example/android/app/src/main/res/values/strings.xml delete mode 100644 example/android/app/src/main/res/values/styles.xml delete mode 100644 example/android/build.gradle delete mode 100644 example/android/gradle.properties delete mode 100644 example/android/settings.gradle delete mode 100644 example/app.json delete mode 100644 example/index.js delete mode 100644 example/ios/Podfile delete mode 100644 example/ios/Podfile.lock delete mode 100644 example/ios/example-tvOS/Info.plist delete mode 100644 example/ios/example-tvOSTests/Info.plist delete mode 100644 example/ios/example.xcodeproj/project.pbxproj delete mode 100644 example/ios/example.xcodeproj/project.xcworkspace/contents.xcworkspacedata delete mode 100644 example/ios/example.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist delete mode 100644 example/ios/example.xcodeproj/xcshareddata/xcschemes/example-tvOS.xcscheme delete mode 100644 example/ios/example.xcodeproj/xcshareddata/xcschemes/example.xcscheme delete mode 100644 example/ios/example.xcworkspace/contents.xcworkspacedata delete mode 100644 example/ios/example.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist delete mode 100644 example/ios/example/AppDelegate.h delete mode 100644 example/ios/example/AppDelegate.m delete mode 100644 example/ios/example/Images.xcassets/AppIcon.appiconset/Contents.json delete mode 100644 example/ios/example/Images.xcassets/Contents.json delete mode 100644 example/ios/example/Info.plist delete mode 100644 example/ios/example/LaunchScreen.storyboard delete mode 100644 example/ios/example/main.m delete mode 100644 example/ios/exampleTests/Info.plist delete mode 100644 example/ios/exampleTests/exampleTests.m delete mode 100644 example/metro.config.js delete mode 100644 example/package.json diff --git a/example/.babelrc b/example/.babelrc deleted file mode 100644 index 12560f9..0000000 --- a/example/.babelrc +++ /dev/null @@ -1,8 +0,0 @@ -{ - "presets": ["module:metro-react-native-babel-preset"], - "env": { - "production": { - "plugins": ["transform-remove-console"] - } - } -} diff --git a/example/.buckconfig b/example/.buckconfig deleted file mode 100644 index 934256c..0000000 --- a/example/.buckconfig +++ /dev/null @@ -1,6 +0,0 @@ - -[android] - target = Google Inc.:Google APIs:23 - -[maven_repositories] - central = https://repo1.maven.org/maven2 diff --git a/example/.eslintrc.js b/example/.eslintrc.js deleted file mode 100644 index 40c6dcd..0000000 --- a/example/.eslintrc.js +++ /dev/null @@ -1,4 +0,0 @@ -module.exports = { - root: true, - extends: '@react-native-community', -}; diff --git a/example/.flowconfig b/example/.flowconfig deleted file mode 100644 index b274ad1..0000000 --- a/example/.flowconfig +++ /dev/null @@ -1,73 +0,0 @@ -[ignore] -; We fork some components by platform -.*/*[.]android.js - -; Ignore "BUCK" generated dirs -/\.buckd/ - -; Ignore polyfills -node_modules/react-native/Libraries/polyfills/.* - -; These should not be required directly -; require from fbjs/lib instead: require('fbjs/lib/warning') -node_modules/warning/.* - -; Flow doesn't support platforms -.*/Libraries/Utilities/LoadingView.js - -[untyped] -.*/node_modules/@react-native-community/cli/.*/.* - -[include] - -[libs] -node_modules/react-native/interface.js -node_modules/react-native/flow/ - -[options] -emoji=true - -esproposal.optional_chaining=enable -esproposal.nullish_coalescing=enable - -module.file_ext=.js -module.file_ext=.json -module.file_ext=.ios.js - -munge_underscores=true - -module.name_mapper='^react-native/\(.*\)$' -> '/node_modules/react-native/\1' -module.name_mapper='^@?[./a-zA-Z0-9$_-]+\.\(bmp\|gif\|jpg\|jpeg\|png\|psd\|svg\|webp\|m4v\|mov\|mp4\|mpeg\|mpg\|webm\|aac\|aiff\|caf\|m4a\|mp3\|wav\|html\|pdf\)$' -> '/node_modules/react-native/Libraries/Image/RelativeImageStub' - -suppress_type=$FlowIssue -suppress_type=$FlowFixMe -suppress_type=$FlowFixMeProps -suppress_type=$FlowFixMeState - -suppress_comment=\\(.\\|\n\\)*\\$FlowFixMe\\($\\|[^(]\\|(\\(\\)? *\\(site=[a-z,_]*react_native\\(_ios\\)?_\\(oss\\|fb\\)[a-z,_]*\\)?)\\) -suppress_comment=\\(.\\|\n\\)*\\$FlowIssue\\((\\(\\)? *\\(site=[a-z,_]*react_native\\(_ios\\)?_\\(oss\\|fb\\)[a-z,_]*\\)?)\\)?:? #[0-9]+ -suppress_comment=\\(.\\|\n\\)*\\$FlowExpectedError - -[lints] -sketchy-null-number=warn -sketchy-null-mixed=warn -sketchy-number=warn -untyped-type-import=warn -nonstrict-import=warn -deprecated-type=warn -unsafe-getters-setters=warn -unnecessary-invariant=warn -signature-verification-failure=warn -deprecated-utility=error - -[strict] -deprecated-type -nonstrict-import -sketchy-null -unclear-type -unsafe-getters-setters -untyped-import -untyped-type-import - -[version] -^0.122.0 diff --git a/example/.gitattributes b/example/.gitattributes deleted file mode 100644 index d42ff18..0000000 --- a/example/.gitattributes +++ /dev/null @@ -1 +0,0 @@ -*.pbxproj -text diff --git a/example/.gitignore b/example/.gitignore deleted file mode 100644 index ad572e6..0000000 --- a/example/.gitignore +++ /dev/null @@ -1,59 +0,0 @@ -# OSX -# -.DS_Store - -# Xcode -# -build/ -*.pbxuser -!default.pbxuser -*.mode1v3 -!default.mode1v3 -*.mode2v3 -!default.mode2v3 -*.perspectivev3 -!default.perspectivev3 -xcuserdata -*.xccheckout -*.moved-aside -DerivedData -*.hmap -*.ipa -*.xcuserstate - -# Android/IntelliJ -# -build/ -.idea -.gradle -local.properties -*.iml - -# node.js -# -node_modules/ -npm-debug.log -yarn-error.log - -# BUCK -buck-out/ -\.buckd/ -*.keystore -!debug.keystore - -# fastlane -# -# It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the -# screenshots whenever they are needed. -# For more information about the recommended setup visit: -# https://docs.fastlane.tools/best-practices/source-control/ - -*/fastlane/report.xml -*/fastlane/Preview.html -*/fastlane/screenshots - -# Bundle artifact -*.jsbundle - -# CocoaPods -/ios/Pods/ diff --git a/example/.prettierrc.js b/example/.prettierrc.js deleted file mode 100644 index 5c4de1a..0000000 --- a/example/.prettierrc.js +++ /dev/null @@ -1,6 +0,0 @@ -module.exports = { - bracketSpacing: false, - jsxBracketSameLine: true, - singleQuote: true, - trailingComma: 'all', -}; diff --git a/example/.watchmanconfig b/example/.watchmanconfig deleted file mode 100644 index 9e26dfe..0000000 --- a/example/.watchmanconfig +++ /dev/null @@ -1 +0,0 @@ -{} \ No newline at end of file diff --git a/example/App.js b/example/App.js deleted file mode 100644 index fb797fe..0000000 --- a/example/App.js +++ /dev/null @@ -1,302 +0,0 @@ -/** - * Sample BLE React Native App - * - * @format - * @flow strict-local - */ - -import React, { - useState, - useEffect, -} from 'react'; -import { - SafeAreaView, - StyleSheet, - ScrollView, - View, - Text, - StatusBar, - NativeModules, - NativeEventEmitter, - Button, - Platform, - PermissionsAndroid, - FlatList, - TouchableHighlight, -} from 'react-native'; - -import { - Colors, -} from 'react-native/Libraries/NewAppScreen'; - -import BleManager from '../BleManager'; -const BleManagerModule = NativeModules.BleManager; -const bleManagerEmitter = new NativeEventEmitter(BleManagerModule); - -const App = () => { - const [isScanning, setIsScanning] = useState(false); - const peripherals = new Map(); - const [list, setList] = useState([]); - - - const startScan = () => { - if (!isScanning) { - BleManager.scan([], 3, true).then((results) => { - console.log('Scanning...'); - setIsScanning(true); - }).catch(err => { - console.error(err); - }); - } - } - - const handleStopScan = () => { - console.log('Scan is stopped'); - setIsScanning(false); - } - - const handleDisconnectedPeripheral = (data) => { - let peripheral = peripherals.get(data.peripheral); - if (peripheral) { - peripheral.connected = false; - peripherals.set(peripheral.id, peripheral); - setList(Array.from(peripherals.values())); - } - console.log('Disconnected from ' + data.peripheral); - } - - const handleUpdateValueForCharacteristic = (data) => { - console.log('Received data from ' + data.peripheral + ' characteristic ' + data.characteristic, data.value); - } - - const retrieveConnected = () => { - BleManager.getConnectedPeripherals([]).then((results) => { - if (results.length == 0) { - console.log('No connected peripherals') - } - console.log(results); - for (var i = 0; i < results.length; i++) { - var peripheral = results[i]; - peripheral.connected = true; - peripherals.set(peripheral.id, peripheral); - setList(Array.from(peripherals.values())); - } - }); - } - - const handleDiscoverPeripheral = (peripheral) => { - console.log('Got ble peripheral', peripheral); - if (!peripheral.name) { - peripheral.name = 'NO NAME'; - } - peripherals.set(peripheral.id, peripheral); - setList(Array.from(peripherals.values())); - } - - const testPeripheral = (peripheral) => { - if (peripheral){ - if (peripheral.connected){ - BleManager.disconnect(peripheral.id); - }else{ - BleManager.connect(peripheral.id).then(() => { - let p = peripherals.get(peripheral.id); - if (p) { - p.connected = true; - peripherals.set(peripheral.id, p); - setList(Array.from(peripherals.values())); - } - console.log('Connected to ' + peripheral.id); - - - setTimeout(() => { - - /* Test read current RSSI value */ - BleManager.retrieveServices(peripheral.id).then((peripheralData) => { - console.log('Retrieved peripheral services', peripheralData); - - BleManager.readRSSI(peripheral.id).then((rssi) => { - console.log('Retrieved actual RSSI value', rssi); - let p = peripherals.get(peripheral.id); - if (p) { - p.rssi = rssi; - peripherals.set(peripheral.id, p); - setList(Array.from(peripherals.values())); - } - }); - }); - - // Test using bleno's pizza example - // https://github.com/sandeepmistry/bleno/tree/master/examples/pizza - /* - BleManager.retrieveServices(peripheral.id).then((peripheralInfo) => { - console.log(peripheralInfo); - var service = '13333333-3333-3333-3333-333333333337'; - var bakeCharacteristic = '13333333-3333-3333-3333-333333330003'; - var crustCharacteristic = '13333333-3333-3333-3333-333333330001'; - - setTimeout(() => { - BleManager.startNotification(peripheral.id, service, bakeCharacteristic).then(() => { - console.log('Started notification on ' + peripheral.id); - setTimeout(() => { - BleManager.write(peripheral.id, service, crustCharacteristic, [0]).then(() => { - console.log('Writed NORMAL crust'); - BleManager.write(peripheral.id, service, bakeCharacteristic, [1,95]).then(() => { - console.log('Writed 351 temperature, the pizza should be BAKED'); - - //var PizzaBakeResult = { - // HALF_BAKED: 0, - // BAKED: 1, - // CRISPY: 2, - // BURNT: 3, - // ON_FIRE: 4 - //}; - }); - }); - - }, 500); - }).catch((error) => { - console.log('Notification error', error); - }); - }, 200); - });*/ - - - - }, 900); - }).catch((error) => { - console.log('Connection error', error); - }); - } - } - - } - - useEffect(() => { - BleManager.start({showAlert: false}); - - bleManagerEmitter.addListener('BleManagerDiscoverPeripheral', handleDiscoverPeripheral); - bleManagerEmitter.addListener('BleManagerStopScan', handleStopScan ); - bleManagerEmitter.addListener('BleManagerDisconnectPeripheral', handleDisconnectedPeripheral ); - bleManagerEmitter.addListener('BleManagerDidUpdateValueForCharacteristic', handleUpdateValueForCharacteristic ); - - if (Platform.OS === 'android' && Platform.Version >= 23) { - PermissionsAndroid.check(PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION).then((result) => { - if (result) { - console.log("Permission is OK"); - } else { - PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION).then((result) => { - if (result) { - console.log("User accept"); - } else { - console.log("User refuse"); - } - }); - } - }); - } - - return (() => { - console.log('unmount'); - bleManagerEmitter.removeListener('BleManagerDiscoverPeripheral', handleDiscoverPeripheral); - bleManagerEmitter.removeListener('BleManagerStopScan', handleStopScan ); - bleManagerEmitter.removeListener('BleManagerDisconnectPeripheral', handleDisconnectedPeripheral ); - bleManagerEmitter.removeListener('BleManagerDidUpdateValueForCharacteristic', handleUpdateValueForCharacteristic ); - }) - }, []); - - const renderItem = (item) => { - const color = item.connected ? 'green' : '#fff'; - return ( - testPeripheral(item) }> - - {item.name} - RSSI: {item.rssi} - {item.id} - - - ); - } - - return ( - <> - - - - {global.HermesInternal == null ? null : ( - - Engine: Hermes - - )} - - - -