-
Notifications
You must be signed in to change notification settings - Fork 52
/
MicroBitBLEManager.cpp
1680 lines (1401 loc) · 58.1 KB
/
MicroBitBLEManager.cpp
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
/*
The MIT License (MIT)
Copyright (c) 2016 British Broadcasting Corporation.
This software is provided by Lancaster University by arrangement with the BBC.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include "MicroBitConfig.h"
#if CONFIG_ENABLED(DEVICE_BLE)
#include "nordic_common.h"
#include "nrf.h"
#include "app_error.h"
#include "ble.h"
#include "ble_hci.h"
#include "ble_dis.h"
#include "ble_srv_common.h"
#include "ble_advdata.h"
#include "ble_conn_params.h"
#include "nrf_sdh.h"
#include "nrf_sdh_soc.h"
#include "nrf_sdh_ble.h"
#include "nrf_sdm.h"
#include "app_timer.h"
#include "peer_manager.h"
#include "peer_manager_handler.h"
#include "peer_data_storage.h"
#include "ble_hci.h"
#include "ble_advdata.h"
#include "ble_conn_state.h"
#include "ble_dfu.h"
#include "nrf_ble_gatt.h"
#include "fds.h"
#include "nrf_pwr_mgmt.h"
#include "nrf_power.h"
#include "nrf_bootloader_info.h"
#include "nrf_log.h"
#include "nrf_log_ctrl.h"
#if ( defined(NRF_LOG_BACKEND_RTT_ENABLED) && NRF_LOG_BACKEND_RTT_ENABLED) || ( defined(NRF_LOG_BACKEND_UART_ENABLED) && NRF_LOG_BACKEND_UART_ENABLED)
#include "nrf_log_default_backends.h"
#endif
#include "MicroBitBLEManager.h"
#include "MicroBitEddystone.h"
#include "MicroBitStorage.h"
#include "MicroBitFiber.h"
#include "MicroBitSystemTimer.h"
#include "MicroBitDevice.h"
#include "MicroBitEventService.h"
#include "MicroBitPartialFlashingService.h"
#include "CodalDmesg.h"
#include "nrf_log_backend_dmesg.h"
#define MICROBIT_PAIRING_FADE_SPEED 4
//
// Local enumeration of valid security modes. Used only to optimise pre‐processor comparisons.
//
#define __SECURITY_MODE_ENCRYPTION_OPEN_LINK 0
#define __SECURITY_MODE_ENCRYPTION_NO_MITM 1
#define __SECURITY_MODE_ENCRYPTION_WITH_MITM 2
//
// Some Black Magic to compare the definition of our security mode in MicroBitConfig with a given parameter.
// Required as the MicroBitConfig option is actually an mbed enum, that is not normally comparable at compile time.
//
#define __CAT(a, ...) a##__VA_ARGS__
#define SECURITY_MODE(x) __CAT(__, x)
#define SECURITY_MODE_IS(x) (SECURITY_MODE(MICROBIT_BLE_SECURITY_LEVEL) == SECURITY_MODE(x))
//
// Times for pairing (ms): delay between pairing events and delay before disconnecting
//
#ifndef MICROBIT_BLE_DISCONNECT_AFTER_PAIRING_DELAY
#define MICROBIT_BLE_DISCONNECT_AFTER_PAIRING_DELAY 2000
#endif
#ifndef MICROBIT_BLE_PAIRING_EVENT_DELAY
#define MICROBIT_BLE_PAIRING_EVENT_DELAY 2000
#endif
//
// Time (ms) to delay shutdown or disabling softdevice
//
#ifndef MICROBIT_BLE_SHUTDOWN_DELAY
#define MICROBIT_BLE_SHUTDOWN_DELAY 500
#endif
const char *MICROBIT_BLE_MANUFACTURER = NULL;
const char *MICROBIT_BLE_MODEL = "BBC micro:bit";
const char *MICROBIT_BLE_VERSION[2] = { "2.0", "2.X" };
const char *MICROBIT_BLE_HARDWARE_VERSION = NULL;
const char *MICROBIT_BLE_FIRMWARE_VERSION = MICROBIT_DAL_VERSION;
const char *MICROBIT_BLE_SOFTWARE_VERSION = NULL;
const int8_t MICROBIT_BLE_POWER_LEVEL[] = { -40, -20, -16, -12, -8, -4, 0, 4};
/*
* Many of the interfaces we need to use only support callbacks to plain C functions, rather than C++ methods.
* So, we maintain a pointer to the MicroBitBLEManager that's in use. Ths way, we can still access resources on the micro:bit
* whilst keeping the code modular.
*/
MicroBitBLEManager *MicroBitBLEManager::manager = NULL; // Singleton reference to the BLE manager. many BLE API callbacks still do not support member functions. :-(
#define microbit_ble_OBSERVER_PRIO 3
#define microbit_ble_CONN_CFG_TAG 1
static int m_power = MICROBIT_BLE_DEFAULT_TX_POWER;
static uint8_t m_adv_handle = BLE_GAP_ADV_SET_HANDLE_NOT_SET;
static uint8_t m_enc_advdata[ BLE_GAP_ADV_SET_DATA_SIZE_MAX];
static volatile int m_pending;
NRF_BLE_GATT_DEF( m_gatt);
static void const_ascii_to_utf8(ble_srv_utf8_str_t * p_utf8, const char * p_ascii);
static void microbit_ble_for_each_connected_disconnect( uint16_t conn_handle, void *p_context);
static void microbit_ble_for_each_connected_tx_power_set( uint16_t conn_handle, void *p_context);
static void bleConnectionCallback( microbit_gaphandle_t handle);
static void passkeyDisplayCallback( microbit_gaphandle_t handle, ManagedString passKey);
static void microbit_ble_evt_handler(ble_evt_t const * p_ble_evt, void * p_context);
static void microbit_ble_pm_evt_handler(pm_evt_t const * p_evt);
static void microbit_ble_evt_handler(ble_evt_t const * p_ble_evt, void * p_context);
static void microbit_dfu_init(void);
static void microbit_ble_configureAdvertising( bool connectable, bool discoverable, bool whitelist, uint16_t interval_ms, int timeout_seconds);
#if CONFIG_ENABLED(MICROBIT_BLE_EDDYSTONE_URL) || CONFIG_ENABLED(MICROBIT_BLE_EDDYSTONE_UID)
static void microbit_ble_configureAdvertising( bool connectable, bool discoverable, bool whitelist, uint16_t interval_ms, int timeout_seconds,
uint8_t *frameData, uint16_t frameSize);
#endif
/**
* Constructor.
*
* Configure and manage the micro:bit's Bluetooth Low Energy (BLE) stack.
*
* @param _storage an instance of MicroBitStorage used to persist sys attribute information. (This is required for compatability with iOS).
*
* @note The BLE stack *cannot* be brought up in a static context (the software simply hangs or corrupts itself).
* Hence, the init() member function should be used to initialise the BLE stack.
*/
MicroBitBLEManager::MicroBitBLEManager(MicroBitStorage &_storage) : storage(&_storage)
{
manager = this;
this->pairingStatus = 0;
#if CONFIG_ENABLED(MICROBIT_BLE_DFU_SERVICE)
// Initialize buttonless SVCI bootloader interface before interrupts are enabled
MICROBIT_BLE_ECHK( ble_dfu_buttonless_async_svci_init());
#endif
}
/**
* Constructor.
*
* Configure and manage the micro:bit's Bluetooth Low Energy (BLE) stack.
*
* @note The BLE stack *cannot* be brought up in a static context (the software simply hangs or corrupts itself).
* Hence, the init() member function should be used to initialise the BLE stack.
*/
MicroBitBLEManager::MicroBitBLEManager() : storage(NULL)
{
manager = this;
this->pairingStatus = 0;
#if CONFIG_ENABLED(MICROBIT_BLE_DFU_SERVICE)
// Initialize buttonless SVCI bootloader interface before interrupts are enabled
MICROBIT_BLE_ECHK( ble_dfu_buttonless_async_svci_init());
#endif
}
/**
* When called, the micro:bit will begin advertising for a predefined period,
* MICROBIT_BLE_ADVERTISING_TIMEOUT seconds to bonded devices.
*/
MicroBitBLEManager *MicroBitBLEManager::getInstance()
{
if (manager == 0)
{
manager = new MicroBitBLEManager;
}
return manager;
}
/**
* Post constructor initialisation method as the BLE stack cannot be brought
* up in a static context.
*
* @param deviceName The name used when advertising
* @param serialNumber The serial number exposed by the device information service
* @param messageBus An instance of an EventModel, used during pairing.
* @param keyValuestorage An instance of a MicroBitStorage key/value pair storage class to use to hold bonding metadata
* @param enableBonding If true, the security manager enabled bonding.
*
* @code
* bleManager.init(uBit.getName(), uBit.getSerial(), uBit.messageBus, true);
* @endcode
*/
void MicroBitBLEManager::init( ManagedString deviceName, ManagedString serialNumber, EventModel &messageBus, MicroBitStorage &keyValueStorage, bool enableBonding, uint16_t board)
{
if ( this->status & DEVICE_COMPONENT_RUNNING)
return;
MICROBIT_DEBUG_DMESG( "MicroBitBLEManager::init");
MICROBIT_DEBUG_DMESG( "NRF_SDH_BLE_VS_UUID_COUNT = %d", (int) NRF_SDH_BLE_VS_UUID_COUNT);
MICROBIT_DEBUG_DMESG( "NRF_SDH_BLE_GATTS_ATTR_TAB_SIZE = %x", (int) NRF_SDH_BLE_GATTS_ATTR_TAB_SIZE);
pairingTime = 0;
shutdownTime = 0;
storage = &keyValueStorage;
#if NRF_LOG_ENABLED
MICROBIT_BLE_ECHK( NRF_LOG_INIT(NULL));
#if ( defined(NRF_LOG_BACKEND_RTT_ENABLED) && NRF_LOG_BACKEND_RTT_ENABLED) || ( defined(NRF_LOG_BACKEND_UART_ENABLED) && NRF_LOG_BACKEND_UART_ENABLED)
NRF_LOG_DEFAULT_BACKENDS_INIT();
#endif
#if defined(NRF_LOG_BACKEND_DMESG_ENABLED) && NRF_LOG_BACKEND_DMESG_ENABLED
nrf_log_backend_dmesg_init();
#endif
#endif // NRF_LOG_ENABLED
MICROBIT_BLE_ECHK( app_timer_init());
nrf_sdh_soc_init();
// Start the BLE stack.
uint32_t ram_start = 0;
MICROBIT_BLE_ECHK( nrf_pwr_mgmt_init());
MICROBIT_BLE_ECHK( nrf_sdh_enable_request());
MICROBIT_BLE_ECHK( nrf_sdh_ble_default_cfg_set( microbit_ble_CONN_CFG_TAG, &ram_start));
// set fixed gap name
gapName = MICROBIT_BLE_MODEL;
if ( enableBonding || !CONFIG_ENABLED(MICROBIT_BLE_WHITELIST))
{
ManagedString namePrefix(" [");
ManagedString namePostfix("]");
gapName = gapName + namePrefix + deviceName + namePostfix;
}
ble_cfg_t ble_cfg;
memset(&ble_cfg, 0, sizeof(ble_cfg));
BLE_GAP_CONN_SEC_MODE_SET_NO_ACCESS( &ble_cfg.gap_cfg.device_name_cfg.write_perm);
ble_cfg.gap_cfg.device_name_cfg.vloc = BLE_GATTS_VLOC_USER;
ble_cfg.gap_cfg.device_name_cfg.p_value = (uint8_t *)gapName.toCharArray();
ble_cfg.gap_cfg.device_name_cfg.current_len = gapName.length();
ble_cfg.gap_cfg.device_name_cfg.max_len = gapName.length();
MICROBIT_BLE_ECHK( sd_ble_cfg_set( BLE_GAP_CFG_DEVICE_NAME, &ble_cfg, ram_start));
MICROBIT_BLE_ECHK( nrf_sdh_ble_enable(&ram_start));
NRF_SDH_BLE_OBSERVER( microbit_ble_observer, microbit_ble_OBSERVER_PRIO, microbit_ble_evt_handler, NULL);
MICROBIT_BLE_ECHK( sd_ble_gap_appearance_set( BLE_APPEARANCE_UNKNOWN));
//#ifdef MICROBIT_V1_MBED_BLE_PATCHES
// // Configure the stack to hold onto the CPU during critical timing events.
// // mbed-classic performs __disable_irq() calls in its timers that can cause
// // MIC failures on secure BLE channels...
// ble_common_opt_radio_cpu_mutex_t opt;
// opt.enable = 1;
// sd_ble_opt_set(BLE_COMMON_OPT_RADIO_CPU_MUTEX, (const ble_opt_t *)&opt);
//#endif
//
//#if CONFIG_ENABLED(MICROBIT_BLE_PRIVATE_ADDRESSES)
// // Configure for private addresses, so kids' behaviour can't be easily tracked.
// ble->gap().setAddress(BLEProtocol::AddressType::RANDOM_PRIVATE_RESOLVABLE, {0});
//#endif
// Setup our security requirements.
// @bluetooth_mdw: select either passkey pairing (more secure),
// "just works" pairing (less secure but nice and simple for the user)
// or no security
// Default to passkey pairing with MITM protection
ble_gap_sec_params_t sec_param;
memset(&sec_param, 0, sizeof(ble_gap_sec_params_t));
#if MICROBIT_BLE_SECURITY_MODE == 3
#if defined(MICROBIT_BLE_SECURITY_LEVEL) && !(SECURITY_MODE_IS(SECURITY_MODE_ENCRYPTION_WITH_MITM))
#error "MICROBIT_BLE_SECURITY_MODE == 2 but MICROBIT_BLE_SECURITY_LEVEL != SECURITY_MODE_ENCRYPTION_WITH_MITM"
#endif
#elif MICROBIT_BLE_SECURITY_MODE == 2
#if defined(MICROBIT_BLE_SECURITY_LEVEL) && !(SECURITY_MODE_IS(SECURITY_MODE_ENCRYPTION_NO_MITM))
#error "MICROBIT_BLE_SECURITY_MODE == 2 but MICROBIT_BLE_SECURITY_LEVEL != SECURITY_MODE_ENCRYPTION_NO_MITM"
#endif
#elif MICROBIT_BLE_SECURITY_MODE == 1
#if defined(MICROBIT_BLE_SECURITY_LEVEL) && !(SECURITY_MODE_IS(SECURITY_MODE_ENCRYPTION_OPEN_LINK))
#error "MICROBIT_BLE_SECURITY_MODE == 2 but MICROBIT_BLE_SECURITY_LEVEL != SECURITY_MODE_ENCRYPTION_OPEN_LINK"
#endif
#else
#error "Unknown MICROBIT_BLE_SECURITY_MODE"
#endif
#if (MICROBIT_BLE_SECURITY_MODE == 2)
MICROBIT_DEBUG_DMESG( "Just Works security");
sec_param.bond = true;
sec_param.mitm = false;
sec_param.lesc = 0;
sec_param.keypress = 0;
sec_param.io_caps = BLE_GAP_IO_CAPS_NONE;
sec_param.oob = false;
sec_param.min_key_size = 7;
sec_param.max_key_size = 16;
sec_param.kdist_own.enc = 1;
sec_param.kdist_own.id = 1;
sec_param.kdist_peer.enc = 1;
sec_param.kdist_peer.id = 1;
#elif (MICROBIT_BLE_SECURITY_MODE == 1)
MICROBIT_DEBUG_DMESG( "No security");
sec_param.bond = false;
sec_param.mitm = false;
sec_param.lesc = 0;
sec_param.keypress = 0;
sec_param.io_caps = BLE_GAP_IO_CAPS_NONE;
sec_param.oob = false;
sec_param.min_key_size = 7;
sec_param.max_key_size = 16;
sec_param.kdist_own.enc = 0;
sec_param.kdist_own.id = 0;
sec_param.kdist_peer.enc = 0;
sec_param.kdist_peer.id = 0;
#elif (MICROBIT_BLE_SECURITY_MODE == 3)
MICROBIT_DEBUG_DMESG( "Passkey security");
sec_param.bond = true;
sec_param.mitm = true;
sec_param.lesc = 0;
sec_param.keypress = 0;
sec_param.io_caps = BLE_GAP_IO_CAPS_DISPLAY_ONLY;
sec_param.oob = false;
sec_param.min_key_size = 7;
sec_param.max_key_size = 16;
sec_param.kdist_own.enc = 1;
sec_param.kdist_own.id = 1;
sec_param.kdist_peer.enc = 1;
sec_param.kdist_peer.id = 1;
#else
#error "Unknown MICROBIT_BLE_SECURITY_MODE"
#endif
MICROBIT_BLE_ECHK( pm_init());
MICROBIT_BLE_ECHK( pm_sec_params_set( &sec_param));
MICROBIT_BLE_ECHK( pm_register( microbit_ble_pm_evt_handler));
// Set up GAP
// Configure for high speed mode where possible.
ble_gap_conn_params_t gap_conn_params;
memset(&gap_conn_params, 0, sizeof(gap_conn_params));
gap_conn_params.min_conn_interval = 8; // 10 ms
gap_conn_params.max_conn_interval = 16; // 20 ms
gap_conn_params.slave_latency = 0;
gap_conn_params.conn_sup_timeout = 400; // 4s
MICROBIT_BLE_ECHK( sd_ble_gap_ppcp_set( &gap_conn_params));
// Set up GATT
MICROBIT_BLE_ECHK( nrf_ble_gatt_init( &m_gatt, NULL));
if ( enableBonding)
{
MICROBIT_DEBUG_DMESG( "enableBonding");
// If we're in pairing mode, review the size of the bond table.
// If we're full, delete the lowest ranked.
if ( getBondCount() >= MICROBIT_BLE_MAXIMUM_BONDS)
{
MICROBIT_DEBUG_DMESG( "delete the lowest ranked peer");
pm_peer_id_t highest_ranked_peer;
uint32_t highest_rank;
pm_peer_id_t lowest_ranked_peer;
uint32_t lowest_rank;
pm_peer_ranks_get( &highest_ranked_peer, &highest_rank, &lowest_ranked_peer, &lowest_rank);
pm_peer_delete( lowest_ranked_peer);
}
}
bool connectable = true;
bool discoverable = true;
bool whitelist = false;
#if CONFIG_ENABLED(MICROBIT_BLE_WHITELIST)
// Configure a whitelist to filter all connection requetss from unbonded devices.
// Most BLE stacks only permit one connection at a time, so this prevents denial of service attacks.
// ble->gap().setScanningPolicyMode(Gap::SCAN_POLICY_IGNORE_WHITELIST);
// ble->gap().setAdvertisingPolicyMode(Gap::ADV_POLICY_FILTER_CONN_REQS);
pm_peer_id_t peer_list[ MICROBIT_BLE_MAXIMUM_BONDS];
uint32_t list_size = MICROBIT_BLE_MAXIMUM_BONDS;
MICROBIT_BLE_ECHK( pm_peer_id_list( peer_list, &list_size, PM_PEER_ID_INVALID, PM_PEER_ID_LIST_ALL_ID ));
MICROBIT_BLE_ECHK( pm_whitelist_set( list_size ? peer_list : NULL, list_size));
MICROBIT_BLE_ECHK( pm_device_identities_list_set( list_size ? peer_list : NULL, list_size));
connectable = discoverable = whitelist = list_size > 0;
MICROBIT_DEBUG_DMESG( "whitelist size = %d", list_size);
#endif
// Bring up core BLE services.
#if CONFIG_ENABLED(MICROBIT_BLE_DFU_SERVICE)
MICROBIT_DEBUG_DMESG( "DFU_SERVICE");
microbit_dfu_init();
#endif
#if CONFIG_ENABLED(MICROBIT_BLE_PARTIAL_FLASHING)
MICROBIT_DEBUG_DMESG( "PARTIAL_FLASHING");
new MicroBitPartialFlashingService( *this, messageBus, *storage);
#endif
#if CONFIG_ENABLED(MICROBIT_BLE_DEVICE_INFORMATION_SERVICE)
MICROBIT_DEBUG_DMESG( "DEVICE_INFORMATION_SERVICE");
int versionIdx = 0;
switch ( board)
{
case 0x9903:
case 0x9904: break;
default: versionIdx = 1; break;
}
ManagedString modelVersion( MICROBIT_BLE_VERSION[versionIdx]);
ManagedString disName( MICROBIT_BLE_MODEL);
disName = disName + " V" + modelVersion;
ble_dis_init_t disi;
memset( &disi, 0, sizeof(disi));
disi.dis_char_rd_sec = SEC_OPEN;
const_ascii_to_utf8( &disi.manufact_name_str, MICROBIT_BLE_MANUFACTURER);
const_ascii_to_utf8( &disi.model_num_str, disName.toCharArray());
const_ascii_to_utf8( &disi.serial_num_str, serialNumber.toCharArray());
const_ascii_to_utf8( &disi.hw_rev_str, MICROBIT_BLE_HARDWARE_VERSION);
const_ascii_to_utf8( &disi.fw_rev_str, MICROBIT_BLE_FIRMWARE_VERSION);
const_ascii_to_utf8( &disi.sw_rev_str, MICROBIT_BLE_SOFTWARE_VERSION);
//ble_dis_sys_id_t * p_sys_id; /**< System ID. */
//ble_dis_reg_cert_data_list_t * p_reg_cert_data_list; /**< IEEE 11073-20601 Regulatory Certification Data List. */
//ble_dis_pnp_id_t * p_pnp_id; /**< PnP ID. */
ble_dis_init( &disi);
#else
(void)serialNumber;
#endif
#if CONFIG_ENABLED(MICROBIT_BLE_EVENT_SERVICE)
MICROBIT_DEBUG_DMESG( "EVENT_SERVICE");
new MicroBitEventService( *this, messageBus);
#else
(void)messageBus;
#endif
servicesChanged();
// Setup advertising.
microbit_ble_configureAdvertising( connectable, discoverable, whitelist,
MICROBIT_BLE_ADVERTISING_INTERVAL, MICROBIT_BLE_ADVERTISING_TIMEOUT);
// Configure the radio at our default power level
setTransmitPower( MICROBIT_BLE_DEFAULT_TX_POWER);
ble_conn_params_init_t cp_init;
memset(&cp_init, 0, sizeof(cp_init));
cp_init.p_conn_params = &gap_conn_params;
cp_init.first_conn_params_update_delay = APP_TIMER_TICKS(5000); // 5 seconds
cp_init.next_conn_params_update_delay = APP_TIMER_TICKS(30000); // 30 seconds
cp_init.max_conn_params_update_count = 3;
cp_init.start_on_notify_cccd_handle = BLE_GATT_HANDLE_INVALID;
cp_init.disconnect_on_fail = false;
MICROBIT_BLE_ECHK( ble_conn_params_init(&cp_init));
setAdvertiseOnDisconnect( true);
// If we have whitelisting enabled, then prevent only enable advertising of we have any binded devices...
// This is to further protect kids' privacy. If no-one initiates BLE, then the device is unreachable.
// If whiltelisting is disabled, then we always advertise.
#if CONFIG_ENABLED(MICROBIT_BLE_WHITELIST)
if ( getBondCount() > 0)
#endif
advertise();
this->status |= DEVICE_COMPONENT_RUNNING;
}
/**
* Change the output power level of the transmitter to the given value.
*
* @param power a value in the range 0..7, where 0 is the lowest power and 7 is the highest.
*
* @return DEVICE_OK on success, or DEVICE_INVALID_PARAMETER if the value is out of range.
*
* @code
* // maximum transmission power.
* bleManager.setTransmitPower(7);
* @endcode
*/
int MicroBitBLEManager::setTransmitPower(int power)
{
if ( power < 0 || power >= MICROBIT_BLE_POWER_LEVELS)
return DEVICE_INVALID_PARAMETER;
MICROBIT_DEBUG_DMESG( "setTransmitPower %d", power);
m_power = power;
ble_conn_state_for_each_connected( microbit_ble_for_each_connected_tx_power_set, &m_power);
if ( m_adv_handle != BLE_GAP_ADV_SET_HANDLE_NOT_SET)
{
MICROBIT_DEBUG_DMESG( " BLE_GAP_TX_POWER_ROLE_ADV");
MICROBIT_BLE_ECHK( sd_ble_gap_tx_power_set( BLE_GAP_TX_POWER_ROLE_ADV, m_adv_handle, MICROBIT_BLE_POWER_LEVEL[ m_power]));
}
return DEVICE_OK;
}
/**
* Determines the number of devices currently bonded with this micro:bit.
* @return The number of active bonds.
*/
int MicroBitBLEManager::getBondCount()
{
MICROBIT_DEBUG_DMESG( "getBondCount %d", pm_peer_count());
return pm_peer_count();
}
/**
* A request to pair has been received from a BLE device.
* If we're in pairing mode, display the passkey to the user.
* Also, purge the bonding table if it has reached capacity.
*
* @note for internal use only.
*/
void MicroBitBLEManager::pairingRequested(ManagedString passKey)
{
MICROBIT_DEBUG_DMESG( "pairingRequested %s", passKey.toCharArray());
// Update our mode to display the passkey.
this->passKey = passKey;
this->pairingStatus = MICROBIT_BLE_PAIR_REQUEST;
}
#define MICROBIT_BLE_PAIR_FAILURE 0
#define MICROBIT_BLE_PAIR_SUCCESS 1
#define MICROBIT_BLE_PAIR_AUTH 2
#define MICROBIT_BLE_PAIR_UPDATE 3
#define MICROBIT_BLE_PAIR_CHECK 4
/**
* Record pairing progress
*
* @note for internal use only.
*/
bool MicroBitBLEManager::pairingComplete( int event)
{
if ( currentMode != MICROBIT_MODE_PAIRING)
return true;
if ( this->pairingStatus & MICROBIT_BLE_PAIR_COMPLETE)
return true;
switch ( event)
{
case MICROBIT_BLE_PAIR_FAILURE:
MICROBIT_DEBUG_DMESG( "pairingComplete FAILURE");
this->pairingStatus = MICROBIT_BLE_PAIR_COMPLETE;
break;
case MICROBIT_BLE_PAIR_SUCCESS:
MICROBIT_DEBUG_DMESG( "pairingComplete SUCCESS");
this->pairingStatus = MICROBIT_BLE_PAIR_COMPLETE | MICROBIT_BLE_PAIR_SUCCESSFUL;
if ( MICROBIT_BLE_DISCONNECT_AFTER_PAIRING_DELAY > 0)
{
this->status |= MICROBIT_BLE_STATUS_DISCONNECT;
fiber_add_idle_component(this);
}
break;
case MICROBIT_BLE_PAIR_AUTH:
MICROBIT_DEBUG_DMESG( "pairingComplete AUTH");
pairingTime = system_timer_current_time();
break;
case MICROBIT_BLE_PAIR_UPDATE:
MICROBIT_DEBUG_DMESG( "pairingComplete UPDATE");
if ( pairingTime)
pairingTime = system_timer_current_time();
break;
case MICROBIT_BLE_PAIR_CHECK:
//MICROBIT_DEBUG_DMESG( "pairingComplete CHECK");
if ( !(pairingStatus & MICROBIT_BLE_PAIR_COMPLETE)
&& pairingTime > 0
&& (system_timer_current_time() - pairingTime) >= MICROBIT_BLE_PAIRING_EVENT_DELAY)
{
pairingComplete( MICROBIT_BLE_PAIR_SUCCESS);
}
break;
default:
break;
}
return this->pairingStatus & MICROBIT_BLE_PAIR_COMPLETE;
}
/**
* Periodic callback in thread context.
* We use this here purely to safely issue a disconnect operation after a pairing operation is complete.
*/
void MicroBitBLEManager::idleCallback()
{
if ( this->status & MICROBIT_BLE_STATUS_DISCONNECT)
{
if ( (system_timer_current_time() - pairingTime) >= MICROBIT_BLE_DISCONNECT_AFTER_PAIRING_DELAY)
{
MICROBIT_DEBUG_DMESG( "%d:MicroBitBLEManager::idleCallback", (int)system_timer_current_time());
MICROBIT_DEBUG_DMESG( "MICROBIT_BLE_STATUS_DISCONNECT");
ble_conn_state_for_each_connected( microbit_ble_for_each_connected_disconnect, NULL);
this->status &= ~MICROBIT_BLE_STATUS_DISCONNECT;
}
}
if ( this->status & MICROBIT_BLE_STATUS_SHUTDOWN)
{
//MICROBIT_DEBUG_DMESG( "MicroBitBLEManager::idleCallback");
//MICROBIT_DEBUG_DMESG( "MICROBIT_BLE_STATUS_SHUTDOWN");
nrf_pwr_mgmt_shutdown(NRF_PWR_MGMT_SHUTDOWN_CONTINUE);
}
}
/**
* When called, the micro:bit will begin advertising for a predefined period,
* MICROBIT_BLE_ADVERTISING_TIMEOUT seconds to bonded devices.
*/
void MicroBitBLEManager::advertise()
{
MICROBIT_DEBUG_DMESG( "advertise");
MICROBIT_BLE_ECHK( sd_ble_gap_adv_start( m_adv_handle, microbit_ble_CONN_CFG_TAG));
}
/**
* Stops any currently running BLE advertisements
*/
void MicroBitBLEManager::stopAdvertising()
{
MICROBIT_DEBUG_DMESG( "stopAdvertising");
MICROBIT_BLE_ECHK( sd_ble_gap_adv_stop( m_adv_handle));
}
/**
* A member function used to restart advertising
* */
void MicroBitBLEManager::onDisconnect()
{
MICROBIT_DEBUG_DMESG( "onDisconnect");
MicroBitEvent(MICROBIT_ID_BLE, MICROBIT_BLE_EVT_DISCONNECTED);
if ( advertiseOnDisconnect && ble_conn_state_peripheral_conn_count() == 0)
advertise();
}
/**
* Determine if Bluetooth is connected
* @return true if connected
*/
bool MicroBitBLEManager::getConnected()
{
return ble_conn_state_peripheral_conn_count() > 0;
}
#if CONFIG_ENABLED(MICROBIT_BLE_EDDYSTONE_URL)
/**
* Set the content of Eddystone URL frames
*
* @param url The url to broadcast
*
* @param calibratedPower the transmission range of the beacon (Defaults to: 0xF0 ~10m).
*
* @param connectable true to keep bluetooth connectable for other services, false otherwise. (Defaults to true)
*
* @param interval the rate at which the micro:bit will advertise url frames. (Defaults to MICROBIT_BLE_EDDYSTONE_ADV_INTERVAL)
*
* @note The calibratedPower value ranges from -100 to +20 to a resolution of 1. The calibrated power should be binary encoded.
* More information can be found at https://github.com/google/eddystone/tree/master/eddystone-uid#tx-power
*/
int MicroBitBLEManager::advertiseEddystoneUrl(const char* url, int8_t calibratedPower, bool connectable, uint16_t interval)
{
MICROBIT_DEBUG_DMESG( "advertiseEddystoneUrl");
uint8_t frameData[ MicroBitEddystone::frameSizeURL];
uint16_t frameSize;
int ret = MicroBitEddystone::getInstance()->getURL( frameData, &frameSize, url, calibratedPower);
if ( ret == MICROBIT_OK)
{
stopAdvertising();
microbit_ble_configureAdvertising( connectable, true /*discoverable*/, false /*whitelist*/, interval, MICROBIT_BLE_ADVERTISING_TIMEOUT, frameData + 2, frameSize - 2);
advertise();
}
return ret;
}
/**
* Set the content of Eddystone URL frames, but accepts a ManagedString as a url.
*
* @param url The url to broadcast
*
* @param calibratedPower the transmission range of the beacon (Defaults to: 0xF0 ~10m).
*
* @param connectable true to keep bluetooth connectable for other services, false otherwise. (Defaults to true)
*
* @param interval the rate at which the micro:bit will advertise url frames. (Defaults to MICROBIT_BLE_EDDYSTONE_ADV_INTERVAL)
*
* @note The calibratedPower value ranges from -100 to +20 to a resolution of 1. The calibrated power should be binary encoded.
* More information can be found at https://github.com/google/eddystone/tree/master/eddystone-uid#tx-power
*/
int MicroBitBLEManager::advertiseEddystoneUrl(ManagedString url, int8_t calibratedPower, bool connectable, uint16_t interval)
{
return advertiseEddystoneUrl((char *)url.toCharArray(), calibratedPower, connectable, interval);
}
#endif
#if CONFIG_ENABLED(MICROBIT_BLE_EDDYSTONE_UID)
/**
* Set the content of Eddystone UID frames
*
* @param uid_namespace: the uid namespace. Must 10 bytes long.
*
* @param uid_instance: the uid instance value. Must 6 bytes long.
*
* @param calibratedPower the transmission range of the beacon (Defaults to: 0xF0 ~10m).
*
* @param connectable true to keep bluetooth connectable for other services, false otherwise. (Defaults to true)
*
* @param interval the rate at which the micro:bit will advertise url frames. (Defaults to MICROBIT_BLE_EDDYSTONE_ADV_INTERVAL)
*
* @note The calibratedPower value ranges from -100 to +20 to a resolution of 1. The calibrated power should be binary encoded.
* More information can be found at https://github.com/google/eddystone/tree/master/eddystone-uid#tx-power
*/
int MicroBitBLEManager::advertiseEddystoneUid(const char* uid_namespace, const char* uid_instance, int8_t calibratedPower, bool connectable, uint16_t interval)
{
MICROBIT_DEBUG_DMESG( "advertiseEddystoneUid");
uint8_t frameData[ MicroBitEddystone::frameSizeUID];
uint16_t frameSize;
int ret = MicroBitEddystone::getInstance()->getUID( frameData, &frameSize, uid_namespace, uid_instance, calibratedPower);
if ( ret == MICROBIT_OK)
{
stopAdvertising();
microbit_ble_configureAdvertising( connectable, true /*discoverable*/, false /*whitelist*/, interval, MICROBIT_BLE_ADVERTISING_TIMEOUT, frameData + 2, frameSize - 2);
advertise();
}
return ret;
}
#endif
/**
* Enter pairing mode. This is mode is called to initiate pairing, and to enable FOTA programming
* of the micro:bit in cases where BLE is disabled during normal operation.
*
* @param display An instance of MicroBitDisplay used when displaying pairing information.
* @param authorizationButton The button to use to authorise a pairing request.
*
* @code
* // initiate pairing mode
* bleManager.pairingMode(uBit.display, uBit.buttonA);
* @endcode
*/
void MicroBitBLEManager::pairingMode(MicroBitDisplay &display, Button &authorisationButton)
{
MICROBIT_DEBUG_DMESG( "pairingMode");
// Do not page this fiber!
currentFiber->flags |= DEVICE_FIBER_FLAG_DO_NOT_PAGE;
int timeInPairingMode = 0;
int brightness = 255;
int fadeDirection = 0;
currentMode = MICROBIT_MODE_PAIRING;
pairingTime = 0;
stopAdvertising();
#if CONFIG_ENABLED(MICROBIT_BLE_WHITELIST)
// Clear the whitelist (if we have one), so that we're discoverable by all BLE devices.
MICROBIT_BLE_ECHK( pm_whitelist_set( NULL, 0));
MICROBIT_BLE_ECHK( pm_device_identities_list_set( NULL, 0));
#endif
microbit_ble_configureAdvertising( true /*connectable*/, true /*discoverable*/, false /*whitelist*/, 200, 0);
advertise();
// Stop any running animations on the display
display.stopAnimation();
showManagementModeAnimation(display);
// Display our name, visualised as a histogram in the display to aid identification.
showNameHistogram(display);
while (1)
{
pairingComplete( MICROBIT_BLE_PAIR_CHECK);
if (pairingStatus & MICROBIT_BLE_PAIR_REQUEST)
{
timeInPairingMode = 0;
MicroBitImage arrow("0,0,255,0,0\n0,255,0,0,0\n255,255,255,255,255\n0,255,0,0,0\n0,0,255,0,0\n");
display.print(arrow, 0, 0, 0);
if (fadeDirection == 0)
brightness -= MICROBIT_PAIRING_FADE_SPEED;
else
brightness += MICROBIT_PAIRING_FADE_SPEED;
if (brightness <= 40)
display.clear();
if (brightness <= 0)
fadeDirection = 1;
if (brightness >= 255)
fadeDirection = 0;
if (authorisationButton.isPressed())
{
pairingStatus &= ~MICROBIT_BLE_PAIR_REQUEST;
pairingStatus |= MICROBIT_BLE_PAIR_PASSCODE;
}
}
if (pairingStatus & MICROBIT_BLE_PAIR_PASSCODE)
{
timeInPairingMode = 0;
display.setBrightness(255);
for (int i = 0; i < passKey.length(); i++)
{
display.image.print(passKey.charAt(i), 0, 0);
if ( pairingComplete( MICROBIT_BLE_PAIR_CHECK))
break;
fiber_sleep(800);
display.clear();
if ( pairingComplete( MICROBIT_BLE_PAIR_CHECK))
break;
fiber_sleep(200);
}
if ( !pairingComplete( MICROBIT_BLE_PAIR_CHECK))
fiber_sleep(1000);
}
if (pairingStatus & MICROBIT_BLE_PAIR_COMPLETE)
{
if (pairingStatus & MICROBIT_BLE_PAIR_SUCCESSFUL)
{
MicroBitImage tick("0,0,0,0,0\n0,0,0,0,255\n0,0,0,255,0\n255,0,255,0,0\n0,255,0,0,0\n");
display.print(tick, 0, 0, 0);
fiber_sleep(15000);
timeInPairingMode = MICROBIT_BLE_PAIRING_TIMEOUT * 30;
/*
* Disabled, as the API to return the number of active bonds is not reliable at present...
*
display.clear();
ManagedString c(getBondCount());
ManagedString c2("/");
ManagedString c3(MICROBIT_BLE_MAXIMUM_BONDS);
ManagedString c4("USED");
display.scroll(c+c2+c3+c4);
*
*
*/
}
else
{
MicroBitImage cross("255,0,0,0,255\n0,255,0,255,0\n0,0,255,0,0\n0,255,0,255,0\n255,0,0,0,255\n");
display.print(cross, 0, 0, 0);
}
}
fiber_sleep(100);
timeInPairingMode++;
if (timeInPairingMode >= MICROBIT_BLE_PAIRING_TIMEOUT * 30)
{
MICROBIT_DEBUG_DMESGF( "Pairing mode reset");
microbit_reset();
}
}
}
/**
* Displays the management mode animation on the provided MicroBitDisplay instance.
*
* @param display The Display instance used for displaying the animation.
*/
void MicroBitBLEManager::showManagementModeAnimation(MicroBitDisplay &display)
{
// Animation for display object
// https://makecode.microbit.org/93264-81126-90471-58367
const uint8_t mgmt_animation[] __attribute__ ((aligned (4))) =
{
0xff, 0xff, 20, 0, 5, 0,
255,255,255,255,255, 255,255,255,255,255, 255,255, 0,255,255, 255, 0, 0, 0,255,
255,255,255,255,255, 255,255, 0,255,255, 255, 0, 0, 0,255, 0, 0, 0, 0, 0,
255,255, 0,255,255, 255, 0, 0, 0,255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
255,255,255,255,255, 255,255, 0,255,255, 255, 0, 0, 0,255, 0, 0, 0, 0, 0,
255,255,255,255,255, 255,255,255,255,255, 255,255, 0,255,255, 255, 0, 0, 0,255
};
MicroBitImage mgmt((ImageData*)mgmt_animation);
display.animate(mgmt,100,5);
const uint8_t bt_icon_raw[] =
{
0, 0,255,255, 0,
255, 0,255, 0,255,
0,255,255,255, 0,
255, 0,255, 0,255,
0, 0,255,255, 0
};
MicroBitImage bt_icon(5,5,bt_icon_raw);
display.print(bt_icon,0,0,0,0);
for(int i=0; i < 255; i = i + 5){
display.setBrightness(i);
fiber_sleep(5);
}
fiber_sleep(1000);
}
// visual ID code constants
#define MICROBIT_DFU_HISTOGRAM_WIDTH 5
#define MICROBIT_DFU_HISTOGRAM_HEIGHT 5
/**
* Displays the device's ID code as a histogram on the provided MicroBitDisplay instance.
*
* @param display The display instance used for displaying the histogram.
*/
void MicroBitBLEManager::showNameHistogram(MicroBitDisplay &display)
{
uint32_t n = NRF_FICR->DEVICEID[1];
int ld = 1;
int d = MICROBIT_DFU_HISTOGRAM_HEIGHT;