-
Notifications
You must be signed in to change notification settings - Fork 88
/
BleModule.java
executable file
·1739 lines (1496 loc) · 73.6 KB
/
BleModule.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package com.polidea.multiplatformbleadapter;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.ParcelUuid;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.util.SparseArray;
import com.polidea.multiplatformbleadapter.errors.BleError;
import com.polidea.multiplatformbleadapter.errors.BleErrorCode;
import com.polidea.multiplatformbleadapter.errors.BleErrorUtils;
import com.polidea.multiplatformbleadapter.errors.ErrorConverter;
import com.polidea.multiplatformbleadapter.exceptions.CannotMonitorCharacteristicException;
import com.polidea.multiplatformbleadapter.utils.Base64Converter;
import com.polidea.multiplatformbleadapter.utils.Constants;
import com.polidea.multiplatformbleadapter.utils.DisposableMap;
import com.polidea.multiplatformbleadapter.utils.IdGenerator;
import com.polidea.multiplatformbleadapter.utils.LogLevel;
import com.polidea.multiplatformbleadapter.utils.RefreshGattCustomOperation;
import com.polidea.multiplatformbleadapter.utils.SafeExecutor;
import com.polidea.multiplatformbleadapter.utils.ServiceFactory;
import com.polidea.multiplatformbleadapter.utils.UUIDConverter;
import com.polidea.multiplatformbleadapter.utils.mapper.RxBleDeviceToDeviceMapper;
import com.polidea.multiplatformbleadapter.utils.mapper.RxScanResultToScanResultMapper;
import com.polidea.rxandroidble.NotificationSetupMode;
import com.polidea.rxandroidble.RxBleAdapterStateObservable;
import com.polidea.rxandroidble.RxBleClient;
import com.polidea.rxandroidble.RxBleConnection;
import com.polidea.rxandroidble.RxBleDevice;
import com.polidea.rxandroidble.RxBleDeviceServices;
import com.polidea.rxandroidble.internal.RxBleLog;
import com.polidea.rxandroidble.scan.ScanFilter;
import com.polidea.rxandroidble.scan.ScanSettings;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import rx.Observable;
import rx.Observer;
import rx.Subscription;
import rx.functions.Action0;
import rx.functions.Action1;
import rx.functions.Func0;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
import static com.polidea.multiplatformbleadapter.utils.Constants.BluetoothState;
public class BleModule implements BleAdapter {
private final ErrorConverter errorConverter = new ErrorConverter();
@Nullable
private RxBleClient rxBleClient;
private HashMap<String, Device> discoveredDevices = new HashMap<>();
private HashMap<String, Device> connectedDevices = new HashMap<>();
private HashMap<String, RxBleConnection> activeConnections = new HashMap<>();
private SparseArray<Service> discoveredServices = new SparseArray<>();
private SparseArray<Characteristic> discoveredCharacteristics = new SparseArray<>();
private SparseArray<Descriptor> discoveredDescriptors = new SparseArray<>();
private final DisposableMap pendingTransactions = new DisposableMap();
private final DisposableMap connectingDevices = new DisposableMap();
private BluetoothManager bluetoothManager;
private BluetoothAdapter bluetoothAdapter;
private Context context;
@Nullable
private Subscription scanSubscription;
@Nullable
private Subscription adapterStateChangesSubscription;
private RxBleDeviceToDeviceMapper rxBleDeviceToDeviceMapper = new RxBleDeviceToDeviceMapper();
private RxScanResultToScanResultMapper rxScanResultToScanResultMapper = new RxScanResultToScanResultMapper();
private ServiceFactory serviceFactory = new ServiceFactory();
private int currentLogLevel = RxBleLog.NONE;
public BleModule(Context context) {
this.context = context;
bluetoothManager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
bluetoothAdapter = bluetoothManager.getAdapter();
}
@Override
public void createClient(String restoreStateIdentifier,
OnEventCallback<String> onAdapterStateChangeCallback,
OnEventCallback<Integer> onStateRestored) {
rxBleClient = RxBleClient.create(context);
adapterStateChangesSubscription = monitorAdapterStateChanges(context, onAdapterStateChangeCallback);
// We need to send signal that BLE Module starts without restored state
if (restoreStateIdentifier != null) {
onStateRestored.onEvent(null);
}
}
@Override
public void destroyClient() {
if (adapterStateChangesSubscription != null) {
adapterStateChangesSubscription.unsubscribe();
adapterStateChangesSubscription = null;
}
if (scanSubscription != null && !scanSubscription.isUnsubscribed()) {
scanSubscription.unsubscribe();
scanSubscription = null;
}
pendingTransactions.removeAllSubscriptions();
connectingDevices.removeAllSubscriptions();
discoveredServices.clear();
discoveredCharacteristics.clear();
discoveredDescriptors.clear();
connectedDevices.clear();
activeConnections.clear();
discoveredDevices.clear();
rxBleClient = null;
IdGenerator.clear();
}
@Override
public void enable(final String transactionId,
final OnSuccessCallback<Void> onSuccessCallback,
final OnErrorCallback onErrorCallback) {
changeAdapterState(
RxBleAdapterStateObservable.BleAdapterState.STATE_ON,
transactionId,
onSuccessCallback,
onErrorCallback);
}
@Override
public void disable(final String transactionId,
final OnSuccessCallback<Void> onSuccessCallback,
final OnErrorCallback onErrorCallback) {
changeAdapterState(
RxBleAdapterStateObservable.BleAdapterState.STATE_OFF,
transactionId,
onSuccessCallback,
onErrorCallback);
}
@BluetoothState
@Override
public String getCurrentState() {
if (!supportsBluetoothLowEnergy()) return BluetoothState.UNSUPPORTED;
if (bluetoothManager == null) return BluetoothState.POWERED_OFF;
return mapNativeAdapterStateToLocalBluetoothState(bluetoothAdapter.getState());
}
@Override
public void startDeviceScan(String[] filteredUUIDs,
int scanMode,
int callbackType,
OnEventCallback<ScanResult> onEventCallback,
OnErrorCallback onErrorCallback) {
UUID[] uuids = null;
if (filteredUUIDs != null) {
uuids = UUIDConverter.convert(filteredUUIDs);
if (uuids == null) {
onErrorCallback.onError(BleErrorUtils.invalidIdentifiers(filteredUUIDs));
return;
}
}
safeStartDeviceScan(uuids, scanMode, callbackType, onEventCallback, onErrorCallback);
}
@Override
public void stopDeviceScan() {
if (scanSubscription != null) {
scanSubscription.unsubscribe();
scanSubscription = null;
}
}
@Override
public void requestConnectionPriorityForDevice(String deviceIdentifier,
int connectionPriority,
final String transactionId,
final OnSuccessCallback<Device> onSuccessCallback,
final OnErrorCallback onErrorCallback) {
final Device device;
try {
device = getDeviceById(deviceIdentifier);
} catch (BleError error) {
onErrorCallback.onError(error);
return;
}
final RxBleConnection connection = getConnectionOrEmitError(device.getId(), onErrorCallback);
if (connection == null) {
return;
}
final SafeExecutor<Device> safeExecutor = new SafeExecutor<>(onSuccessCallback, onErrorCallback);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
final Subscription subscription = connection
.requestConnectionPriority(connectionPriority, 1, TimeUnit.MILLISECONDS)
.doOnUnsubscribe(new Action0() {
@Override
public void call() {
safeExecutor.error(BleErrorUtils.cancelled());
pendingTransactions.removeSubscription(transactionId);
}
}).subscribe(new Action0() {
@Override
public void call() {
safeExecutor.success(device);
pendingTransactions.removeSubscription(transactionId);
}
}, new Action1<Throwable>() {
@Override
public void call(Throwable error) {
safeExecutor.error(errorConverter.toError(error));
pendingTransactions.removeSubscription(transactionId);
}
});
pendingTransactions.replaceSubscription(transactionId, subscription);
} else {
onSuccessCallback.onSuccess(device);
}
}
@Override
public void readRSSIForDevice(String deviceIdentifier,
final String transactionId,
final OnSuccessCallback<Device> onSuccessCallback,
final OnErrorCallback onErrorCallback) {
final Device device;
try {
device = getDeviceById(deviceIdentifier);
} catch (BleError error) {
onErrorCallback.onError(error);
return;
}
final RxBleConnection connection = getConnectionOrEmitError(device.getId(), onErrorCallback);
if (connection == null) {
return;
}
final SafeExecutor<Device> safeExecutor = new SafeExecutor<>(onSuccessCallback, onErrorCallback);
final Subscription subscription = connection
.readRssi()
.doOnUnsubscribe(new Action0() {
@Override
public void call() {
safeExecutor.error(BleErrorUtils.cancelled());
pendingTransactions.removeSubscription(transactionId);
}
})
.subscribe(new Observer<Integer>() {
@Override
public void onCompleted() {
pendingTransactions.removeSubscription(transactionId);
}
@Override
public void onError(Throwable error) {
safeExecutor.error(errorConverter.toError(error));
pendingTransactions.removeSubscription(transactionId);
}
@Override
public void onNext(Integer rssi) {
device.setRssi(rssi);
safeExecutor.success(device);
}
});
pendingTransactions.replaceSubscription(transactionId, subscription);
}
@Override
public void requestMTUForDevice(String deviceIdentifier, int mtu,
final String transactionId,
final OnSuccessCallback<Device> onSuccessCallback,
final OnErrorCallback onErrorCallback) {
final Device device;
try {
device = getDeviceById(deviceIdentifier);
} catch (BleError error) {
onErrorCallback.onError(error);
return;
}
final RxBleConnection connection = getConnectionOrEmitError(device.getId(), onErrorCallback);
if (connection == null) {
return;
}
final SafeExecutor<Device> safeExecutor = new SafeExecutor<>(onSuccessCallback, onErrorCallback);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
final Subscription subscription = connection
.requestMtu(mtu)
.doOnUnsubscribe(new Action0() {
@Override
public void call() {
safeExecutor.error(BleErrorUtils.cancelled());
pendingTransactions.removeSubscription(transactionId);
}
}).subscribe(new Observer<Integer>() {
@Override
public void onCompleted() {
pendingTransactions.removeSubscription(transactionId);
}
@Override
public void onError(Throwable error) {
safeExecutor.error(errorConverter.toError(error));
pendingTransactions.removeSubscription(transactionId);
}
@Override
public void onNext(Integer mtu) {
device.setMtu(mtu);
safeExecutor.success(device);
}
});
pendingTransactions.replaceSubscription(transactionId, subscription);
} else {
onSuccessCallback.onSuccess(device);
}
}
@Override
public void getKnownDevices(String[] deviceIdentifiers,
OnSuccessCallback<Device[]> onSuccessCallback,
OnErrorCallback onErrorCallback) {
if (rxBleClient == null) {
throw new IllegalStateException("BleManager not created when tried to get known devices");
}
List<Device> knownDevices = new ArrayList<>();
for (final String deviceId : deviceIdentifiers) {
if (deviceId == null) {
onErrorCallback.onError(BleErrorUtils.invalidIdentifiers(deviceIdentifiers));
return;
}
final Device device = discoveredDevices.get(deviceId);
if (device != null) {
knownDevices.add(device);
}
}
onSuccessCallback.onSuccess(knownDevices.toArray(new Device[knownDevices.size()]));
}
@Override
public void getConnectedDevices(String[] serviceUUIDs,
OnSuccessCallback<Device[]> onSuccessCallback,
OnErrorCallback onErrorCallback) {
if (rxBleClient == null) {
throw new IllegalStateException("BleManager not created when tried to get connected devices");
}
if (serviceUUIDs.length == 0) {
onSuccessCallback.onSuccess(new Device[0]);
return;
}
UUID[] uuids = new UUID[serviceUUIDs.length];
for (int i = 0; i < serviceUUIDs.length; i++) {
UUID uuid = UUIDConverter.convert(serviceUUIDs[i]);
if (uuid == null) {
onErrorCallback.onError(BleErrorUtils.invalidIdentifiers(serviceUUIDs));
return;
}
uuids[i] = uuid;
}
List<Device> localConnectedDevices = new ArrayList<>();
for (Device device : connectedDevices.values()) {
for (UUID uuid : uuids) {
if (device.getServiceByUUID(uuid) != null) {
localConnectedDevices.add(device);
break;
}
}
}
onSuccessCallback.onSuccess(localConnectedDevices.toArray(new Device[localConnectedDevices.size()]));
}
@Override
public void connectToDevice(String deviceIdentifier,
ConnectionOptions connectionOptions,
OnSuccessCallback<Device> onSuccessCallback,
OnEventCallback<ConnectionState> onConnectionStateChangedCallback,
OnErrorCallback onErrorCallback) {
if (rxBleClient == null) {
throw new IllegalStateException("BleManager not created when tried to connect to device");
}
final RxBleDevice device = rxBleClient.getBleDevice(deviceIdentifier);
if (device == null) {
onErrorCallback.onError(BleErrorUtils.deviceNotFound(deviceIdentifier));
return;
}
safeConnectToDevice(
device,
connectionOptions.getAutoConnect(),
connectionOptions.getRequestMTU(),
connectionOptions.getRefreshGattMoment(),
connectionOptions.getTimeoutInMillis(),
connectionOptions.getConnectionPriority(),
onSuccessCallback, onConnectionStateChangedCallback, onErrorCallback);
}
@Override
public void cancelDeviceConnection(String deviceIdentifier,
OnSuccessCallback<Device> onSuccessCallback,
OnErrorCallback onErrorCallback) {
if (rxBleClient == null) {
throw new IllegalStateException("BleManager not created when tried to cancel device connection");
}
final RxBleDevice device = rxBleClient.getBleDevice(deviceIdentifier);
if (connectingDevices.removeSubscription(deviceIdentifier) && device != null) {
onSuccessCallback.onSuccess(rxBleDeviceToDeviceMapper.map(device));
} else {
if (device == null) {
onErrorCallback.onError(BleErrorUtils.deviceNotFound(deviceIdentifier));
} else {
onErrorCallback.onError(BleErrorUtils.deviceNotConnected(deviceIdentifier));
}
}
}
@Override
public void isDeviceConnected(String deviceIdentifier,
OnSuccessCallback<Boolean> onSuccessCallback,
OnErrorCallback onErrorCallback) {
if (rxBleClient == null) {
throw new IllegalStateException("BleManager not created when tried to check if device is connected");
}
final RxBleDevice device = rxBleClient.getBleDevice(deviceIdentifier);
if (device == null) {
onErrorCallback.onError(BleErrorUtils.deviceNotFound(deviceIdentifier));
return;
}
boolean connected = device.getConnectionState()
.equals(RxBleConnection.RxBleConnectionState.CONNECTED);
onSuccessCallback.onSuccess(connected);
}
@Override
public void discoverAllServicesAndCharacteristicsForDevice(String deviceIdentifier,
String transactionId,
OnSuccessCallback<Device> onSuccessCallback,
OnErrorCallback onErrorCallback) {
final Device device;
try {
device = getDeviceById(deviceIdentifier);
} catch (BleError error) {
onErrorCallback.onError(error);
return;
}
safeDiscoverAllServicesAndCharacteristicsForDevice(device, transactionId, onSuccessCallback, onErrorCallback);
}
@Override
public List<Service> getServicesForDevice(String deviceIdentifier) throws BleError {
final Device device = getDeviceById(deviceIdentifier);
final List<Service> services = device.getServices();
if (services == null) {
throw BleErrorUtils.deviceServicesNotDiscovered(device.getId());
}
return services;
}
@Override
public List<Characteristic> getCharacteristicsForDevice(String deviceIdentifier,
String serviceUUID) throws BleError {
final UUID convertedServiceUUID = UUIDConverter.convert(serviceUUID);
if (convertedServiceUUID == null) {
throw BleErrorUtils.invalidIdentifiers(serviceUUID);
}
final Device device = getDeviceById(deviceIdentifier);
final Service service = device.getServiceByUUID(convertedServiceUUID);
if (service == null) {
throw BleErrorUtils.serviceNotFound(serviceUUID);
}
return service.getCharacteristics();
}
@Override
public List<Characteristic> getCharacteristicsForService(int serviceIdentifier) throws BleError {
Service service = discoveredServices.get(serviceIdentifier);
if (service == null) {
throw BleErrorUtils.serviceNotFound(Integer.toString(serviceIdentifier));
}
return service.getCharacteristics();
}
@Override
public List<Descriptor> descriptorsForDevice(final String deviceIdentifier,
final String serviceUUID,
final String characteristicUUID) throws BleError {
final UUID[] uuids = UUIDConverter.convert(serviceUUID, characteristicUUID);
if (uuids == null) {
throw BleErrorUtils.invalidIdentifiers(serviceUUID, characteristicUUID);
}
Device device = getDeviceById(deviceIdentifier);
final Service service = device.getServiceByUUID(uuids[0]);
if (service == null) {
throw BleErrorUtils.serviceNotFound(serviceUUID);
}
final Characteristic characteristic = service.getCharacteristicByUUID(uuids[1]);
if (characteristic == null) {
throw BleErrorUtils.characteristicNotFound(characteristicUUID);
}
return characteristic.getDescriptors();
}
@Override
public List<Descriptor> descriptorsForService(final int serviceIdentifier,
final String characteristicUUID) throws BleError {
final UUID uuid = UUIDConverter.convert(characteristicUUID);
if (uuid == null) {
throw BleErrorUtils.invalidIdentifiers(characteristicUUID);
}
Service service = discoveredServices.get(serviceIdentifier);
if (service == null) {
throw BleErrorUtils.serviceNotFound(Integer.toString(serviceIdentifier));
}
final Characteristic characteristic = service.getCharacteristicByUUID(uuid);
if (characteristic == null) {
throw BleErrorUtils.characteristicNotFound(characteristicUUID);
}
return characteristic.getDescriptors();
}
@Override
public List<Descriptor> descriptorsForCharacteristic(final int characteristicIdentifier) throws BleError {
Characteristic characteristic = discoveredCharacteristics.get(characteristicIdentifier);
if (characteristic == null) {
throw BleErrorUtils.characteristicNotFound(Integer.toString(characteristicIdentifier));
}
return characteristic.getDescriptors();
}
@Override
public void readCharacteristicForDevice(String deviceIdentifier,
String serviceUUID,
String characteristicUUID,
String transactionId,
OnSuccessCallback<Characteristic> onSuccessCallback,
OnErrorCallback onErrorCallback) {
final Characteristic characteristic = getCharacteristicOrEmitError(
deviceIdentifier, serviceUUID, characteristicUUID, onErrorCallback);
if (characteristic == null) {
return;
}
safeReadCharacteristicForDevice(characteristic, transactionId, onSuccessCallback, onErrorCallback);
}
@Override
public void readCharacteristicForService(int serviceIdentifier,
String characteristicUUID,
String transactionId,
OnSuccessCallback<Characteristic> onSuccessCallback,
OnErrorCallback onErrorCallback) {
final Characteristic characteristic = getCharacteristicOrEmitError(
serviceIdentifier, characteristicUUID, onErrorCallback);
if (characteristic == null) {
return;
}
safeReadCharacteristicForDevice(characteristic, transactionId, onSuccessCallback, onErrorCallback);
}
@Override
public void readCharacteristic(int characteristicIdentifier,
String transactionId,
OnSuccessCallback<Characteristic> onSuccessCallback,
OnErrorCallback onErrorCallback) {
final Characteristic characteristic = getCharacteristicOrEmitError(characteristicIdentifier, onErrorCallback);
if (characteristic == null) {
return;
}
safeReadCharacteristicForDevice(characteristic, transactionId, onSuccessCallback, onErrorCallback);
}
@Override
public void writeCharacteristicForDevice(String deviceIdentifier,
String serviceUUID,
String characteristicUUID,
String valueBase64,
boolean withResponse,
String transactionId,
OnSuccessCallback<Characteristic> onSuccessCallback,
OnErrorCallback onErrorCallback) {
final Characteristic characteristic = getCharacteristicOrEmitError(
deviceIdentifier, serviceUUID, characteristicUUID, onErrorCallback);
if (characteristic == null) {
return;
}
writeCharacteristicWithValue(
characteristic,
valueBase64,
withResponse,
transactionId,
onSuccessCallback,
onErrorCallback);
}
@Override
public void writeCharacteristicForService(int serviceIdentifier,
String characteristicUUID,
String valueBase64,
boolean withResponse,
String transactionId,
OnSuccessCallback<Characteristic> onSuccessCallback,
OnErrorCallback onErrorCallback) {
final Characteristic characteristic = getCharacteristicOrEmitError(
serviceIdentifier, characteristicUUID, onErrorCallback);
if (characteristic == null) {
return;
}
writeCharacteristicWithValue(
characteristic,
valueBase64,
withResponse,
transactionId,
onSuccessCallback,
onErrorCallback);
}
@Override
public void writeCharacteristic(int characteristicIdentifier,
String valueBase64,
boolean withResponse,
String transactionId,
OnSuccessCallback<Characteristic> onSuccessCallback,
OnErrorCallback onErrorCallback) {
final Characteristic characteristic = getCharacteristicOrEmitError(characteristicIdentifier, onErrorCallback);
if (characteristic == null) {
return;
}
writeCharacteristicWithValue(
characteristic,
valueBase64,
withResponse,
transactionId,
onSuccessCallback,
onErrorCallback
);
}
@Override
public void monitorCharacteristicForDevice(String deviceIdentifier,
String serviceUUID,
String characteristicUUID,
String transactionId,
OnEventCallback<Characteristic> onEventCallback,
OnErrorCallback onErrorCallback) {
final Characteristic characteristic = getCharacteristicOrEmitError(
deviceIdentifier, serviceUUID, characteristicUUID, onErrorCallback);
if (characteristic == null) {
return;
}
safeMonitorCharacteristicForDevice(characteristic, transactionId, onEventCallback, onErrorCallback);
}
@Override
public void monitorCharacteristicForService(int serviceIdentifier,
String characteristicUUID,
String transactionId,
OnEventCallback<Characteristic> onEventCallback,
OnErrorCallback onErrorCallback) {
final Characteristic characteristic = getCharacteristicOrEmitError(
serviceIdentifier, characteristicUUID, onErrorCallback);
if (characteristic == null) {
return;
}
safeMonitorCharacteristicForDevice(characteristic, transactionId, onEventCallback, onErrorCallback);
}
@Override
public void monitorCharacteristic(int characteristicIdentifier, String transactionId,
OnEventCallback<Characteristic> onEventCallback,
OnErrorCallback onErrorCallback) {
final Characteristic characteristic = getCharacteristicOrEmitError(characteristicIdentifier, onErrorCallback);
if (characteristic == null) {
return;
}
safeMonitorCharacteristicForDevice(characteristic, transactionId, onEventCallback, onErrorCallback);
}
@Override
public void readDescriptorForDevice(final String deviceId,
final String serviceUUID,
final String characteristicUUID,
final String descriptorUUID,
final String transactionId,
OnSuccessCallback<Descriptor> successCallback,
OnErrorCallback errorCallback) {
try {
Descriptor descriptor = getDescriptor(deviceId, serviceUUID, characteristicUUID, descriptorUUID);
safeReadDescriptorForDevice(descriptor, transactionId, successCallback, errorCallback);
} catch (BleError error) {
errorCallback.onError(error);
}
}
@Override
public void readDescriptorForService(final int serviceIdentifier,
final String characteristicUUID,
final String descriptorUUID,
final String transactionId,
OnSuccessCallback<Descriptor> successCallback,
OnErrorCallback errorCallback) {
try {
Descriptor descriptor = getDescriptor(serviceIdentifier, characteristicUUID, descriptorUUID);
safeReadDescriptorForDevice(descriptor, transactionId, successCallback, errorCallback);
} catch (BleError error) {
errorCallback.onError(error);
}
}
@Override
public void readDescriptorForCharacteristic(final int characteristicIdentifier,
final String descriptorUUID,
final String transactionId,
OnSuccessCallback<Descriptor> successCallback,
OnErrorCallback errorCallback) {
try {
Descriptor descriptor = getDescriptor(characteristicIdentifier, descriptorUUID);
safeReadDescriptorForDevice(descriptor, transactionId, successCallback, errorCallback);
} catch (BleError error) {
errorCallback.onError(error);
}
}
@Override
public void readDescriptor(final int descriptorIdentifier,
final String transactionId,
OnSuccessCallback<Descriptor> onSuccessCallback,
OnErrorCallback onErrorCallback) {
try {
Descriptor descriptor = getDescriptor(descriptorIdentifier);
safeReadDescriptorForDevice(descriptor, transactionId, onSuccessCallback, onErrorCallback);
} catch (BleError error) {
onErrorCallback.onError(error);
}
}
private void safeReadDescriptorForDevice(final Descriptor descriptor,
final String transactionId,
OnSuccessCallback<Descriptor> onSuccessCallback,
OnErrorCallback onErrorCallback) {
final RxBleConnection connection = getConnectionOrEmitError(descriptor.getDeviceId(), onErrorCallback);
if (connection == null) {
return;
}
final SafeExecutor<Descriptor> safeExecutor = new SafeExecutor<>(onSuccessCallback, onErrorCallback);
final Subscription subscription = connection
.readDescriptor(descriptor.getNativeDescriptor())
.doOnUnsubscribe(new Action0() {
@Override
public void call() {
safeExecutor.error(BleErrorUtils.cancelled());
pendingTransactions.removeSubscription(transactionId);
}
})
.subscribe(new Observer<byte[]>() {
@Override
public void onCompleted() {
pendingTransactions.removeSubscription(transactionId);
}
@Override
public void onError(Throwable e) {
safeExecutor.error(errorConverter.toError(e));
pendingTransactions.removeSubscription(transactionId);
}
@Override
public void onNext(byte[] bytes) {
descriptor.logValue("Read from", bytes);
descriptor.setValue(bytes);
safeExecutor.success(new Descriptor(descriptor));
}
});
pendingTransactions.replaceSubscription(transactionId, subscription);
}
@Override
public void writeDescriptorForDevice(final String deviceId,
final String serviceUUID,
final String characteristicUUID,
final String descriptorUUID,
final String valueBase64,
final String transactionId,
OnSuccessCallback<Descriptor> successCallback,
OnErrorCallback errorCallback) {
try {
Descriptor descriptor = getDescriptor(deviceId, serviceUUID, characteristicUUID, descriptorUUID);
safeWriteDescriptorForDevice(
descriptor,
valueBase64,
transactionId,
successCallback,
errorCallback);
} catch (BleError error) {
errorCallback.onError(error);
}
}
@Override
public void writeDescriptorForService(final int serviceIdentifier,
final String characteristicUUID,
final String descriptorUUID,
final String valueBase64,
final String transactionId,
OnSuccessCallback<Descriptor> successCallback,
OnErrorCallback errorCallback) {
try {
Descriptor descriptor = getDescriptor(serviceIdentifier, characteristicUUID, descriptorUUID);
safeWriteDescriptorForDevice(
descriptor,
valueBase64,
transactionId,
successCallback,
errorCallback);
} catch (BleError error) {
errorCallback.onError(error);
}
}
@Override
public void writeDescriptorForCharacteristic(final int characteristicIdentifier,
final String descriptorUUID,
final String valueBase64,
final String transactionId,
OnSuccessCallback<Descriptor> successCallback,
OnErrorCallback errorCallback) {
try {
Descriptor descriptor = getDescriptor(characteristicIdentifier, descriptorUUID);
safeWriteDescriptorForDevice(
descriptor,
valueBase64,
transactionId,
successCallback,
errorCallback);
} catch (BleError error) {
errorCallback.onError(error);
}
}
@Override
public void writeDescriptor(final int descriptorIdentifier,
final String valueBase64,
final String transactionId,
OnSuccessCallback<Descriptor> successCallback,
OnErrorCallback errorCallback) {
try {
Descriptor descriptor = getDescriptor(descriptorIdentifier);
safeWriteDescriptorForDevice(
descriptor,
valueBase64,
transactionId,
successCallback,
errorCallback);
} catch (BleError error) {
errorCallback.onError(error);
}
}
private void safeWriteDescriptorForDevice(final Descriptor descriptor,
final String valueBase64,
final String transactionId,
OnSuccessCallback<Descriptor> successCallback,
OnErrorCallback errorCallback) {
BluetoothGattDescriptor nativeDescriptor = descriptor.getNativeDescriptor();
if (nativeDescriptor.getUuid().equals(Constants.CLIENT_CHARACTERISTIC_CONFIG_UUID)) {
errorCallback.onError(BleErrorUtils.descriptorWriteNotAllowed(UUIDConverter.fromUUID(nativeDescriptor.getUuid())));
return;
}
final RxBleConnection connection = getConnectionOrEmitError(descriptor.getDeviceId(), errorCallback);
if (connection == null) {
return;
}
final byte[] value;
try {
value = Base64Converter.decode(valueBase64);
} catch (Throwable e) {
String uuid = UUIDConverter.fromUUID(nativeDescriptor.getUuid());
errorCallback.onError(BleErrorUtils.invalidWriteDataForDescriptor(valueBase64, uuid));
return;
}
final SafeExecutor<Descriptor> safeExecutor = new SafeExecutor<>(successCallback, errorCallback);
final Subscription subscription = connection
.writeDescriptor(nativeDescriptor, value)
.doOnUnsubscribe(new Action0() {
@Override
public void call() {
safeExecutor.error(BleErrorUtils.cancelled());
pendingTransactions.removeSubscription(transactionId);
}
})
.subscribe(new Observer<byte[]>() {
@Override
public void onCompleted() {
pendingTransactions.removeSubscription(transactionId);
}
@Override
public void onError(Throwable e) {
safeExecutor.error(errorConverter.toError(e));
pendingTransactions.removeSubscription(transactionId);
}
@Override
public void onNext(byte[] bytes) {
descriptor.logValue("Write to", bytes);
descriptor.setValue(bytes);
safeExecutor.success(new Descriptor(descriptor));
}
});
pendingTransactions.replaceSubscription(transactionId, subscription);
}
// Mark: Descriptors getters -------------------------------------------------------------------
private Descriptor getDescriptor(@NonNull final String deviceId,
@NonNull final String serviceUUID,