forked from NordicSemiconductor/pc-ble-driver-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
adapter.js
4125 lines (3584 loc) · 169 KB
/
adapter.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
/* Copyright (c) 2010 - 2017, Nordic Semiconductor ASA
*
* All rights reserved.
*
* Use in source and binary forms, redistribution in binary form only, with
* or without modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 2. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 3. This software, with or without modification, must only be used with a Nordic
* Semiconductor ASA integrated circuit.
*
* 4. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
'use strict';
const EventEmitter = require('events');
const _ = require('underscore');
const AdapterState = require('./adapterState');
const Device = require('./device');
const Service = require('./service');
const Characteristic = require('./characteristic');
const Descriptor = require('./descriptor');
const AdType = require('./util/adType');
const Converter = require('./util/sdConv');
const ToText = require('./util/toText');
const logLevel = require('./util/logLevel');
const Security = require('./security');
const HexConv = require('./util/hexConv');
/** Class to mediate error conditions. */
class Error {
/**
* Create an error object.
*
* @constructor
* @param {string} userMessage The message to display to the user.
* @param {string} description A detailed description of the error.
*/
constructor(userMessage, description) {
this.message = userMessage;
this.description = description;
}
}
const _makeError = function (userMessage, description) {
return new Error(userMessage, description);
};
/**
* Class representing a transport adapter (SoftDevice RPC module).
*
* @fires Adapter#advertiseTimedOut
* @fires Adapter#attMtuChanged
* @fires Adapter#authKeyRequest
* @fires Adapter#authStatus
* @fires Adapter#characteristicAdded
* @fires Adapter#characteristicValueChanged
* @fires Adapter#closed
* @fires Adapter#connectTimedOut
* @fires Adapter#connParamUpdate
* @fires Adapter#connParamUpdateRequest
* @fires Adapter#connSecUpdate
* @fires Adapter#dataLengthChanged
* @fires Adapter#descriptorAdded
* @fires Adapter#descriptorValueChanged
* @fires Adapter#deviceConnected
* @fires Adapter#deviceDisconnected
* @fires Adapter#deviceDiscovered
* @fires Adapter#deviceNotifiedOrIndicated
* @fires Adapter#error
* @fires Adapter#keyPressed
* @fires Adapter#lescDhkeyRequest
* @fires Adapter#logMessage
* @fires Adapter#opened
* @fires Adapter#passkeyDisplay
* @fires Adapter#scanTimedOut
* @fires Adapter#secInfoRequest
* @fires Adapter#secParamsRequest
* @fires Adapter#securityChanged
* @fires Adapter#securityRequest
* @fires Adapter#securityRequestTimedOut
* @fires Adapter#serviceAdded
* @fires Adapter#stateChanged
* @fires Adapter#status
* @fires Adapter#txComplete
* @fires Adapter#warning
*/
class Adapter extends EventEmitter {
/**
* @summary Create an object representing an adapter.
*
* This constructor is called by `AdapterFactory` and it should not be necessary for the developer to call directly.
*
* @constructor
* @param {Object} bleDriver The driver to use for getting constants from the pc-ble-driver-js AddOn.
* @param {Object} adapter The adapter to use. The adapter is an object received from the pc-ble-driver-js AddOn.
* @param {string} instanceId The unique Id that identifies this Adapter instance.
* @param {string} port The port this adapter uses. For example it can be 'COM1', '/dev/ttyUSB0' or similar.
* @param {string} [serialNumber] The serial number of hardware device this adapter is controlling via serial.
* @param {string} [notSupportedMessage] Message displayed to developer if this adapter is not supported on platform.
*
*/
constructor(bleDriver, adapter, instanceId, port, serialNumber, notSupportedMessage) {
super();
if (bleDriver === undefined) throw new Error('Missing argument bleDriver.');
if (adapter === undefined) throw new Error('Missing argument adapter.');
if (instanceId === undefined) throw new Error('Missing argument instanceId.');
if (port === undefined) throw new Error('Missing argument port.');
this._bleDriver = bleDriver;
this._adapter = adapter;
this._instanceId = instanceId;
this._state = new AdapterState(instanceId, port, serialNumber);
this._security = new Security(this._bleDriver);
this._notSupportedMessage = notSupportedMessage;
this._keys = null;
this._attMtuMap = {};
this._init();
}
_init() {
this._devices = {};
this._services = {};
this._characteristics = {};
this._descriptors = {};
this._converter = new Converter(this._bleDriver, this._adapter);
this._gapOperationsMap = {};
this._gattOperationsMap = {};
this._preparedWritesMap = {};
this._pendingNotificationsAndIndications = {};
}
_getServiceType(service) {
let type;
if (service.type) {
if (service.type === 'primary') {
type = this._bleDriver.BLE_GATTS_SRVC_TYPE_PRIMARY;
} else if (service.type === 'secondary') {
type = this._bleDriver.BLE_GATTS_SRVC_TYPE_SECONDARY;
} else {
throw new Error(`Service type ${service.type} is unknown to me. Must be 'primary' or 'secondary'.`);
}
} else {
throw new Error('Service type is not specified. Must be \'primary\' or \'secondary\'.');
}
return type;
}
/**
* Get the instanceId of this adapter.
* @returns {string} Unique Id of this adapter.
*/
get instanceId() {
return this._instanceId;
}
/**
* Get the state of this adapter. @ref: ./adapterState.js
* @returns {AdapterState} `AdapterState` store object of this adapter.
*/
get state() {
return this._state;
}
/**
* Get the driver of this adapter.
* @returns {Object} The pc-ble-driver to use for this adapter, from the pc-ble-driver-js add-on.
*/
get driver() {
return this._bleDriver;
}
/**
* Get the `notSupportedMessage` of this adapter.
* @returns {string} The error message thrown if this adapter is not supported on the platform/hardware.
*/
get notSupportedMessage() {
return this._notSupportedMessage;
}
_maxReadPayloadSize(deviceInstanceId) {
return this.getCurrentAttMtu(deviceInstanceId) - 1;
}
_maxShortWritePayloadSize(deviceInstanceId) {
return this.getCurrentAttMtu(deviceInstanceId) - 3;
}
_maxLongWritePayloadSize(deviceInstanceId) {
return this.getCurrentAttMtu(deviceInstanceId) - 5;
}
_generateKeyPair() {
if (this._keys === null) {
this._keys = this._security.generateKeyPair();
}
}
/**
* Compute shared secret.
*
* @param {string} [peerPublicKey] Peer public key.
* @returns {string} The computed shared secret generated from this adapter's key-pair.
*/
computeSharedSecret(peerPublicKey) {
this._generateKeyPair();
let publicKey = peerPublicKey;
if (publicKey === null || publicKey === undefined) {
publicKey = this._keys;
}
return this._security.generateSharedSecret(this._keys.sk, publicKey.pk).ss;
}
/**
* Compute public key.
*
* @returns {string} The public key generated from this adapter's key-pair.
*/
computePublicKey() {
this._generateKeyPair();
return this._security.generatePublicKey(this._keys.sk).pk;
}
/**
* Deletes any previously generated key-pair.
*
* The next time `computeSharedSecret` or `computePublicKey` is invoked, a new key-pair will be generated and used.
* @returns {void}
*/
deleteKeys() {
this._keys = null;
}
_checkAndPropagateError(err, userMessage, callback) {
if (err) {
this._emitError(err, userMessage);
if (callback) callback(err);
return true;
}
return false;
}
_emitError(err, userMessage) {
const error = new Error(userMessage, err);
/**
* Error event.
*
* @event Adapter#error
* @type {Object}
* @property {Error} error - Provides information related to an error that occurred.
*/
this.emit('error', error);
}
_changeState(changingStates, swallowEmit) {
let changed = false;
for (const state in changingStates) {
const newValue = changingStates[state];
const previousValue = this._state[state];
// Use isEqual to compare objects
if (!_.isEqual(previousValue, newValue)) {
this._state[state] = newValue;
changed = true;
}
}
if (swallowEmit) {
return;
}
if (changed) {
/**
* Adapter state changed event.
*
* @event Adapter#stateChanged
* @type {Object}
* @property {AdapterState} this._state - The updated adapter's state store.
*/
this.emit('stateChanged', this._state);
}
}
_getDefaultEnableBLEParams() {
return {
gap_enable_params: {
periph_conn_count: 1,
central_conn_count: 7,
central_sec_count: 1,
},
gatts_enable_params: {
service_changed: false,
attr_tab_size: this._bleDriver.BLE_GATTS_ATTR_TAB_SIZE_DEFAULT,
},
common_enable_params: {
conn_bw_counts: null, // tell SD to use default
vs_uuid_count: 10,
},
gatt_enable_params: {
att_mtu: 247, // 247 is max att mtu size
},
};
}
/**
* @summary Initialize the adapter.
*
* The serial port will be attempted to be opened with the configured serial port settings in
* <code>adapterOptions</code>.
*
* @param {Object} options Options to initialize/open this adapter with.
* Available adapter open options:
* <ul>
* <li>{number} [baudRate=115200]: The baud rate this adapter's serial port should be configured with.
* <li>{string} [parity='none']: The parity this adapter's serial port should be configured with.
* <li>{string} [flowControl='none']: Whether flow control should be configured with this adapter's serial port.
* <li>{number} [eventInterval=0]: Interval to use for sending BLE driver events to JavaScript.
* If `0`, events will be sent as soon as they are received from the BLE driver.
* <li>{string} [logLevel='info']: The verbosity of logging the developer wants with this adapter.
* <li>{number} [retransmissionInterval=250]: The time interval to wait between retransmitted packets.
* <li>{number} [responseTimeout=1500]: Response timeout of the data link layer.
* <li>{boolean} [enableBLE=true]: Whether the BLE stack should be initialized and enabled.
* </ul>
* @param {function(Error)} [callback] Callback signature: err => {}.
* @returns {void}
*/
open(options, callback) {
if (this.state.opening || this.state.available) {
callback(_makeError('Adapter is already open.'));
return;
}
if (this.notSupportedMessage !== undefined) {
const error = new Error(this.notSupportedMessage);
/**
* Warning event.
*
* @event Adapter#warning
* @type {Object}
* @property {Error} error - A non fatal Error.
*/
this.emit('warning', error);
}
if (!options) {
options = {
baudRate: 115200,
parity: 'none',
flowControl: 'none',
eventInterval: 0,
logLevel: 'info',
retransmissionInterval: 250,
responseTimeout: 1500,
enableBLE: true,
};
} else {
if (!options.baudRate) options.baudRate = 115200;
if (!options.parity) options.parity = 'none';
if (!options.flowControl) options.flowControl = 'none';
if (!options.eventInterval) options.eventInterval = 0;
if (!options.logLevel) options.logLevel = 'info';
if (!options.retransmissionInterval) options.retransmissionInterval = 250;
if (!options.responseTimeout) options.responseTimeout = 1500;
if (options.enableBLE === undefined) options.enableBLE = true;
}
this._changeState({
opening: true,
baudRate: options.baudRate,
parity: options.parity,
flowControl: options.flowControl,
});
options.logCallback = this._logCallback.bind(this);
options.eventCallback = this._eventCallback.bind(this);
options.statusCallback = this._statusCallback.bind(this);
options.enableBLEParams = this._getDefaultEnableBLEParams();
this._adapter.open(this._state.port, options, err => {
this._changeState({ opening: false });
if (this._checkAndPropagateError(err, 'Error occurred opening serial port.', callback)) { return; }
this._changeState({ available: true });
/**
* Adapter opened event.
*
* @event Adapter#opened
* @type {Object}
* @property {Adapter} this - An instance of the opened <code>Adapter</code>.
*/
this.emit('opened', this);
if (options.enableBLE) {
this._changeState({ bleEnabled: true });
this.getState(getStateError => {
this._checkAndPropagateError(getStateError, 'Error retrieving adapter state.', callback);
});
}
if (callback) { callback(); }
});
}
/**
* @summary Close the adapter.
*
* This function will close the serial port, release allocated resources and remove event listeners.
* Before closing, a reset command is issued to set the connectivity device to idle state.
*
* @param {function(Error)} [callback] Callback signature: err => {}.
* @returns {void}
*/
close(callback) {
if (!this._state.available) {
if (callback) callback();
return;
}
this.connReset(err => {
if (err) {
this.emit('logMessage', logLevel.DEBUG, `Failed to issue connectivity reset: ${err.message}. Proceeding with close.`);
}
this._changeState({
available: false,
bleEnabled: false,
});
this._adapter.close(error => {
/**
* Adapter closed event.
*
* @event Adapter#closed
* @type {Object}
* @property {Adapter} this - An instance of the closed <code>Adapter</code>.
*/
this.emit('closed', this);
if (callback) callback(error);
});
});
}
/**
* @summary Reset the connectivity device
*
* This function will issue a reset command to the connectivity device.
*
* @param {function(Error)} [callback] Callback signature: err => {}.
* @returns {void}
*/
connReset(callback) {
if (!this.state.available) {
if (callback) callback(_makeError('The adapter is not available.'));
return;
}
this._adapter.connReset(error => {
if (callback) callback(error);
});
}
/**
* This function is for debugging purposes. It will return an object with these members:
* <ul>
* <li>{number} eventCallbackTotalTime
* <li>{number} eventCallbackTotalCount
* <li>{number} eventCallbackBatchMaxCount
* <li>{number} eventCallbackBatchAvgCount
* </ul>
*
* @returns {Object} This adapters stats.
*/
getStats() {
return this._adapter.getStats();
}
/**
* @summary Enable the BLE stack.
*
* This call initializes the BLE stack, no other BLE related function can be called before this one.
*
* @param {Object} [options] BLE Initialization parameters. If `undefined` or `null` the BLE stack will be
* initialized with default options (see code for `enableBLE()` below for default values).
* Available BLE enable parameters:
* <ul>
* <li>{Object} gap_enable_params: GAP init parameters
* <ul>
* <li>{number} periph_conn_count: Number of connections acting as a peripheral.
* <li>{number} central_conn_count: Number of connections acting as a central.
* <li>{number} central_sec_count: Number of SMP instances for all connections acting as a central.
* </ul>
* <li>{Object} gatts_enable_params: GATTS init parameters
* <ul>
* <li>{boolean} service_changed: Include the Service Changed characteristic in the Attribute Table.
* <li>{number} attr_tab_size: Attribute Table size in bytes. The size must be a multiple of 4.
* </ul>
* <li>{Object} common_enable_params: Common init parameters
* <ul>
* <li>{null|number} conn_bw_counts: Bandwidth configuration parameters or null for defaults.
* <li>{number} vs_uuid_count: Maximum number of 128-bit, Vendor Specific UUID bases to allocate.
* </ul>
* <li>{Object} gatt_enable_params: GATT init parameters
* <ul>
* <li>{number} att_mtu: Maximum size of ATT packet the SoftDevice can send or receive.
* If it is 0 then @ref GATT_MTU_SIZE_DEFAULT will be used.
* Otherwise @ref GATT_MTU_SIZE_DEFAULT is the minimum value.
* </ul>
* </ul>
* @param {function(Error, Object, number)} [callback] Callback signature: (err, parameters, app_ram_base) => {}
* where `parameters` is the BLE initialization parameters as
* described above and `app_ram_base` is the minimum start address
* of the application RAM region required by the SoftDevice for
* this configuration.
* @returns {void}
*/
enableBLE(options, callback) {
if (options === undefined || options === null) {
options = this._getDefaultEnableBLEParams();
}
this._adapter.enableBLE(
options,
(err, parameters, app_ram_base) => {
if (this._checkAndPropagateError(err, 'Enabling BLE failed.', callback)) { return; }
this._changeState({ bleEnabled: true });
if (callback) {
callback(err, parameters, app_ram_base);
}
});
}
_statusCallback(status) {
switch (status.id) {
case this._bleDriver.RESET_PERFORMED:
this._init();
this._changeState(
{
available: false,
bleEnabled: false,
connecting: false,
scanning: false,
advertising: false,
}
);
break;
case this._bleDriver.CONNECTION_ACTIVE:
this._changeState(
{
available: true,
}
);
break;
}
/**
* Status event.
*
* @event Adapter#status
* @type {Object}
* @property {string} status - Human-readable status message.
*/
this.emit('status', status);
}
_logCallback(severity, message) {
/**
* Log message event.
*
* @event Adapter#logMessage
* @type {Object}
* @property {string} severity - Severity of the log event.
* @property {string} message - Human-readable log message.
*/
this.emit('logMessage', severity, message);
}
_eventCallback(eventArray) {
eventArray.forEach(event => {
const text = new ToText(event);
// TODO: set the correct level for different types of events:
this.emit('logMessage', logLevel.DEBUG, text.toString());
switch (event.id) {
case this._bleDriver.BLE_GAP_EVT_CONNECTED:
this._parseConnectedEvent(event);
break;
case this._bleDriver.BLE_GAP_EVT_DISCONNECTED:
this._parseDisconnectedEvent(event);
break;
case this._bleDriver.BLE_GAP_EVT_CONN_PARAM_UPDATE:
this._parseConnectionParameterUpdateEvent(event);
break;
case this._bleDriver.BLE_GAP_EVT_SEC_REQUEST:
this._parseGapSecurityRequestEvent(event);
break;
case this._bleDriver.BLE_GAP_EVT_SEC_PARAMS_REQUEST:
this._parseSecParamsRequestEvent(event);
break;
case this._bleDriver.BLE_GAP_EVT_CONN_SEC_UPDATE:
this._parseConnSecUpdateEvent(event);
break;
case this._bleDriver.BLE_GAP_EVT_AUTH_STATUS:
this._parseAuthStatusEvent(event);
break;
case this._bleDriver.BLE_GAP_EVT_PASSKEY_DISPLAY:
this._parsePasskeyDisplayEvent(event);
break;
case this._bleDriver.BLE_GAP_EVT_AUTH_KEY_REQUEST:
this._parseAuthKeyRequest(event);
break;
case this._bleDriver.BLE_GAP_EVT_KEY_PRESSED:
this._parseGapKeyPressedEvent(event);
break;
case this._bleDriver.BLE_GAP_EVT_LESC_DHKEY_REQUEST:
this._parseLescDhkeyRequest(event);
break;
case this._bleDriver.BLE_GAP_EVT_SEC_INFO_REQUEST:
this._parseSecInfoRequest(event);
break;
case this._bleDriver.BLE_GAP_EVT_TIMEOUT:
this._parseGapTimeoutEvent(event);
break;
case this._bleDriver.BLE_GAP_EVT_RSSI_CHANGED:
this._parseGapRssiChangedEvent(event);
break;
case this._bleDriver.BLE_GAP_EVT_ADV_REPORT:
this._parseGapAdvertismentReportEvent(event);
break;
case this._bleDriver.BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
this._parseGapConnectionParameterUpdateRequestEvent(event);
break;
case this._bleDriver.BLE_GAP_EVT_SCAN_REQ_REPORT:
// Not needed. Received when a scan request is received.
break;
case this._bleDriver.BLE_GATTC_EVT_PRIM_SRVC_DISC_RSP:
this._parseGattcPrimaryServiceDiscoveryResponseEvent(event);
break;
case this._bleDriver.BLE_GATTC_EVT_REL_DISC_RSP:
// Not needed. Used for included services discovery.
break;
case this._bleDriver.BLE_GATTC_EVT_CHAR_DISC_RSP:
this._parseGattcCharacteristicDiscoveryResponseEvent(event);
break;
case this._bleDriver.BLE_GATTC_EVT_DESC_DISC_RSP:
this._parseGattcDescriptorDiscoveryResponseEvent(event);
break;
case this._bleDriver.BLE_GATTC_EVT_CHAR_VAL_BY_UUID_READ_RSP:
// Not needed, service discovery is not using the related function.
break;
case this._bleDriver.BLE_GATTC_EVT_READ_RSP:
this._parseGattcReadResponseEvent(event);
break;
case this._bleDriver.BLE_GATTC_EVT_CHAR_VALS_READ_RSP:
// Not needed, characteristic discovery is not using the related function.
break;
case this._bleDriver.BLE_GATTC_EVT_WRITE_RSP:
this._parseGattcWriteResponseEvent(event);
break;
case this._bleDriver.BLE_GATTC_EVT_HVX:
this._parseGattcHvxEvent(event);
break;
case this._bleDriver.BLE_GATTC_EVT_TIMEOUT:
this._parseGattTimeoutEvent(event);
break;
case this._bleDriver.BLE_GATTC_EVT_EXCHANGE_MTU_RSP:
this._parseGattcExchangeMtuResponseEvent(event);
break;
case this._bleDriver.BLE_GATTS_EVT_WRITE:
this._parseGattsWriteEvent(event);
break;
case this._bleDriver.BLE_GATTS_EVT_RW_AUTHORIZE_REQUEST:
this._parseGattsRWAutorizeRequestEvent(event);
break;
case this._bleDriver.BLE_GATTS_EVT_SYS_ATTR_MISSING:
this._parseGattsSysAttrMissingEvent(event);
break;
case this._bleDriver.BLE_GATTS_EVT_HVC:
this._parseGattsHvcEvent(event);
break;
case this._bleDriver.BLE_GATTS_EVT_SC_CONFIRM:
// Not needed, service changed is not supported currently.
break;
case this._bleDriver.BLE_GATTS_EVT_TIMEOUT:
this._parseGattTimeoutEvent(event);
break;
case this._bleDriver.BLE_GATTS_EVT_EXCHANGE_MTU_REQUEST:
this._parseGattsExchangeMtuRequestEvent(event);
break;
case this._bleDriver.BLE_EVT_USER_MEM_REQUEST:
this._parseMemoryRequestEvent(event);
break;
case this._bleDriver.BLE_EVT_TX_COMPLETE:
this._parseTxCompleteEvent(event);
break;
case this._bleDriver.BLE_EVT_DATA_LENGTH_CHANGED:
this._parseDataLengthChangedEvent(event);
break;
default:
this.emit('logMessage', logLevel.INFO, `Unsupported event received from SoftDevice: ${event.id} - ${event.name}`);
break;
}
});
}
_parseConnectedEvent(event) {
// TODO: Update device with connection handle
// TODO: Should 'deviceConnected' event emit the updated device?
const deviceAddress = event.peer_addr;
const connectionParameters = event.conn_params;
let deviceRole;
// If our role is central set the device role to be peripheral.
if (event.role === 'BLE_GAP_ROLE_CENTRAL') {
deviceRole = 'peripheral';
} else if (event.role === 'BLE_GAP_ROLE_PERIPH') {
deviceRole = 'central';
}
const device = new Device(deviceAddress, deviceRole);
device.connectionHandle = event.conn_handle;
device.minConnectionInterval = connectionParameters.min_conn_interval;
device.maxConnectionInterval = connectionParameters.max_conn_interval;
device.slaveLatency = connectionParameters.slave_latency;
device.connectionSupervisionTimeout = connectionParameters.conn_sup_timeout;
device.connected = true;
this._devices[device.instanceId] = device;
this._attMtuMap[device.instanceId] = this.driver.GATT_MTU_SIZE_DEFAULT;
this._changeState({ connecting: false });
if (deviceRole === 'central') {
this._changeState({ advertising: false });
}
/**
* Connection established.
*
* @event Adapter#deviceConnected
* @type {Object}
* @property {Device} device - The <code>Device</code> instance representing the BLE peer we've connected to.
*/
this.emit('deviceConnected', device);
this._addDeviceToAllPerConnectionValues(device.instanceId);
if (deviceRole === 'peripheral') {
const callback = this._gapOperationsMap.connecting.callback;
delete this._gapOperationsMap.connecting;
if (callback) { callback(undefined, device); }
}
}
_parseDisconnectedEvent(event) {
const device = this._getDeviceByConnectionHandle(event.conn_handle);
if (!device) {
this._emitError('Internal inconsistency: Could not find device with connection handle ' + event.conn_handle, 'Disconnect failed');
const errorObject = _makeError('Disconnect failed', 'Internal inconsistency: Could not find device with connection handle ' + event.conn_handle);
// cannot reach callback when there is no device. The best we can do is emit error and return.
this.emit('error', errorObject);
return;
}
device.connected = false;
if (device.instanceId in this._attMtuMap) delete this._attMtuMap[device.instanceId];
// TODO: Delete all operations for this device.
if (this._gapOperationsMap[device.instanceId]) {
// TODO: How do we know what the callback expects? Check disconnected event reason?
const callback = this._gapOperationsMap[device.instanceId].callback;
delete this._gapOperationsMap[device.instanceId];
if (callback) { callback(undefined, device); }
}
if (this._gattOperationsMap[device.instanceId]) {
const callback = this._gattOperationsMap[device.instanceId].callback;
delete this._gattOperationsMap[device.instanceId];
if (callback) {
callback(_makeError('Device disconnected', 'Device with address ' + device.address + ' disconnected'));
}
}
delete this._devices[device.instanceId];
/**
* Disconnected from peer.
*
* @event Adapter#deviceDisconnected
* @type {Object}
* @property {Device} device - The <code>Device</code> instance representing the BLE peer we've disconnected
* from.
* @property {string} event.reason_name - Human-readable reason for disconnection.
* @property {string} event.reason - HCI status code.
*/
this.emit('deviceDisconnected', device, event.reason_name, event.reason);
this._clearDeviceFromAllPerConnectionValues(device.instanceId);
this._clearDeviceFromDiscoveredServices(device.instanceId);
}
_parseConnectionParameterUpdateEvent(event) {
const device = this._getDeviceByConnectionHandle(event.conn_handle);
if (!device) {
this.emit('error', 'Internal inconsistency: Could not find device with connection handle ' + event.conn_handle);
return;
}
device.minConnectionInterval = event.conn_params.min_conn_interval;
device.maxConnectionInterval = event.conn_params.max_conn_interval;
device.slaveLatency = event.conn_params.slave_latency;
device.connectionSupervisionTimeout = event.conn_params.conn_sup_timeout;
if (this._gapOperationsMap[device.instanceId]) {
const callback = this._gapOperationsMap[device.instanceId].callback;
delete this._gapOperationsMap[device.instanceId];
if (callback) { callback(undefined, device); }
}
const connectionParameters = {
minConnectionInterval: event.conn_params.min_conn_interval,
maxConnectionInterval: event.conn_params.max_conn_interval,
slaveLatency: event.conn_params.slave_latency,
connectionSupervisionTimeout: event.conn_params.conn_sup_timeout,
};
/**
* Connection parameter update event.
*
* @event Adapter#connParamUpdate
* @type {Object}
* @property {Device} device - The <code>Device</code> instance representing the BLE peer we're connected to.
* @property {Object} connectionParameters - The updated connection parameters.
*/
this.emit('connParamUpdate', device, connectionParameters);
}
_parseSecParamsRequestEvent(event) {
const device = this._getDeviceByConnectionHandle(event.conn_handle);
/**
* Request to provide security parameters.
*
* @event Adapter#secParamsRequest
* @type {Object}
* @property {Device} device - The <code>Device</code> instance representing the BLE peer we're connected to.
* @property {Object} event.peer_params - Initiator Security Parameters.
*/
this.emit('secParamsRequest', device, event.peer_params);
}
_parseConnSecUpdateEvent(event) {
const device = this._getDeviceByConnectionHandle(event.conn_handle);
/**
* Connection security updated.
*
* @event Adapter#connSecUpdate
* @type {Object}
* @property {Device} device - The <code>Device</code> instance representing the BLE peer we're connected to.
* @property {Object} event.conn_sec - Connection security level.
*/
this.emit('connSecUpdate', device, event.conn_sec);
const authParamters = {
securityMode: event.conn_sec.sec_mode.sm,
securityLevel: event.conn_sec.sec_mode.lv,
};
/**
* Connection security updated.
*
* @event Adapter#securityChanged
* @type {Object}
* @property {Device} device - The <code>Device</code> instance representing the BLE peer we're connected to.
* @property {Object} authParamters - Connection security level.
*/
this.emit('securityChanged', device, authParamters);
}
_parseAuthStatusEvent(event) {
const device = this._getDeviceByConnectionHandle(event.conn_handle);
device.ownPeriphInitiatedPairingPending = false;
/**
* Authentication procedure completed with status.
*
* @event Adapter#authStatus
* @type {Object}
* @property {Device} device - The <code>Device</code> instance representing the BLE peer we're connected to.
* @property {Object} _ - Authentication status and corresponding parameters.
*/
this.emit('authStatus',
device,
{
auth_status: event.auth_status,
auth_status_name: event.auth_status_name,
error_src: event.error_src,
error_src_name: event.error_src_name,
bonded: event.bonded,
sm1_levels: event.sm1_levels,
sm2_levels: event.sm2_levels,
kdist_own: event.kdist_own,
kdist_peer: event.kdist_peer,
keyset: event.keyset,
}
);
}
_parsePasskeyDisplayEvent(event) {
const device = this._getDeviceByConnectionHandle(event.conn_handle);
/**
* Request to display a passkey to the user.
*
* @event Adapter#passkeyDisplay
* @type {Object}
* @property {Device} device - The <code>Device</code> instance representing the BLE peer we're connected to.
* @property {number} event.match_request - If 1 requires the application to report the match using
<code>replyAuthKey</code>.
* @property {string} event.passkey - 6 digit passkey in ASCII ('0'-'9' digits only).
*/
this.emit('passkeyDisplay', device, event.match_request, event.passkey);
}
_parseAuthKeyRequest(event) {
const device = this._getDeviceByConnectionHandle(event.conn_handle);
/**
* Request to provide an authentication key.
*
* @event Adapter#authKeyRequest
* @type {Object}
* @property {Device} device - The <code>Device</code> instance representing the BLE peer we're connected to.
* @property {string} event.key_type - The GAP Authentication Key Types.
*/
this.emit('authKeyRequest', device, event.key_type);
}
_parseGapKeyPressedEvent(event) {
const device = this._getDeviceByConnectionHandle(event.conn_handle);
/**
* Notify of a key press during an authentication procedure.
*
* @event Adapter#keyPressed
* @type {Object}
* @property {Device} device - The <code>Device</code> instance representing the BLE peer we're connected to.
* @property {string} event.kp_not - The Key press notification type.
*/
this.emit('keyPressed', device, event.kp_not);
}
_parseLescDhkeyRequest(event) {