/
bluetooth.c
2090 lines (1822 loc) · 81.6 KB
/
bluetooth.c
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 is part of Espruino, a JavaScript interpreter for Microcontrollers
*
* Copyright (C) 2013 Gordon Williams <gw@pur3.co.uk>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* ----------------------------------------------------------------------------
* Platform Specific Bluetooth Functionality
* ----------------------------------------------------------------------------
*/
#ifdef BLUETOOTH
#include "jswrap_bluetooth.h"
#include "jsinteractive.h"
#include "jsdevices.h"
#include "jshardware.h"
#include "nrf5x_utils.h"
#include "bluetooth.h"
#include "bluetooth_utils.h"
#include <stdint.h>
#include <string.h>
#include <stdbool.h>
#include "nordic_common.h"
#include "nrf.h"
#include "nrf_log.h"
#include "ble_hci.h"
#include "ble_advdata.h"
#include "ble_conn_params.h"
#include "softdevice_handler.h"
#include "app_timer.h"
#include "ble_nus.h"
#include "app_util_platform.h"
#include "nrf_delay.h"
#ifdef USE_NFC
#include "nfc_t2t_lib.h"
#include "nfc_uri_msg.h"
#endif
#if BLE_HIDS_ENABLED
#include "ble_hids.h"
#endif
#if PEER_MANAGER_ENABLED
#include "peer_manager.h"
#include "fds.h"
#include "fstorage.h"
#include "ble_conn_state.h"
static pm_peer_id_t m_peer_id; /**< Device reference handle to the current bonded central. */
static pm_peer_id_t m_whitelist_peers[BLE_GAP_WHITELIST_ADDR_MAX_COUNT]; /**< List of peers currently in the whitelist. */
static uint32_t m_whitelist_peer_cnt; /**< Number of peers currently in the whitelist. */
static bool m_is_wl_changed; /**< Indicates if the whitelist has been changed since last time it has been updated in the Peer Manager. */
// needed for peer_manager_init so we can smoothly upgrade from pre 1v92 firmwares
#include "fds_internal_defs.h"
#include "fstorage_internal_defs.h"
// If we have peer manager we have central mode and NRF52
// So just enable link security
#define LINK_SECURITY
#endif
#ifdef LINK_SECURITY
// Code to handle secure Bluetooth links
#include "ecc.h"
#define BLE_GAP_LESC_P256_SK_LEN 32
/**@brief GAP LE Secure Connections P-256 Private Key. */
typedef struct
{
uint8_t sk[BLE_GAP_LESC_P256_SK_LEN]; /**< LE Secure Connections Elliptic Curve Diffie-Hellman P-256 Private Key in little-endian. */
} ble_gap_lesc_p256_sk_t;
__ALIGN(4) static ble_gap_lesc_p256_sk_t m_lesc_sk; /**< LESC ECC Private Key */
__ALIGN(4) static ble_gap_lesc_p256_pk_t m_lesc_pk; /**< LESC ECC Public Key */
__ALIGN(4) static ble_gap_lesc_dhkey_t m_lesc_dhkey; /**< LESC ECC DH Key*/
#endif
// -----------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------
#if (NRF_SD_BLE_API_VERSION == 3)
#define NRF_BLE_MAX_MTU_SIZE GATT_MTU_SIZE_DEFAULT /**< MTU size used in the softdevice enabling and to reply to a BLE_GATTS_EVT_EXCHANGE_MTU_REQUEST event. */
#endif
/* We want to listen as much of the time as possible. Not sure if 100/100 is feasible (50/100 is what's used in examples), but it seems to work fine like this. */
#define SCAN_INTERVAL MSEC_TO_UNITS(100, UNIT_0_625_MS) /**< Scan interval in units of 0.625 millisecond - 100 msec */
#define SCAN_WINDOW MSEC_TO_UNITS(100, UNIT_0_625_MS) /**< Scan window in units of 0.625 millisecond - 100 msec */
#define APP_ADV_TIMEOUT_IN_SECONDS 180 /**< The advertising timeout (in units of seconds). */
#define FIRST_CONN_PARAMS_UPDATE_DELAY APP_TIMER_TICKS(5000, APP_TIMER_PRESCALER) /**< Time from initiating event (connect or start of notification) to first time sd_ble_gap_conn_param_update is called (5 seconds). */
#define NEXT_CONN_PARAMS_UPDATE_DELAY APP_TIMER_TICKS(30000, APP_TIMER_PRESCALER) /**< Time between each call to sd_ble_gap_conn_param_update after the first call (30 seconds). */
#define MAX_CONN_PARAMS_UPDATE_COUNT 3 /**< Number of attempts before giving up the connection parameter negotiation. */
// BLE HID stuff
#define BASE_USB_HID_SPEC_VERSION 0x0101 /**< Version number of base USB HID Specification implemented by this application. */
#define HID_OUTPUT_REPORT_INDEX 0 /**< Index of Output Report. */
#define HID_OUTPUT_REPORT_MAX_LEN 1 /**< Maximum length of Output Report. */
#define HID_INPUT_REPORT_KEYS_INDEX 0 /**< Index of Input Report. */
#define HID_INPUT_REP_REF_ID 0 /**< Id of reference to Keyboard Input Report. */
#define HID_OUTPUT_REP_REF_ID 0 /**< Id of reference to Keyboard Output Report. */
#define APP_FEATURE_NOT_SUPPORTED BLE_GATT_STATUS_ATTERR_APP_BEGIN + 2 /**< Reply when unsupported features are requested. */
// -----------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------
#define ADVERTISE_MAX_UUIDS 4 ///< maximum custom UUIDs to advertise
static ble_nus_t m_nus; /**< Structure to identify the Nordic UART Service. */
#if BLE_HIDS_ENABLED
static ble_hids_t m_hids; /**< Structure used to identify the HID service. */
static bool m_in_boot_mode = false;
#endif
volatile uint16_t m_conn_handle = BLE_CONN_HANDLE_INVALID; /**< Handle of the current connection. */
#if CENTRAL_LINK_COUNT>0
volatile uint16_t m_central_conn_handle = BLE_CONN_HANDLE_INVALID; /**< Handle for central mode connection */
#endif
#ifdef USE_NFC
volatile bool nfcEnabled = false;
#endif
uint16_t bleAdvertisingInterval = DEFAULT_ADVERTISING_INTERVAL;
volatile BLEStatus bleStatus = 0;
ble_uuid_t bleUUIDFilter;
uint16_t bleFinalHandle;
// -----------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------
/** Is BLE connected to any device at all? */
bool jsble_has_connection() {
#if CENTRAL_LINK_COUNT>0
return (m_central_conn_handle != BLE_CONN_HANDLE_INVALID) ||
(m_conn_handle != BLE_CONN_HANDLE_INVALID);
#else
return m_conn_handle != BLE_CONN_HANDLE_INVALID;
#endif
}
/** Is BLE connected to a central device at all? */
bool jsble_has_central_connection() {
#if CENTRAL_LINK_COUNT>0
return (m_central_conn_handle != BLE_CONN_HANDLE_INVALID);
#else
return false;
#endif
}
/** Is BLE connected to a server device at all (eg, the simple, 'slave' mode)? */
bool jsble_has_simple_connection() {
return (m_conn_handle != BLE_CONN_HANDLE_INVALID);
}
/// Checks for error and reports an exception string if there was one, else 0 if no error
JsVar *jsble_get_error_string(uint32_t err_code) {
if (!err_code) return 0;
const char *name = 0;
switch (err_code) {
case NRF_ERROR_NO_MEM : name="NO_MEM"; break;
case NRF_ERROR_INVALID_PARAM : name="INVALID_PARAM"; break;
case NRF_ERROR_INVALID_STATE : name="INVALID_STATE"; break;
case NRF_ERROR_INVALID_LENGTH: name="INVALID_LENGTH"; break;
case NRF_ERROR_INVALID_FLAGS : name="INVALID_FLAGS"; break;
case NRF_ERROR_DATA_SIZE : name="DATA_SIZE"; break;
case NRF_ERROR_FORBIDDEN : name="FORBIDDEN"; break;
case NRF_ERROR_BUSY : name="BUSY"; break;
case BLE_ERROR_INVALID_CONN_HANDLE
: name="INVALID_CONN_HANDLE"; break;
}
if (name) return jsvVarPrintf("Got BLE error 0x%x (%s)", err_code, name);
else return jsvVarPrintf("Got BLE error code %d", err_code);
}
/// Checks for error and reports an exception if there was one. Return true on error
bool jsble_check_error(uint32_t err_code) {
JsVar *v = jsble_get_error_string(err_code);
if (!v) return 0;
jsExceptionHere(JSET_ERROR, "%v", v);
jsvUnLock(v);
return true;
}
// -----------------------------------------------------------------------------------
// --------------------------------------------------------------------------- ERRORS
void ble_app_error_handler(uint32_t error_code, uint32_t line_num, const uint8_t * p_file_name) {
#ifdef LED1_PININDEX
jshPinOutput(LED1_PININDEX, LED1_ONSTATE);
#endif
#ifdef LED2_PININDEX
jshPinOutput(LED2_PININDEX, LED2_ONSTATE);
#endif
#ifdef LED3_PININDEX
jshPinOutput(LED3_PININDEX, LED3_ONSTATE);
#endif
jsiConsolePrintf("NRF ERROR 0x%x at %s:%d\n", error_code, p_file_name?(const char *)p_file_name:"?", line_num);
jsiConsolePrint("REBOOTING.\n");
/* don't flush - just delay. If this happened in an IRQ, waiting to flush
* will result in the device locking up. */
nrf_delay_ms(1000);
NVIC_SystemReset();
}
void assert_nrf_callback(uint16_t line_num, const uint8_t * p_file_name) {
ble_app_error_handler(0xDEADBEEF, line_num, p_file_name);
}
void app_error_fault_handler(uint32_t id, uint32_t pc, uint32_t info) {
if (id == NRF_FAULT_ID_SDK_ERROR) {
error_info_t *error_info = (error_info_t *)info;
ble_app_error_handler(error_info->err_code, error_info->line_num, error_info->p_file_name);
} else
ble_app_error_handler(id, pc, 0);
}
/// Function for handling errors from the Connection Parameters module.
static void conn_params_error_handler(uint32_t nrf_error) {
/* connection parameters module can produce this if the connection
* is disconnected at just the right point while it is trying to
* negotiate connection parameters. Ignore it, since we don't
* want it to be able to reboot the device!
*/
if (nrf_error == NRF_ERROR_INVALID_STATE)
return;
APP_ERROR_HANDLER(nrf_error);
}
#if BLE_HIDS_ENABLED
static void service_error_handler(uint32_t nrf_error) {
APP_ERROR_HANDLER(nrf_error);
}
#endif
/// Function for handling an event from the Connection Parameters Module.
static void on_conn_params_evt(ble_conn_params_evt_t * p_evt) {
}
/// Sigh - NFC has lots of these, so we need to define it to build
void log_uart_printf(const char * format_msg, ...) {
// jsiConsolePrintf("NFC: %s\n", format_msg);
}
// -----------------------------------------------------------------------------------
// -------------------------------------------------------------------------- HANDLERS
static void nus_data_handler(ble_nus_t * p_nus, uint8_t * p_data, uint16_t length) {
jshPushIOCharEvents(EV_BLUETOOTH, (char*)p_data, length);
jshHadEvent();
}
bool nus_transmit_string() {
if (!jsble_has_simple_connection() ||
!(bleStatus & BLE_NUS_INITED) ||
(bleStatus & BLE_IS_SLEEPING)) {
// If no connection, drain the output buffer
while (jshGetCharToTransmit(EV_BLUETOOTH)>=0);
return false;
}
if (bleStatus & BLE_IS_SENDING) return false;
static uint8_t buf[BLE_NUS_MAX_DATA_LEN];
int idx = 0;
int ch = jshGetCharToTransmit(EV_BLUETOOTH);
while (ch>=0) {
buf[idx++] = ch;
if (idx>=BLE_NUS_MAX_DATA_LEN) break;
ch = jshGetCharToTransmit(EV_BLUETOOTH);
}
if (idx>0) {
uint32_t err_code = ble_nus_string_send(&m_nus, buf, idx);
if (err_code == NRF_SUCCESS)
bleStatus |= BLE_IS_SENDING;
}
return idx>0;
}
/// Radio Notification handler
void SWI1_IRQHandler(bool radio_evt) {
if (bleStatus & BLE_NUS_INITED)
nus_transmit_string();
// If we're doing multiple advertising, iterate through advertising options
if (bleStatus & BLE_IS_ADVERTISING_MULTIPLE) {
int idx = (bleStatus&BLE_ADVERTISING_MULTIPLE_MASK)>>BLE_ADVERTISING_MULTIPLE_SHIFT;
JsVar *advData = jsvObjectGetChild(execInfo.hiddenRoot, BLE_NAME_ADVERTISE_DATA, 0);
bool ok = true;
if (jsvIsArray(advData)) {
JsVar *data = jsvGetArrayItem(advData, idx);
idx = (idx+1) % jsvGetArrayLength(advData);
bleStatus = (bleStatus&~BLE_ADVERTISING_MULTIPLE_MASK) | (idx<<BLE_ADVERTISING_MULTIPLE_SHIFT);
JSV_GET_AS_CHAR_ARRAY(dPtr, dLen, data);
if (dPtr && dLen) {
uint32_t err_code = sd_ble_gap_adv_data_set((uint8_t *)dPtr, dLen, NULL, 0);
if (err_code)
ok = false; // error setting BLE - disable
} else {
// Invalid adv data - disable
ok = false;
}
jsvUnLock(data);
} else {
// no advdata - disable multiple advertising
ok = false;
}
if (!ok) {
bleStatus &= ~(BLE_IS_ADVERTISING_MULTIPLE|BLE_ADVERTISING_MULTIPLE_MASK);
}
jsvUnLock(advData);
}
#ifndef NRF52
/* NRF52 has a systick. On nRF51 we just hook on
to this, since it happens quite often */
void SysTick_Handler(void);
SysTick_Handler();
#endif
}
#if PEER_MANAGER_ENABLED
static void ble_update_whitelist() {
uint32_t err_code;
if (m_is_wl_changed) {
// The whitelist has been modified, update it in the Peer Manager.
err_code = pm_whitelist_set(m_whitelist_peers, m_whitelist_peer_cnt);
APP_ERROR_CHECK(err_code);
err_code = pm_device_identities_list_set(m_whitelist_peers, m_whitelist_peer_cnt);
if (err_code != NRF_ERROR_NOT_SUPPORTED)
{
APP_ERROR_CHECK(err_code);
}
m_is_wl_changed = false;
}
}
#endif
/// Function for the application's SoftDevice event handler.
static void on_ble_evt(ble_evt_t * p_ble_evt) {
uint32_t err_code;
//jsiConsolePrintf("\n[%d %d]\n", p_ble_evt->header.evt_id, p_ble_evt->evt.gattc_evt.params.hvx.handle );
switch (p_ble_evt->header.evt_id) {
case BLE_GAP_EVT_TIMEOUT:
#if CENTRAL_LINK_COUNT>0
if (bleInTask(BLETASK_BONDING)) { // BLE_GAP_TIMEOUT_SRC_SECURITY_REQUEST ?
bleCompleteTaskFailAndUnLock(BLETASK_BONDING, jsvNewFromString("Connection Timeout"));
} else if (bleInTask(BLETASK_CONNECT)) {
// timeout!
bleCompleteTaskFailAndUnLock(BLETASK_CONNECT, jsvNewFromString("Connection Timeout"));
} else
#endif
{
// the timeout for sd_ble_gap_adv_start expired - kick it off again
bleStatus &= ~BLE_IS_ADVERTISING; // we still think we're advertising, but we stopped
jsble_advertising_start();
}
break;
#if CENTRAL_LINK_COUNT>0
case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
{
const ble_gap_evt_t * const p_gap_evt = &p_ble_evt->evt.gap_evt;
// Accept parameters requested by peer.
err_code = sd_ble_gap_conn_param_update(p_gap_evt->conn_handle,
&p_gap_evt->params.conn_param_update_request.conn_params);
if (err_code!=NRF_ERROR_INVALID_STATE) APP_ERROR_CHECK(err_code);
// This sometimes fails with NRF_ERROR_INVALID_STATE if this request
// comes in between sd_ble_gap_disconnect being called and the DISCONNECT
// event being received. The SD obviously does the checks for us, so lets
// avoid crashing because of it!
} break; // BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST
#endif
case BLE_GAP_EVT_CONNECTED:
if (p_ble_evt->evt.gap_evt.params.connected.role == BLE_GAP_ROLE_PERIPH) {
m_conn_handle = p_ble_evt->evt.gap_evt.conn_handle;
if (bleStatus & BLE_IS_RSSI_SCANNING) // attempt to restart RSSI scan
sd_ble_gap_rssi_start(m_conn_handle, 0, 0);
bleStatus &= ~BLE_IS_SENDING; // reset state - just in case
#if BLE_HIDS_ENABLED
bleStatus &= ~BLE_IS_SENDING_HID;
#endif
bleStatus &= ~BLE_IS_ADVERTISING; // we're not advertising now we're connected
if (!jsiIsConsoleDeviceForced() && (bleStatus & BLE_NUS_INITED))
jsiSetConsoleDevice(EV_BLUETOOTH, false);
JsVar *addr = bleAddrToStr(p_ble_evt->evt.gap_evt.params.connected.peer_addr);
bleQueueEventAndUnLock(JS_EVENT_PREFIX"connect", addr);
jshHadEvent();
}
#if CENTRAL_LINK_COUNT>0
if (p_ble_evt->evt.gap_evt.params.connected.role == BLE_GAP_ROLE_CENTRAL) {
m_central_conn_handle = p_ble_evt->evt.gap_evt.conn_handle;
bleSetActiveBluetoothGattServer(bleTaskInfo);
jsvObjectSetChildAndUnLock(bleTaskInfo, "connected", jsvNewFromBool(true));
bleCompleteTaskSuccess(BLETASK_CONNECT, bleTaskInfo);
}
#endif
break;
case BLE_GAP_EVT_DISCONNECTED:
#if PEER_MANAGER_ENABLED
ble_update_whitelist();
#endif
#if CENTRAL_LINK_COUNT>0
if (m_central_conn_handle == p_ble_evt->evt.gap_evt.conn_handle) {
if (bleInTask(BLETASK_BONDING))
bleCompleteTaskFailAndUnLock(BLETASK_BONDING, jsvNewFromString("Disconnected"));
JsVar *gattServer = bleGetActiveBluetoothGattServer();
if (gattServer) {
JsVar *bluetoothDevice = jsvObjectGetChild(gattServer, "device", 0);
jsvObjectSetChildAndUnLock(gattServer, "connected", jsvNewFromBool(false));
if (bluetoothDevice) {
// HCI error code, see BLE_HCI_STATUS_CODES in ble_hci.h
JsVar *reason = jsvNewFromInteger(p_ble_evt->evt.gap_evt.params.disconnected.reason);
jsiQueueObjectCallbacks(bluetoothDevice, JS_EVENT_PREFIX"gattserverdisconnected", &reason, 1);
jsvUnLock(reason);
jshHadEvent();
}
jsvUnLock2(gattServer, bluetoothDevice);
}
m_central_conn_handle = BLE_CONN_HANDLE_INVALID;
bleSetActiveBluetoothGattServer(0);
BleTask task = bleGetCurrentTask();
if (BLETASK_IS_CENTRAL(task)) {
bleCompleteTaskFailAndUnLock(task, jsvNewFromString("Disconnected"));
}
} else
#endif
{
bleStatus &= ~BLE_IS_RSSI_SCANNING; // scanning will have stopped now we're disconnected
m_conn_handle = BLE_CONN_HANDLE_INVALID;
if (!jsiIsConsoleDeviceForced()) jsiSetConsoleDevice(DEFAULT_CONSOLE_DEVICE, 0);
// by calling nus_transmit_string here, without a connection, we clear the Bluetooth output buffer
nus_transmit_string();
// restart advertising after disconnection
if (!(bleStatus & BLE_IS_SLEEPING))
jsble_advertising_start();
JsVar *reason = jsvNewFromInteger(p_ble_evt->evt.gap_evt.params.disconnected.reason);
bleQueueEventAndUnLock(JS_EVENT_PREFIX"disconnect", reason);
jshHadEvent();
}
if ((bleStatus & BLE_NEEDS_SOFTDEVICE_RESTART) && !jsble_has_connection())
jsble_restart_softdevice();
break;
case BLE_GAP_EVT_RSSI_CHANGED:
#if CENTRAL_LINK_COUNT>0
if (m_central_conn_handle == p_ble_evt->evt.gap_evt.conn_handle) {
JsVar *gattServer = bleGetActiveBluetoothGattServer();
if (gattServer) {
JsVar *rssi = jsvNewFromInteger(p_ble_evt->evt.gap_evt.params.rssi_changed.rssi);
JsVar *bluetoothDevice = jsvObjectGetChild(gattServer, "device", 0);
if (bluetoothDevice) {
jsvObjectSetChild(bluetoothDevice, "rssi", rssi);
}
jsiQueueObjectCallbacks(gattServer, BLE_RSSI_EVENT, &rssi, 1);
jshHadEvent();
jsvUnLock3(rssi, gattServer, bluetoothDevice);
}
} else
#endif
{
JsVar *evt = jsvNewFromInteger(p_ble_evt->evt.gap_evt.params.rssi_changed.rssi);
if (evt) jsiQueueObjectCallbacks(execInfo.root, BLE_RSSI_EVENT, &evt, 1);
jsvUnLock(evt);
jshHadEvent();
}
break;
#if PEER_MANAGER_ENABLED==0
case BLE_GAP_EVT_SEC_PARAMS_REQUEST:{
//jsiConsolePrintf("BLE_GAP_EVT_SEC_PARAMS_REQUEST\n");
ble_gap_sec_params_t sec_param;
memset(&sec_param, 0, sizeof(ble_gap_sec_params_t));
sec_param.bond = 1;
sec_param.mitm = 0;
sec_param.lesc = 1;
sec_param.io_caps = BLE_GAP_IO_CAPS_NONE;
sec_param.oob = 0; // Out Of Band data not available.
sec_param.min_key_size = 7;
sec_param.max_key_size = 16;
err_code = sd_ble_gap_sec_params_reply(m_conn_handle, BLE_GAP_SEC_STATUS_SUCCESS, &sec_param, NULL);
// or BLE_GAP_SEC_STATUS_PAIRING_NOT_SUPP to disable pairing
APP_ERROR_CHECK(err_code);
} break; // BLE_GAP_EVT_SEC_PARAMS_REQUEST
case BLE_GATTS_EVT_SYS_ATTR_MISSING:
// No system attributes have been stored.
err_code = sd_ble_gatts_sys_attr_set(m_conn_handle, NULL, 0, 0);
APP_ERROR_CHECK(err_code);
break;
#endif
#ifdef LINK_SECURITY
case BLE_GAP_EVT_PASSKEY_DISPLAY:
//jsiConsolePrintf("BLE_GAP_EVT_PASSKEY_DISPLAY\n");
// display p_ble_evt->evt.gap_evt.params.passkey_display.passkey
break;
case BLE_GAP_EVT_AUTH_KEY_REQUEST:
//jsiConsolePrintf("BLE_GAP_EVT_AUTH_KEY_REQUEST\n");
break;
case BLE_GAP_EVT_LESC_DHKEY_REQUEST:
//jsiConsolePrintf("BLE_GAP_EVT_LESC_DHKEY_REQUEST\n");
err_code = ecc_p256_shared_secret_compute(&m_lesc_sk.sk[0], &p_ble_evt->evt.gap_evt.params.lesc_dhkey_request.p_pk_peer->pk[0], &m_lesc_dhkey.key[0]);
APP_ERROR_CHECK(err_code);
err_code = sd_ble_gap_lesc_dhkey_reply(p_ble_evt->evt.gap_evt.conn_handle, &m_lesc_dhkey);
APP_ERROR_CHECK(err_code);
break;
case BLE_GAP_EVT_AUTH_STATUS:
/*jsiConsolePrintf("BLE_GAP_EVT_AUTH_STATUS: status=0x%x bond=0x%x lv4: %d kdist_own:0x%x kdist_peer:0x%x\r\n",
p_ble_evt->evt.gap_evt.params.auth_status.auth_status,
p_ble_evt->evt.gap_evt.params.auth_status.bonded,
p_ble_evt->evt.gap_evt.params.auth_status.sm1_levels.lv4,
*((uint8_t *)&p_ble_evt->evt.gap_evt.params.auth_status.kdist_own),
*((uint8_t *)&p_ble_evt->evt.gap_evt.params.auth_status.kdist_peer));*/
break;
#endif
case BLE_GATTC_EVT_TIMEOUT:
// Disconnect on GATT Client timeout event.
err_code = sd_ble_gap_disconnect(p_ble_evt->evt.gattc_evt.conn_handle,
BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
APP_ERROR_CHECK(err_code);
break; // BLE_GATTC_EVT_TIMEOUT
case BLE_GATTS_EVT_TIMEOUT:
// Disconnect on GATT Server timeout event.
err_code = sd_ble_gap_disconnect(p_ble_evt->evt.gatts_evt.conn_handle,
BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
APP_ERROR_CHECK(err_code);
break; // BLE_GATTS_EVT_TIMEOUT
case BLE_EVT_USER_MEM_REQUEST:
err_code = sd_ble_user_mem_reply(p_ble_evt->evt.gattc_evt.conn_handle, NULL);
APP_ERROR_CHECK(err_code);
break; // BLE_EVT_USER_MEM_REQUEST
case BLE_GATTS_EVT_RW_AUTHORIZE_REQUEST:
{
ble_gatts_evt_rw_authorize_request_t req;
ble_gatts_rw_authorize_reply_params_t auth_reply;
req = p_ble_evt->evt.gatts_evt.params.authorize_request;
if (req.type != BLE_GATTS_AUTHORIZE_TYPE_INVALID)
{
if ((req.request.write.op == BLE_GATTS_OP_PREP_WRITE_REQ) ||
(req.request.write.op == BLE_GATTS_OP_EXEC_WRITE_REQ_NOW) ||
(req.request.write.op == BLE_GATTS_OP_EXEC_WRITE_REQ_CANCEL))
{
if (req.type == BLE_GATTS_AUTHORIZE_TYPE_WRITE)
{
auth_reply.type = BLE_GATTS_AUTHORIZE_TYPE_WRITE;
}
else
{
auth_reply.type = BLE_GATTS_AUTHORIZE_TYPE_READ;
}
if (req.request.write.op == BLE_GATTS_OP_EXEC_WRITE_REQ_CANCEL)
{
auth_reply.params.write.gatt_status = BLE_GATT_STATUS_SUCCESS;
}
else
{
auth_reply.params.write.gatt_status = APP_FEATURE_NOT_SUPPORTED;
}
err_code = sd_ble_gatts_rw_authorize_reply(p_ble_evt->evt.gatts_evt.conn_handle,
&auth_reply);
APP_ERROR_CHECK(err_code);
}
}
} break; // BLE_GATTS_EVT_RW_AUTHORIZE_REQUEST
#if (NRF_SD_BLE_API_VERSION == 3)
case BLE_GATTS_EVT_EXCHANGE_MTU_REQUEST:
err_code = sd_ble_gatts_exchange_mtu_reply(p_ble_evt->evt.gatts_evt.conn_handle,
NRF_BLE_MAX_MTU_SIZE);
APP_ERROR_CHECK(err_code);
break; // BLE_GATTS_EVT_EXCHANGE_MTU_REQUEST
#endif
case BLE_EVT_TX_COMPLETE:
// BLE transmit finished - reset flags
#if CENTRAL_LINK_COUNT>0
if (p_ble_evt->evt.common_evt.conn_handle == m_central_conn_handle) {
if (bleInTask(BLETASK_CHARACTERISTIC_WRITE))
bleCompleteTaskSuccess(BLETASK_CHARACTERISTIC_WRITE, 0);
}
#endif
if (p_ble_evt->evt.common_evt.conn_handle == m_conn_handle) {
//TODO: probably want to figure out *which one* finished?
bleStatus &= ~BLE_IS_SENDING;
if (bleStatus & BLE_IS_SENDING_HID) {
bleStatus &= ~BLE_IS_SENDING_HID;
jsiQueueObjectCallbacks(execInfo.root, BLE_HID_SENT_EVENT, 0, 0);
jsvObjectSetChild(execInfo.root, BLE_HID_SENT_EVENT, 0); // fire only once
jshHadEvent();
}
}
break;
case BLE_GAP_EVT_ADV_REPORT: {
// Advertising data received
const ble_gap_evt_adv_report_t *p_adv = &p_ble_evt->evt.gap_evt.params.adv_report;
JsVar *evt = jsvNewObject();
if (evt) {
jsvObjectSetChildAndUnLock(evt, "rssi", jsvNewFromInteger(p_adv->rssi));
//jsvObjectSetChildAndUnLock(evt, "addr_type", jsvNewFromInteger(p_adv->peer_addr.addr_type));
jsvObjectSetChildAndUnLock(evt, "id", bleAddrToStr(p_adv->peer_addr));
JsVar *data = jsvNewStringOfLength(p_adv->dlen, (char*)p_adv->data);
if (data) {
JsVar *ab = jsvNewArrayBufferFromString(data, p_adv->dlen);
jsvUnLock(data);
jsvObjectSetChildAndUnLock(evt, "data", ab);
}
// push onto queue
jsiQueueObjectCallbacks(execInfo.root, BLE_SCAN_EVENT, &evt, 1);
jsvUnLock(evt);
jshHadEvent();
}
break;
}
case BLE_GATTS_EVT_WRITE: {
ble_gatts_evt_write_t * p_evt_write = &p_ble_evt->evt.gatts_evt.params.write;
// We got a param write event - add this to the object callback queue
JsVar *evt = jsvNewObject();
if (evt) {
JsVar *data = jsvNewStringOfLength(p_evt_write->len, (char*)p_evt_write->data);
if (data) {
JsVar *ab = jsvNewArrayBufferFromString(data, p_evt_write->len);
jsvUnLock(data);
jsvObjectSetChildAndUnLock(evt, "data", ab);
}
char eventName[12];
bleGetWriteEventName(eventName, p_evt_write->handle);
jsiQueueObjectCallbacks(execInfo.root, eventName, &evt, 1);
jsvUnLock(evt);
jshHadEvent();
}
break;
}
#if CENTRAL_LINK_COUNT>0
// For discovery....
case BLE_GATTC_EVT_PRIM_SRVC_DISC_RSP: if (bleInTask(BLETASK_PRIMARYSERVICE)) {
bool done = true;
if (!bleTaskInfo) bleTaskInfo = jsvNewEmptyArray();
if (p_ble_evt->evt.gattc_evt.gatt_status == BLE_GATT_STATUS_SUCCESS &&
p_ble_evt->evt.gattc_evt.params.prim_srvc_disc_rsp.count!=0) {
if (bleTaskInfo) {
int i;
// Should actually return 'BLEService' object here
for (i=0;i<p_ble_evt->evt.gattc_evt.params.prim_srvc_disc_rsp.count;i++) {
ble_gattc_service_t *p_srv = &p_ble_evt->evt.gattc_evt.params.prim_srvc_disc_rsp.services[i];
// filter based on bleUUIDFilter if it's not invalid
if (bleUUIDFilter.type != BLE_UUID_TYPE_UNKNOWN)
if (!bleUUIDEqual(p_srv->uuid, bleUUIDFilter)) continue;
JsVar *o = jspNewObject(0, "BluetoothRemoteGATTService");
if (o) {
jsvObjectSetChildAndUnLock(o,"uuid", bleUUIDToStr(p_srv->uuid));
jsvObjectSetChildAndUnLock(o,"isPrimary", jsvNewFromBool(true));
jsvObjectSetChildAndUnLock(o,"start_handle", jsvNewFromInteger(p_srv->handle_range.start_handle));
jsvObjectSetChildAndUnLock(o,"end_handle", jsvNewFromInteger(p_srv->handle_range.end_handle));
jsvArrayPushAndUnLock(bleTaskInfo, o);
}
}
}
uint16_t last = p_ble_evt->evt.gattc_evt.params.prim_srvc_disc_rsp.count-1;
if (p_ble_evt->evt.gattc_evt.params.prim_srvc_disc_rsp.services[last].handle_range.end_handle < 0xFFFF) {
// Now try again
uint16_t start_handle = p_ble_evt->evt.gattc_evt.params.prim_srvc_disc_rsp.services[last].handle_range.end_handle+1;
done = sd_ble_gattc_primary_services_discover(p_ble_evt->evt.gap_evt.conn_handle, start_handle, NULL) != NRF_SUCCESS;;
}
}
if (done) {
// When done, send the result to the handler
if (bleTaskInfo && bleUUIDFilter.type != BLE_UUID_TYPE_UNKNOWN) {
// single item because filtering
JsVar *t = jsvSkipNameAndUnLock(jsvArrayPopFirst(bleTaskInfo));
jsvUnLock(bleTaskInfo);
bleTaskInfo = t;
}
if (bleTaskInfo) bleCompleteTaskSuccess(BLETASK_PRIMARYSERVICE, bleTaskInfo);
else bleCompleteTaskFailAndUnLock(BLETASK_PRIMARYSERVICE, jsvNewFromString("No Services found"));
} // else error
break;
}
case BLE_GATTC_EVT_CHAR_DISC_RSP: if (bleInTask(BLETASK_CHARACTERISTIC)) {
bool done = true;
if (!bleTaskInfo) bleTaskInfo = jsvNewEmptyArray();
if (bleTaskInfo &&
p_ble_evt->evt.gattc_evt.gatt_status == BLE_GATT_STATUS_SUCCESS &&
p_ble_evt->evt.gattc_evt.params.char_disc_rsp.count!=0) {
int i;
for (i=0;i<p_ble_evt->evt.gattc_evt.params.char_disc_rsp.count;i++) {
ble_gattc_char_t *p_chr = &p_ble_evt->evt.gattc_evt.params.char_disc_rsp.chars[i];
// filter based on bleUUIDFilter if it's not invalid
if (bleUUIDFilter.type != BLE_UUID_TYPE_UNKNOWN)
if (!bleUUIDEqual(p_chr->uuid, bleUUIDFilter)) continue;
JsVar *o = jspNewObject(0, "BluetoothRemoteGATTCharacteristic");
if (o) {
jsvObjectSetChildAndUnLock(o,"uuid", bleUUIDToStr(p_chr->uuid));
jsvObjectSetChildAndUnLock(o,"handle_value", jsvNewFromInteger(p_chr->handle_value));
jsvObjectSetChildAndUnLock(o,"handle_decl", jsvNewFromInteger(p_chr->handle_decl));
JsVar *p = jsvNewObject();
if (p) {
jsvObjectSetChildAndUnLock(p,"broadcast",jsvNewFromBool(p_chr->char_props.broadcast));
jsvObjectSetChildAndUnLock(p,"read",jsvNewFromBool(p_chr->char_props.read));
jsvObjectSetChildAndUnLock(p,"writeWithoutResponse",jsvNewFromBool(p_chr->char_props.write_wo_resp));
jsvObjectSetChildAndUnLock(p,"write",jsvNewFromBool(p_chr->char_props.write));
jsvObjectSetChildAndUnLock(p,"notify",jsvNewFromBool(p_chr->char_props.notify));
jsvObjectSetChildAndUnLock(p,"indicate",jsvNewFromBool(p_chr->char_props.indicate));
jsvObjectSetChildAndUnLock(p,"authenticatedSignedWrites",jsvNewFromBool(p_chr->char_props.auth_signed_wr));
jsvObjectSetChildAndUnLock(o,"properties", p);
}
// char_props?
jsvArrayPushAndUnLock(bleTaskInfo, o);
}
}
uint16_t last = p_ble_evt->evt.gattc_evt.params.char_disc_rsp.count-1;
if (p_ble_evt->evt.gattc_evt.params.char_disc_rsp.chars[last].handle_value < bleFinalHandle) {
// Now try again
uint16_t start_handle = p_ble_evt->evt.gattc_evt.params.char_disc_rsp.chars[last].handle_value+1;
ble_gattc_handle_range_t range;
range.start_handle = start_handle;
range.end_handle = bleFinalHandle;
/* Might report an error for invalid handle (we have no way to know for the last characteristic
* in the last service it seems). If it does, we're sorted */
done = sd_ble_gattc_characteristics_discover(p_ble_evt->evt.gap_evt.conn_handle, &range) != NRF_SUCCESS;
}
}
if (done) {
// When done, send the result to the handler
if (bleTaskInfo && bleUUIDFilter.type != BLE_UUID_TYPE_UNKNOWN) {
// single item because filtering
JsVar *t = jsvSkipNameAndUnLock(jsvArrayPopFirst(bleTaskInfo));
jsvUnLock(bleTaskInfo);
bleTaskInfo = t;
}
if (bleTaskInfo) bleCompleteTaskSuccess(BLETASK_CHARACTERISTIC, bleTaskInfo);
else bleCompleteTaskFailAndUnLock(BLETASK_CHARACTERISTIC, jsvNewFromString("No Characteristics found"));
}
break;
}
case BLE_GATTC_EVT_DESC_DISC_RSP: if (bleInTask(BLETASK_CHARACTERISTIC_DESC_AND_STARTNOTIFY)) {
// trigger this with sd_ble_gattc_descriptors_discover(conn_handle, &handle_range);
uint16_t cccd_handle = 0;
ble_gattc_evt_desc_disc_rsp_t * p_desc_disc_rsp_evt = &p_ble_evt->evt.gattc_evt.params.desc_disc_rsp;
if (p_ble_evt->evt.gattc_evt.gatt_status == BLE_GATT_STATUS_SUCCESS) {
// The descriptor was found at the peer.
// If the descriptor was a CCCD, then the cccd_handle needs to be populated.
uint32_t i;
// Loop through all the descriptors to find the CCCD.
for (i = 0; i < p_desc_disc_rsp_evt->count; i++) {
if (p_desc_disc_rsp_evt->descs[i].uuid.uuid ==
BLE_UUID_DESCRIPTOR_CLIENT_CHAR_CONFIG) {
cccd_handle = p_desc_disc_rsp_evt->descs[i].handle;
}
}
}
if (cccd_handle) {
if(bleTaskInfo)
jsvObjectSetChildAndUnLock(bleTaskInfo, "handle_cccd", jsvNewFromInteger(cccd_handle));
// FIXME: we just switch task here - this is not nice...
bleSwitchTask(BLETASK_CHARACTERISTIC_NOTIFY);
jsble_central_characteristicNotify(bleTaskInfo, true);
} else {
bleCompleteTaskFailAndUnLock(BLETASK_CHARACTERISTIC_DESC_AND_STARTNOTIFY, jsvNewFromString("CCCD Handle not found"));
}
break;
}
case BLE_GATTC_EVT_READ_RSP: if (bleInTask(BLETASK_CHARACTERISTIC_READ)) {
ble_gattc_evt_read_rsp_t *p_read = &p_ble_evt->evt.gattc_evt.params.read_rsp;
JsVar *data = jsvNewDataViewWithData(p_read->len, (unsigned char*)&p_read->data[0]);
jsvObjectSetChild(bleTaskInfo, "value", data); // set this.value
bleCompleteTaskSuccessAndUnLock(BLETASK_CHARACTERISTIC_READ, data);
break;
}
case BLE_GATTC_EVT_WRITE_RSP: {
if (bleInTask(BLETASK_CHARACTERISTIC_NOTIFY))
bleCompleteTaskSuccess(BLETASK_CHARACTERISTIC_NOTIFY, 0);
else if (bleInTask(BLETASK_CHARACTERISTIC_WRITE))
bleCompleteTaskSuccess(BLETASK_CHARACTERISTIC_WRITE, 0);
break;
}
case BLE_GATTC_EVT_HVX: {
// Notification/Indication
ble_gattc_evt_hvx_t *p_hvx = &p_ble_evt->evt.gattc_evt.params.hvx;
// p_hvx>type is BLE_GATT_HVX_NOTIFICATION or BLE_GATT_HVX_INDICATION
JsVar *handles = jsvObjectGetChild(execInfo.hiddenRoot, "bleHdl", 0);
if (handles) {
JsVar *characteristic = jsvGetArrayItem(handles, p_hvx->handle);
if (characteristic) {
// Set characteristic.value, and return {target:characteristic}
jsvObjectSetChildAndUnLock(characteristic, "value",
jsvNewDataViewWithData(p_hvx->len, (unsigned char*)p_hvx->data));
JsVar *evt = jsvNewObject();
if (evt) {
jsvObjectSetChild(evt, "target", characteristic);
jsiQueueObjectCallbacks(characteristic, JS_EVENT_PREFIX"characteristicvaluechanged", &evt, 1);
jshHadEvent();
jsvUnLock(evt);
}
}
jsvUnLock2(characteristic, handles);
}
break;
}
#endif
default:
// No implementation needed.
break;
}
}
#ifdef USE_NFC
/// Callback function for handling NFC events.
static void nfc_callback(void * p_context, nfc_t2t_event_t event, const uint8_t * p_data, size_t data_length) {
(void)p_context;
switch (event) {
case NFC_T2T_EVENT_FIELD_ON:
bleQueueEventAndUnLock(JS_EVENT_PREFIX"NFCon", 0);
break;
case NFC_T2T_EVENT_FIELD_OFF:
bleQueueEventAndUnLock(JS_EVENT_PREFIX"NFCoff", 0);
break;
default:
break;
}
}
#endif
/// Function for dispatching a SoftDevice event to all modules with a SoftDevice event handler.
static void ble_evt_dispatch(ble_evt_t * p_ble_evt) {
#if PEER_MANAGER_ENABLED
ble_conn_state_on_ble_evt(p_ble_evt);
pm_on_ble_evt(p_ble_evt);
#endif
if (!((p_ble_evt->header.evt_id==BLE_GAP_EVT_CONNECTED) &&
(p_ble_evt->evt.gap_evt.params.connected.role != BLE_GAP_ROLE_PERIPH)) &&
!((p_ble_evt->header.evt_id==BLE_GAP_EVT_DISCONNECTED) &&
m_conn_handle != p_ble_evt->evt.gap_evt.conn_handle)) {
// Stuff in here should ONLY get called for Peripheral events (not central)
ble_conn_params_on_ble_evt(p_ble_evt);
if (bleStatus & BLE_NUS_INITED)
ble_nus_on_ble_evt(&m_nus, p_ble_evt);
}
#if BLE_HIDS_ENABLED
if (bleStatus & BLE_HID_INITED)
ble_hids_on_ble_evt(&m_hids, p_ble_evt);
#endif
on_ble_evt(p_ble_evt);
}
/// Function for dispatching a system event to interested modules.
static void sys_evt_dispatch(uint32_t sys_evt) {
#if PEER_MANAGER_ENABLED
// Dispatch the system event to the fstorage module, where it will be
// dispatched to the Flash Data Storage (FDS) module.
fs_sys_event_handler(sys_evt);
#endif
void jsh_sys_evt_handler(uint32_t sys_evt);
jsh_sys_evt_handler(sys_evt);
}
#if PEER_MANAGER_ENABLED
/// Function for handling Peer Manager events.
static void pm_evt_handler(pm_evt_t const * p_evt) {
ret_code_t err_code;
switch (p_evt->evt_id)
{
case PM_EVT_BONDED_PEER_CONNECTED:
{
NRF_LOG_DEBUG("Connected to previously bonded device\r\n");
m_peer_id = p_evt->peer_id;
err_code = pm_peer_rank_highest(p_evt->peer_id);
if (err_code != NRF_ERROR_BUSY)
{
APP_ERROR_CHECK(err_code);
}
} break;
case PM_EVT_CONN_SEC_START:
if (bleInTask(BLETASK_BONDING))
bleCompleteTaskSuccess(BLETASK_BONDING, 0);
break;
case PM_EVT_CONN_SEC_SUCCEEDED:
{
NRF_LOG_DEBUG("Link secured. Role: %d. conn_handle: %d, Procedure: %d\r\n",
-1/*ble_conn_state_role(p_evt->conn_handle)*/,
p_evt->conn_handle,
p_evt->params.conn_sec_succeeded.procedure);
m_peer_id = p_evt->peer_id;
err_code = pm_peer_rank_highest(p_evt->peer_id);
if (err_code != NRF_ERROR_BUSY)
{
APP_ERROR_CHECK(err_code);
}
if (p_evt->params.conn_sec_succeeded.procedure == PM_LINK_SECURED_PROCEDURE_BONDING &&
bleStatus & BLE_WHITELIST_ON_BOND)
{
NRF_LOG_DEBUG("New Bond, add the peer to the whitelist if possible\r\n");
NRF_LOG_DEBUG("\tm_whitelist_peer_cnt %d, MAX_PEERS_WLIST %d\r\n",
m_whitelist_peer_cnt + 1,
BLE_GAP_WHITELIST_ADDR_MAX_COUNT);
if (m_whitelist_peer_cnt < BLE_GAP_WHITELIST_ADDR_MAX_COUNT)
{
//bonded to a new peer, add it to the whitelist.
// but first check it's not in there already!
uint32_t i;
bool found = false;
for (i=0;i<m_whitelist_peer_cnt;i++)
if (m_whitelist_peers[i]==m_peer_id)
found = true;
// not in already, so add it!
if (!found) {
m_whitelist_peers[m_whitelist_peer_cnt++] = m_peer_id;
m_is_wl_changed = true;
}
}
//Note: This code will use the older bonded device in the white list and not add any newer bonded to it
// You should check on what kind of white list policy your application should use.
}
} break;
case PM_EVT_CONN_SEC_FAILED:
{
if (bleInTask(BLETASK_BONDING))
bleCompleteTaskFailAndUnLock(BLETASK_BONDING, jsvNewFromString("Securing failed"));
/** In some cases, when securing fails, it can be restarted directly. Sometimes it can
* be restarted, but only after changing some Security Parameters. Sometimes, it cannot
* be restarted until the link is disconnected and reconnected. Sometimes it is
* impossible, to secure the link, or the peer device does not support it. How to
* handle this error is highly application dependent. */
switch (p_evt->params.conn_sec_failed.error)
{
case PM_CONN_SEC_ERROR_PIN_OR_KEY_MISSING:
// Rebond if one party has lost its keys.
err_code = pm_conn_secure(p_evt->conn_handle, true);
if (err_code != NRF_ERROR_INVALID_STATE)
{
APP_ERROR_CHECK(err_code);
}
break; // PM_CONN_SEC_ERROR_PIN_OR_KEY_MISSING
default:
break;
}
} break;
case PM_EVT_CONN_SEC_CONFIG_REQ:
{
// Reject pairing request from an already bonded peer.
// Still allow a device to pair if it doesn't have bonding info for us
/* TODO: we could turn this off with a flag? Stops someone reconnecting
* by spoofing a peer. */
pm_conn_sec_config_t conn_sec_config = {.allow_repairing = true };
pm_conn_sec_config_reply(p_evt->conn_handle, &conn_sec_config);
} break;
case PM_EVT_STORAGE_FULL:
{
// Run garbage collection on the flash.
err_code = fds_gc();
if (err_code == FDS_ERR_BUSY || err_code == FDS_ERR_NO_SPACE_IN_QUEUES)
{
// Retry.
}
else
{
APP_ERROR_CHECK(err_code);
}