-
Notifications
You must be signed in to change notification settings - Fork 2
/
spp_ble_server.c
1603 lines (1336 loc) · 47.8 KB
/
spp_ble_server.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
/******************************************************************************
@file spp_ble_server.c
@brief This file contains the SPP BLE Server sample application for use
with the SimpleLink CC26xx SDK
Group: CMCU, SCS
Target Device: CC2640R2
******************************************************************************
Copyright (c) 2013-2017, Texas Instruments Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* 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.
* Neither the name of Texas Instruments Incorporated 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.
*****************************************************************************/
/*********************************************************************
* INCLUDES
*/
#include <string.h>
#include <ti/sysbios/knl/Task.h>
#include <ti/sysbios/knl/Clock.h>
#include <ti/sysbios/knl/Event.h>
#include <ti/sysbios/knl/Queue.h>
#include <icall.h>
#include "util.h"
/* This Header file contains all BLE API and icall structure definition */
#include "icall_ble_api.h"
#include "devinfoservice.h"
#if defined(FEATURE_OAD) || defined(IMAGE_INVALIDATE)
#include "oad_target.h"
#include "oad.h"
#endif //FEATURE_OAD || IMAGE_INVALIDATE
#include "peripheral.h"
#ifdef USE_RCOSC
#include "rcosc_calibration.h"
#endif //USE_RCOSC
#include "board.h"
#include "board_key.h"
#include "spp_ble_server.h"
#include "serial_port_service.h"
#include "inc/sdi_task.h"
/*********************************************************************
* CONSTANTS
*/
// Advertising interval when device is discoverable (units of 625us, 160=100ms)
#define DEFAULT_ADVERTISING_INTERVAL 160
// Limited discoverable mode advertises for 30.72s, and then stops
// General discoverable mode advertises indefinitely
#define DEFAULT_DISCOVERABLE_MODE GAP_ADTYPE_FLAGS_GENERAL
#ifndef FEATURE_OAD
// Minimum connection interval (units of 1.25ms, 80=100ms) if automatic
// parameter update request is enabled
#define DEFAULT_DESIRED_MIN_CONN_INTERVAL 16
// Maximum connection interval (units of 1.25ms, 800=1000ms) if automatic
// parameter update request is enabled
#define DEFAULT_DESIRED_MAX_CONN_INTERVAL 16
#else //!FEATURE_OAD
// Minimum connection interval (units of 1.25ms, 8=10ms) if automatic
// parameter update request is enabled
#define DEFAULT_DESIRED_MIN_CONN_INTERVAL 8
// Maximum connection interval (units of 1.25ms, 8=10ms) if automatic
// parameter update request is enabled
#define DEFAULT_DESIRED_MAX_CONN_INTERVAL 8
#endif // FEATURE_OAD
// Slave latency to use if automatic parameter update request is enabled
#define DEFAULT_DESIRED_SLAVE_LATENCY 0
// Supervision timeout value (units of 10ms, 1000=10s) if automatic parameter
// update request is enabled
#define DEFAULT_DESIRED_CONN_TIMEOUT 200
// Whether to enable automatic parameter update request when a connection is
// formed
#define DEFAULT_ENABLE_UPDATE_REQUEST GAPROLE_LINK_PARAM_UPDATE_WAIT_REMOTE_PARAMS
// Connection Pause Peripheral time value (in seconds)
#define DEFAULT_CONN_PAUSE_PERIPHERAL 6
// How often to perform periodic event (in msec)
#define SBP_PERIODIC_EVT_PERIOD 5000
// Application specific event ID for HCI Connection Event End Events
#define SBP_HCI_CONN_EVT_END_EVT 0x0001
// Type of Display to open
#if !defined(Display_DISABLE_ALL)
#if defined(BOARD_DISPLAY_USE_LCD) && (BOARD_DISPLAY_USE_LCD!=0)
#define SBC_DISPLAY_TYPE Display_Type_LCD
#elif defined (BOARD_DISPLAY_USE_UART) && (BOARD_DISPLAY_USE_UART!=0)
#define SBC_DISPLAY_TYPE Display_Type_UART
#else // !BOARD_DISPLAY_USE_LCD && !BOARD_DISPLAY_USE_UART
#define SBC_DISPLAY_TYPE 0 // Option not supported
#endif // BOARD_DISPLAY_USE_LCD && BOARD_DISPLAY_USE_UART
#else // Display_DISABLE_ALL
#define SBC_DISPLAY_TYPE 0 // No Display
#endif // Display_DISABLE_ALL
#ifdef FEATURE_OAD
// The size of an OAD packet.
#define OAD_PACKET_SIZE ((OAD_BLOCK_SIZE) + 2)
#endif // FEATURE_OAD
// Task configuration
#define SBP_TASK_PRIORITY 1
#ifndef SBP_TASK_STACK_SIZE
#define SBP_TASK_STACK_SIZE 644
#endif
#define SBP_STATE_CHANGE_EVT 0x0001
#define SBP_CHAR_CHANGE_EVT 0x0002
#define SBP_KEY_CHANGE_EVT 0x0004
// Internal Events for RTOS application
#define SBP_ICALL_EVT ICALL_MSG_EVENT_ID // Event_Id_31
#define SBP_QUEUE_EVT UTIL_QUEUE_EVENT_ID // Event_Id_30
#define SBP_PERIODIC_EVT Event_Id_00
#define SBP_UART_QUEUE_EVT Event_Id_02
#ifdef FEATURE_OAD
#define SBP_QUEUE_PING_EVT Event_Id_01
#define SBP_ALL_EVENTS (SBP_ICALL_EVT | \
SBP_QUEUE_EVT | \
SBP_UART_QUEUE_EVT | \
SBP_PERIODIC_EVT | \
SBP_QUEUE_PING_EVT)
#else
#define SBP_ALL_EVENTS (SBP_ICALL_EVT | \
SBP_QUEUE_EVT | \
SBP_UART_QUEUE_EVT | \
SBP_PERIODIC_EVT)
#endif /* FEATURE_OAD */
// Row numbers for two-button menu
#define SBP_ROW_RESULT TBM_ROW_APP
#define SBP_ROW_STATUS_1 (TBM_ROW_APP + 1)
#define SBP_ROW_STATUS_2 (TBM_ROW_APP + 2)
#define SBP_ROW_ROLESTATE (TBM_ROW_APP + 3)
#define SBP_ROW_BDADDR (TBM_ROW_APP + 4)
/*********************************************************************
* TYPEDEFS
*/
// RTOS queue for profile/app messages.
typedef struct _queueRec_
{
Queue_Elem _elem; // queue element
uint8_t *pData; // pointer to app data
} queueRec_t;
// App event passed from profiles.
typedef struct
{
appEvtHdr_t hdr; // event header.
} sbpEvt_t;
// App event passed from profiles.
typedef struct
{
uint8_t event; // Type of event
uint8_t *pData; // New data
uint8_t length; // New status
} sbpUARTEvt_t;
/*********************************************************************
* GLOBAL VARIABLES
*/
// Global pin resources
PIN_State pinGpioState;
PIN_Handle hGpioPin;
uint16 currentMTUSize;
/*********************************************************************
* LOCAL VARIABLES
*/
// Entity ID globally used to check for source and/or destination of messages
static ICall_EntityID selfEntity;
// Event globally used to post local events and pend on system and
// local events.
static ICall_SyncHandle syncEvent;
// Clock instances for internal periodic events.
static Clock_Struct periodicClock;
// Queue object used for app messages
static Queue_Struct appMsg;
static Queue_Handle appMsgQueue;
// Queue object used for UART messages
static Queue_Struct appUARTMsg;
static Queue_Handle appUARTMsgQueue;
#if defined(FEATURE_OAD)
// Event data from OAD profile.
static Queue_Struct oadQ;
static Queue_Handle hOadQ;
#endif //FEATURE_OAD
// Task configuration
Task_Struct sbpTask;
Char sbpTaskStack[SBP_TASK_STACK_SIZE];
// Value to write
static uint8_t charVal = 0x41;
// Profile state and parameters
static gaprole_States_t gapProfileState = GAPROLE_INIT;
// Connection handle of current connection
static uint16_t connHandle = GAP_CONNHANDLE_INIT;
// GAP - SCAN RSP data (max size = 31 bytes)
static uint8_t scanRspData[] =
{
// complete name
0x0F, // length of this data
GAP_ADTYPE_LOCAL_NAME_COMPLETE,
'S',
'P',
'P',
' ',
'B',
'L',
'E',
' ',
'S',
'E',
'R',
'V',
'E',
'R',
// connection interval range
0x05, // length of this data
GAP_ADTYPE_SLAVE_CONN_INTERVAL_RANGE,
LO_UINT16(DEFAULT_DESIRED_MIN_CONN_INTERVAL), // 100ms
HI_UINT16(DEFAULT_DESIRED_MIN_CONN_INTERVAL),
LO_UINT16(DEFAULT_DESIRED_MAX_CONN_INTERVAL), // 1s
HI_UINT16(DEFAULT_DESIRED_MAX_CONN_INTERVAL),
// Tx power level
0x02, // length of this data
GAP_ADTYPE_POWER_LEVEL,
0 // 0dBm
};
// GAP - Advertisement data (max size = 31 bytes, though this is
// best kept short to conserve power while advertisting)
static uint8_t advertData[] =
{
// Flags; this sets the device to use limited discoverable
// mode (advertises for 30 seconds at a time) instead of general
// discoverable mode (advertises indefinitely)
0x02, // length of this data
GAP_ADTYPE_FLAGS,
DEFAULT_DISCOVERABLE_MODE | GAP_ADTYPE_FLAGS_BREDR_NOT_SUPPORTED,
// service UUID, to notify central devices what services are included
// in this peripheral
#if !defined(FEATURE_OAD)
0x03, // length of this data
#else //OAD for external flash
0x05, // length of this data
#endif //FEATURE_OAD
GAP_ADTYPE_16BIT_MORE, // some of the UUID's, but not all
#ifdef FEATURE_OAD
LO_UINT16(OAD_SERVICE_UUID),
HI_UINT16(OAD_SERVICE_UUID),
#endif //FEATURE_OAD
LO_UINT16(SERIALPORTSERVICE_SERV_UUID),
HI_UINT16(SERIALPORTSERVICE_SERV_UUID)
};
// GAP GATT Attributes
static uint8_t attDeviceName[GAP_DEVICE_NAME_LEN] = "SPP BLE Server";
// Globals used for ATT Response retransmission
static gattMsgEvent_t *pAttRsp = NULL;
static uint8_t rspTxRetry = 0;
// Pins that are actively used by the application
static PIN_Config SPPBLEAppPinTable[] =
{
Board_RLED | PIN_GPIO_OUTPUT_EN | PIN_GPIO_LOW | PIN_PUSHPULL | PIN_DRVSTR_MAX, /* LED initially off */
Board_GLED | PIN_GPIO_OUTPUT_EN | PIN_GPIO_LOW | PIN_PUSHPULL | PIN_DRVSTR_MAX, /* LED initially off */
PIN_TERMINATE
};
static uint8 currentPHY = HCI_PHY_1_MBPS;
/*********************************************************************
* LOCAL FUNCTIONS
*/
static void SPPBLEServer_init( void );
static void SPPBLEServer_taskFxn(UArg a0, UArg a1);
static uint8_t SPPBLEServer_processStackMsg(ICall_Hdr *pMsg);
static uint8_t SPPBLEServer_processGATTMsg(gattMsgEvent_t *pMsg);
static void SPPBLEServer_processAppMsg(sbpEvt_t *pMsg);
static void SPPBLEServer_processStateChangeEvt(gaprole_States_t newState);
static void SPPBLEServer_processCharValueChangeEvt(uint8_t paramID);
static void SPPBLEServer_performPeriodicTask(void);
static void SPPBLEServer_clockHandler(UArg arg);
static void SPPBLEServer_sendAttRsp(void);
static void SPPBLEServer_freeAttRsp(uint8_t status);
static void SPPBLEServer_stateChangeCB(gaprole_States_t newState);
static void SPPBLEServer_charValueChangeCB(uint8_t paramID);
static void SPPBLEServer_enqueueMsg(uint8_t event, uint8_t state);
#ifdef FEATURE_OAD
void SPPBLEServer_processOadWriteCB(uint8_t event, uint16_t connHandle,
uint8_t *pData);
#endif //FEATURE_OAD
static void SPPBLEServer_handleKeys(uint8_t shift, uint8_t keys);
void SPPBLEServer_enqueueUARTMsg(uint8_t event, uint8_t *data, uint8_t len);
char* convInt32ToText(int32 value);
void SPPBLEServer_keyChangeHandler(uint8 keys);
bool SPPBLEServer_doSetPhy(uint8 index);
/*********************************************************************
* EXTERN FUNCTIONS
*/
extern void AssertHandler(uint8 assertCause, uint8 assertSubcause);
/*********************************************************************
* PROFILE CALLBACKS
*/
// GAP Role Callbacks
static gapRolesCBs_t SPPBLEServer_gapRoleCBs =
{
SPPBLEServer_stateChangeCB // Profile State Change Callbacks
};
// GAP Bond Manager Callbacks
static gapBondCBs_t SPPBLEServer_BondMgrCBs =
{
NULL, // Passcode callback (not used by application)
NULL // Pairing / Bonding state Callback (not used by application)
};
// Simple GATT Profile Callbacks
static SerialPortServiceCBs_t SPPBLEServer_SerialPortService_CBs =
{
SPPBLEServer_charValueChangeCB // Characteristic value change callback
};
#ifdef FEATURE_OAD
static oadTargetCBs_t SPPBLEServer_oadCBs =
{
SPPBLEServer_processOadWriteCB // Write Callback.
};
#endif //FEATURE_OAD
/*********************************************************************
* PUBLIC FUNCTIONS
*/
/*********************************************************************
* @fn SPPBLEServer_createTask
*
* @brief Task creation function for the Simple BLE Peripheral.
*
* @param None.
*
* @return None.
*/
void SPPBLEServer_createTask(void)
{
Task_Params taskParams;
// Configure task
Task_Params_init(&taskParams);
taskParams.stack = sbpTaskStack;
taskParams.stackSize = SBP_TASK_STACK_SIZE;
taskParams.priority = SBP_TASK_PRIORITY;
Task_construct(&sbpTask, SPPBLEServer_taskFxn, &taskParams, NULL);
}
/*******************************************************************************
* @fn SPPBLEServer_blinkLed
*
* @brief Blinks a led 'n' times, duty-cycle 50-50
* @param led - led identifier
* @param nBlinks - number of blinks
*
* @return none
*/
void SPPBLEServer_blinkLed(uint8_t led, uint8_t nBlinks)
{
uint8_t i;
for (i=0; i<nBlinks; i++)
{
PIN_setOutputValue(hGpioPin, led, Board_LED_ON);
delay_ms(BLINK_DURATION);
PIN_setOutputValue(hGpioPin, led, Board_LED_OFF);
delay_ms(BLINK_DURATION);
}
}
/*******************************************************************************
* @fn SPPBLEServer_toggleLed
*
* @brief Toggle an LED
* @param led - led identifier
* @param state - state to change the LED
*
* @return none
*/
void SPPBLEServer_toggleLed(uint8_t led, uint8_t state)
{
uint8_t nextLEDstate = 0;
if(state == Board_LED_TOGGLE)
{
nextLEDstate = !(PIN_getOutputValue(led));
}
else
{
nextLEDstate = state;
}
PIN_setOutputValue(hGpioPin, led, nextLEDstate);
}
/*********************************************************************
* @fn SPPBLEServer_init
*
* @brief Called during initialization and contains application
* specific initialization (ie. hardware initialization/setup,
* table initialization, power up notification, etc), and
* profile initialization/setup.
*
* @param None.
*
* @return None.
*/
static void SPPBLEServer_init(void)
{
// ******************************************************************
// N0 STACK API CALLS CAN OCCUR BEFORE THIS CALL TO ICall_registerApp
// ******************************************************************
// Register the current thread as an ICall dispatcher application
// so that the application can send and receive messages.
ICall_registerApp(&selfEntity, &syncEvent);
// Hard code the BD Address till CC2650 board gets its own IEEE address
uint8 bdAddress[B_ADDR_LEN] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05 };
HCI_EXT_SetBDADDRCmd(bdAddress);
// Handling of LED
hGpioPin = PIN_open(&pinGpioState, SPPBLEAppPinTable);
// Create an RTOS queue for message from profile to be sent to app.
appMsgQueue = Util_constructQueue(&appMsg);
appUARTMsgQueue = Util_constructQueue(&appUARTMsg);
// Create one-shot clocks for internal periodic events.
Util_constructClock(&periodicClock, SPPBLEServer_clockHandler,
SBP_PERIODIC_EVT_PERIOD, 0, false, SBP_PERIODIC_EVT);
Board_initKeys(SPPBLEServer_keyChangeHandler);
// Setup the GAP
GAP_SetParamValue(TGAP_CONN_PAUSE_PERIPHERAL, DEFAULT_CONN_PAUSE_PERIPHERAL);
// Setup the GAP Peripheral Role Profile
{
// For all hardware platforms, device starts advertising upon initialization
uint8_t initialAdvertEnable = TRUE;
// By setting this to zero, the device will go into the waiting state after
// being discoverable for 30.72 second, and will not being advertising again
// until the enabler is set back to TRUE
uint16_t advertOffTime = 0;
uint8_t enableUpdateRequest = DEFAULT_ENABLE_UPDATE_REQUEST;
uint16_t desiredMinInterval = DEFAULT_DESIRED_MIN_CONN_INTERVAL;
uint16_t desiredMaxInterval = DEFAULT_DESIRED_MAX_CONN_INTERVAL;
uint16_t desiredSlaveLatency = DEFAULT_DESIRED_SLAVE_LATENCY;
uint16_t desiredConnTimeout = DEFAULT_DESIRED_CONN_TIMEOUT;
// Set the GAP Role Parameters
GAPRole_SetParameter(GAPROLE_ADVERT_ENABLED, sizeof(uint8_t),
&initialAdvertEnable);
GAPRole_SetParameter(GAPROLE_ADVERT_OFF_TIME, sizeof(uint16_t),
&advertOffTime);
GAPRole_SetParameter(GAPROLE_SCAN_RSP_DATA, sizeof(scanRspData),
scanRspData);
GAPRole_SetParameter(GAPROLE_ADVERT_DATA, sizeof(advertData), advertData);
GAPRole_SetParameter(GAPROLE_PARAM_UPDATE_ENABLE, sizeof(uint8_t),
&enableUpdateRequest);
GAPRole_SetParameter(GAPROLE_MIN_CONN_INTERVAL, sizeof(uint16_t),
&desiredMinInterval);
GAPRole_SetParameter(GAPROLE_MAX_CONN_INTERVAL, sizeof(uint16_t),
&desiredMaxInterval);
GAPRole_SetParameter(GAPROLE_SLAVE_LATENCY, sizeof(uint16_t),
&desiredSlaveLatency);
GAPRole_SetParameter(GAPROLE_TIMEOUT_MULTIPLIER, sizeof(uint16_t),
&desiredConnTimeout);
}
// Set the GAP Characteristics
GGS_SetParameter(GGS_DEVICE_NAME_ATT, GAP_DEVICE_NAME_LEN, attDeviceName);
// Set advertising interval
{
uint16_t advInt = DEFAULT_ADVERTISING_INTERVAL;
GAP_SetParamValue(TGAP_LIM_DISC_ADV_INT_MIN, advInt);
GAP_SetParamValue(TGAP_LIM_DISC_ADV_INT_MAX, advInt);
GAP_SetParamValue(TGAP_GEN_DISC_ADV_INT_MIN, advInt);
GAP_SetParamValue(TGAP_GEN_DISC_ADV_INT_MAX, advInt);
}
// Setup the GAP Bond Manager
{
uint32_t passkey = 0; // passkey "000000"
uint8_t pairMode = GAPBOND_PAIRING_MODE_WAIT_FOR_REQ;
uint8_t mitm = TRUE;
uint8_t ioCap = GAPBOND_IO_CAP_DISPLAY_ONLY;
uint8_t bonding = TRUE;
GAPBondMgr_SetParameter(GAPBOND_DEFAULT_PASSCODE, sizeof(uint32_t),
&passkey);
GAPBondMgr_SetParameter(GAPBOND_PAIRING_MODE, sizeof(uint8_t), &pairMode);
GAPBondMgr_SetParameter(GAPBOND_MITM_PROTECTION, sizeof(uint8_t), &mitm);
GAPBondMgr_SetParameter(GAPBOND_IO_CAPABILITIES, sizeof(uint8_t), &ioCap);
GAPBondMgr_SetParameter(GAPBOND_BONDING_ENABLED, sizeof(uint8_t), &bonding);
}
// Initialize GATT attributes
GGS_AddService(GATT_ALL_SERVICES); // GAP
GATTServApp_AddService(GATT_ALL_SERVICES); // GATT attributes
DevInfo_AddService(); // Device Information Service
SerialPortService_AddService(GATT_ALL_SERVICES); //SerialPortBLE service
#ifdef FEATURE_OAD
VOID OAD_addService(); // OAD Profile
OAD_register((oadTargetCBs_t *)&SPPBLEServer_oadCBs);
hOadQ = Util_constructQueue(&oadQ);
#endif //FEATURE_OAD
#ifdef IMAGE_INVALIDATE
Reset_addService();
#endif //IMAGE_INVALIDATE
// Register callback with SimpleGATTprofile
SerialPortService_RegisterAppCBs(&SPPBLEServer_SerialPortService_CBs);
// Start Bond Manager
VOID GAPBondMgr_Register(&SPPBLEServer_BondMgrCBs);
// Register with GAP for HCI/Host messages
GAP_RegisterForMsgs(selfEntity);
// Register for GATT local events and ATT Responses pending for transmission
GATT_RegisterForMsgs(selfEntity);
#ifdef SDI_USE_UART
//Register to receive UART messages
SDITask_registerIncomingRXEventAppCB(SPPBLEServer_enqueueUARTMsg);
#endif
//Set default values for Data Length Extension
//This should be included only if Extended Data Length Feature is enabled
//in build_config.opt in stack project.
{
//Set initial values to maximum, RX is set to max. by default(251 octets, 2120us)
#define APP_SUGGESTED_PDU_SIZE 251 //default is 27 octets(TX)
#define APP_SUGGESTED_TX_TIME 2120 //default is 328us(TX)
//This API is documented in hci.h
//See BLE5-Stack User's Guide for information on using this command:
//http://software-dl.ti.com/lprf/ble5stack-docs-latest/html/ble-stack/data-length-extensions.html
HCI_LE_WriteSuggestedDefaultDataLenCmd(APP_SUGGESTED_PDU_SIZE, APP_SUGGESTED_TX_TIME);
}
#if !defined (USE_LL_CONN_PARAM_UPDATE)
// Get the currently set local supported LE features
// The HCI will generate an HCI event that will get received in the main
// loop
HCI_LE_ReadLocalSupportedFeaturesCmd();
#endif // !defined (USE_LL_CONN_PARAM_UPDATE)
// Start the Device
VOID GAPRole_StartDevice(&SPPBLEServer_gapRoleCBs);
//Display project name and Bluetooth 5 support
uint8_t hello[] = "Hello from SPP BLE Server! With Bluetooth 5 support!\n\r";
DEBUG(hello);
SPPBLEServer_blinkLed(Board_RLED, 1);
}
/*********************************************************************
* @fn SPPBLEServer_taskFxn
*
* @brief Application task entry point for the Simple BLE Peripheral.
*
* @param a0, a1 - not used.
*
* @return None.
*/
static void SPPBLEServer_taskFxn(UArg a0, UArg a1)
{
// Initialize application
SPPBLEServer_init();
// Application main loop
for (;;)
{
uint32_t events;
// Waits for an event to be posted associated with the calling thread.
// Note that an event associated with a thread is posted when a
// message is queued to the message receive queue of the thread
events = Event_pend(syncEvent, Event_Id_NONE, SBP_ALL_EVENTS,
ICALL_TIMEOUT_FOREVER);
if (events)
{
ICall_EntityID dest;
ICall_ServiceEnum src;
ICall_HciExtEvt *pMsg = NULL;
if (ICall_fetchServiceMsg(&src, &dest,
(void **)&pMsg) == ICALL_ERRNO_SUCCESS)
{
uint8 safeToDealloc = TRUE;
if ((src == ICALL_SERVICE_CLASS_BLE) && (dest == selfEntity))
{
ICall_Stack_Event *pEvt = (ICall_Stack_Event *)pMsg;
// Check for BLE stack events first
if (pEvt->signature == 0xffff)
{
if (pEvt->event_flag & SBP_HCI_CONN_EVT_END_EVT)
{
// Try to retransmit pending ATT Response (if any)
SPPBLEServer_sendAttRsp();
}
}
else
{
// Process inter-task message
safeToDealloc = SPPBLEServer_processStackMsg((ICall_Hdr *)pMsg);
}
}
if (pMsg && safeToDealloc)
{
ICall_freeMsg(pMsg);
}
}
// If RTOS queue is not empty, process app message.
if (events & SBP_UART_QUEUE_EVT)
{
// If RTOS queue is not empty, process app message.
if (!Queue_empty(appUARTMsgQueue))
{
//Get the message at the front of the queue but still keep it in the queue
queueRec_t *pRec = Queue_head(appUARTMsgQueue);
sbpUARTEvt_t *pMsg = (sbpUARTEvt_t *)pRec->pData;
if (pMsg && ((gapProfileState == GAPROLE_CONNECTED) || (gapProfileState == GAPROLE_CONNECTED_ADV)))
{
bStatus_t retVal = FAILURE;
switch(pMsg->event)
{
case SBP_UART_DATA_EVT:
{
//Send the notification
retVal = SerialPortService_SetParameter(SERIALPORTSERVICE_CHAR_DATA, pMsg->length, pMsg->pData);
if(retVal != SUCCESS)
{
DEBUG("Noti FAIL");
}
else
{
//Increment TX status counter
SerialPortService_AddStatusTXBytes(pMsg->length);
//Remove from queue
Util_dequeueMsg(appUARTMsgQueue);
//Toggle LED to indicate data received from UART terminal and sent over the air
//SPPBLEServer_toggleLed(Board_GLED, Board_LED_TOGGLE);
//Deallocate data payload being transmitted.
ICall_freeMsg(pMsg->pData);
// Free the space from the message.
ICall_free(pMsg);
}
if(!Queue_empty(appUARTMsgQueue))
{
// Wake up the application to flush out any remaining UART data in the queue.
Event_post(syncEvent, SBP_UART_QUEUE_EVT);
}
break;
}
default:
break;
}
}
}
}
// If RTOS queue is not empty, process app message.
if (events & SBP_QUEUE_EVT)
{
while (!Queue_empty(appMsgQueue))
{
sbpEvt_t *pMsg = (sbpEvt_t *)Util_dequeueMsg(appMsgQueue);
if (pMsg)
{
// Process message.
SPPBLEServer_processAppMsg(pMsg);
// Free the space from the message.
ICall_free(pMsg);
}
}
}
if (events & SBP_PERIODIC_EVT)
{
Util_startClock(&periodicClock);
// Perform periodic application task
SPPBLEServer_performPeriodicTask();
}
#ifdef FEATURE_OAD
if (events & SBP_QUEUE_PING_EVT)
{
while (!Queue_empty(hOadQ))
{
oadTargetWrite_t *oadWriteEvt = Queue_get(hOadQ);
// Identify new image.
if (oadWriteEvt->event == OAD_WRITE_IDENTIFY_REQ)
{
OAD_imgIdentifyWrite(oadWriteEvt->connHandle, oadWriteEvt->pData);
}
// Write a next block request.
else if (oadWriteEvt->event == OAD_WRITE_BLOCK_REQ)
{
OAD_imgBlockWrite(oadWriteEvt->connHandle, oadWriteEvt->pData);
}
// Free buffer.
ICall_free(oadWriteEvt);
}
}
#endif //FEATURE_OAD
}
}
}
/*********************************************************************
* @fn SPPBLEServer_processStackMsg
*
* @brief Process an incoming stack message.
*
* @param pMsg - message to process
*
* @return TRUE if safe to deallocate incoming message, FALSE otherwise.
*/
static uint8_t SPPBLEServer_processStackMsg(ICall_Hdr *pMsg)
{
uint8_t safeToDealloc = TRUE;
switch (pMsg->event)
{
case GATT_MSG_EVENT:
// Process GATT message
safeToDealloc = SPPBLEServer_processGATTMsg((gattMsgEvent_t *)pMsg);
break;
case HCI_GAP_EVENT_EVENT:
{
// Process HCI message
switch(pMsg->status)
{
case HCI_COMMAND_COMPLETE_EVENT_CODE:
// Process HCI Command Complete Event
{
#if !defined (USE_LL_CONN_PARAM_UPDATE)
// This code will disable the use of the LL_CONNECTION_PARAM_REQ
// control procedure (for connection parameter updates, the
// L2CAP Connection Parameter Update procedure will be used
// instead). To re-enable the LL_CONNECTION_PARAM_REQ control
// procedures, define the symbol USE_LL_CONN_PARAM_UPDATE
// Parse Command Complete Event for opcode and status
hciEvt_CmdComplete_t* command_complete = (hciEvt_CmdComplete_t*) pMsg;
uint8_t pktStatus = command_complete->pReturnParam[0];
//find which command this command complete is for
switch (command_complete->cmdOpcode)
{
case HCI_LE_READ_LOCAL_SUPPORTED_FEATURES:
{
if (pktStatus == SUCCESS)
{
uint8_t featSet[8];
// get current feature set from received event (bits 1-9 of
// the returned data
memcpy( featSet, &command_complete->pReturnParam[1], 8 );
// Clear bit 1 of byte 0 of feature set to disable LL
// Connection Parameter Updates
CLR_FEATURE_FLAG( featSet[0], LL_FEATURE_CONN_PARAMS_REQ );
// Update controller with modified features
HCI_EXT_SetLocalSupportedFeaturesCmd( featSet );
}
}
break;
default:
//do nothing
break;
}
#endif // !defined (USE_LL_CONN_PARAM_UPDATE)
}
break;
case HCI_BLE_HARDWARE_ERROR_EVENT_CODE:
AssertHandler(HAL_ASSERT_CAUSE_HARDWARE_ERROR,0);
break;
case HCI_LE_EVENT_CODE:
{
hciEvt_BLEPhyUpdateComplete_t *pPUC
= (hciEvt_BLEPhyUpdateComplete_t*) pMsg;
if (pPUC->BLEEventCode == HCI_BLE_PHY_UPDATE_COMPLETE_EVENT)
{
if (pPUC->status != SUCCESS)
{
DEBUG("PHY Change failure");
}
else
{
Display_print0(dispHandle, 3, 0, "PHY Update Complete");
// Only symmetrical PHY is supported.
// rxPhy should be equal to txPhy.
DEBUG("PHY Changed to: ");
DEBUG((uint8_t*)((pPUC->rxPhy == HCI_PHY_1_MBPS) ? "1 Mbps" : "2 Mbps"));
DEBUG_NEWLINE();
currentPHY = pPUC->rxPhy;
}
}
}
break;
default:
break;
}
}
break;
default:
// do nothing
break;
}
return (safeToDealloc);
}
/*********************************************************************
* @fn SPPBLEServer_processGATTMsg
*
* @brief Process GATT messages and events.
*
* @return TRUE if safe to deallocate incoming message, FALSE otherwise.
*/
static uint8_t SPPBLEServer_processGATTMsg(gattMsgEvent_t *pMsg)
{
// See if GATT server was unable to transmit an ATT response
if (pMsg->hdr.status == blePending)
{
// No HCI buffer was available. Let's try to retransmit the response
// on the next connection event.
if (HCI_EXT_ConnEventNoticeCmd(pMsg->connHandle, selfEntity,
SBP_HCI_CONN_EVT_END_EVT) == SUCCESS)
{
// First free any pending response
SPPBLEServer_freeAttRsp(FAILURE);
// Hold on to the response message for retransmission
pAttRsp = pMsg;
// Don't free the response message yet
return (FALSE);
}
}
else if (pMsg->method == ATT_FLOW_CTRL_VIOLATED_EVENT)
{
// ATT request-response or indication-confirmation flow control is
// violated. All subsequent ATT requests or indications will be dropped.
// The app is informed in case it wants to drop the connection.
// Display the opcode of the message that caused the violation.
//Display_print1(dispHandle, SBP_ROW_RESULT, 0, "FC Violated: %d", pMsg->msg.flowCtrlEvt.opcode);
}
else if (pMsg->method == ATT_MTU_UPDATED_EVENT)
{
// MTU size updated
currentMTUSize = pMsg->msg.mtuEvt.MTU;
SDITask_setAppDataSize(currentMTUSize);
DEBUG("MTU Size: "); DEBUG((uint8_t*)convInt32ToText((int)currentMTUSize)); DEBUG_NEWLINE();
}
// Free message payload. Needed only for ATT Protocol messages
GATT_bm_free(&pMsg->msg, pMsg->method);
// It's safe to free the incoming message
return (TRUE);
}
/*********************************************************************
* @fn SPPBLEServer_sendAttRsp
*