-
Notifications
You must be signed in to change notification settings - Fork 103
/
ble.js
2111 lines (1944 loc) · 62.5 KB
/
ble.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
// API definition for EvoThings BLE plugin.
//
// Use jsdoc to generate documentation.
// The following line causes a jsdoc error.
// Use the jsdoc option -l to ignore the error.
var exec = cordova.require('cordova/exec');
/**
* @module cordova-plugin-ble
* @description Functions and properties in this module are available
* under the global name <code>evothings.ble</code>
*/
/********** BLE Central API **********/
// Flag that tracks if scanning is in progress.
// Used by startScan and stopScan.
var isScanning = false;
/**
* Start scanning for devices.
* <p>An array of service UUID strings may be given in the options object parameter.
* One or more service UUIDs must be specified for iOS background scanning to work.</p>
* <p>Found devices and errors are reported to the supplied callback functions.</p>
* <p>Will keep scanning until you call stopScan().</p>
* <p>To conserve energy, call stopScan() as soon as you've found the device
* you're looking for.</p>
* <p>Call stopScan() before calling startScan() again.</p>
*
* @param {scanCallback} success - Success callback, called repeatedly
* for each found device.
* @param {failCallback} fail - Error callback.
* @param {ScanOptions} options - Optional object with options.
* Set field serviceUUIDs to an array of service UUIDs to scan for.
* Set field parseAdvertisementData to false to disable automatic
* parsing of advertisement data.
*
* @example
* // Scan for all services.
* evothings.ble.startScan(
* function(device)
* {
* console.log('startScan found device named: ' + device.name);
* },
* function(errorCode)
* {
* console.log('startScan error: ' + errorCode);
* }
* );
*
* // Scan for specific service (Eddystone Service UUID).
* evothings.ble.startScan(
* function(device)
* {
* console.log('startScan found device named: ' + device.name);
* },
* function(errorCode)
* {
* console.log('startScan error: ' + errorCode);
* },
* { serviceUUIDs: ['0000feaa-0000-1000-8000-00805f9b34fb'] }
* );
*/
exports.startScan = function(arg1, arg2, arg3, arg4)
{
// Scanning parameters.
var serviceUUIDs;
var success;
var fail;
var options;
var parseAdvertisementData = true;
function onFail(error)
{
isScanning = false;
fail(error);
}
function onSuccess(device)
{
// Only report results while scanning is requested.
if (isScanning)
{
if (parseAdvertisementData)
{
exports.parseAdvertisementData(device);
}
success(device);
}
}
// Determine parameters.
if (Array.isArray(arg1))
{
// First param is an array of serviceUUIDs.
serviceUUIDs = arg1;
success = arg2;
fail = arg3;
options = arg4;
}
else if ('function' == typeof arg1)
{
// First param is a function.
serviceUUIDs = null;
success = arg1;
fail = arg2;
options = arg3;
}
if (isScanning)
{
fail('Scan already in progress');
return;
}
isScanning = true;
// Set options.
if (options)
{
if (Array.isArray(options.serviceUUIDs))
{
serviceUUIDs = options.serviceUUIDs;
}
if (options.parseAdvertisementData === true)
{
parseAdvertisementData = true;
}
else if (options.parseAdvertisementData === false)
{
parseAdvertisementData = false;
}
}
// Start scanning.
isScanning = true;
if (Array.isArray(serviceUUIDs))
{
serviceUUIDs = getCanonicalUUIDArray(serviceUUIDs);
exec(onSuccess, onFail, 'BLE', 'startScan', [serviceUUIDs]);
}
else
{
exec(onSuccess, onFail, 'BLE', 'startScan', []);
}
};
/**
* Ensure that all UUIDs in an array has canonical form.
* @private
*/
function getCanonicalUUIDArray(uuidArray)
{
var result = [];
for (var i in uuidArray)
{
result.push(exports.getCanonicalUUID(uuidArray[i]));
}
return result;
}
/**
* Options for startScan.
* @typedef {Object} ScanOptions
* @param {array} serviceUUIDs - Array with service UUID strings (optional).
* On iOS multiple UUIDs are scanned for using logical OR operator,
* any UUID that matches any of the UUIDs adverticed by the device
* will count as a match. On Android, multiple UUIDs are scanned for
* using AND logic, the device must advertise all of the given UUIDs
* to produce a match. (The matching logic will be unified in future
* versions of the plugin.) When providing one service UUID, behaviour
* is the same on Android and iOS. Learning out this parameter or
* setting it to null, will scan for all devices, regardless of
* advertised services.
* @property {boolean} parseAdvertisementData - Set to false to disable
* automatic parsing of advertisement data from the scan record.
* Default is true.
*/
/**
* This function is a parameter to startScan() and is called when a new device is discovered.
* @callback scanCallback
* @param {DeviceInfo} device
*/
/**
* Info about a BLE device.
* @typedef {Object} DeviceInfo
* @property {string} address - Uniquely identifies the device.
* Pass this to connect().
* The form of the address depends on the host platform.
* @property {number} rssi - A negative integer, the signal strength in decibels.
* @property {string} name - The device's name, or nil.
* @property {string} scanRecord - Base64-encoded binary data.
* Its meaning is device-specific. Not available on iOS.
* @property {AdvertisementData} advertisementData - Object containing some
* of the data from the scanRecord. Available natively on iOS. Available on
* Android by parsing the scanRecord, which is implemented in the library EasyBLE:
* {@link https://github.com/evothings/evothings-libraries/blob/master/libs/evothings/easyble/easyble.js}.
*/
/**
* Information extracted from a scanRecord. Some or all of the fields may
* be undefined. This varies between BLE devices.
* Depending on OS version and BLE device, additional fields, not documented
* here, may be present.
* @typedef {Object} AdvertisementData
* @property {string} kCBAdvDataLocalName - The device's name. Might or might
* not be equal to DeviceInfo.name. iOS caches DeviceInfo.name which means if
* the name is changed on the device, the new name might not be visible.
* kCBAdvDataLocalName is not cached and is therefore safer to use, when available.
* @property {number} kCBAdvDataTxPowerLevel - Transmission power level as
* advertised by the device.
* @property {number} kCBAdvDataChannel - A positive integer, the BLE channel
* on which the device listens for connections. Ignore this number.
* @property {boolean} kCBAdvDataIsConnectable - True if the device accepts
* connections. False if it doesn't.
* @property {array} kCBAdvDataServiceUUIDs - Array of strings, the UUIDs of
* services advertised by the device. Formatted according to RFC 4122, all lowercase.
* @property {object} kCBAdvDataServiceData - Dictionary of strings to strings.
* The keys are service UUIDs. The values are base-64-encoded binary data.
* @property {string} kCBAdvDataManufacturerData - Base-64-encoded binary data.
* This field is used by BLE devices to advertise custom data that don't fit into
* any of the other fields.
*/
/**
* This function is called when an operation fails.
* @callback failCallback
* @param {string} errorString - A human-readable string that describes the error that occurred.
*/
/**
* Stops scanning for devices.
*
* @example
* evothings.ble.stopScan();
*/
exports.stopScan = function()
{
isScanning = false;
exec(null, null, 'BLE', 'stopScan', []);
};
// Create closure for parseAdvertisementData and helper functions.
// TODO: Investigate if the code can be simplified, compare to how
// how the Evothings Bleat implementation does this.
;(function()
{
var base64;
/**
* Parse the advertisement data in the scan record.
* If device already has AdvertisementData, does nothing.
* If device instead has scanRecord, creates AdvertisementData.
* See {@link AdvertisementData} for reference documentation.
* @param {DeviceInfo} device - Device object.
*/
exports.parseAdvertisementData = function(device)
{
if (!base64) { base64 = cordova.require('cordova/base64'); }
// If device object already has advertisementData we
// do not need to parse the scanRecord.
if (device.advertisementData) { return; }
// Must have scanRecord yo continue.
if (!device.scanRecord) { return; }
// Here we parse BLE/GAP Scan Response Data.
// See the Bluetooth Specification, v4.0, Volume 3, Part C, Section 11,
// for details.
var byteArray = base64DecToArr(device.scanRecord);
var pos = 0;
var advertisementData = {};
var serviceUUIDs;
var serviceData;
// The scan record is a list of structures.
// Each structure has a length byte, a type byte, and (length-1) data bytes.
// The format of the data bytes depends on the type.
// Malformed scanRecords will likely cause an exception in this function.
while (pos < byteArray.length)
{
var length = byteArray[pos++];
if (length == 0)
{
break;
}
length -= 1;
var type = byteArray[pos++];
// Parse types we know and care about.
// Skip other types.
var BLUETOOTH_BASE_UUID = '-0000-1000-8000-00805f9b34fb'
// Convert 16-byte Uint8Array to RFC-4122-formatted UUID.
function arrayToUUID(array, offset)
{
var k=0;
var string = '';
var UUID_format = [4, 2, 2, 2, 6];
for (var l=0; l<UUID_format.length; l++)
{
if (l != 0)
{
string += '-';
}
for (var j=0; j<UUID_format[l]; j++, k++)
{
string += toHexString(array[offset+k], 1);
}
}
return string;
}
if (type == 0x02 || type == 0x03) // 16-bit Service Class UUIDs.
{
serviceUUIDs = serviceUUIDs ? serviceUUIDs : [];
for(var i=0; i<length; i+=2)
{
serviceUUIDs.push(
'0000' +
toHexString(
littleEndianToUint16(byteArray, pos + i),
2) +
BLUETOOTH_BASE_UUID);
}
}
if (type == 0x04 || type == 0x05) // 32-bit Service Class UUIDs.
{
serviceUUIDs = serviceUUIDs ? serviceUUIDs : [];
for (var i=0; i<length; i+=4)
{
serviceUUIDs.push(
toHexString(
littleEndianToUint32(byteArray, pos + i),
4) +
BLUETOOTH_BASE_UUID);
}
}
if (type == 0x06 || type == 0x07) // 128-bit Service Class UUIDs.
{
serviceUUIDs = serviceUUIDs ? serviceUUIDs : [];
for (var i=0; i<length; i+=16)
{
serviceUUIDs.push(arrayToUUID(byteArray, pos + i));
}
}
if (type == 0x08 || type == 0x09) // Local Name.
{
advertisementData.kCBAdvDataLocalName = evothings.ble.fromUtf8(
new Uint8Array(byteArray.buffer, pos, length));
}
if (type == 0x0a) // TX Power Level.
{
advertisementData.kCBAdvDataTxPowerLevel =
littleEndianToInt8(byteArray, pos);
}
if (type == 0x16) // Service Data, 16-bit UUID.
{
serviceData = serviceData ? serviceData : {};
var uuid =
'0000' +
toHexString(
littleEndianToUint16(byteArray, pos),
2) +
BLUETOOTH_BASE_UUID;
var data = new Uint8Array(byteArray.buffer, pos+2, length-2);
serviceData[uuid] = base64.fromArrayBuffer(data);
}
if (type == 0x20) // Service Data, 32-bit UUID.
{
serviceData = serviceData ? serviceData : {};
var uuid =
toHexString(
littleEndianToUint32(byteArray, pos),
4) +
BLUETOOTH_BASE_UUID;
var data = new Uint8Array(byteArray.buffer, pos+4, length-4);
serviceData[uuid] = base64.fromArrayBuffer(data);
}
if (type == 0x21) // Service Data, 128-bit UUID.
{
serviceData = serviceData ? serviceData : {};
var uuid = arrayToUUID(byteArray, pos);
var data = new Uint8Array(byteArray.buffer, pos+16, length-16);
serviceData[uuid] = base64.fromArrayBuffer(data);
}
if (type == 0xff) // Manufacturer-specific Data.
{
// Annoying to have to transform base64 back and forth,
// but it has to be done in order to maintain the API.
advertisementData.kCBAdvDataManufacturerData =
base64.fromArrayBuffer(new Uint8Array(byteArray.buffer, pos, length));
}
pos += length;
}
advertisementData.kCBAdvDataServiceUUIDs = serviceUUIDs;
advertisementData.kCBAdvDataServiceData = serviceData;
device.advertisementData = advertisementData;
/*
// Log raw data for debugging purposes.
console.log("scanRecord: "+evothings.util.typedArrayToHexString(byteArray));
console.log(JSON.stringify(advertisementData));
*/
};
/**
* Decodes a Base64 string. Returns a Uint8Array.
* nBlocksSize is optional.
* @param {String} sBase64
* @param {int} nBlocksSize
* @return {Uint8Array}
* @public
*/
function base64DecToArr(sBase64, nBlocksSize) {
var sB64Enc = sBase64.replace(/[^A-Za-z0-9\+\/]/g, "");
var nInLen = sB64Enc.length;
var nOutLen = nBlocksSize ?
Math.ceil((nInLen * 3 + 1 >> 2) / nBlocksSize) * nBlocksSize
: nInLen * 3 + 1 >> 2;
var taBytes = new Uint8Array(nOutLen);
for (var nMod3, nMod4, nUint24 = 0, nOutIdx = 0, nInIdx = 0; nInIdx < nInLen; nInIdx++) {
nMod4 = nInIdx & 3;
nUint24 |= b64ToUint6(sB64Enc.charCodeAt(nInIdx)) << 18 - 6 * nMod4;
if (nMod4 === 3 || nInLen - nInIdx === 1) {
for (nMod3 = 0; nMod3 < 3 && nOutIdx < nOutLen; nMod3++, nOutIdx++) {
taBytes[nOutIdx] = nUint24 >>> (16 >>> nMod3 & 24) & 255;
}
nUint24 = 0;
}
}
return taBytes;
}
/**
* Converts a single Base64 character to a 6-bit integer.
* @private
*/
function b64ToUint6(nChr) {
return nChr > 64 && nChr < 91 ?
nChr - 65
: nChr > 96 && nChr < 123 ?
nChr - 71
: nChr > 47 && nChr < 58 ?
nChr + 4
: nChr === 43 ?
62
: nChr === 47 ?
63
:
0;
}
/**
* Returns the integer i in hexadecimal string form,
* with leading zeroes, such that
* the resulting string is at least byteCount*2 characters long.
* @param {int} i
* @param {int} byteCount
* @public
*/
function toHexString(i, byteCount) {
var string = (new Number(i)).toString(16);
while(string.length < byteCount*2) {
string = '0'+string;
}
return string;
}
/**
* Interpret byte buffer as unsigned little endian 16 bit integer.
* Returns converted number.
* @param {ArrayBuffer} data - Input buffer.
* @param {number} offset - Start of data.
* @return Converted number.
* @public
*/
function littleEndianToUint16(data, offset)
{
return (littleEndianToUint8(data, offset + 1) << 8) +
littleEndianToUint8(data, offset)
}
/**
* Interpret byte buffer as unsigned little endian 32 bit integer.
* Returns converted number.
* @param {ArrayBuffer} data - Input buffer.
* @param {number} offset - Start of data.
* @return Converted number.
* @public
*/
function littleEndianToUint32(data, offset)
{
return (littleEndianToUint8(data, offset + 3) << 24) +
(littleEndianToUint8(data, offset + 2) << 16) +
(littleEndianToUint8(data, offset + 1) << 8) +
littleEndianToUint8(data, offset)
}
/**
* Interpret byte buffer as little endian 8 bit integer.
* Returns converted number.
* @param {ArrayBuffer} data - Input buffer.
* @param {number} offset - Start of data.
* @return Converted number.
* @public
*/
function littleEndianToInt8(data, offset)
{
var x = littleEndianToUint8(data, offset)
if (x & 0x80) x = x - 256
return x
}
/**
* Interpret byte buffer as unsigned little endian 8 bit integer.
* Returns converted number.
* @param {ArrayBuffer} data - Input buffer.
* @param {number} offset - Start of data.
* @return Converted number.
* @public
*/
function littleEndianToUint8(data, offset)
{
return data[offset]
}
})(); // End of closure for parseAdvertisementData.
/**
* Success callback function for getBondedDevices.
* Called with array of bonded devices (may be empty).
* @callback getBondedDevicesCallback
* @param {Array} devices - Array of {DeviceInfo} objects. Note that
* only fields name and address are available in the device info object.
*/
/**
* Options for getBondedDevices.
* @typedef {Object} GetBondedDevicesOptions
* @param {array} serviceUUIDs - Array with or or more service UUID strings (mandatory).
*/
/**
* Get a list of bonded devices.
* @param {getBondedDevicesCallback} success - Callback function
* called with list of bonded devices.
* @param {failCallback} fail - Error callback function.
* @param {GetBondedDevicesOptions} options - Mandatory object
* that specifies service UUIDs to search for.
* @example
* evothings.ble.getBondedDevices(
* function(devices)
* {
* console.log('Bonded devices: ' + JSON.stringify(devices));
* },
* function(errorCode)
* {
* console.log('getBondedDevices error: ' + errorCode);
* },
* { serviceUUIDs: ['0000180a-0000-1000-8000-00805f9b34fb'] });
*/
exports.getBondedDevices = function(success, fail, options)
{
exec(success, fail, 'BLE', 'getBondedDevices', [options.serviceUUIDs]);
}
/**
* Success callback function for getBondState.
* @callback getBondStateCallback
* @param {string} state - The bond state of the device.
* Possible values are: 'bonded', 'bonding' (Android only),
* 'unbonded', and 'unknown'.
*/
/**
* Options for getBondState.
* @typedef {Object} GetBondStateOptions
* @param {string} serviceUUID - String with service UUID (mandatory on iOS,
* ignored on Android).
*/
/**
* Get bond state for device.
* @param {DeviceInfo} device - Object with address of the device
* (a device object that contains just the address field may be used).
* On iOS the address is a UUID, on Android the address is a MAC address.
* This value can be found in the device objects obtained using startScan().
* @param {getBondStateCallback} success - Callback function
* called with the current bond state (a string).
* @param {failCallback} fail - Error callback function.
* @param {GetBondStateOptions} options - Mandatory on iOS where
* a serviceUUID of the device must be specified. Ignored on Android.
* @example
* evothings.ble.getBondState(
* { address: uuidOrMacAddress }
* function(state)
* {
* console.log('Bond state: ' + state);
* },
* function(errorCode)
* {
* console.log('getBondState error: ' + errorCode);
* },
* { serviceUUID: '0000180a-0000-1000-8000-00805f9b34fb' });
*/
exports.getBondState = function(device, success, fail, options)
{
// On iOS we must provide a service UUID.
var serviceUUID = (options && options.serviceUUID) ? options.serviceUUID : null;
if (exports.os.isAndroid())
{
// On Android we call the native getBondState function.
// Note that serviceUUID is ignored on Android.
exec(success, fail, 'BLE', 'getBondState', [device.address, serviceUUID]);
}
else
{
// On iOS (and other platforms in the future) we get the list of
// bonded devices and search it.
exports.getBondedDevices(
// Success function.
function(devices)
{
for (var i in devices)
{
var d = devices[i];
if (d.address == device.address)
{
success("bonded");
return; // bonded device found
}
}
success("unbonded")
},
// Error function.
function(error)
{
success("unknown");
},
{ serviceUUIDs: [serviceUUID] }
);
}
}
/**
* Success callback function for bond. On iOS the bond state returned
* will always be 'unknown' (this function is a NOP on iOS). Note that
* bonding on Android may fail and then this function is called with
* 'unbonded' as the new state.
* @callback bondCallback
* @param {string} newState - The new bond state of the device.
* Possible values are: 'bonded' (Android), 'bonding' (Android),
* 'unbonded' (Android), and 'unknown' (iOS).
*/
/**
* Bond with device. This function shows a pairing UI on Android.
* Does nothing on iOS (on iOS paring cannot be requested programatically).
* @param {DeviceInfo} device - Object with address of the device
* (a device object that contains just the address field may be used).
* On iOS the address is a UUID, on Android the address is a MAC address.
* This value can be found in the device objects obtained using startScan().
* @param {bondCallback} success - Callback function
* called with the new bond state (a string). On iOS the result is
* always 'unknown'.
* @param {failCallback} fail - Error callback function.
* @example
* evothings.ble.bond(
* { address: uuidOrMacAddress }
* function(newState)
* {
* console.log('New bond state: ' + newState);
* },
* function(errorCode)
* {
* console.log('bond error: ' + errorCode);
* });
*/
exports.bond = function(device, success, fail)
{
exec(success, fail, 'BLE', 'bond', [device.address]);
}
/**
* Success callback function for unbond. On iOS the bond state returned
* will always be 'unknown' (this function is a NOP on iOS). On Anroid
* the result should be 'unbonded', but other states are possible. Check
* the state to make sure the function was successful.
* @callback unbondCallback
* @param {string} newState - The new bond state of the device.
* Possible values are: 'unbonded' (Android), 'bonding' (Android),
* 'bonded' (Android), and 'unknown' (iOS).
*/
/**
* Unbond with device. This function does nothing on iOS.
* @param {DeviceInfo} device - Object with address of the device
* (a device object that contains just the address field may be used).
* On iOS the address is a UUID, on Android the address is a MAC address.
* This value can be found in the device objects obtained using startScan().
* @param {unbondCallback} success - Callback function
* called with the new bond state (a string). On iOS the result is
* always 'unknown'.
* @param {failCallback} fail - Error callback function.
* @example
* evothings.ble.unbond(
* { address: uuidOrMacAddress }
* function(newState)
* {
* console.log('New bond state: ' + newState);
* },
* function(errorCode)
* {
* console.log('bond error: ' + errorCode);
* });
*/
exports.unbond = function(device, success, fail)
{
exec(success, fail, 'BLE', 'unbond', [device.address]);
}
/**
* Connect to a remote device. It is recommended that you use the high-level
* function {evothings.ble.connectToDevice} in place of this function.
* On Android connect may fail with error 133. If this happens, wait about 500ms
* and connect again.
* @param {DeviceInfo} device - Device object from scanCallback (for backwards
* compatibility, this parameter may also be the address string of the device object).
* @param {connectCallback} success
* @param {failCallback} fail
* @example
* evothings.ble.connect(
* device,
* function(connectInfo)
* {
* console.log('Connect status for device: '
* + connectInfo.device.name
* + ' state: '
* + connectInfo.state);
* },
* function(errorCode)
* {
* console.log('Connect error: ' + errorCode);
* });
*/
exports.connect = function(deviceOrAddress, success, fail)
{
if (typeof deviceOrAddress == 'string')
{
var address = deviceOrAddress;
exec(success, fail, 'BLE', 'connect', [address]);
}
else
if (typeof deviceOrAddress == 'object')
{
var device = deviceOrAddress;
function onSuccess(connectInfo)
{
connectInfo.device = device;
device.handle = connectInfo.deviceHandle;
success(connectInfo);
}
exec(onSuccess, fail, 'BLE', 'connect', [device.address]);
}
else
{
fail('Invalid first argument');
}
};
/**
* Will be called whenever the device's connection state changes.
* @callback connectCallback
* @param {ConnectInfo} info
*/
/**
* Info about connection events and state.
* @typedef {Object} ConnectInfo
* @property {DeviceInfo} device - The device object is available in the
* ConnectInfo if a device object was passed to connect; passing the address
* string to connect is allowed for backwards compatibility, but this does not
* set the device field.
* @property {number} deviceHandle - Handle to the device.
* @property {number} state - One of the {@link module:cordova-plugin-ble.connectionState} keys.
*/
/**
* A map describing possible connection states.
* @alias module:cordova-plugin-ble.connectionState
* @readonly
* @enum
*/
exports.connectionState = {
/** STATE_DISCONNECTED */
0: 'STATE_DISCONNECTED',
/** STATE_CONNECTING */
1: 'STATE_CONNECTING',
/** STATE_CONNECTED */
2: 'STATE_CONNECTED',
/** STATE_DISCONNECTING */
3: 'STATE_DISCONNECTING',
/** 0 */
'STATE_DISCONNECTED': 0,
/** 1 */
'STATE_CONNECTING': 1,
/** 2 */
'STATE_CONNECTED': 2,
/** 3 */
'STATE_DISCONNECTING': 3,
};
/**
* Connect to a BLE device and discover services. This is a more high-level
* function than {evothings.ble.connect}. You can configure which services
* to discover and also turn off automatic service discovery by supplying
* an options parameter.
* On Android connect may fail with error 133. If this happens, wait about 500ms
* and connect again.
* @param {DeviceInfo} device - Device object from {scanCallback}.
* @param {connectedCallback} connected - Called when connected to the device.
* @param {disconnectedCallback} disconnected - Called when disconnected from the device.
* Note that this callback is not called when evothings.ble.close() is called.
* @param {failCallback} fail - Called on error.
* @param {ConnectOptions} options - Optional connect options object.
* @example
* evothings.ble.connectToDevice(
* device,
* function(device)
* {
* console.log('Connected to device: ' + device.name);
* },
* function(device)
* {
* console.log('Disconnected from device: ' + device.name);
* },
* function(errorCode)
* {
* console.log('Connect error: ' + errorCode);
* });
*/
exports.connectToDevice = function(device, connected, disconnected, fail, options)
{
// Default options.
var discoverServices = true;
var serviceUUIDs = null;
// Set options.
if (options && (typeof options == 'object'))
{
if (options.discoverServices === false)
{
discoverServices = false;
}
if (Array.isArray(options.serviceUUIDs))
{
serviceUUIDs = options.serviceUUIDs;
}
}
function onConnectEvent(connectInfo)
{
if (connectInfo.state == evothings.ble.connectionState.STATE_CONNECTED)
{
device.handle = connectInfo.deviceHandle;
if (discoverServices)
{
// Read services, characteristics and descriptors.
// device.services is set by readServiceData to
// the resulting services array.
evothings.ble.readServiceData(
device,
function readServicesSuccess(services)
{
// Notify connected callback.
connected(device);
},
fail,
{ serviceUUIDs: serviceUUIDs });
}
else
{
// Call connected callback without auto discovery of services.
connected(device);
}
}
else if (connectInfo.state == evothings.ble.connectionState.STATE_DISCONNECTED)
{
// Call disconnected callback.
disconnected(device);
}
}
// Connect to device.
exec(onConnectEvent, fail, 'BLE', 'connect', [device.address]);
};
/**
* Options for connectToDevice.
* @typedef {Object} ConnectOptions
* @property {boolean} discoverServices - Set to false to disable
* automatic service discovery. Default is true.
* @property {array} serviceUUIDs - Array with service UUID strings for
* services to discover (optional). If empty or null, all services are
* read, this is the default.
*/
/**
* Get the handle of an object. If a handle is passed return it.
* Allows to pass in either an object or a handle to API functions.
* @private
*/
function objectHandle(objectOrHandle)
{
if ((typeof objectOrHandle == 'object') && objectOrHandle.handle)
{
// It's an object, return the handle.
return objectOrHandle.handle;
}
else
{
// It's a handle.
return objectOrHandle;
}
}
/**
* Close the connection to a remote device.
* <p>Frees any native resources associated with the device.</p>
* <p>Does not cause any callbacks to the function passed to evothings.ble.connect().
* The disconnectedCallback in evothings.ble.connectToDevice()
* is not called when calling evothings.ble.close()</p>
*
* @param {DeviceInfo} device - Device object or a device handle
* from {@link connectCallback}.
* @example
* evothings.ble.close(device);
*/
exports.close = function(deviceOrHandle)
{
exec(null, null, 'BLE', 'close', [objectHandle(deviceOrHandle)]);
};
/**
* Fetch the remote device's RSSI (signal strength).
* @param {DeviceInfo} device - Device object or a device handle from {@link connectCallback}.
* @param {rssiCallback} success
* @param {failCallback} fail
* @example
* evothings.ble.rssi(
* device,
* function(rssi)
* {
* console.log('rssi: ' + rssi);
* },
* function(errorCode)
* {
* console.log('rssi error: ' + errorCode);
* });
*/
exports.rssi = function(deviceOrHandle, success, fail)
{
exec(deviceOrHandle, success, fail, 'BLE', 'rssi', [objectHandle(deviceOrHandle)]);
};
/**
* This function is called with an RSSI value.
* @callback rssiCallback
* @param {number} rssi - A negative integer, the signal strength in decibels.
*/
/**
* Fetch information about a remote device's services.
* @param {DeviceInfo} device - Device object or a device handle from {@link connectCallback}.
* @param {serviceCallback} success - Called with array of {@link Service} objects.
* @param {failCallback} fail
* @example
* evothings.ble.services(
* device,
* function(services)