forked from sandeepmistry/arduino-BLEPeripheral
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathnRF51822.cpp
1126 lines (877 loc) · 41 KB
/
nRF51822.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
#if defined(NRF51) || defined(__RFduino__)
#ifdef __RFduino__
#include <utility/RFduino/ble.h>
#include <utility/RFduino/ble_hci.h>
#include <utility/RFduino/nrf_sdm.h>
#else
#include <s110/ble.h>
#include <s110/ble_hci.h>
#include <s110/nrf_sdm.h>
#endif
#include "Arduino.h"
#include "BLEAttribute.h"
#include "BLEService.h"
#include "BLECharacteristic.h"
#include "BLEDescriptor.h"
#include "BLEUtil.h"
#include "BLEUuid.h"
#include "nRF51822.h"
// #define NRF_51822_DEBUG
#define BLE_STACK_EVT_MSG_BUF_SIZE (sizeof(ble_evt_t) + (GATT_MTU_SIZE_DEFAULT))
nRF51822::nRF51822() :
BLEDevice(),
_connectionHandle(BLE_CONN_HANDLE_INVALID),
_storeAuthStatus(false),
_advDataLen(0),
_broadcastCharacteristic(NULL),
_numLocalCharacteristics(0),
_localCharacteristicInfo(NULL),
_numRemoteServices(0),
_remoteServiceInfo(NULL),
_remoteServiceDiscoveryIndex(0),
_numRemoteCharacteristics(0),
_remoteCharacteristicInfo(NULL),
_remoteRequestInProgress(false)
{
this->_authStatus = (ble_gap_evt_auth_status_t*)&this->_authStatusBuffer;
memset(&this->_authStatusBuffer, 0, sizeof(this->_authStatusBuffer));
}
nRF51822::~nRF51822() {
if (this->_remoteCharacteristicInfo) {
free(this->_remoteCharacteristicInfo);
}
if (this->_remoteServiceInfo) {
free(this->_remoteServiceInfo);
}
if (this->_localCharacteristicInfo) {
free(this->_localCharacteristicInfo);
}
}
void nRF51822::begin(unsigned char advertisementDataType,
unsigned char advertisementDataLength,
const unsigned char* advertisementData,
unsigned char scanDataType,
unsigned char scanDataLength,
const unsigned char* scanData,
BLELocalAttribute** localAttributes,
unsigned char numLocalAttributes,
BLERemoteAttribute** remoteAttributes,
unsigned char numRemoteAttributes)
{
#ifdef __RFduino__
sd_softdevice_enable(NRF_CLOCK_LFCLKSRC_SYNTH_250_PPM, NULL);
#else
sd_softdevice_enable(NRF_CLOCK_LFCLKSRC_XTAL_20_PPM, NULL); // sd_nvic_EnableIRQ(SWI2_IRQn);
#endif
#ifdef NRF_51822_DEBUG
ble_version_t version;
sd_ble_version_get(&version);
Serial.print(F("version = "));
Serial.print(version.version_number);
Serial.print(F(" "));
Serial.print(version.company_id);
Serial.print(F(" "));
Serial.print(version.subversion_number);
Serial.println();
#endif
ble_gap_conn_params_t gap_conn_params = {0};
gap_conn_params.min_conn_interval = 40; // in 1.25ms units
gap_conn_params.max_conn_interval = 80; // in 1.25ms unit
gap_conn_params.slave_latency = 0;
gap_conn_params.conn_sup_timeout = 4000 / 10; // in 10ms unit
sd_ble_gap_ppcp_set(&gap_conn_params);
sd_ble_gap_tx_power_set(0);
unsigned char srData[31];
unsigned char srDataLen = 0;
this->_advDataLen = 0;
// flags
this->_advData[this->_advDataLen + 0] = 2;
this->_advData[this->_advDataLen + 1] = 0x01;
this->_advData[this->_advDataLen + 2] = 0x06;
this->_advDataLen += 3;
if (advertisementDataType && advertisementDataLength && advertisementData) {
this->_advData[this->_advDataLen + 0] = advertisementDataLength + 1;
this->_advData[this->_advDataLen + 1] = advertisementDataType;
this->_advDataLen += 2;
memcpy(&this->_advData[this->_advDataLen], advertisementData, advertisementDataLength);
this->_advDataLen += advertisementDataLength;
}
if (scanDataType && scanDataLength && srData) {
srData[0] = scanDataLength + 1;
srData[1] = scanDataType;
memcpy(&srData[2], scanData, scanDataLength);
srDataLen = 2 + scanDataLength;
}
sd_ble_gap_adv_data_set(this->_advData, this->_advDataLen, srData, srDataLen);
sd_ble_gap_appearance_set(0);
for (int i = 0; i < numLocalAttributes; i++) {
BLELocalAttribute *localAttribute = localAttributes[i];
if (localAttribute->type() == BLETypeCharacteristic) {
this->_numLocalCharacteristics++;
}
}
this->_numLocalCharacteristics -= 3; // 0x2a00, 0x2a01, 0x2a05
this->_localCharacteristicInfo = (struct localCharacteristicInfo*)malloc(sizeof(struct localCharacteristicInfo) * this->_numLocalCharacteristics);
unsigned char localCharacteristicIndex = 0;
uint16_t handle = 0;
BLEService *lastService = NULL;
for (int i = 0; i < numLocalAttributes; i++) {
BLELocalAttribute *localAttribute = localAttributes[i];
BLEUuid uuid = BLEUuid(localAttribute->uuid());
const unsigned char* uuidData = uuid.data();
unsigned char value[255];
ble_uuid_t nordicUUID;
if (uuid.length() == 2) {
nordicUUID.uuid = (uuidData[1] << 8) | uuidData[0];
nordicUUID.type = BLE_UUID_TYPE_BLE;
} else {
unsigned char uuidDataTemp[16];
memcpy(&uuidDataTemp, uuidData, sizeof(uuidDataTemp));
nordicUUID.uuid = (uuidData[13] << 8) | uuidData[12];
uuidDataTemp[13] = 0;
uuidDataTemp[12] = 0;
sd_ble_uuid_vs_add((ble_uuid128_t*)&uuidDataTemp, &nordicUUID.type);
}
if (localAttribute->type() == BLETypeService) {
BLEService *service = (BLEService *)localAttribute;
if (strcmp(service->uuid(), "1800") == 0 || strcmp(service->uuid(), "1801") == 0) {
continue; // skip
}
sd_ble_gatts_service_add(BLE_GATTS_SRVC_TYPE_PRIMARY, &nordicUUID, &handle);
lastService = service;
} else if (localAttribute->type() == BLETypeCharacteristic) {
BLECharacteristic *characteristic = (BLECharacteristic *)localAttribute;
if (strcmp(characteristic->uuid(), "2a00") == 0) {
ble_gap_conn_sec_mode_t secMode;
BLE_GAP_CONN_SEC_MODE_SET_OPEN(&secMode); // no security is needed
sd_ble_gap_device_name_set(&secMode, characteristic->value(), characteristic->valueLength());
} else if (strcmp(characteristic->uuid(), "2a01") == 0) {
const uint16_t *appearance = (const uint16_t*)characteristic->value();
sd_ble_gap_appearance_set(*appearance);
} else if (strcmp(characteristic->uuid(), "2a05") == 0) {
// do nothing
} else {
uint8_t properties = characteristic->properties() & 0xfe;
uint16_t valueLength = characteristic->valueLength();
this->_localCharacteristicInfo[localCharacteristicIndex].characteristic = characteristic;
this->_localCharacteristicInfo[localCharacteristicIndex].notifySubscribed = false;
this->_localCharacteristicInfo[localCharacteristicIndex].indicateSubscribed = false;
this->_localCharacteristicInfo[localCharacteristicIndex].service = lastService;
ble_gatts_char_md_t characteristicMetaData;
ble_gatts_attr_md_t clientCharacteristicConfigurationMetaData;
ble_gatts_attr_t characteristicValueAttribute;
ble_gatts_attr_md_t characteristicValueAttributeMetaData;
memset(&characteristicMetaData, 0, sizeof(characteristicMetaData));
memcpy(&characteristicMetaData.char_props, &properties, 1);
characteristicMetaData.p_char_user_desc = NULL;
characteristicMetaData.p_char_pf = NULL;
characteristicMetaData.p_user_desc_md = NULL;
characteristicMetaData.p_cccd_md = NULL;
characteristicMetaData.p_sccd_md = NULL;
if (properties & (BLENotify | BLEIndicate)) {
memset(&clientCharacteristicConfigurationMetaData, 0, sizeof(clientCharacteristicConfigurationMetaData));
BLE_GAP_CONN_SEC_MODE_SET_OPEN(&clientCharacteristicConfigurationMetaData.read_perm);
BLE_GAP_CONN_SEC_MODE_SET_OPEN(&clientCharacteristicConfigurationMetaData.write_perm);
clientCharacteristicConfigurationMetaData.vloc = BLE_GATTS_VLOC_STACK;
characteristicMetaData.p_cccd_md = &clientCharacteristicConfigurationMetaData;
}
memset(&characteristicValueAttributeMetaData, 0, sizeof(characteristicValueAttributeMetaData));
if (properties & (BLERead | BLENotify | BLEIndicate)) {
if (this->_bondStore) {
BLE_GAP_CONN_SEC_MODE_SET_ENC_NO_MITM(&characteristicValueAttributeMetaData.read_perm);
} else {
BLE_GAP_CONN_SEC_MODE_SET_OPEN(&characteristicValueAttributeMetaData.read_perm);
}
}
if (properties & (BLEWriteWithoutResponse | BLEWrite)) {
if (this->_bondStore) {
BLE_GAP_CONN_SEC_MODE_SET_ENC_NO_MITM(&characteristicValueAttributeMetaData.write_perm);
} else {
BLE_GAP_CONN_SEC_MODE_SET_OPEN(&characteristicValueAttributeMetaData.write_perm);
}
}
characteristicValueAttributeMetaData.vloc = BLE_GATTS_VLOC_STACK;
characteristicValueAttributeMetaData.rd_auth = 0;
characteristicValueAttributeMetaData.wr_auth = 0;
characteristicValueAttributeMetaData.vlen = 0;
for (int j = (i + 1); j < numLocalAttributes; j++) {
localAttribute = localAttributes[j];
if (localAttribute->type() != BLETypeDescriptor) {
break;
}
BLEDescriptor *descriptor = (BLEDescriptor *)localAttribute;
if (strcmp(descriptor->uuid(), "2901") == 0) {
characteristicMetaData.p_char_user_desc = (uint8_t*)descriptor->value();
characteristicMetaData.char_user_desc_max_size = descriptor->valueLength();
characteristicMetaData.char_user_desc_size = descriptor->valueLength();
} else if (strcmp(descriptor->uuid(), "2904") == 0) {
characteristicMetaData.p_char_pf = (ble_gatts_char_pf_t *)descriptor->value();
}
}
memset(&characteristicValueAttribute, 0, sizeof(characteristicValueAttribute));
characteristicValueAttribute.p_uuid = &nordicUUID;
characteristicValueAttribute.p_attr_md = &characteristicValueAttributeMetaData;
characteristicValueAttribute.init_len = valueLength;
characteristicValueAttribute.init_offs = 0;
characteristicValueAttribute.max_len = characteristic->valueSize();
characteristicValueAttribute.p_value = NULL;
sd_ble_gatts_characteristic_add(BLE_GATT_HANDLE_INVALID, &characteristicMetaData, &characteristicValueAttribute, &this->_localCharacteristicInfo[localCharacteristicIndex].handles);
if (valueLength) {
for (int j = 0; j < valueLength; j++) {
value[j] = (*characteristic)[j];
}
Serial.println(valueLength);
sd_ble_gatts_value_set(this->_localCharacteristicInfo[localCharacteristicIndex].handles.value_handle, 0, &valueLength, value);
}
localCharacteristicIndex++;
}
} else if (localAttribute->type() == BLETypeDescriptor) {
BLEDescriptor *descriptor = (BLEDescriptor *)localAttribute;
if (strcmp(descriptor->uuid(), "2901") == 0 ||
strcmp(descriptor->uuid(), "2902") == 0 ||
strcmp(descriptor->uuid(), "2903") == 0 ||
strcmp(descriptor->uuid(), "2904") == 0) {
continue; // skip
}
uint16_t valueLength = descriptor->valueLength();
ble_gatts_attr_t descriptorAttribute;
ble_gatts_attr_md_t descriptorMetaData;
memset(&descriptorAttribute, 0, sizeof(descriptorAttribute));
memset(&descriptorMetaData, 0, sizeof(descriptorMetaData));
descriptorMetaData.vloc = BLE_GATTS_VLOC_STACK;
descriptorMetaData.vlen = (valueLength == descriptor->valueLength()) ? 0 : 1;
if (this->_bondStore) {
BLE_GAP_CONN_SEC_MODE_SET_ENC_NO_MITM(&descriptorMetaData.read_perm);
} else {
BLE_GAP_CONN_SEC_MODE_SET_OPEN(&descriptorMetaData.read_perm);
}
descriptorAttribute.p_uuid = &nordicUUID;
descriptorAttribute.p_attr_md = &descriptorMetaData;
descriptorAttribute.init_len = valueLength;
descriptorAttribute.max_len = descriptor->valueLength();
descriptorAttribute.p_value = NULL;
sd_ble_gatts_descriptor_add(BLE_GATT_HANDLE_INVALID, &descriptorAttribute, &handle);
if (valueLength) {
for (int j = 0; j < valueLength; j++) {
value[j] = (*descriptor)[j];
}
sd_ble_gatts_value_set(handle, 0, &valueLength, value);
}
}
}
if ( numRemoteAttributes > 0) {
numRemoteAttributes -= 2; // 0x1801, 0x2a05
}
for (int i = 0; i < numRemoteAttributes; i++) {
BLERemoteAttribute *remoteAttribute = remoteAttributes[i];
if (remoteAttribute->type() == BLETypeService) {
this->_numRemoteServices++;
} else if (remoteAttribute->type() == BLETypeCharacteristic) {
this->_numRemoteCharacteristics++;
}
}
this->_remoteServiceInfo = (struct remoteServiceInfo*)malloc(sizeof(struct remoteServiceInfo) * this->_numRemoteServices);
this->_remoteCharacteristicInfo = (struct remoteCharacteristicInfo*)malloc(sizeof(struct remoteCharacteristicInfo) * this->_numRemoteCharacteristics);
BLERemoteService *lastRemoteService = NULL;
unsigned char remoteServiceIndex = 0;
unsigned char remoteCharacteristicIndex = 0;
for (int i = 0; i < numRemoteAttributes; i++) {
BLERemoteAttribute *remoteAttribute = remoteAttributes[i];
BLEUuid uuid = BLEUuid(remoteAttribute->uuid());
const unsigned char* uuidData = uuid.data();
ble_uuid_t nordicUUID;
if (uuid.length() == 2) {
nordicUUID.uuid = (uuidData[1] << 8) | uuidData[0];
nordicUUID.type = BLE_UUID_TYPE_BLE;
} else {
unsigned char uuidDataTemp[16];
memcpy(&uuidDataTemp, uuidData, sizeof(uuidDataTemp));
nordicUUID.uuid = (uuidData[13] << 8) | uuidData[12];
uuidDataTemp[13] = 0;
uuidDataTemp[12] = 0;
sd_ble_uuid_vs_add((ble_uuid128_t*)&uuidDataTemp, &nordicUUID.type);
}
if (remoteAttribute->type() == BLETypeService) {
this->_remoteServiceInfo[remoteServiceIndex].service = lastRemoteService = (BLERemoteService *)remoteAttribute;
this->_remoteServiceInfo[remoteServiceIndex].uuid = nordicUUID;
memset(&this->_remoteServiceInfo[remoteServiceIndex].handlesRange, 0, sizeof(this->_remoteServiceInfo[remoteServiceIndex].handlesRange));
remoteServiceIndex++;
} else if (remoteAttribute->type() == BLETypeCharacteristic) {
this->_remoteCharacteristicInfo[remoteCharacteristicIndex].characteristic = (BLERemoteCharacteristic *)remoteAttribute;
this->_remoteCharacteristicInfo[remoteCharacteristicIndex].service = lastRemoteService;
this->_remoteCharacteristicInfo[remoteCharacteristicIndex].uuid = nordicUUID;
memset(&this->_remoteCharacteristicInfo[remoteCharacteristicIndex].properties, 0, sizeof(this->_remoteCharacteristicInfo[remoteCharacteristicIndex].properties));
this->_remoteCharacteristicInfo[remoteCharacteristicIndex].valueHandle = 0;
remoteCharacteristicIndex++;
}
}
if (this->_bondStore && this->_bondStore->hasData()) {
#ifdef NRF_51822_DEBUG
Serial.println(F("Restoring bond data"));
#endif
this->_bondStore->getData(this->_authStatusBuffer, 0, sizeof(this->_authStatusBuffer));
}
this->startAdvertising();
}
void nRF51822::poll() {
uint32_t evtBuf[BLE_STACK_EVT_MSG_BUF_SIZE] __attribute__ ((__aligned__(BLE_EVTS_PTR_ALIGNMENT)));
uint16_t evtLen = sizeof(evtBuf);
ble_evt_t* bleEvt = (ble_evt_t*)evtBuf;
if (sd_ble_evt_get((uint8_t*)evtBuf, &evtLen) == NRF_SUCCESS) {
switch (bleEvt->header.evt_id) {
case BLE_EVT_TX_COMPLETE:
#ifdef NRF_51822_DEBUG
Serial.print(F("Evt TX complete "));
Serial.println(bleEvt->evt.common_evt.params.tx_complete.count);
#endif
break;
case BLE_GAP_EVT_CONNECTED:
#ifdef NRF_51822_DEBUG
char address[18];
BLEUtil::addressToString(bleEvt->evt.gap_evt.params.connected.peer_addr.addr, address);
Serial.print(F("Evt Connected "));
Serial.println(address);
#endif
this->_connectionHandle = bleEvt->evt.gap_evt.conn_handle;
this->_storeAuthStatus = false;
if (this->_eventListener) {
this->_eventListener->BLEDeviceConnected(*this, bleEvt->evt.gap_evt.params.connected.peer_addr.addr);
}
sd_ble_gattc_primary_services_discover(this->_connectionHandle, 1, NULL);
break;
case BLE_GAP_EVT_DISCONNECTED:
#ifdef NRF_51822_DEBUG
Serial.println(F("Evt Disconnected"));
#endif
this->_connectionHandle = BLE_CONN_HANDLE_INVALID;
for (int i = 0; i < this->_numLocalCharacteristics; i++) {
struct localCharacteristicInfo* localCharacteristicInfo = &this->_localCharacteristicInfo[i];
localCharacteristicInfo->notifySubscribed = false;
localCharacteristicInfo->indicateSubscribed = false;
if (localCharacteristicInfo->characteristic->subscribed()) {
if (this->_eventListener) {
this->_eventListener->BLEDeviceCharacteristicSubscribedChanged(*this, *localCharacteristicInfo->characteristic, false);
}
}
}
if (this->_eventListener) {
this->_eventListener->BLEDeviceDisconnected(*this);
}
// clear remote handle info
for (int i = 0; i < this->_numRemoteServices; i++) {
memset(&this->_remoteServiceInfo[i].handlesRange, 0, sizeof(this->_remoteServiceInfo[i].handlesRange));
}
for (int i = 0; i < this->_numRemoteCharacteristics; i++) {
memset(&this->_remoteCharacteristicInfo[i].properties, 0, sizeof(this->_remoteCharacteristicInfo[i].properties));
this->_remoteCharacteristicInfo[i].valueHandle = 0;
}
this->_remoteRequestInProgress = false;
if (this->_bondStore && this->_storeAuthStatus) {
#ifdef NRF_51822_DEBUG
Serial.println(F("Storing bond data"));
#endif
this->_bondStore->putData(this->_authStatusBuffer, 0, sizeof(this->_authStatusBuffer));
this->_storeAuthStatus = false;
}
this->startAdvertising();
break;
case BLE_GAP_EVT_CONN_PARAM_UPDATE:
#ifdef NRF_51822_DEBUG
Serial.print(F("Evt Conn Param Update 0x"));
Serial.print(bleEvt->evt.gap_evt.params.conn_param_update.conn_params.min_conn_interval, HEX);
Serial.print(F(" 0x"));
Serial.print(bleEvt->evt.gap_evt.params.conn_param_update.conn_params.max_conn_interval, HEX);
Serial.print(F(" 0x"));
Serial.print(bleEvt->evt.gap_evt.params.conn_param_update.conn_params.slave_latency, HEX);
Serial.print(F(" 0x"));
Serial.print(bleEvt->evt.gap_evt.params.conn_param_update.conn_params.conn_sup_timeout, HEX);
Serial.println();
#endif
break;
case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
#ifdef NRF_51822_DEBUG
Serial.print(F("Evt Sec Params Request "));
Serial.print(bleEvt->evt.gap_evt.params.sec_params_request.peer_params.timeout);
Serial.print(F(" "));
Serial.print(bleEvt->evt.gap_evt.params.sec_params_request.peer_params.bond);
Serial.print(F(" "));
Serial.print(bleEvt->evt.gap_evt.params.sec_params_request.peer_params.mitm);
Serial.print(F(" "));
Serial.print(bleEvt->evt.gap_evt.params.sec_params_request.peer_params.io_caps);
Serial.print(F(" "));
Serial.print(bleEvt->evt.gap_evt.params.sec_params_request.peer_params.oob);
Serial.print(F(" "));
Serial.print(bleEvt->evt.gap_evt.params.sec_params_request.peer_params.min_key_size);
Serial.print(F(" "));
Serial.print(bleEvt->evt.gap_evt.params.sec_params_request.peer_params.max_key_size);
Serial.println();
#endif
if (this->_bondStore && !this->_bondStore->hasData()) {
// only allow bonding if bond store exists and there is no data
ble_gap_sec_params_t gapSecParams;
gapSecParams.timeout = 30; // must be 30s
gapSecParams.bond = true;
gapSecParams.mitm = false;
gapSecParams.io_caps = BLE_GAP_IO_CAPS_NONE;
gapSecParams.oob = false;
gapSecParams.min_key_size = 7;
gapSecParams.max_key_size = 16;
sd_ble_gap_sec_params_reply(this->_connectionHandle, BLE_GAP_SEC_STATUS_SUCCESS, &gapSecParams);
} else {
sd_ble_gap_sec_params_reply(this->_connectionHandle, BLE_GAP_SEC_STATUS_PAIRING_NOT_SUPP, NULL);
}
break;
case BLE_GAP_EVT_SEC_INFO_REQUEST:
#ifdef NRF_51822_DEBUG
Serial.print(F("Evt Sec Info Request "));
// Serial.print(bleEvt->evt.gap_evt.params.sec_info_request.peer_addr);
// Serial.print(F(" "));
Serial.print(bleEvt->evt.gap_evt.params.sec_info_request.div);
Serial.print(F(" "));
Serial.print(bleEvt->evt.gap_evt.params.sec_info_request.enc_info);
Serial.print(F(" "));
Serial.print(bleEvt->evt.gap_evt.params.sec_info_request.id_info);
Serial.print(F(" "));
Serial.print(bleEvt->evt.gap_evt.params.sec_info_request.sign_info);
Serial.println();
#endif
if (this->_authStatus->periph_keys.enc_info.div == bleEvt->evt.gap_evt.params.sec_info_request.div) {
sd_ble_gap_sec_info_reply(this->_connectionHandle, &this->_authStatus->periph_keys.enc_info, NULL);
} else {
sd_ble_gap_sec_info_reply(this->_connectionHandle, NULL, NULL);
}
break;
case BLE_GAP_EVT_AUTH_STATUS:
#ifdef NRF_51822_DEBUG
Serial.println(F("Evt Auth Status"));
#endif
this->_storeAuthStatus = true;
*this->_authStatus = bleEvt->evt.gap_evt.params.auth_status;
if (this->_eventListener) {
this->_eventListener->BLEDeviceBonded(*this);
}
break;
case BLE_GAP_EVT_CONN_SEC_UPDATE:
#ifdef NRF_51822_DEBUG
Serial.print(F("Evt Conn Sec Update "));
Serial.print(bleEvt->evt.gap_evt.params.conn_sec_update.conn_sec.sec_mode.sm);
Serial.print(F(" "));
Serial.print(bleEvt->evt.gap_evt.params.conn_sec_update.conn_sec.sec_mode.lv);
Serial.print(F(" "));
Serial.print(bleEvt->evt.gap_evt.params.conn_sec_update.conn_sec.encr_key_size);
Serial.println();
#endif
break;
case BLE_GATTS_EVT_WRITE: {
#ifdef NRF_51822_DEBUG
Serial.print(F("Evt Write, handle = "));
Serial.println(bleEvt->evt.gatts_evt.params.write.handle, DEC);
BLEUtil::printBuffer(bleEvt->evt.gatts_evt.params.write.data, bleEvt->evt.gatts_evt.params.write.len);
#endif
uint16_t handle = bleEvt->evt.gatts_evt.params.write.handle;
for (int i = 0; i < this->_numLocalCharacteristics; i++) {
struct localCharacteristicInfo* localCharacteristicInfo = &this->_localCharacteristicInfo[i];
if (localCharacteristicInfo->handles.value_handle == handle) {
if (this->_eventListener) {
this->_eventListener->BLEDeviceCharacteristicValueChanged(*this, *localCharacteristicInfo->characteristic, bleEvt->evt.gatts_evt.params.write.data, bleEvt->evt.gatts_evt.params.write.len);
}
break;
} else if (localCharacteristicInfo->handles.cccd_handle == handle) {
uint16_t value = bleEvt->evt.gatts_evt.params.write.data[0] | (bleEvt->evt.gatts_evt.params.write.data[1] << 8);
localCharacteristicInfo->notifySubscribed = (value & 0x0001);
localCharacteristicInfo->indicateSubscribed = (value & 0x0002);
bool subscribed = (localCharacteristicInfo->notifySubscribed || localCharacteristicInfo->indicateSubscribed);
if (subscribed != localCharacteristicInfo->characteristic->subscribed()) {
if (this->_eventListener) {
this->_eventListener->BLEDeviceCharacteristicSubscribedChanged(*this, *localCharacteristicInfo->characteristic, subscribed);
}
}
}
}
break;
}
case BLE_GATTS_EVT_SYS_ATTR_MISSING:
#ifdef NRF_51822_DEBUG
Serial.print(F("Evt Sys Attr Missing "));
Serial.println(bleEvt->evt.gatts_evt.params.sys_attr_missing.hint);
#endif
sd_ble_gatts_sys_attr_set(this->_connectionHandle, NULL, 0);
break;
case BLE_GATTC_EVT_PRIM_SRVC_DISC_RSP:
#ifdef NRF_51822_DEBUG
Serial.print(F("Evt Prim Srvc Disc Rsp 0x"));
Serial.println(bleEvt->evt.gattc_evt.gatt_status, HEX);
#endif
if (bleEvt->evt.gattc_evt.gatt_status == BLE_GATT_STATUS_SUCCESS) {
uint16_t count = bleEvt->evt.gattc_evt.params.prim_srvc_disc_rsp.count;
for (int i = 0; i < count; i++) {
for (int j = 0; j < this->_numRemoteServices; j++) {
if ((bleEvt->evt.gattc_evt.params.prim_srvc_disc_rsp.services[i].uuid.type == this->_remoteServiceInfo[j].uuid.type) &&
(bleEvt->evt.gattc_evt.params.prim_srvc_disc_rsp.services[i].uuid.uuid == this->_remoteServiceInfo[j].uuid.uuid)) {
this->_remoteServiceInfo[j].handlesRange = bleEvt->evt.gattc_evt.params.prim_srvc_disc_rsp.services[i].handle_range;
break;
}
}
}
uint16_t startHandle = bleEvt->evt.gattc_evt.params.prim_srvc_disc_rsp.services[count - 1].handle_range.end_handle + 1;
sd_ble_gattc_primary_services_discover(this->_connectionHandle, startHandle, NULL);
} else {
// done discovering services
for (int i = 0; i < this->_numRemoteServices; i++) {
if (this->_remoteServiceInfo[i].handlesRange.start_handle != 0 && this->_remoteServiceInfo[i].handlesRange.end_handle != 0) {
this->_remoteServiceDiscoveryIndex = i;
sd_ble_gattc_characteristics_discover(this->_connectionHandle, &this->_remoteServiceInfo[i].handlesRange);
break;
}
}
}
break;
case BLE_GATTC_EVT_CHAR_DISC_RSP:
#ifdef NRF_51822_DEBUG
Serial.print(F("Evt Char Disc Rsp 0x"));
Serial.println(bleEvt->evt.gattc_evt.gatt_status, HEX);
#endif
if (bleEvt->evt.gattc_evt.gatt_status == BLE_GATT_STATUS_SUCCESS) {
ble_gattc_handle_range_t serviceHandlesRange = this->_remoteServiceInfo[this->_remoteServiceDiscoveryIndex].handlesRange;
uint16_t count = bleEvt->evt.gattc_evt.params.char_disc_rsp.count;
for (int i = 0; i < count; i++) {
for (int j = 0; j < this->_numRemoteCharacteristics; j++) {
if ((this->_remoteServiceInfo[this->_remoteServiceDiscoveryIndex].service == this->_remoteCharacteristicInfo[j].service) &&
(bleEvt->evt.gattc_evt.params.char_disc_rsp.chars[i].uuid.type == this->_remoteCharacteristicInfo[j].uuid.type) &&
(bleEvt->evt.gattc_evt.params.char_disc_rsp.chars[i].uuid.uuid == this->_remoteCharacteristicInfo[j].uuid.uuid)) {
this->_remoteCharacteristicInfo[j].properties = bleEvt->evt.gattc_evt.params.char_disc_rsp.chars[i].char_props;
this->_remoteCharacteristicInfo[j].valueHandle = bleEvt->evt.gattc_evt.params.char_disc_rsp.chars[i].handle_value;
}
}
serviceHandlesRange.start_handle = bleEvt->evt.gattc_evt.params.char_disc_rsp.chars[i].handle_value;
}
sd_ble_gattc_characteristics_discover(this->_connectionHandle, &serviceHandlesRange);
} else {
bool discoverCharacteristics = false;
for (int i = this->_remoteServiceDiscoveryIndex + 1; i < this->_numRemoteServices; i++) {
if (this->_remoteServiceInfo[i].handlesRange.start_handle != 0 && this->_remoteServiceInfo[i].handlesRange.end_handle != 0) {
this->_remoteServiceDiscoveryIndex = i;
sd_ble_gattc_characteristics_discover(this->_connectionHandle, &this->_remoteServiceInfo[i].handlesRange);
discoverCharacteristics = true;
break;
}
}
if (!discoverCharacteristics) {
if (this->_eventListener) {
this->_eventListener->BLEDeviceRemoteServicesDiscovered(*this);
}
}
}
break;
case BLE_GATTC_EVT_READ_RSP: {
#ifdef NRF_51822_DEBUG
Serial.print(F("Evt Read Rsp 0x"));
Serial.println(bleEvt->evt.gattc_evt.gatt_status, HEX);
Serial.println(bleEvt->evt.gattc_evt.params.read_rsp.handle, DEC);
BLEUtil::printBuffer(bleEvt->evt.gattc_evt.params.read_rsp.data, bleEvt->evt.gattc_evt.params.read_rsp.len);
#endif
this->_remoteRequestInProgress = false;
if (bleEvt->evt.gattc_evt.gatt_status == BLE_GATT_STATUS_ATTERR_INSUF_AUTHENTICATION &&
this->_bondStore) {
ble_gap_sec_params_t gapSecParams;
gapSecParams.timeout = 30; // must be 30s
gapSecParams.bond = true;
gapSecParams.mitm = false;
gapSecParams.io_caps = BLE_GAP_IO_CAPS_NONE;
gapSecParams.oob = false;
gapSecParams.min_key_size = 7;
gapSecParams.max_key_size = 16;
sd_ble_gap_authenticate(this->_connectionHandle, &gapSecParams);
} else {
uint16_t handle = bleEvt->evt.gattc_evt.params.read_rsp.handle;
for (int i = 0; i < this->_numRemoteCharacteristics; i++) {
if (this->_remoteCharacteristicInfo[i].valueHandle == handle) {
if (this->_eventListener) {
this->_eventListener->BLEDeviceRemoteCharacteristicValueChanged(*this, *this->_remoteCharacteristicInfo[i].characteristic, bleEvt->evt.gattc_evt.params.read_rsp.data, bleEvt->evt.gattc_evt.params.read_rsp. len);
}
break;
}
}
}
break;
}
case BLE_GATTC_EVT_WRITE_RSP:
#ifdef NRF_51822_DEBUG
Serial.print(F("Evt Write Rsp 0x"));
Serial.println(bleEvt->evt.gattc_evt.gatt_status, HEX);
Serial.println(bleEvt->evt.gattc_evt.params.write_rsp.handle, DEC);
#endif
this->_remoteRequestInProgress = false;
if (bleEvt->evt.gattc_evt.gatt_status == BLE_GATT_STATUS_ATTERR_INSUF_AUTHENTICATION &&
this->_bondStore) {
ble_gap_sec_params_t gapSecParams;
gapSecParams.timeout = 30; // must be 30s
gapSecParams.bond = true;
gapSecParams.mitm = false;
gapSecParams.io_caps = BLE_GAP_IO_CAPS_NONE;
gapSecParams.oob = false;
gapSecParams.min_key_size = 7;
gapSecParams.max_key_size = 16;
sd_ble_gap_authenticate(this->_connectionHandle, &gapSecParams);
}
break;
case BLE_GATTC_EVT_HVX: {
#ifdef NRF_51822_DEBUG
Serial.print(F("Evt Hvx 0x"));
Serial.println(bleEvt->evt.gattc_evt.gatt_status, HEX);
Serial.println(bleEvt->evt.gattc_evt.params.hvx.handle, DEC);
#endif
uint16_t handle = bleEvt->evt.gattc_evt.params.hvx.handle;
if (bleEvt->evt.gattc_evt.params.hvx.type == BLE_GATT_HVX_INDICATION) {
sd_ble_gattc_hv_confirm(this->_connectionHandle, handle);
}
for (int i = 0; i < this->_numRemoteCharacteristics; i++) {
if (this->_remoteCharacteristicInfo[i].valueHandle == handle) {
if (this->_eventListener) {
this->_eventListener->BLEDeviceRemoteCharacteristicValueChanged(*this, *this->_remoteCharacteristicInfo[i].characteristic, bleEvt->evt.gattc_evt.params.read_rsp.data, bleEvt->evt.gattc_evt.params.read_rsp. len);
}
break;
}
}
break;
}
default:
#ifdef NRF_51822_DEBUG
Serial.print(F("bleEvt->header.evt_id = 0x"));
Serial.print(bleEvt->header.evt_id, HEX);
Serial.print(F(" "));
Serial.println(bleEvt->header.evt_len);
#endif
break;
}
}
// sd_app_evt_wait();
}
bool nRF51822::updateCharacteristicValue(BLECharacteristic& characteristic) {
for (int i = 0; i < this->_numLocalCharacteristics; i++) {
struct localCharacteristicInfo* localCharacteristicInfo = &this->_localCharacteristicInfo[i];
if (localCharacteristicInfo->characteristic == &characteristic) {
if (&characteristic == this->_broadcastCharacteristic) {
this->broadcastCharacteristic(characteristic);
}
uint16_t valueLength = characteristic.valueLength();
sd_ble_gatts_value_set(localCharacteristicInfo->handles.value_handle, 0, &valueLength, characteristic.value());
ble_gatts_hvx_params_t hvxParams;
memset(&hvxParams, 0, sizeof(hvxParams));
hvxParams.handle = localCharacteristicInfo->handles.value_handle;
hvxParams.offset = 0;
hvxParams.p_data = NULL;
hvxParams.p_len = &valueLength;
if (localCharacteristicInfo->notifySubscribed) {
hvxParams.type = BLE_GATT_HVX_NOTIFICATION;
sd_ble_gatts_hvx(this->_connectionHandle, &hvxParams);
}
if (localCharacteristicInfo->indicateSubscribed) {
hvxParams.type = BLE_GATT_HVX_INDICATION;
sd_ble_gatts_hvx(this->_connectionHandle, &hvxParams);
}
}
}
return true;
}
bool nRF51822::broadcastCharacteristic(BLECharacteristic& characteristic) {
bool success = false;
for (int i = 0; i < this->_numLocalCharacteristics; i++) {
struct localCharacteristicInfo* localCharacteristicInfo = &this->_localCharacteristicInfo[i];
if (localCharacteristicInfo->characteristic == &characteristic) {
if (characteristic.properties() & BLEBroadcast && localCharacteristicInfo->service) {
unsigned char advData[31];
unsigned char advDataLen = this->_advDataLen;
// copy the existing advertisement data
memcpy(advData, this->_advData, advDataLen);
advDataLen += (4 + characteristic.valueLength());
if (advDataLen <= 31) {
BLEUuid uuid = BLEUuid(localCharacteristicInfo->service->uuid());
advData[this->_advDataLen + 0] = 3 + characteristic.valueLength();
advData[this->_advDataLen + 1] = 0x16;
memcpy(&advData[this->_advDataLen + 2], uuid.data(), 2);
memcpy(&advData[this->_advDataLen + 4], characteristic.value(), characteristic.valueLength());
sd_ble_gap_adv_data_set(advData, advDataLen, NULL, 0); // update advertisement data
success = true;
this->_broadcastCharacteristic = &characteristic;
}
}
}
break;
}
return success;
}
bool nRF51822::canNotifyCharacteristic(BLECharacteristic& characteristic) {
uint8_t count = 0;
sd_ble_tx_buffer_count_get(&count);
return (count > 0);
}
bool nRF51822::canIndicateCharacteristic(BLECharacteristic& characteristic) {
uint8_t count = 0;
sd_ble_tx_buffer_count_get(&count);
return (count > 0);
}
bool nRF51822::canReadRemoteCharacteristic(BLERemoteCharacteristic& characteristic) {
bool success = false;
for (int i = 0; i < this->_numRemoteCharacteristics; i++) {
if (this->_remoteCharacteristicInfo[i].characteristic == &characteristic) {
success = (this->_remoteCharacteristicInfo[i].valueHandle &&
this->_remoteCharacteristicInfo[i].properties.read &&
!this->_remoteRequestInProgress);
break;
}
}
return success;
}
bool nRF51822::readRemoteCharacteristic(BLERemoteCharacteristic& characteristic) {
bool success = false;
for (int i = 0; i < this->_numRemoteCharacteristics; i++) {
if (this->_remoteCharacteristicInfo[i].characteristic == &characteristic) {
if (this->_remoteCharacteristicInfo[i].valueHandle && this->_remoteCharacteristicInfo[i].properties.read) {
this->_remoteRequestInProgress = true;
success = (sd_ble_gattc_read(this->_connectionHandle, this->_remoteCharacteristicInfo[i].valueHandle, 0) == NRF_SUCCESS);
}
break;
}
}
return success;
}
bool nRF51822::canWriteRemoteCharacteristic(BLERemoteCharacteristic& characteristic) {
bool success = false;
for (int i = 0; i < this->_numRemoteCharacteristics; i++) {
if (this->_remoteCharacteristicInfo[i].characteristic == &characteristic) {
if (this->_remoteCharacteristicInfo[i].valueHandle) {
if (this->_remoteCharacteristicInfo[i].properties.write) {
success = !this->_remoteRequestInProgress;
} else if (this->_remoteCharacteristicInfo[i].properties.write_wo_resp) {
uint8_t count = 0;
sd_ble_tx_buffer_count_get(&count);
success = (count > 0);
}
}
break;
}
}
return success;
}
bool nRF51822::writeRemoteCharacteristic(BLERemoteCharacteristic& characteristic, const unsigned char value[], unsigned char length) {
bool success = false;
for (int i = 0; i < this->_numRemoteCharacteristics; i++) {
if (this->_remoteCharacteristicInfo[i].characteristic == &characteristic) {
if (this->_remoteCharacteristicInfo[i].valueHandle &&
(this->_remoteCharacteristicInfo[i].properties.write_wo_resp || this->_remoteCharacteristicInfo[i].properties.write)) {
ble_gattc_write_params_t writeParams;
writeParams.write_op = (this->_remoteCharacteristicInfo[i].properties.write) ? BLE_GATT_OP_WRITE_REQ : BLE_GATT_OP_WRITE_CMD;
#ifndef __RFduino__
writeParams.flags = 0;
#endif
writeParams.handle = this->_remoteCharacteristicInfo[i].valueHandle;
writeParams.offset = 0;
writeParams.len = length;
writeParams.p_value = (uint8_t*)value;
this->_remoteRequestInProgress = true;
success = (sd_ble_gattc_write(this->_connectionHandle, &writeParams) == NRF_SUCCESS);
}
break;
}
}
return success;
}
bool nRF51822::canSubscribeRemoteCharacteristic(BLERemoteCharacteristic& characteristic) {
bool success = false;
for (int i = 0; i < this->_numRemoteCharacteristics; i++) {
if (this->_remoteCharacteristicInfo[i].characteristic == &characteristic) {