-
Notifications
You must be signed in to change notification settings - Fork 513
/
BleManager.js
1290 lines (1206 loc) · 49.9 KB
/
BleManager.js
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
// @flow
'use strict'
import { Device } from './Device'
import { Service } from './Service'
import { Characteristic } from './Characteristic'
import { Descriptor } from './Descriptor'
import { State, LogLevel, type BleErrorCodeMessageMapping, ConnectionPriority } from './TypeDefinition'
import { BleModule, EventEmitter } from './BleModule'
import {
parseBleError,
BleError,
BleErrorCode,
BleErrorCodeMessage,
BleATTErrorCode,
BleAndroidErrorCode,
BleIOSErrorCode
} from './BleError'
import type { NativeDevice, NativeCharacteristic, NativeDescriptor, NativeBleRestoredState } from './BleModule'
import type {
Subscription,
DeviceId,
Identifier,
UUID,
TransactionId,
Base64,
ScanOptions,
ConnectionOptions,
BleManagerOptions
} from './TypeDefinition'
import { Platform } from 'react-native'
const enableDisableDeprecatedMessage =
'react-native-ble-plx: The enable and disable feature is no longer supported. In Android SDK 31+ there were major changes in permissions, which may cause problems with these functions, and in SDK 33+ they were completely removed.'
/**
*
* BleManager is an entry point for react-native-ble-plx library. It provides all means to discover and work with
* {@link Device} instances. It should be initialized only once with `new` keyword and method
* {@link #blemanagerdestroy|destroy()} should be called on its instance when user wants to deallocate all resources.
*
* In case you want to properly support Background Mode, you should provide `restoreStateIdentifier` and
* `restoreStateFunction` in {@link BleManagerOptions}.
*
* @example
* const manager = new BleManager();
* // ... work with BLE manager ...
* manager.destroy();
*/
export class BleManager {
// Scan subscriptions
// $FlowIssue[missing-type-arg]
_scanEventSubscription: ?EventEmitter
// Listening to BleModule events
// $FlowIssue[missing-type-arg]
_eventEmitter: EventEmitter
// Unique identifier used to create internal transactionIds
_uniqueId: number
// Map of active promises with functions to forcibly cancel them
_activePromises: { [id: string]: (error: BleError) => void }
// Map of active subscriptions
_activeSubscriptions: { [id: string]: Subscription }
// Map of error codes to error messages
_errorCodesToMessagesMapping: BleErrorCodeMessageMapping
/**
* Creates an instance of {@link BleManager}.
*/
constructor(options: BleManagerOptions = {}) {
this._eventEmitter = new EventEmitter(BleModule)
this._uniqueId = 0
this._activePromises = {}
this._activeSubscriptions = {}
const restoreStateFunction = options.restoreStateFunction
if (restoreStateFunction != null && options.restoreStateIdentifier != null) {
// $FlowIssue[prop-missing]
this._activeSubscriptions[this._nextUniqueID()] = this._eventEmitter.addListener(
BleModule.RestoreStateEvent,
(nativeRestoredState: NativeBleRestoredState) => {
if (nativeRestoredState == null) {
restoreStateFunction(null)
return
}
restoreStateFunction({
connectedPeripherals: nativeRestoredState.connectedPeripherals.map(
nativeDevice => new Device(nativeDevice, this)
)
})
}
)
}
this._errorCodesToMessagesMapping = options.errorCodesToMessagesMapping
? options.errorCodesToMessagesMapping
: BleErrorCodeMessage
BleModule.createClient(options.restoreStateIdentifier || null)
}
/**
* Destroys all promises which are in progress.
* @private
*/
_destroyPromises() {
const destroyedError = new BleError(
{
errorCode: BleErrorCode.BluetoothManagerDestroyed,
attErrorCode: (null: ?$Values<typeof BleATTErrorCode>),
iosErrorCode: (null: ?$Values<typeof BleIOSErrorCode>),
androidErrorCode: (null: ?$Values<typeof BleAndroidErrorCode>),
reason: (null: ?string)
},
this._errorCodesToMessagesMapping
)
for (const id in this._activePromises) {
this._activePromises[id](destroyedError)
}
}
/**
* Destroys all subscriptions.
* @private
*/
_destroySubscriptions() {
for (const id in this._activeSubscriptions) {
this._activeSubscriptions[id].remove()
}
}
// async readRSSIForDevice(deviceIdentifier: DeviceId, transactionId: ?TransactionId): Promise<Device> {
// if (!transactionId) {
// transactionId = this._nextUniqueID()
// }
// const nativeDevice = await this._callPromise(BleModule.readRSSIForDevice(deviceIdentifier, transactionId))
// return new Device(nativeDevice, this)
// }
/**
* Destroys {@link BleManager} instance. A new instance needs to be created to continue working with
* this library. All operations which were in progress completes with
* @returns {Promise<void>} Promise may return an error when the function cannot be called.
* {@link #bleerrorcodebluetoothmanagerdestroyed|BluetoothManagerDestroyed} error code.
*/
destroy = async (): Promise<void> => {
const response = await this._callPromise(BleModule.destroyClient())
// Unsubscribe from any subscriptions
if (this._scanEventSubscription != null) {
this._scanEventSubscription.remove()
this._scanEventSubscription = null
}
this._destroySubscriptions()
// Destroy all promises
this._destroyPromises()
return response
}
/**
* Generates new unique identifier to be used internally.
*
* @returns {string} New identifier.
* @private
*/
_nextUniqueID(): string {
this._uniqueId += 1
return this._uniqueId.toString()
}
/**
* Calls promise and checks if it completed successfully
*
* @param {Promise<T>} promise Promise to be called
* @returns {Promise<T>} Value of called promise.
* @private
*/
async _callPromise<T>(promise: Promise<T>): Promise<T> {
const id = this._nextUniqueID()
try {
const destroyPromise = new Promise((resolve, reject) => {
this._activePromises[id] = reject
})
const value = await Promise.race([destroyPromise, promise])
delete this._activePromises[id]
// $FlowIssue[incompatible-return]
return value
} catch (error) {
delete this._activePromises[id]
throw parseBleError(error.message, this._errorCodesToMessagesMapping)
}
}
// Mark: Common ------------------------------------------------------------------------------------------------------
/**
* Sets new log level for native module's logging mechanism.
* @param {LogLevel} logLevel New log level to be set.
* @returns {Promise<LogLevel>} Current log level.
*/
setLogLevel(logLevel: $Keys<typeof LogLevel>): Promise<$Keys<typeof LogLevel> | void> {
return this._callPromise(BleModule.setLogLevel(logLevel))
}
/**
* Get current log level for native module's logging mechanism.
* @returns {Promise<LogLevel>} Current log level.
*/
logLevel(): Promise<$Keys<typeof LogLevel>> {
return this._callPromise(BleModule.logLevel())
}
/**
* Cancels pending transaction.
*
* Few operations such as monitoring characteristic's value changes can be cancelled by a user. Basically every API
* entry which accepts `transactionId` allows to call `cancelTransaction` function. When cancelled operation is a
* promise or a callback which registers errors, {@link #bleerror|BleError} with error code
* {@link #bleerrorcodeoperationcancelled|OperationCancelled} will be emitted in that case. Cancelling transaction
* which doesn't exist is ignored.
*
* @example
* const transactionId = 'monitor_battery';
*
* // Monitor battery notifications
* manager.monitorCharacteristicForDevice(
* device.id, '180F', '2A19',
* (error, characteristic) => {
* // Handle battery level changes...
* }, transactionId);
*
* // Cancel after specified amount of time
* setTimeout(() => manager.cancelTransaction(transactionId), 2000);
*
* @param {TransactionId} transactionId Id of pending transactions.
* @returns {Promise<void>}
*/
cancelTransaction(transactionId: TransactionId) {
return this._callPromise(BleModule.cancelTransaction(transactionId))
}
// Mark: Monitoring state --------------------------------------------------------------------------------------------
/**
* Enable Bluetooth. This function blocks until BLE is in PoweredOn state. [Android only]
*
* @param {?TransactionId} transactionId Transaction handle used to cancel operation
* @returns {Promise<BleManager>} Promise completes when state transition was successful.
*/
async enable(transactionId: ?TransactionId): Promise<BleManager> {
if (!transactionId) {
transactionId = this._nextUniqueID()
}
await this._callPromise(BleModule.enable(transactionId))
return this
}
/**
* Deprecated
* Disable Bluetooth. This function blocks until BLE is in PoweredOff state. [Android only]
*
* @param {?TransactionId} transactionId Transaction handle used to cancel operation
* @returns {Promise<BleManager>} Promise completes when state transition was successful.
*/
async disable(transactionId: ?TransactionId): Promise<BleManager> {
console.warn(enableDisableDeprecatedMessage)
if (!transactionId) {
transactionId = this._nextUniqueID()
}
await this._callPromise(BleModule.disable(transactionId))
return this
}
/**
* Current, global {@link State} of a {@link BleManager}. All APIs are working only when active state
* is "PoweredOn".
*
* @returns {Promise<State>} Promise which emits current state of BleManager.
*/
state = (): Promise<$Keys<typeof State>> => {
return this._callPromise(BleModule.state())
}
/**
* Notifies about {@link State} changes of a {@link BleManager}.
*
* @example
* const subscription = this.manager.onStateChange((state) => {
* if (state === 'PoweredOn') {
* this.scanAndConnect();
* subscription.remove();
* }
* }, true);
*
* @param {function(newState: State)} listener Callback which emits state changes of BLE Manager.
* Look at {@link State} for possible values.
* @param {boolean} [emitCurrentState=false] If true, current state will be emitted as well. Defaults to false.
*
* @returns {Subscription} Subscription on which `remove()` function can be called to unsubscribe.
*/
onStateChange = (
listener: (newState: $Keys<typeof State>) => void,
emitCurrentState: boolean = false
): Subscription => {
const subscription: Subscription = this._eventEmitter.addListener(BleModule.StateChangeEvent, listener)
const id = this._nextUniqueID()
var wrappedSubscription: Subscription
if (emitCurrentState) {
var cancelled = false
this._callPromise(this.state()).then(currentState => {
console.log(currentState)
if (!cancelled) {
listener(currentState)
}
})
wrappedSubscription = {
remove: () => {
if (this._activeSubscriptions[id] != null) {
cancelled = true
delete this._activeSubscriptions[id]
subscription.remove()
}
}
}
} else {
wrappedSubscription = {
remove: () => {
if (this._activeSubscriptions[id] != null) {
delete this._activeSubscriptions[id]
subscription.remove()
}
}
}
}
this._activeSubscriptions[id] = wrappedSubscription
return wrappedSubscription
}
// Mark: Scanning ----------------------------------------------------------------------------------------------------
/**
* Starts device scanning. When previous scan is in progress it will be stopped before executing this command.
*
* @param {?Array<UUID>} UUIDs Array of strings containing {@link UUID}s of {@link Service}s which are registered in
* scanned {@link Device}. If `null` is passed, all available {@link Device}s will be scanned.
* @param {?ScanOptions} options Optional configuration for scanning operation.
* @param {function(error: ?BleError, scannedDevice: ?Device)} listener Function which will be called for every scanned
* @returns {Promise<void>} Promise may return an error when the function cannot be called.
* {@link Device} (devices may be scanned multiple times). It's first argument is potential {@link Error} which is set
* to non `null` value when scanning failed. You have to start scanning process again if that happens. Second argument
* is a scanned {@link Device}.
* @returns {Promise<void>} the promise may be rejected if the operation is impossible to perform.
*/
async startDeviceScan(
UUIDs: ?Array<UUID>,
options: ?ScanOptions,
listener: (error: ?BleError, scannedDevice: ?Device) => Promise<void>
) {
const scanListener = ([error, nativeDevice]: [?string, ?NativeDevice]) => {
listener(
error ? parseBleError(error, this._errorCodesToMessagesMapping) : null,
nativeDevice ? new Device(nativeDevice, this) : null
)
}
// $FlowFixMe: Flow cannot deduce EmitterSubscription type.
this._scanEventSubscription = this._eventEmitter.addListener(BleModule.ScanEvent, scanListener)
return this._callPromise(BleModule.startDeviceScan(UUIDs, options))
}
/**
* Stops {@link Device} scan if in progress.
* @returns {Promise<void>} the promise may be rejected if the operation is impossible to perform.
*/
stopDeviceScan = async (): Promise<void> => {
if (this._scanEventSubscription != null) {
this._scanEventSubscription.remove()
this._scanEventSubscription = null
}
return this._callPromise(BleModule.stopDeviceScan())
}
/**
* Request a connection parameter update. This functions may update connection parameters on Android API level 21 or
* above.
*
* @param {DeviceId} deviceIdentifier Device identifier.
* @param {ConnectionPriority} connectionPriority: Connection priority.
* @param {?TransactionId} transactionId Transaction handle used to cancel operation.
* @returns {Promise<Device>} Connected device.
*/
async requestConnectionPriorityForDevice(
deviceIdentifier: DeviceId,
connectionPriority: $Values<typeof ConnectionPriority>,
transactionId: ?TransactionId
): Promise<Device> {
if (!transactionId) {
transactionId = this._nextUniqueID()
}
const nativeDevice = await this._callPromise(
BleModule.requestConnectionPriorityForDevice(deviceIdentifier, connectionPriority, transactionId)
)
return new Device(nativeDevice, this)
}
/**
* Reads RSSI for connected device.
*
* @param {DeviceId} deviceIdentifier Device identifier.
* @param {?TransactionId} transactionId Transaction handle used to cancel operation
* @returns {Promise<Device>} Connected device with updated RSSI value.
*/
async readRSSIForDevice(deviceIdentifier: DeviceId, transactionId: ?TransactionId): Promise<Device> {
if (!transactionId) {
transactionId = this._nextUniqueID()
}
const nativeDevice = await this._callPromise(BleModule.readRSSIForDevice(deviceIdentifier, transactionId))
return new Device(nativeDevice, this)
}
/**
* Request new MTU value for this device. This function currently is not doing anything
* on iOS platform as MTU exchange is done automatically.
* @param {DeviceId} deviceIdentifier Device identifier.
* @param {number} mtu New MTU to negotiate.
* @param {?TransactionId} transactionId Transaction handle used to cancel operation
* @returns {Promise<Device>} Device with updated MTU size. Default value is 23.
*/
async requestMTUForDevice(deviceIdentifier: DeviceId, mtu: number, transactionId: ?TransactionId): Promise<Device> {
if (!transactionId) {
transactionId = this._nextUniqueID()
}
const nativeDevice = await this._callPromise(BleModule.requestMTUForDevice(deviceIdentifier, mtu, transactionId))
return new Device(nativeDevice, this)
}
// Mark: Connection management ---------------------------------------------------------------------------------------
/**
* Returns a list of known devices by their identifiers.
* @param {Array<DeviceId>} deviceIdentifiers List of device identifiers.
* @returns {Promise<Array<Device>>} List of known devices by their identifiers.
*/
async devices(deviceIdentifiers: Array<DeviceId>): Promise<Array<Device>> {
const nativeDevices = await this._callPromise(BleModule.devices(deviceIdentifiers))
return nativeDevices.map((nativeDevice: NativeDevice) => {
return new Device(nativeDevice, this)
})
}
/**
* Returns a list of the peripherals (containing any of the specified services) currently connected to the system
* which have discovered services. Returned devices **may not be connected** to your application. Make sure to check
* if that's the case with function {@link #blemanagerisdeviceconnected|isDeviceConnected}.
* @param {Array<UUID>} serviceUUIDs List of service UUIDs. Device must contain at least one of them to be listed.
* @returns {Promise<Array<Device>>} List of known devices with discovered services as stated in the parameter.
*/
async connectedDevices(serviceUUIDs: Array<UUID>): Promise<Array<Device>> {
const nativeDevices = await this._callPromise(BleModule.connectedDevices(serviceUUIDs))
return nativeDevices.map((nativeDevice: NativeDevice) => {
return new Device(nativeDevice, this)
})
}
// Mark: Connection management ---------------------------------------------------------------------------------------
/**
* Connects to {@link Device} with provided ID.
*
* @param {DeviceId} deviceIdentifier {@link Device} identifier.
* @param {?ConnectionOptions} options Platform specific options for connection establishment.
* @returns {Promise<Device>} Connected {@link Device} object if successful.
*/
async connectToDevice(deviceIdentifier: DeviceId, options: ?ConnectionOptions): Promise<Device> {
if (Platform.OS === 'android' && (await this.isDeviceConnected(deviceIdentifier))) {
await this.cancelDeviceConnection(deviceIdentifier)
}
const nativeDevice = await this._callPromise(BleModule.connectToDevice(deviceIdentifier, options))
return new Device(nativeDevice, this)
}
/**
* Disconnects from {@link Device} if it's connected or cancels pending connection.
*
* @param {DeviceId} deviceIdentifier {@link Device} identifier to be closed.
* @returns {Promise<Device>} Returns closed {@link Device} when operation is successful.
*/
async cancelDeviceConnection(deviceIdentifier: DeviceId): Promise<Device> {
const nativeDevice = await this._callPromise(BleModule.cancelDeviceConnection(deviceIdentifier))
return new Device(nativeDevice, this)
}
/**
* Monitors if {@link Device} was disconnected due to any errors or connection problems.
*
* @param {DeviceId} deviceIdentifier {@link Device} identifier to be monitored.
* @param {function(error: ?BleError, device: Device)} listener - callback returning error as a reason of disconnection
* if available and {@link Device} object. If an error is null, that means the connection was terminated by
* {@link #blemanagercanceldeviceconnection|bleManager.cancelDeviceConnection()} call.
* @returns {Subscription} Subscription on which `remove()` function can be called to unsubscribe.
*/
onDeviceDisconnected(deviceIdentifier: DeviceId, listener: (error: ?BleError, device: Device) => void): Subscription {
const disconnectionListener = ([error, nativeDevice]: [?string, NativeDevice]) => {
if (deviceIdentifier !== nativeDevice.id) {
return
}
listener(error ? parseBleError(error, this._errorCodesToMessagesMapping) : null, new Device(nativeDevice, this))
}
const subscription: Subscription = this._eventEmitter.addListener(
BleModule.DisconnectionEvent,
disconnectionListener
)
const id = this._nextUniqueID()
const wrappedSubscription = {
remove: () => {
if (this._activeSubscriptions[id] != null) {
delete this._activeSubscriptions[id]
subscription.remove()
}
}
}
this._activeSubscriptions[id] = wrappedSubscription
return wrappedSubscription
}
/**
* Check connection state of a {@link Device}.
*
* @param {DeviceId} deviceIdentifier {@link Device} identifier.
* @returns {Promise<boolean>} Promise which emits `true` if device is connected, and `false` otherwise.
*/
isDeviceConnected(deviceIdentifier: DeviceId): Promise<boolean> {
return this._callPromise(BleModule.isDeviceConnected(deviceIdentifier))
}
// Mark: Discovery ---------------------------------------------------------------------------------------------------
/**
* Discovers all {@link Service}s, {@link Characteristic}s and {@link Descriptor}s for {@link Device}.
*
* @param {DeviceId} deviceIdentifier {@link Device} identifier.
* @param {?TransactionId} transactionId Transaction handle used to cancel operation
* @returns {Promise<Device>} Promise which emits {@link Device} object if all available services and
* characteristics have been discovered.
*/
async discoverAllServicesAndCharacteristicsForDevice(
deviceIdentifier: DeviceId,
transactionId: ?TransactionId
): Promise<Device> {
if (!transactionId) {
transactionId = this._nextUniqueID()
}
const nativeDevice = await this._callPromise(
BleModule.discoverAllServicesAndCharacteristicsForDevice(deviceIdentifier, transactionId)
)
return new Device(nativeDevice, this)
}
// Mark: Service and characteristic getters --------------------------------------------------------------------------
/**
* List of discovered {@link Service}s for {@link Device}.
*
* @param {DeviceId} deviceIdentifier {@link Device} identifier.
* @returns {Promise<Array<Service>>} Promise which emits array of {@link Service} objects which are discovered for a
* {@link Device}.
*/
async servicesForDevice(deviceIdentifier: DeviceId): Promise<Array<Service>> {
const services = await this._callPromise(BleModule.servicesForDevice(deviceIdentifier))
return services.map(nativeService => {
return new Service(nativeService, this)
})
}
/**
* List of discovered {@link Characteristic}s for given {@link Device} and {@link Service}.
*
* @param {DeviceId} deviceIdentifier {@link Device} identifier.
* @param {UUID} serviceUUID {@link Service} UUID.
* @returns {Promise<Array<Characteristic>>} Promise which emits array of {@link Characteristic} objects which are
* discovered for a {@link Device} in specified {@link Service}.
*/
characteristicsForDevice(deviceIdentifier: DeviceId, serviceUUID: UUID): Promise<Array<Characteristic>> {
return this._handleCharacteristics(BleModule.characteristicsForDevice(deviceIdentifier, serviceUUID))
}
/**
* List of discovered {@link Characteristic}s for unique {@link Service}.
*
* @param {Identifier} serviceIdentifier {@link Service} ID.
* @returns {Promise<Array<Characteristic>>} Promise which emits array of {@link Characteristic} objects which are
* discovered in unique {@link Service}.
* @private
*/
_characteristicsForService(serviceIdentifier: Identifier): Promise<Array<Characteristic>> {
return this._handleCharacteristics(BleModule.characteristicsForService(serviceIdentifier))
}
/**
* Common code for handling NativeCharacteristic fetches.
*
* @param {Promise<Array<NativeCharacteristic>>} characteristicsPromise Native characteristics.
* @returns {Promise<Array<Characteristic>>} Promise which emits array of {@link Characteristic} objects which are
* discovered in unique {@link Service}.
* @private
*/
async _handleCharacteristics(
characteristicsPromise: Promise<Array<NativeCharacteristic>>
): Promise<Array<Characteristic>> {
const characteristics = await this._callPromise(characteristicsPromise)
return characteristics.map(nativeCharacteristic => {
return new Characteristic(nativeCharacteristic, this)
})
}
/**
* List of discovered {@link Descriptor}s for given {@link Device}, {@link Service} and {@link Characteristic}.
*
* @param {DeviceId} deviceIdentifier {@link Device} identifier.
* @param {UUID} serviceUUID {@link Service} UUID.
* @param {UUID} characteristicUUID {@link Characteristic} UUID.
* @returns {Promise<Array<Descriptor>>} Promise which emits array of {@link Descriptor} objects which are
* discovered for a {@link Device}, {@link Service} in specified {@link Characteristic}.
*/
descriptorsForDevice(
deviceIdentifier: DeviceId,
serviceUUID: UUID,
characteristicUUID: UUID
): Promise<Array<Descriptor>> {
return this._handleDescriptors(BleModule.descriptorsForDevice(deviceIdentifier, serviceUUID, characteristicUUID))
}
/**
* List of discovered {@link Descriptor}s for given {@link Service} and {@link Characteristic}.
*
* @param {Identifier} serviceIdentifier {@link Service} identifier.
* @param {UUID} characteristicUUID {@link Characteristic} UUID.
* @returns {Promise<Array<Descriptor>>} Promise which emits array of {@link Descriptor} objects which are
* discovered for a {@link Service} in specified {@link Characteristic}.
* @private
*/
_descriptorsForService(serviceIdentifier: Identifier, characteristicUUID: UUID): Promise<Array<Descriptor>> {
return this._handleDescriptors(BleModule.descriptorsForService(serviceIdentifier, characteristicUUID))
}
/**
* List of discovered {@link Descriptor}s for given {@link Characteristic}.
*
* @param {Identifier} characteristicIdentifier {@link Characteristic} identifier.
* @returns {Promise<Array<Descriptor>>} Promise which emits array of {@link Descriptor} objects which are
* discovered in specified {@link Characteristic}.
* @private
*/
_descriptorsForCharacteristic(characteristicIdentifier: Identifier): Promise<Array<Descriptor>> {
return this._handleDescriptors(BleModule.descriptorsForCharacteristic(characteristicIdentifier))
}
/**
* Common code for handling NativeDescriptor fetches.
* @param {Promise<Array<NativeDescriptor>>} descriptorsPromise Native descriptors.
* @returns {Promise<Array<Descriptor>>} Promise which emits array of {@link Descriptor} objects which are
* discovered in unique {@link Characteristic}.
* @private
*/
async _handleDescriptors(descriptorsPromise: Promise<Array<NativeDescriptor>>): Promise<Array<Descriptor>> {
const descriptors = await this._callPromise(descriptorsPromise)
return descriptors.map(nativeDescriptor => {
return new Descriptor(nativeDescriptor, this)
})
}
// Mark: Characteristics operations ----------------------------------------------------------------------------------
/**
* Read {@link Characteristic} value.
*
* @param {DeviceId} deviceIdentifier {@link Device} identifier.
* @param {UUID} serviceUUID {@link Service} UUID.
* @param {UUID} characteristicUUID {@link Characteristic} UUID.
* @param {?TransactionId} transactionId optional `transactionId` which can be used in
* {@link #blemanagercanceltransaction|cancelTransaction()} function.
* @returns {Promise<Characteristic>} Promise which emits first {@link Characteristic} object matching specified
* UUID paths. Latest value of {@link Characteristic} will be stored inside returned object.
*/
async readCharacteristicForDevice(
deviceIdentifier: DeviceId,
serviceUUID: UUID,
characteristicUUID: UUID,
transactionId: ?TransactionId
): Promise<Characteristic> {
if (!transactionId) {
transactionId = this._nextUniqueID()
}
const nativeCharacteristic = await this._callPromise(
BleModule.readCharacteristicForDevice(deviceIdentifier, serviceUUID, characteristicUUID, transactionId)
)
return new Characteristic(nativeCharacteristic, this)
}
/**
* Read {@link Characteristic} value.
*
* @param {Identifier} serviceIdentifier {@link Service} ID.
* @param {UUID} characteristicUUID {@link Characteristic} UUID.
* @param {?TransactionId} transactionId optional `transactionId` which can be used in
* {@link #blemanagercanceltransaction|cancelTransaction()} function.
* @returns {Promise<Characteristic>} Promise which emits first {@link Characteristic} object matching specified
* UUID paths. Latest value of {@link Characteristic} will be stored inside returned object.
* @private
*/
async _readCharacteristicForService(
serviceIdentifier: Identifier,
characteristicUUID: UUID,
transactionId: ?TransactionId
): Promise<Characteristic> {
if (!transactionId) {
transactionId = this._nextUniqueID()
}
const nativeCharacteristic = await this._callPromise(
BleModule.readCharacteristicForService(serviceIdentifier, characteristicUUID, transactionId)
)
return new Characteristic(nativeCharacteristic, this)
}
/**
* Read {@link Characteristic} value.
*
* @param {Identifier} characteristicIdentifier {@link Characteristic} ID.
* @param {?TransactionId} transactionId optional `transactionId` which can be used in
* {@link #blemanagercanceltransaction|cancelTransaction()} function.
* @returns {Promise<Characteristic>} Promise which emits first {@link Characteristic} object matching specified ID.
* Latest value of {@link Characteristic} will be stored inside returned object.
* @private
*/
async _readCharacteristic(
characteristicIdentifier: Identifier,
transactionId: ?TransactionId
): Promise<Characteristic> {
if (!transactionId) {
transactionId = this._nextUniqueID()
}
const nativeCharacteristic = await this._callPromise(
BleModule.readCharacteristic(characteristicIdentifier, transactionId)
)
return new Characteristic(nativeCharacteristic, this)
}
/**
* Write {@link Characteristic} value with response.
*
* @param {DeviceId} deviceIdentifier {@link Device} identifier.
* @param {UUID} serviceUUID {@link Service} UUID.
* @param {UUID} characteristicUUID {@link Characteristic} UUID.
* @param {Base64} base64Value Value in Base64 format.
* @param {?TransactionId} transactionId optional `transactionId` which can be used in
* {@link #blemanagercanceltransaction|cancelTransaction()} function.
* @returns {Promise<Characteristic>} Promise which emits first {@link Characteristic} object matching specified
* UUID paths. Latest value of characteristic may not be stored inside returned object.
*/
async writeCharacteristicWithResponseForDevice(
deviceIdentifier: DeviceId,
serviceUUID: UUID,
characteristicUUID: UUID,
base64Value: Base64,
transactionId: ?TransactionId
): Promise<Characteristic> {
if (!transactionId) {
transactionId = this._nextUniqueID()
}
const nativeCharacteristic = await this._callPromise(
BleModule.writeCharacteristicForDevice(
deviceIdentifier,
serviceUUID,
characteristicUUID,
base64Value,
true,
transactionId
)
)
return new Characteristic(nativeCharacteristic, this)
}
/**
* Write {@link Characteristic} value with response.
*
* @param {Identifier} serviceIdentifier {@link Service} ID.
* @param {UUID} characteristicUUID {@link Characteristic} UUID.
* @param {Base64} base64Value Value in Base64 format.
* @param {?TransactionId} transactionId optional `transactionId` which can be used in
* {@link #blemanagercanceltransaction|cancelTransaction()} function.
* @returns {Promise<Characteristic>} Promise which emits first {@link Characteristic} object matching specified
* UUID paths. Latest value of characteristic may not be stored inside returned object.
* @private
*/
async _writeCharacteristicWithResponseForService(
serviceIdentifier: Identifier,
characteristicUUID: UUID,
base64Value: Base64,
transactionId: ?TransactionId
): Promise<Characteristic> {
if (!transactionId) {
transactionId = this._nextUniqueID()
}
const nativeCharacteristic = await this._callPromise(
BleModule.writeCharacteristicForService(serviceIdentifier, characteristicUUID, base64Value, true, transactionId)
)
return new Characteristic(nativeCharacteristic, this)
}
/**
* Write {@link Characteristic} value with response.
*
* @param {Identifier} characteristicIdentifier {@link Characteristic} ID.
* @param {Base64} base64Value Value in Base64 format.
* @param {?TransactionId} transactionId optional `transactionId` which can be used in
* {@link #blemanagercanceltransaction|cancelTransaction()} function.
* @returns {Promise<Characteristic>} Promise which emits first {@link Characteristic} object matching specified ID.
* Latest value of characteristic may not be stored inside returned object.
* @private
*/
async _writeCharacteristicWithResponse(
characteristicIdentifier: Identifier,
base64Value: Base64,
transactionId: ?TransactionId
): Promise<Characteristic> {
if (!transactionId) {
transactionId = this._nextUniqueID()
}
const nativeCharacteristic = await this._callPromise(
BleModule.writeCharacteristic(characteristicIdentifier, base64Value, true, transactionId)
)
return new Characteristic(nativeCharacteristic, this)
}
/**
* Write {@link Characteristic} value without response.
*
* @param {DeviceId} deviceIdentifier {@link Device} identifier.
* @param {UUID} serviceUUID {@link Service} UUID.
* @param {UUID} characteristicUUID {@link Characteristic} UUID.
* @param {Base64} base64Value Value in Base64 format.
* @param {?TransactionId} transactionId optional `transactionId` which can be used in
* {@link #blemanagercanceltransaction|cancelTransaction()} function.
* @returns {Promise<Characteristic>} Promise which emits first {@link Characteristic} object matching specified
* UUID paths. Latest value of characteristic may not be stored inside returned object.
*/
async writeCharacteristicWithoutResponseForDevice(
deviceIdentifier: DeviceId,
serviceUUID: UUID,
characteristicUUID: UUID,
base64Value: Base64,
transactionId: ?TransactionId
): Promise<Characteristic> {
if (!transactionId) {
transactionId = this._nextUniqueID()
}
const nativeCharacteristic = await this._callPromise(
BleModule.writeCharacteristicForDevice(
deviceIdentifier,
serviceUUID,
characteristicUUID,
base64Value,
false,
transactionId
)
)
return new Characteristic(nativeCharacteristic, this)
}
/**
* Write {@link Characteristic} value without response.
*
* @param {Identifier} serviceIdentifier {@link Service} ID.
* @param {UUID} characteristicUUID {@link Characteristic} UUID.
* @param {Base64} base64Value Value in Base64 format.
* @param {?TransactionId} transactionId optional `transactionId` which can be used in
* {@link #blemanagercanceltransaction|cancelTransaction()} function.
* @returns {Promise<Characteristic>} Promise which emits first {@link Characteristic} object matching specified
* UUID paths. Latest value of characteristic may not be stored inside returned object.
* @private
*/
async _writeCharacteristicWithoutResponseForService(
serviceIdentifier: Identifier,
characteristicUUID: UUID,
base64Value: Base64,
transactionId: ?TransactionId
): Promise<Characteristic> {
if (!transactionId) {
transactionId = this._nextUniqueID()
}
const nativeCharacteristic = await this._callPromise(
BleModule.writeCharacteristicForService(serviceIdentifier, characteristicUUID, base64Value, false, transactionId)
)
return new Characteristic(nativeCharacteristic, this)
}
/**
* Write {@link Characteristic} value without response.
*
* @param {Identifier} characteristicIdentifier {@link Characteristic} UUID.
* @param {Base64} base64Value Value in Base64 format.
* @param {?TransactionId} transactionId optional `transactionId` which can be used in
* {@link #blemanagercanceltransaction|cancelTransaction()} function.
* @returns {Promise<Characteristic>} Promise which emits first {@link Characteristic} object matching specified ID.
* Latest value of characteristic may not be stored inside returned object.
* @private
*/
async _writeCharacteristicWithoutResponse(
characteristicIdentifier: Identifier,
base64Value: Base64,
transactionId: ?TransactionId
): Promise<Characteristic> {
if (!transactionId) {
transactionId = this._nextUniqueID()
}
const nativeCharacteristic = await this._callPromise(
BleModule.writeCharacteristic(characteristicIdentifier, base64Value, false, transactionId)
)
return new Characteristic(nativeCharacteristic, this)
}
/**
* Monitor value changes of a {@link Characteristic}. If notifications are enabled they will be used
* in favour of indications.
*
* @param {DeviceId} deviceIdentifier {@link Device} identifier.
* @param {UUID} serviceUUID {@link Service} UUID.
* @param {UUID} characteristicUUID {@link Characteristic} UUID.
* @param {function(error: ?BleError, characteristic: ?Characteristic)} listener - callback which emits
* {@link Characteristic} objects with modified value for each notification.
* @param {?TransactionId} transactionId optional `transactionId` which can be used in
* {@link #blemanagercanceltransaction|cancelTransaction()} function.
* @returns {Subscription} Subscription on which `remove()` function can be called to unsubscribe.
*/
monitorCharacteristicForDevice(
deviceIdentifier: DeviceId,
serviceUUID: UUID,
characteristicUUID: UUID,
listener: (error: ?BleError, characteristic: ?Characteristic) => void,
transactionId: ?TransactionId
): Subscription {
const filledTransactionId = transactionId || this._nextUniqueID()
return this._handleMonitorCharacteristic(
BleModule.monitorCharacteristicForDevice(deviceIdentifier, serviceUUID, characteristicUUID, filledTransactionId),
filledTransactionId,
listener
)
}
/**
* Monitor value changes of a {@link Characteristic}. If notifications are enabled they will be used
* in favour of indications.
*
* @param {Identifier} serviceIdentifier {@link Service} ID.
* @param {UUID} characteristicUUID {@link Characteristic} UUID.
* @param {function(error: ?BleError, characteristic: ?Characteristic)} listener - callback which emits
* {@link Characteristic} objects with modified value for each notification.
* @param {?TransactionId} transactionId optional `transactionId` which can be used in
* {@link #blemanagercanceltransaction|cancelTransaction()} function.
* @returns {Subscription} Subscription on which `remove()` function can be called to unsubscribe.
* @private
*/
_monitorCharacteristicForService(
serviceIdentifier: Identifier,
characteristicUUID: UUID,
listener: (error: ?BleError, characteristic: ?Characteristic) => void,
transactionId: ?TransactionId
): Subscription {
const filledTransactionId = transactionId || this._nextUniqueID()
return this._handleMonitorCharacteristic(
BleModule.monitorCharacteristicForService(serviceIdentifier, characteristicUUID, filledTransactionId),
filledTransactionId,
listener
)
}
/**
* Monitor value changes of a {@link Characteristic}. If notifications are enabled they will be used
* in favour of indications.
*
* @param {Identifier} characteristicIdentifier - {@link Characteristic} ID.
* @param {function(error: ?BleError, characteristic: ?Characteristic)} listener - callback which emits
* {@link Characteristic} objects with modified value for each notification.
* @param {?TransactionId} transactionId optional `transactionId` which can be used in
* {@link #blemanagercanceltransaction|cancelTransaction()} function.
* @returns {Subscription} Subscription on which `remove()` function can be called to unsubscribe.
* @private
*/
_monitorCharacteristic(
characteristicIdentifier: Identifier,
listener: (error: ?BleError, characteristic: ?Characteristic) => void,
transactionId: ?TransactionId
): Subscription {