-
Notifications
You must be signed in to change notification settings - Fork 35
/
eddystone-plugin.js
2588 lines (2328 loc) · 72.8 KB
/
eddystone-plugin.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
// This file was generated by buildEddystonePluginJS.rb
// --------------------------------------------------
// File: evothings-base.js
//
// Set up definitions needed by Eddystone JavaScript library.
//
// Global holding everything.
window.evothings = window.evothings || {};
// Define an empty No Operation function. This function is called
// in place of async script loading, since we build a single merged file.
// See the build script buildEddystonePlauginJS.rb which is where
// async loading gets replaced by this function.
evothings.__NOOP_FUN__ = function() {};
// --------------------------------------------------
// File: util.js
evothings = window.evothings || {};
/**
* @namespace
* @author Aaron Ardiri
* @author Fredrik Eldh
* @description Utilities for byte arrays.
*/
evothings.util = {};
;(function()
{
/**
* 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
*/
evothings.util.littleEndianToInt8 = function(data, offset)
{
var x = evothings.util.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
*/
evothings.util.littleEndianToUint8 = function(data, offset)
{
return data[offset]
}
/**
* Interpret byte buffer as little endian 16 bit integer.
* Returns converted number.
* @param {ArrayBuffer} data - Input buffer.
* @param {number} offset - Start of data.
* @return Converted number.
* @public
*/
evothings.util.littleEndianToInt16 = function(data, offset)
{
return (evothings.util.littleEndianToInt8(data, offset + 1) << 8) +
evothings.util.littleEndianToUint8(data, offset)
}
/**
* 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
*/
evothings.util.littleEndianToUint16 = function(data, offset)
{
return (evothings.util.littleEndianToUint8(data, offset + 1) << 8) +
evothings.util.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
*/
evothings.util.littleEndianToUint32 = function(data, offset)
{
return (evothings.util.littleEndianToUint8(data, offset + 3) << 24) +
(evothings.util.littleEndianToUint8(data, offset + 2) << 16) +
(evothings.util.littleEndianToUint8(data, offset + 1) << 8) +
evothings.util.littleEndianToUint8(data, offset)
}
/**
* Interpret byte buffer as signed big endian 16 bit integer.
* Returns converted number.
* @param {ArrayBuffer} data - Input buffer.
* @param {number} offset - Start of data.
* @return Converted number.
* @public
*/
evothings.util.bigEndianToInt16 = function(data, offset)
{
return (evothings.util.littleEndianToInt8(data, offset) << 8) +
evothings.util.littleEndianToUint8(data, offset + 1)
}
/**
* Interpret byte buffer as unsigned big endian 16 bit integer.
* Returns converted number.
* @param {ArrayBuffer} data - Input buffer.
* @param {number} offset - Start of data.
* @return Converted number.
* @public
*/
evothings.util.bigEndianToUint16 = function(data, offset)
{
return (evothings.util.littleEndianToUint8(data, offset) << 8) +
evothings.util.littleEndianToUint8(data, offset + 1)
}
/**
* Interpret byte buffer as unsigned big endian 32 bit integer.
* Returns converted number.
* @param {ArrayBuffer} data - Input buffer.
* @param {number} offset - Start of data.
* @return Converted number.
* @public
*/
evothings.util.bigEndianToUint32 = function(data, offset)
{
return (evothings.util.littleEndianToUint8(data, offset) << 24) +
(evothings.util.littleEndianToUint8(data, offset + 1) << 16) +
(evothings.util.littleEndianToUint8(data, offset + 2) << 8) +
evothings.util.littleEndianToUint8(data, offset + 3)
}
/**
* 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;
}
/**
* Decodes a Base64 string. Returns a Uint8Array.
* nBlocksSize is optional.
* @param {String} sBase64
* @param {int} nBlocksSize
* @return {Uint8Array}
* @public
*/
evothings.util.base64DecToArr = function(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;
}
/**
* 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
*/
evothings.util.toHexString = function(i, byteCount) {
var string = (new Number(i)).toString(16);
while(string.length < byteCount*2) {
string = '0'+string;
}
return string;
}
/**
* Takes a ArrayBuffer or TypedArray and returns its hexadecimal representation.
* No spaces or linebreaks.
* @param data
* @public
*/
evothings.util.typedArrayToHexString = function(data) {
// view data as a Uint8Array, unless it already is one.
if(data.buffer) {
if(!(data instanceof Uint8Array))
data = new Uint8Array(data.buffer);
} else if(data instanceof ArrayBuffer) {
data = new Uint8Array(data);
} else {
throw "not an ArrayBuffer or TypedArray.";
}
var str = '';
for(var i=0; i<data.length; i++) {
str += evothings.util.toHexString(data[i], 1);
}
return str;
}
})();
// --------------------------------------------------
// File: easyble.js updated 160713
;(function()
{
// Load script used by this file.
evothings.__NOOP_FUN__('libs/evothings/util/util.js');
/**
* @namespace
* @description <p>Library for making BLE programming easier.</p>
* <p>An all-in-one file with this library and helper libraries included is
* available in file <a href=""https://github.com/evothings/evothings-libraries/blob/master/libs/evothings/easyble/easyble.dist.js>easyble.dist.js</a>. Include this file in index.html (recommended).</p>
* <p>If you include <code>easyble.js</code> rather than <code>easyble.dist.js</code> it is safe practise to call function {@link evothings.scriptsLoaded}
* to ensure dependent libraries are loaded before calling functions
* in this library (in this case you also need to have the dependent library folders).</p>
*/
evothings.easyble = {};
/**
* @namespace
* @description Error string.
*/
evothings.easyble.error = {};
/**
* @description BLE device already connected.
*/
evothings.easyble.error.DEVICE_ALREADY_CONNECTED = 'EASYBLE_ERROR_DEVICE_ALREADY_CONNECTED';
/**
* @description BLE device was disconnected.
*/
evothings.easyble.error.DISCONNECTED = 'EASYBLE_ERROR_DISCONNECTED';
/**
* @description BLE service was not found.
*/
evothings.easyble.error.SERVICE_NOT_FOUND = 'EASYBLE_ERROR_SERVICE_NOT_FOUND';
/**
* @description BLE characteristic was not found.
*/
evothings.easyble.error.CHARACTERISTIC_NOT_FOUND = 'EASYBLE_ERROR_CHARACTERISTIC_NOT_FOUND';
/**
* @description BLE descriptor was not found.
*/
evothings.easyble.error.DESCRIPTOR_NOT_FOUND = 'EASYBLE_ERROR_DESCRIPTOR_NOT_FOUND';
/**
* @private
* This variable is set "lazily", because when this script is loaded
* the Base64 Cordova module may not be loaded yet.
*/
var base64;
/**
* Set to true to report found devices only once,
* set to false to report continuously.
* @private
*/
var reportDeviceOnce = false;
/**
* @private
*/
var serviceFilter = false;
/**
* @private
*/
var isScanning = false;
/**
* Internal properties and functions.
* @private
*/
var internal = {};
/**
* Internal variable used to track reading of service data.
* @private
*/
var readCounter = 0;
/**
* Table of discovered devices.
* @private
*/
internal.knownDevices = {};
/**
* Table of connected devices.
* @private
*/
internal.connectedDevices = {};
/**
* @description <strong>Deprecated.</strong> Set whether to report devices once or continuously during scan.
* The default is to report continously.
* @deprecated Use the options parameter {@link evothings.easyble.ScanOptions} in
* function {@link evothings.easyble.startScan}.
* @param {boolean} reportOnce - Set to true to report found devices only once.
* Set to false to report continuously.
* @public
*/
evothings.easyble.reportDeviceOnce = function(reportOnce)
{
reportDeviceOnce = reportOnce;
};
/**
* @description Set to an Array of UUID strings to enable filtering of devices
* found by startScan().
* @param services - Array of UUID strings. Set to false to disable filtering.
* The default is no filtering. An empty array will cause no devices to be reported.
* @public
*/
evothings.easyble.filterDevicesByService = function(services)
{
serviceFilter = services;
};
/**
* @description Called during scanning when a BLE device is found.
* @callback evothings.easyble.scanCallback
* @param {evothings.easyble.EasyBLEDevice} device - EasyBLE device object
* found during scanning.
*/
/**
* @description This callback indicates that an operation was successful,
* without specifying and additional information.
* @callback evothings.easyble.emptyCallback - Callback that takes no parameters.
*/
/**
* @description This function is called when an operation fails.
* @callback evothings.easyble.failCallback
* @param {string} errorString - A human-readable string that
* describes the error that occurred.
*/
/**
* @description Called when successfully connected to a device.
* @callback evothings.easyble.connectCallback
* @param {evothings.easyble.EasyBLEDevice} device - EasyBLE devices object.
*/
/**
* @description Called when services are successfully read.
* @callback evothings.easyble.servicesCallback
* @param {evothings.easyble.EasyBLEDevice} device - EasyBLE devices object.
*/
/**
* @description Function when data is available.
* @callback evothings.easyble.dataCallback
* @param {ArrayBuffer} data - The data is an array buffer.
* Use an ArrayBufferView to access the data.
*/
/**
* @description Called with RSSI value.
* @callback evothings.easyble.rssiCallback
* @param {number} rssi - A negative integer, the signal strength in decibels.
* This value may be 127 which indicates an unknown value.
*/
/**
* @typedef {Object} evothings.easyble.ScanOptions
* @description Options for function {evothings.easyble.startScan}
* @property {array} serviceUUIDs - Array with strings of service UUIDs
* to scan for. When providing one service UUID, behaviour is the same on
* Android and iOS, when providing multiple UUIDs behaviour differs between
* platforms.
* 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. Leaving out this parameter or setting it to null
* will scan for all devices regardless of advertised services (default
* behaviour).
* @property {boolean} allowDuplicates - If true same device will be reported
* repeatedly during scanning, if false it will only be reported once.
* Default is true.
*/
/**
* Start scanning for devices. Note that the optional parameter serviceUUIDs
* has been deprecated. Please use the options parmameter
* {@link evothings.easyble.ScanOptions} instead to specify any specific
* service UUID to scan for.
* @param {evothings.easyble.scanCallback} success - Success function called when a
* device is found.
* Format: success({@link evothings.easyble.EasyBLEDevice}).
* @param {evothings.easyble.failCallback} fail - Error callback: fail(error).
* @param {evothings.easyble.ScanOptions} [options] - Object with scan options.
* @public
* @example
* // Scan for all services.
* evothings.easyble.startScan(
* function(device)
* {
* console.log('Found device named: ' + device.name);
* },
* function(errorCode)
* {
* console.log('startScan error: ' + errorCode);
* }
* );
*
* // Scan for specific service.
* evothings.easyble.startScan(
* function(device)
* {
* console.log('Found device named: ' + device.name);
* },
* function(errorCode)
* {
* console.log('startScan error: ' + errorCode);
* },
* // Eddystone service UUID specified in options.
* { serviceUUIDs: ['0000FEAA-0000-1000-8000-00805F9B34FB'] }
* );
*/
evothings.easyble.startScan = function(arg1, arg2, arg3, arg4)
{
// Stop ongoing scan.
evothings.easyble.stopScan();
// Clear list of found devices.
internal.knownDevices = {};
// Scanning parameters.
var serviceUUIDs;
var success;
var fail;
var options;
var allowDuplicates = undefined;
// 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;
}
// Set options.
if (options)
{
if (Array.isArray(options.serviceUUIDs))
{
serviceUUIDs = options.serviceUUIDs;
}
if (options.allowDuplicates === true)
{
allowDuplicates = true;
}
else if (options.allowDuplicates === false)
{
allowDuplicates = false;
}
}
// Start scanning.
isScanning = true;
if (Array.isArray(serviceUUIDs))
{
evothings.ble.startScan(serviceUUIDs, onDeviceFound, onError);
}
else
{
evothings.ble.startScan(onDeviceFound, onError);
}
function onDeviceFound(device)
{
// Don't report devices unless the isScanning flag is true.
// This is to prevent devices being reported after stopScanning
// has been called (this can happen since scanning does not stop
// instantly when evothings.ble.stopScan is called).
if (!isScanning) return;
// Ensure we have advertisementData.
internal.ensureAdvertisementData(device);
// Check if the device matches the filter, if we have a filter.
if (!internal.deviceMatchesServiceFilter(device))
{
return;
}
// Check if we already have got the device.
var existingDevice = internal.knownDevices[device.address]
if (existingDevice)
{
// Do not report device again if flag is set.
if (allowDuplicates === false || reportDeviceOnce === true) { return; }
// Duplicates allowed, report device again.
existingDevice.rssi = device.rssi;
existingDevice.name = device.name;
existingDevice.scanRecord = device.scanRecord;
existingDevice.advertisementData = device.advertisementData;
success(existingDevice);
return;
}
// New device, add to known devices.
internal.knownDevices[device.address] = device;
// Set connect status.
device.__isConnected = false;
// Add methods to the device info object.
internal.addMethodsToDeviceObject(device);
// Call callback function with device info.
success(device);
}
function onError(errorCode)
{
fail(errorCode);
}
};
/**
* Stop scanning for devices.
* @example
* evothings.easyble.stopScan();
*/
evothings.easyble.stopScan = function()
{
isScanning = false;
evothings.ble.stopScan();
};
/**
* Disconnect and close all connected BLE devices.
* @example
* evothings.easyble.closeConnectedDevices();
*/
evothings.easyble.closeConnectedDevices = function()
{
for (var key in internal.connectedDevices)
{
var device = internal.connectedDevices[key];
device && device.close();
internal.connectedDevices[key] = null;
}
};
/**
* If device already has advertisementData, does nothing.
* If device instead has scanRecord, creates advertisementData.
* See ble.js for AdvertisementData reference.
* @param device - Device object.
* @private
*/
internal.ensureAdvertisementData = 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 = evothings.util.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 += evothings.util.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' +
evothings.util.toHexString(
evothings.util.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(
evothings.util.toHexString(
evothings.util.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 =
evothings.util.littleEndianToInt8(byteArray, pos);
}
if (type == 0x16) // Service Data, 16-bit UUID.
{
serviceData = serviceData ? serviceData : {};
var uuid =
'0000' +
evothings.util.toHexString(
evothings.util.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 =
evothings.util.toHexString(
evothings.util.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));
*/
}
/**
* Returns true if the device matches the serviceFilter, or if there is no filter.
* Returns false otherwise.
* @private
*/
internal.deviceMatchesServiceFilter = function(device)
{
if (!serviceFilter) { return true; }
var advertisementData = device.advertisementData;
if (advertisementData)
{
var serviceUUIDs = advertisementData.kCBAdvDataServiceUUIDs;
if (serviceUUIDs)
{
for (var i in serviceUUIDs)
{
for (var j in serviceFilter)
{
if (serviceUUIDs[i].toLowerCase() ==
serviceFilter[j].toLowerCase())
{
return true;
}
}
}
}
}
return false;
}
/**
* Add functions to the device object to allow calling them
* in an object-oriented style.
* @private
*/
internal.addMethodsToDeviceObject = function(deviceObject)
{
/**
* @namespace
* @alias evothings.easyble.EasyBLEDevice
* @description This is the BLE DeviceInfo object obtained from the
* underlying Cordova plugin.
* @property {string} address - Uniquely identifies the device.
* 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 {evothings.easyble.AdvertisementData} advertisementData -
* Object containing some of the data from the scanRecord.
*/
var device = deviceObject;
/**
* @typedef {Object} evothings.easyble.AdvertisementData
* @description 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.
* @property {string} kCBAdvDataLocalName - The device's name. Use this field
* rather than device.name, since on iOS the device name is cached and changes
* are not reflected in device.name.
* @property {number} kCBAdvDataTxPowerLevel - Transmission power level as
* advertised by the device.
* @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.
*/
/**
* Get device name. If there is a device name present in
* advertisement data, this is returned. Otherwise the value of
* the device.name field is returned. Note that iOS caches the
* device.name field, but not the name in advertisement data.
* If you change name of the device, it is more reliable to use
* the field in advertisement data (this name is set in the device
* firmware code).
* @return Name of the device.
* @public
* @instance
* @example
* var name = device.getName();
*/
device.getName = function()
{
// If there is a device name present in advertisement data,
// check if this matches. (This name is not cached by iOS.)
var deviceName = device.advertisementData ?
device.advertisementData.kCBAdvDataLocalName : false;
if (deviceName)
{
return deviceName;
}
else
{
return device.name;
}
};
/**
* Match device name. First checks the device name present in
* advertisement data, if not present checks device.name field.
* @param name The name to match.
* @return true if device has the given name, false if not.
* @public
* @instance
* @example
* device.hasName('MyBLEDevice');
*/
device.hasName = function(name)
{
// If there is a device name present in advertisement data,
// check if this matches. (This name is not cached by iOS.)
var deviceName = device.advertisementData ?
device.advertisementData.kCBAdvDataLocalName : false;
if (deviceName)
{
// TODO: This should be a comparison, but there has been
// instances of the kCBAdvDataLocalName field ending with
// a non-printable character, using indexOf is a quick
// fix for this.
return 0 == deviceName.indexOf(name);
}
// Otherwise check if device.name matches (cached by iOS,
// might not match if device name is updated).
return name == device.name;
};
/**
* Connect to the device.
* @param {evothings.easyble.connectCallback} success -
* Called when connected: success(device).
* @param {evothings.easyble.failCallback} fail -
* Called on error and if a disconnect happens.
* Format: error(errorMessage)
* @public
* @instance
* @example
* device.connect(
* function(device)
* {
* console.log('device connected.');
* // Read services here.
* },
* function(errorCode)
* {
* console.log('connect error: ' + errorCode);
* });
*/
device.connect = function(success, fail)
{
internal.connectToDevice(device, success, fail);
};
/**
* Check if device is connected.
* @return true if connected, false if not connected.
* @public
* @instance
* @example
* var connected = device.isConnected();
*/
device.isConnected = function()
{
return device.__isConnected;
};
/**
* Close the device. This disconnects from the BLE device.
* @public
* @instance
* @example
* device.close();
*/
device.close = function()
{
if (device.deviceHandle)
{
device.__isConnected = false;
evothings.ble.close(device.deviceHandle);
}
};
/**
* Read devices RSSI. Device must be connected.
* @param {evothings.easyble.rssiCallback} success - Callback called with
* RSSI value: success(rssi).
* @param {evothings.easyble.failCallback} fail - Called on error: fail(error).
* @public
* @instance
*/
device.readRSSI = function(success, fail)
{
evothings.ble.rssi(device.deviceHandle, success, fail);
};
/**
* @typedef {Object} evothings.easyble.ReadServicesOptions
* @description Options object for function
* {@link evothings.easyble.EasyBLEDevice#readServices}
* @property {array} serviceUUIDs - Array of service UUID strings.
*/
/**
* Read services, characteristics and descriptors for the
* specified service UUIDs.
* <strong>Services must be read be able to access characteristics and
* descriptors</strong>. Call this function before reading and writing
* characteristics/descriptors. (This function took an array of service
* UUIDs as first parameter in previous versions of this library, that
* is still supported for backwards compatibility but has ben deprecated.)
* @param {evothings.easyble.servicesCallback} success -
* Called when services are read: success(device)
* @param {evothings.easyble.failCallback} fail - error callback: