-
Notifications
You must be signed in to change notification settings - Fork 106
/
ble_comm.c
3203 lines (2814 loc) · 103 KB
/
ble_comm.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
/****************************************************************************
* modules/bluetooth/hal/nrf52/ble_comm.c
*
* Copyright 2022 Sony Semiconductor Solutions Corporation
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name of Sony Semiconductor Solutions Corporation nor
* the names of its contributors may be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#include <string.h>
#include <unistd.h>
#include <crc16.h>
#include <ble/ble_comm.h>
#include <ble/ble_gap.h>
#include <ble/ble_gatts.h>
#include <ble/ble_gattc.h>
#include "ble_storage_operations.h"
#include "ble_comm_internal.h"
#include "nrf_sdh.h"
#include "nrf_sdh_ble.h"
#include <arch/board/board.h>
#include <system/readline.h>
/******************************************************************************
* externs
*****************************************************************************/
extern bleGapMem *bleGetGapMem(void);
extern void bleMngEvtDispatch(ble_evt_t *nrfEvt);
extern void board_nrf52_initialize(void);
extern void board_nrf52_reset(bool en);
/****************************************************************************
* Pre-processor Definitions
****************************************************************************/
// #define BLE_DBGPRT_ENABLE
#ifdef BLE_DBGPRT_ENABLE
#include <stdio.h>
#define BLE_PRT printf
#define BLE_PRT2(...)
#define BLE_ERR printf
#else
#define BLE_PRT(...)
#define BLE_PRT2(...)
#define BLE_ERR(...)
#endif
#define NRF52_SYS_ATTR_DATA_OFFSET_HANDLE (0)
#define NRF52_SYS_ATTR_DATA_OFFSET_LEN (2)
#define NRF52_SYS_ATTR_DATA_OFFSET_VALUE (4)
#define NRF52_SYS_ATTR_DATA_LEN_HANDLE (2)
#define NRF52_SYS_ATTR_DATA_LEN_LEN (2)
#define NRF52_SYS_ATTR_DATA_LEN_VALUE (2)
/******************************************************************************
* Structure define
*****************************************************************************/
/******************************************************************************
* Function prototype declaration
*****************************************************************************/
static int blePowerOn(void);
static int bleStackInit(void);
static int bleStackFin(void);
#ifdef BLE_USE_SECTION
static void bleEvtDispatch(ble_evt_t *pBleNrfEvt);
#endif
#if NRF_SD_BLE_API_VERSION > 5
static void onAdvSetTerminate(BLE_Evt *pBleEvent, ble_evt_t *pBleNrfEvt);
#endif
static void onScanReqReport(BLE_Evt *pBleEvent, ble_evt_t *pBleNrfEvt);
static void onPhyUpdateReq(BLE_Evt *pBleEvent, ble_evt_t *pBleNrfEvt);
static void onPhyUpdate(BLE_Evt *pBleEvent, ble_evt_t *pBleNrfEvt);
static void onDataLengthUpdateRequest(BLE_Evt *pBleEvent, ble_evt_t *pBleNrfEvt);
static void onDataLengthUpdate(BLE_Evt *pBleEvent, ble_evt_t *pBleNrfEvt);
static void onExchangeMtuRequest(BLE_Evt *pBleEvent, ble_evt_t *pBleNrfEvt);
static void onExchangeMtuResponse(BLE_Evt *pBleEvent, ble_evt_t *pBleNrfEvt);
static void onTxComplete(BLE_Evt *pBleEvent, ble_evt_t *pBleNrfEvt);
static void onConnect(BLE_Evt *pBleEvent, ble_evt_t *pBleNrfEvt);
static void onConnParamUpdate(BLE_Evt *pBleEvent, ble_evt_t *pBleNrfEvt);
static void onConnParamUpdateRequest(BLE_Evt *pBleEvent, ble_evt_t *pBleNrfEvt);
static void onDisconnect(BLE_Evt *pBleEvent, ble_evt_t *pBleNrfEvt);
static void onSecParamsRequest(BLE_Evt *pBleEvent, ble_evt_t *pBleNrfEvt);
static void onAuthStatus(BLE_Evt *pBleEvent, ble_evt_t *pBleNrfEvt);
static void onDispPasskey(BLE_Evt *pBleEvent, ble_evt_t *pBleNrfEvt);
static void onAdvReport(BLE_Evt *pBleEvent, ble_evt_t *pBleNrfEvt);
static void onAuthKeyRequest(BLE_Evt *pBleEvent, ble_evt_t *pBleNrfEvt);
static void onConnSecUpdate(BLE_Evt *pBleEvent, ble_evt_t *pBleNrfEvt);
static void onSecInfoRequest(BLE_Evt *pBleEvent, ble_evt_t *pBleNrfEvt);
static void onTimeout(BLE_Evt *pBleEvent, ble_evt_t *pBleNrfEvt);
static void onGattsTimeout(BLE_Evt *pBleEvent, ble_evt_t *pBleNrfEvt);
static void onRssiChanged(BLE_Evt *pBleEvent, ble_evt_t *pBleNrfEvt);
static void onGattsWrite(BLE_Evt *pBleEvent, ble_evt_t *pBleNrfEvt);
static void onGattsIndConfirm(BLE_Evt *pBleEvent, ble_evt_t *pBleNrfEvt);
static void onPrimarySrvDiscoveryRsp(bleGattcDb *gattcDbDiscovery, BLE_Evt *pBleEvent, ble_evt_t *pBleNrfEvt);
static void onCharacteristicDiscoveryRsp(bleGattcDb *const gattcDbDiscovery, BLE_Evt *pBleEvent, ble_evt_t *pBleNrfEvt);
static void onDescriptorDiscoveryRsp(bleGattcDb *const gattcDbDiscovery, BLE_Evt *pBleEvent, ble_evt_t *pBleNrfEvt);
static void onHvx(BLE_Evt *pBleEvent, ble_evt_t *pBleNrfEvt);
static void onSysAttrMissing(BLE_Evt *pBleEvent, ble_evt_t *pBleNrfEvt);
static void onReadRsp(BLE_Evt *pBleEvent, ble_evt_t *pBleNrfEvt);
static void onWriteRsp(BLE_Evt *pBleEvent, ble_evt_t *pBleNrfEvt);
static void onSrvDiscCompletion(BLE_Evt *pBleEvent, bleGattcDb *gattcDbDiscovery);
static int characteristicsDiscover(BLE_Evt *pBleEvent, bleGattcDb *const gattcDbDiscovery);
static bool isCharDiscoveryReqd(bleGattcDb *const gattcDbDiscovery, BLE_GattcChar *afterChar);
static bool isDescDiscoveryReqd(bleGattcDb *gattcDbDiscovery, BLE_GattcDbDiscChar *currChar, BLE_GattcDbDiscChar *nextChar, BLE_GattcHandleRange *handleRange);
static int descriptorsDiscover(BLE_Evt *pBleEvent, bleGattcDb *const gattcDbDiscovery, bool *raiseDiscovComplete);
static int nrf52_ble_start_scan(bool duplicate_filter);
static int nrf52_ble_stop_scan(void);
static int nrf52_ble_connect(const BT_ADDR *addr);
static int nrf52_ble_disconnect(const uint16_t conn_handle);
static int nrf52_ble_advertise(bool enable);
static int nrf52_ble_set_dev_addr(BT_ADDR *addr);
static int nrf52_ble_set_dev_name(char *name);
static int nrf52_ble_set_appearance(BLE_APPEARANCE appearance);
static int nrf52_ble_set_ppcp(BLE_CONN_PARAMS ppcp);
static uint16_t nrf52_ble_set_mtusize(uint16_t sz);
static uint16_t nrf52_ble_get_mtusize(void);
static int nrf52_ble_get_negotiated_mtusize(uint16_t handle);
static int nrf52_ble_pairing(uint16_t handle);
static int nrf52_bt_init(void);
static int nrf52_bt_finalize(void);
static int nrf52_bt_enable(bool enable);
/******************************************************************************
* Private Data
*****************************************************************************/
bleCommMem commMem = {0};
bleGapWrapperBondInfo BondInfoInFlash[BLE_SAVE_BOND_DEVICE_MAX_NUM] = {{0}};
uint32_t bleBondEnableList = 0;
bleBondInfoKey bleKey = {0};
struct bt_common_context_s bt_common_context = {0};
#define BUF_LEN_MAX 32
#ifndef CONFIG_NRF51822
#define READ_BUFF_LEN 512
#else
#define READ_BUFF_LEN 20
#endif
#define WAIT_TIME (100*1000)
#define LOG_OUT printf
#define AUTH_KEY_SIZE 6
static struct ble_hal_common_ops_s ble_hal_common_ops =
{
.setDevAddr = nrf52_ble_set_dev_addr,
.setDevName = nrf52_ble_set_dev_name,
.setAppearance = nrf52_ble_set_appearance,
.setPPCP = nrf52_ble_set_ppcp,
.advertise = nrf52_ble_advertise,
.startScan = nrf52_ble_start_scan,
.stopScan = nrf52_ble_stop_scan,
.connect = nrf52_ble_connect,
.disconnect = nrf52_ble_disconnect,
.setMtuSize = nrf52_ble_set_mtusize,
.getMtuSize = nrf52_ble_get_mtusize,
.getNegotiatedMtuSize = nrf52_ble_get_negotiated_mtusize,
.pairing = nrf52_ble_pairing,
};
static struct bt_hal_common_ops_s bt_hal_common_ops =
{
.init = nrf52_bt_init,
.finalize = nrf52_bt_finalize,
.enable = nrf52_bt_enable,
.setDevAddr = NULL,
.getDevAddr = NULL,
.setDevName = NULL,
.getDevName = NULL,
.paringEnable = NULL,
.getBondList = NULL,
.unBond = NULL,
.setVisibility = NULL,
.inquiryStart = NULL,
.inquiryCancel = NULL
};
/****************************************************************************
* Private Functions
****************************************************************************/
static int blePowerOff(void)
{
int ret = 0;
// for support reset pin. (Will be valid later)
// board_nrf52_reset(true);
ret = board_power_control(POWER_BTBLE, false);
if (ret)
{
BLE_PRT("board_power_control(off): NG %d\n", ret);
return ret;
}
BLE_PRT("Power off BLE!!\n");
return BLE_SUCCESS;
}
static void bleInitBondInfoKey(void)
{
bleKey.enable_key = BSO_GenerateRegistryKey(BOND_ENABLE_KEY_NAME, 0);
bleKey.info_key[0] = BSO_GenerateRegistryKey(BOND_INFO_1_KEY_NAME, 0);
bleKey.info_key[1] = BSO_GenerateRegistryKey(BOND_INFO_2_KEY_NAME, 0);
bleKey.info_key[2] = BSO_GenerateRegistryKey(BOND_INFO_3_KEY_NAME, 0);
bleKey.info_key[3] = BSO_GenerateRegistryKey(BOND_INFO_4_KEY_NAME, 0);
bleKey.info_key[4] = BSO_GenerateRegistryKey(BOND_INFO_5_KEY_NAME, 0);
bleKey.info_key[5] = BSO_GenerateRegistryKey(BOND_INFO_6_KEY_NAME, 0);
bleKey.info_key[6] = BSO_GenerateRegistryKey(BOND_INFO_7_KEY_NAME, 0);
bleKey.info_key[7] = BSO_GenerateRegistryKey(BOND_INFO_8_KEY_NAME, 0);
#ifdef BLE_DBGPRT_ENABLE
BLE_PRT("bleInitBondInfoKey: enable_key 0x%lx\n", bleKey.enable_key);
for (int i=0; i<BLE_SAVE_BOND_DEVICE_MAX_NUM; i++) {
BLE_PRT("bleInitBondInfoKey: info_key[%d] 0x%lx\n", i, bleKey.info_key[i]);
}
#endif
}
static void set_EncKey_for_save_event(struct ble_idkey_s *apps,
ble_gap_enc_key_t *nrf52)
{
memcpy(apps->ltk, nrf52->enc_info.ltk, BLE_LTK_LEN);
apps->ediv = nrf52->master_id.ediv;
memcpy(apps->rand, nrf52->master_id.rand, BLE_RAND_LEN);
}
static void set_bondinfo_for_save_event(struct ble_bondinfo_s *apps,
bleGapWrapperBondInfo *nrf52)
{
static struct ble_cccd_s cccd;
apps->peer_addr.type = nrf52->bondInfo.addrType;
memcpy(apps->peer_addr.addr,
nrf52->bondInfo.addr,
BLE_GAP_ADDR_LENGTH);
memcpy(nrf52->ownIdKey.id_info.irk, apps->own.irk, BLE_GAP_SEC_KEY_LEN);
memcpy(nrf52->peerIdKey.id_info.irk, apps->peer.irk, BLE_GAP_SEC_KEY_LEN);
set_EncKey_for_save_event(&apps->own, &nrf52->ownEncKey);
set_EncKey_for_save_event(&apps->peer, &nrf52->peerEncKey);
apps->cccd_num = 1;
apps->cccd = &cccd;
memcpy(&cccd.handle,
&nrf52->sys_attr_data[NRF52_SYS_ATTR_DATA_OFFSET_HANDLE],
NRF52_SYS_ATTR_DATA_LEN_HANDLE);
memcpy(&cccd.value,
&nrf52->sys_attr_data[NRF52_SYS_ATTR_DATA_OFFSET_VALUE],
NRF52_SYS_ATTR_DATA_LEN_VALUE);
}
static void mk_save_bondinfo_event(void)
{
int i;
static struct ble_bondinfo_s bond[BLE_SAVE_BOND_DEVICE_MAX_NUM];
struct ble_event_bondinfo_t evt;
evt.group_id = BLE_GROUP_COMMON;
evt.event_id = BLE_COMMON_EVENT_SAVE_BOND;
evt.num = 0;
for (i = 0; i < BLE_SAVE_BOND_DEVICE_MAX_NUM; i++)
{
if (((bleBondEnableList >> i) & 1) == 1)
{
set_bondinfo_for_save_event(&bond[evt.num],
&BondInfoInFlash[i]);
evt.num++;
}
}
evt.bond = bond;
ble_common_event_handler((struct bt_event_t *) &evt);
}
static int mk_load_bondinfo_event(struct ble_bondinfo_s *bond)
{
struct ble_event_bondinfo_t evt;
evt.group_id = BLE_GROUP_COMMON;
evt.event_id = BLE_COMMON_EVENT_LOAD_BOND;
evt.num = BLE_SAVE_BOND_DEVICE_MAX_NUM;
evt.bond = bond;
return ble_common_event_handler((struct bt_event_t *) &evt);
}
static void save_EncKey(ble_gap_enc_key_t *nrf52,
struct ble_idkey_s *apps)
{
memcpy(nrf52->enc_info.ltk, apps->ltk, BLE_GAP_SEC_KEY_LEN);
nrf52->enc_info.ltk_len = BLE_GAP_SEC_KEY_LEN;
nrf52->master_id.ediv = apps->ediv;
memcpy(nrf52->master_id.rand, apps->rand, BLE_GAP_SEC_RAND_LEN);
}
static void save_cccd(int num,
struct ble_cccd_s *cccd,
uint8_t *sys_attr_data)
{
int i;
uint16_t *p = (uint16_t *)sys_attr_data;
for (i = 0; i < num; i++)
{
*p++ = cccd[i].handle;
*p++ = sizeof(cccd[i].value);
*p++ = cccd[i].value;
}
/* Append CRC16 value for created sys_attr_data. */
*p = crc16part(sys_attr_data, (uint8_t *)p - sys_attr_data, 0xFFFF);
}
static void save_apps_bondinfo(int num,
struct ble_bondinfo_s *apps_bond,
uint32_t *enable_list,
bleGapWrapperBondInfo *bond)
{
int i;
struct ble_bondinfo_s *apps = &apps_bond[0];
bleGapWrapperBondInfo *nrf52 = &bond[0];
*enable_list = 0;
for (i = 0, apps = &apps_bond[0], nrf52 = &bond[0];
i < num;
i++, apps++, nrf52++)
{
*enable_list |= (1 << i);
nrf52->bondInfo.addrType = apps->peer_addr.type;
memcpy(nrf52->bondInfo.addr,
apps->peer_addr.addr,
BLE_GAP_ADDR_LENGTH);
memcpy(nrf52->ownIdKey.id_info.irk, apps->own.irk, BLE_GAP_SEC_KEY_LEN);
memcpy(nrf52->peerIdKey.id_info.irk, apps->peer.irk, BLE_GAP_SEC_KEY_LEN);
nrf52->peerIdKey.id_addr_info.addr_id_peer = 1;
nrf52->peerIdKey.id_addr_info.addr_type = apps->peer_addr.type;
memcpy(nrf52->peerIdKey.id_addr_info.addr,
apps->peer_addr.addr,
BLE_GAP_ADDR_LENGTH);
save_EncKey(&nrf52->ownEncKey, &apps->own);
save_EncKey(&nrf52->peerEncKey, &apps->peer);
save_cccd(apps->cccd_num, apps->cccd, nrf52->sys_attr_data);
}
}
static void load_apps_bondinfo(uint32_t *enable_list,
bleGapWrapperBondInfo *bond)
{
int num;
static struct ble_bondinfo_s apps_bond[BLE_SAVE_BOND_DEVICE_MAX_NUM];
num = mk_load_bondinfo_event(apps_bond);
save_apps_bondinfo(num, apps_bond, enable_list, bond);
}
static int bleGetBondInfo(void)
{
bleInitBondInfoKey();
load_apps_bondinfo(&bleBondEnableList, BondInfoInFlash);
return 0;
}
int BLE_CommonInitializeStack(BLE_InitializeParams *initializeParams)
{
uint8_t role = 0;
int ret = BLE_SUCCESS;
if (initializeParams == NULL)
{
return -EINVAL;
}
if (commMem.stackInited)
{
return -EPERM;
}
// for pin configuration. (Will be valid later)
// board_nrf52_initialize();
commMem.gapMem = bleGetGapMem();
role = initializeParams->role;
ret = BSO_Init(NULL);
if (ret)
{
BLE_PRT("BSO_Init failed\n");
return ret;
}
ret = bleGetBondInfo();
if (ret)
{
BLE_PRT("bleGetBondInfo: NG %d\n", ret);
return ret;
}
switch (role)
{
case BLE_ROLE_PERIPHERAL:
case BLE_ROLE_CENTRAL:
case BLE_ROLE_PERIPHERAL_AND_CENTRAL:
ret = blePowerOn();
if (ret)
{
goto errPower;
}
ret = bleStackInit();
if (ret)
{
BLE_PRT("bleStackInit: NG %d\n", ret);
goto errInit;
}
else
{
commMem.stackInited = true;
}
commMem.requested_mtu = NRF_SDH_BLE_GATT_MAX_MTU_SIZE;
commMem.client_rx_mtu = BLE_GATT_ATT_MTU_DEFAULT;
break;
default:
ret = -EINVAL;
break;
}
return ret;
errInit:
bleStackFin();
blePowerOff();
errPower:
return ret;
}
int BLE_CommonSetBleEvtCallback(BLE_EfCb funcCb, BLE_EvtCtx *ctx)
{
if (ctx == NULL)
{
return -EINVAL;
}
if (commMem.managerCbFlag)
{
return -EPERM;
}
commMem.cbId = funcCb;
commMem.bleEvtCtx = ctx;
commMem.callbackFlag = 1;
BLE_PRT("%s:commMem.callbackFlag=%d\n", __func__, commMem.callbackFlag);
return BLE_SUCCESS;
}
int BLE_CommonFinalizeStack(void)
{
int ret = BLE_SUCCESS;
if (!commMem.stackInited)
{
return ret;
}
commMem.callbackFlag = 0;
commMem.gapMem = NULL;
if (bleStackFin())
{
ret = -EPERM;
}
if (blePowerOff())
{
ret = -EPERM;
}
commMem.stackInited = false;
return ret;
}
static
int blePowerOn(void)
{
int ret = 0;
ret = board_power_control(POWER_BTBLE, true);
if (ret)
{
BLE_PRT("board_power_control(on): NG %d\n", ret);
goto errPower;
}
// for support reset pin. (Will be valid later)
// board_nrf52_reset(false);
BLE_PRT("Power on BLE!!\n");
return BLE_SUCCESS;
errPower:
(void)board_power_control(POWER_BTBLE, false);
return ret;
}
int bleConvertErrorCode(uint32_t errCode)
{
int ret = 0;
switch (errCode)
{
case NRF_SUCCESS:
ret = BLE_SUCCESS;
break;
case NRF_ERROR_INVALID_PARAM:
BLE_ERR("errno: 0x%lx, Invalid parameter.\n", errCode);
ret = -EINVAL;
break;
case NRF_ERROR_INVALID_STATE:
BLE_ERR("errno: 0x%lx, Invalid state.\n", errCode);
ret = -EPERM;
break;
case NRF_ERROR_INVALID_ADDR:
BLE_ERR("errno: 0x%lx, Bad Memory Address.\n", errCode);
ret = -EINVAL;
break;
case NRF_ERROR_INVALID_FLAGS:
BLE_ERR("errno: 0x%lx, Invalid flags.\n", errCode);
ret = -EINVAL;
break;
case NRF_ERROR_INVALID_DATA:
BLE_ERR("errno: 0x%lx, Invalid data.\n", errCode);
ret = -EINVAL;
break;
case NRF_ERROR_DATA_SIZE:
BLE_ERR("errno: 0x%lx, Data size exceeds limit.\n", errCode);
ret = -EINVAL;
break;
case NRF_ERROR_INVALID_LENGTH:
BLE_ERR("errno: 0x%lx, Invalid length.\n", errCode);
ret = -EINVAL;
break;
case NRF_ERROR_NOT_SUPPORTED:
BLE_ERR("errno: 0x%lx, Not supported.\n", errCode);
ret = -ENOTSUP;
break;
case NRF_ERROR_BUSY:
BLE_ERR("errno: 0x%lx, Busy.\n", errCode);
ret = -EBUSY;
break;
case NRF_ERROR_NO_MEM:
BLE_ERR("errno: 0x%lx, No Memory for operation.\n", errCode);
ret = -ENOMEM;
break;
case NRF_ERROR_FORBIDDEN:
BLE_ERR("errno: 0x%lx, Forbidden Operation.\n", errCode);
ret = -EPERM;
break;
case BLE_ERROR_INVALID_CONN_HANDLE:
BLE_ERR("errno: 0x%lx, Invalid connection handler.\n", errCode);
ret = -EPERM;
break;
case BLE_ERROR_GAP_UUID_LIST_MISMATCH:
BLE_ERR("errno: 0x%lx, BLE_ERROR_GAP_UUID_LIST_MISMATCH.\n", errCode);
ret = -EINVAL;
break;
case BLE_ERROR_GAP_INVALID_BLE_ADDR:
BLE_ERR("errno: 0x%lx, BLE_ERROR_GAP_INVALID_BLE_ADDR.\n", errCode);
ret = -EPERM;
break;
case BLE_ERROR_GAP_WHITELIST_IN_USE:
BLE_ERR("errno: 0x%lx, BLE_ERROR_GAP_WHITELIST_IN_USE.\n", errCode);
ret = -EPERM;
break;
case BLE_ERROR_GAP_DISCOVERABLE_WITH_WHITELIST:
BLE_ERR("errno: 0x%lx, BLE_ERROR_GAP_DISCOVERABLE_WITH_WHITELIST.\n", errCode);
ret = -EPERM;
break;
case NRF_ERROR_TIMEOUT:
BLE_ERR("errno: 0x%lx, NRF_ERROR_TIMEOUT.\n", errCode);
ret = -ETIMEDOUT;
break;
default:
if (errCode > 0)
{
BLE_ERR("errno: 0x%lx, Stack error.\n", errCode);
ret = -EPERM;
}
break;
}
return ret;
}
static
int bleStackInit(void)
{
int ret;
BLE_PRT("nrf_sdh_enable_request\n");
ret = nrf_sdh_enable_request();
if (ret)
{
return bleConvertErrorCode(ret);
}
// Configure the BLE stack using the default settings.
// Fetch the start address of the application RAM.
BLE_PRT("nrf_sdh_ble_default_cfg_set\n");
ret = nrf_sdh_ble_default_cfg_set(APP_BLE_CONN_CFG_TAG, NULL);
if (ret)
{
goto err;
}
// Enable BLE stack.
BLE_PRT("nrf_sdh_ble_enable\n");
ret = nrf_sdh_ble_enable(NULL);
if (ret)
{
goto err;
}
// Register a handler for BLE events.
#ifdef BLE_USE_SECTION
BLE_PRT("NRF_SDH_BLE_OBSERVER\n");
NRF_SDH_BLE_OBSERVER(m_ble_observer, 0, (void *)bleEvtDispatch, NULL);
#endif
return ret;
err:
nrf_sdh_disable_request();
return bleConvertErrorCode(ret);
}
static
int bleStackFin(void)
{
int ret = 0;
switch (g_ble_context.conn_sts)
{
case BLE_CONN_STS_CONNECTED:
BLE_GapDisconnectLink(g_ble_context.ble_conn_handle);
g_ble_context.ble_conn_handle = CONN_HANDLE_INVALED;
break;
case BLE_CONN_STS_CONNECTING:
BLE_GapCancelConnecting();
break;
default:
break;
}
g_ble_context.conn_sts = BLE_CONN_STS_NOTCONNECTED;
if (g_ble_context.is_advertising)
{
BLE_GapStopAdv();
g_ble_context.is_advertising = false;
}
if (g_ble_context.is_scanning)
{
BLE_GapStopScan();
g_ble_context.is_scanning = false;
}
ret = nrf_sdh_disable_request();
return bleConvertErrorCode(ret);
}
void bleNrfEvtHandler(BLE_Evt *bleEvent, ble_evt_t *pBleNrfEvt)
{
BLE_PRT("bleNrfEvtHandler 0x%x\n", pBleNrfEvt->header.evt_id);
memset(bleEvent, 0x00, sizeof(BLE_Evt));
switch(pBleNrfEvt->header.evt_id)
{
case BLE_GATTC_EVT_WRITE_CMD_TX_COMPLETE:
case BLE_GATTS_EVT_HVN_TX_COMPLETE:
onTxComplete(bleEvent, pBleNrfEvt);
break;
case BLE_GAP_EVT_CONNECTED:
onConnect(bleEvent, pBleNrfEvt);
break;
case BLE_GAP_EVT_CONN_PARAM_UPDATE:
onConnParamUpdate(bleEvent, pBleNrfEvt);
break;
case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
onConnParamUpdateRequest(bleEvent, pBleNrfEvt);
break;
case BLE_GAP_EVT_DISCONNECTED:
onDisconnect(bleEvent, pBleNrfEvt);
break;
case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
onSecParamsRequest(bleEvent, pBleNrfEvt);
break;
case BLE_GAP_EVT_AUTH_STATUS:
onAuthStatus(bleEvent, pBleNrfEvt);
break;
case BLE_GAP_EVT_PASSKEY_DISPLAY:
onDispPasskey(bleEvent, pBleNrfEvt);
break;
case BLE_GAP_EVT_ADV_REPORT:
onAdvReport(bleEvent, pBleNrfEvt);
break;
case BLE_GAP_EVT_AUTH_KEY_REQUEST:
onAuthKeyRequest(bleEvent, pBleNrfEvt);
break;
case BLE_GAP_EVT_SEC_INFO_REQUEST:
onSecInfoRequest(bleEvent, pBleNrfEvt);
break;
case BLE_GAP_EVT_RSSI_CHANGED:
onRssiChanged(bleEvent, pBleNrfEvt);
break;
case BLE_GATTS_EVT_WRITE:
onGattsWrite(bleEvent, pBleNrfEvt);
break;
case BLE_GATTS_EVT_HVC:
onGattsIndConfirm(bleEvent, pBleNrfEvt);
break;
case BLE_GAP_EVT_CONN_SEC_UPDATE:
onConnSecUpdate(bleEvent, pBleNrfEvt);
break;
case BLE_GAP_EVT_TIMEOUT:
onTimeout(bleEvent, pBleNrfEvt);
break;
case BLE_GAP_EVT_DATA_LENGTH_UPDATE_REQUEST:
onDataLengthUpdateRequest(bleEvent, pBleNrfEvt);
break;
case BLE_GAP_EVT_DATA_LENGTH_UPDATE:
onDataLengthUpdate(bleEvent, pBleNrfEvt);
break;
case BLE_GAP_EVT_SCAN_REQ_REPORT:
onScanReqReport(bleEvent, pBleNrfEvt);
break;
case BLE_GAP_EVT_PHY_UPDATE_REQUEST:
onPhyUpdateReq(bleEvent, pBleNrfEvt);
break;
case BLE_GAP_EVT_PHY_UPDATE:
onPhyUpdate(bleEvent, pBleNrfEvt);
break;
case BLE_GATTC_EVT_PRIM_SRVC_DISC_RSP:
onPrimarySrvDiscoveryRsp(&commMem.gattcDb, bleEvent, pBleNrfEvt);
break;
case BLE_GATTC_EVT_CHAR_DISC_RSP:
onCharacteristicDiscoveryRsp(&commMem.gattcDb, bleEvent, pBleNrfEvt);
break;
case BLE_GATTC_EVT_DESC_DISC_RSP:
onDescriptorDiscoveryRsp(&commMem.gattcDb, bleEvent, pBleNrfEvt);
break;
case BLE_GATTC_EVT_READ_RSP:
onReadRsp(bleEvent, pBleNrfEvt);
break;
case BLE_GATTC_EVT_WRITE_RSP:
onWriteRsp(bleEvent, pBleNrfEvt);
break;
case BLE_GATTC_EVT_HVX:
onHvx(bleEvent, pBleNrfEvt);
break;
case BLE_GATTC_EVT_EXCHANGE_MTU_RSP:
onExchangeMtuResponse(bleEvent, pBleNrfEvt);
break;
case BLE_GATTS_EVT_SYS_ATTR_MISSING:
onSysAttrMissing(bleEvent, pBleNrfEvt);
break;
case BLE_GATTS_EVT_TIMEOUT:
onGattsTimeout(bleEvent, pBleNrfEvt);
break;
case BLE_GATTS_EVT_EXCHANGE_MTU_REQUEST:
onExchangeMtuRequest(bleEvent, pBleNrfEvt);
break;
#if NRF_SD_BLE_API_VERSION > 5
case BLE_GAP_EVT_ADV_SET_TERMINATED:
onAdvSetTerminate(bleEvent, pBleNrfEvt);
break;
#endif
default:
bleEvent->evtHeader = (BLE_EventTypes)pBleNrfEvt->header.evt_id;
BLE_ERR("Unknown event 0x%x\n", bleEvent->evtHeader);
break;
}
}
static void ble_advertise(int mode)
{
int ret = 0;
if (mode == 2)
{
LOG_OUT("ble_peripheral: Long range\n");
BLE_GapAdvParams p = {0x40, 0, BLE_GAP_PHY_CODED, 0};
ret = BLE_GapStartAdvExt(&p);
if (BLE_SUCCESS != ret)
{
LOG_OUT("ble enable advertise failed, ret=%d\n", ret);
}
}
else if (mode == 1)
{
ret = BLE_GapStartAdv();
if (BLE_SUCCESS != ret)
{
LOG_OUT("ble enable advertise failed, ret=%d\n", ret);
}
}
else
{
ret = BLE_GapStopAdv();
if (BLE_SUCCESS != ret)
{
LOG_OUT("ble disable advertise failed, ret=%d\n", ret);
}
}
}
static void on_connected(const BLE_EvtConnected* evt)
{
struct ble_event_conn_stat_t conn_stat_evt;
LOG_OUT("Connected: handle %d, role %d\n", evt->handle, evt->role);
g_ble_context.ble_srv_sds.conn_handle = evt->handle;
g_ble_context.ble_conn_handle = evt->handle;
g_ble_context.ble_role = evt->role;
g_ble_context.conn_sts = BLE_CONN_STS_CONNECTED;
g_ble_context.is_scanning = false;
g_ble_context.is_advertising = false;
memcpy(g_ble_context.ble_addr.addr, evt->addr.addr, BT_ADDR_LEN);
conn_stat_evt.connected = true;
conn_stat_evt.handle = evt->handle;
memcpy(conn_stat_evt.addr.address, evt->addr.addr, BT_ADDR_LEN);
conn_stat_evt.group_id = BLE_GROUP_COMMON;
conn_stat_evt.event_id = BLE_COMMON_EVENT_CONN_STAT_CHANGE;
ble_common_event_handler((struct bt_event_t *) &conn_stat_evt);
if ((evt->role == BLE_ROLE_CENTRAL) &&
(commMem.requested_mtu != BLE_GATT_ATT_MTU_DEFAULT))
{
sd_ble_gattc_exchange_mtu_request(evt->handle, commMem.requested_mtu);
}
}
static void on_disconnected(const BLE_EvtDisconnected* evt)
{
struct ble_event_conn_stat_t conn_stat_evt;
LOG_OUT("Disconnected: HCI status 0x%x\n", evt->reason);
g_ble_context.ble_conn_handle = CONN_HANDLE_INVALED;
g_ble_context.conn_sts = BLE_CONN_STS_NOTCONNECTED;
conn_stat_evt.connected = false;
conn_stat_evt.group_id = BLE_GROUP_COMMON;
conn_stat_evt.event_id = BLE_COMMON_EVENT_CONN_STAT_CHANGE;
ble_common_event_handler((struct bt_event_t *) &conn_stat_evt);
if (g_ble_context.ble_role == BLE_ROLE_PERIPHERAL)
{
int ret;
g_ble_context.ble_srv_sds.notify_enabled = 0;
LOG_OUT("Advertising restart !!\n");
ret = BLE_GapStartAdv();
if (BLE_SUCCESS != ret)
{
LOG_OUT("BLE_GapStartAdv failed, ret=%d\n", ret);
}
else
{
g_ble_context.is_advertising = true;
}
}
}
static void on_read_rsp(BLE_EvtGattcRead *readRsp)
{
struct ble_gatt_event_read_rsp_t evt;
evt.group_id = BLE_GROUP_GATT;
evt.event_id = BLE_GATT_EVENT_READ_RESP;
evt.conn_handle = readRsp->connHandle;
evt.char_handle = readRsp->charValHandle;
evt.length = readRsp->charValLen;
memcpy(evt.data, readRsp->charValData, sizeof(evt.data));
ble_gatt_event_handler((struct bt_event_t *)&evt);
}
static void on_exchange_feature(const BLE_EvtExchangeFeature* exchange_feature)
{
int ret;
BLE_GapPairingFeature* pf = NULL;
/* In central case, pairing feature must not be set,
* because it is transmitted in the parameter of
* preceding sd_ble_gap_authenticate()
*/
if (g_ble_context.ble_role == BLE_ROLE_PERIPHERAL)
{
pf = &g_ble_context.pairing_feature;
}
ret = BLE_GapExchangePairingFeature(exchange_feature->handle, pf);
if (BLE_SUCCESS != ret)
{
LOG_OUT("exchange pairing feature failed, ret=%d\n", ret);
}
else
{
LOG_OUT("exchange pairing feature success\n");
}
}
static void on_rssi_changed(const BLE_EvtRssiChanged* evt)
{
LOG_OUT("[BLE][LOG]RSSI changed, value: %d\n", evt->rssi);
}
static void on_disp_passkey(BLE_EvtDisplayPasskey* disp_passkey)
{
LOG_OUT("[BLE][LOG]Passkey: %s\n", disp_passkey->passkey);
}
static void mk_encryption_result_event(uint16_t handle, bool result)
{
struct ble_event_encryption_result_t evt;
evt.group_id = BLE_GROUP_COMMON;
evt.event_id = BLE_COMMON_EVENT_ENCRYPTION_RESULT;
evt.conn_handle = handle;
evt.result = result;
ble_common_event_handler((struct bt_event_t *) &evt);
}
static void on_auth_status(BLE_EvtAuthStatus* auth_status)
{
int ret = BLE_SUCCESS;
int index = 0;
BLE_GapBondInfoList bond_id = {0};
if (auth_status->status != BLE_GAP_SM_STATUS_SUCCESS)
{
LOG_OUT("[BLE][LOG]Pairing failed! ErrCode: %x\n", auth_status->status);
mk_encryption_result_event(auth_status->handle, false);
return;
}
else
{
LOG_OUT("[BLE][LOG]Pairing success!\n");
}
LOG_OUT("[BLE][LOG]save bond address:%02X:%02X:%02X:%02X:%02X:%02X\n",\
auth_status->bondInfo.addr[5],\
auth_status->bondInfo.addr[4],\
auth_status->bondInfo.addr[3],\
auth_status->bondInfo.addr[2],\
auth_status->bondInfo.addr[1],\
auth_status->bondInfo.addr[0]);
ret = BLE_GapSaveBondInfo(&auth_status->bondInfo);
if (BLE_SUCCESS == ret)
{
LOG_OUT("[BLE][SUCCESS]BLE_GapSaveBondInfo\n");
}
else
{
LOG_OUT("[BLE][ERROR]BLE_GapSaveBondInfo\n");
LOG_OUT("[BLE][ERROR]Error number = %d\n", ret);
}
ret = BLE_GapGetBondInfoIdList(&bond_id);
if (BLE_SUCCESS == ret)
{
LOG_OUT("[BLE][SUCCESS]BLE_GapGetBondInfoIdList\n");
}
else
{
LOG_OUT("[BLE][ERROR]BLE_GapGetBondInfoIdList\n");
LOG_OUT("[BLE][ERROR]Error number = %d\n", ret);
}