-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsimpleBLECentral .c
1764 lines (1509 loc) · 58.1 KB
/
simpleBLECentral .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
/**************************************************************************************************
Filename: simpleBLECentral.c
Revised: $Date: 2011-06-20 11:57:59 -0700 (Mon, 20 Jun 2011) $
Revision: $Revision: 28 $
Description: This file contains the Simple BLE Central sample application
for use with the CC2540 Bluetooth Low Energy Protocol Stack.
Copyright 2010 Texas Instruments Incorporated. All rights reserved.
IMPORTANT: Your use of this Software is limited to those specific rights
granted under the terms of a software license agreement between the user
who downloaded the software, his/her employer (which must be your employer)
and Texas Instruments Incorporated (the "License"). You may not use this
Software unless you agree to abide by the terms of the License. The License
limits your use, and you acknowledge, that the Software may not be modified,
copied or distributed unless embedded on a Texas Instruments microcontroller
or used solely and exclusively in conjunction with a Texas Instruments radio
frequency transceiver, which is integrated into your product. Other than for
the foregoing purpose, you may not use, reproduce, copy, prepare derivative
works of, modify, distribute, perform, display or sell this Software and/or
its documentation for any purpose.
YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
PROVIDED 揂S IS?WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
Should you have any questions regarding your right to use this Software,
contact Texas Instruments Incorporated at www.TI.com.
**************************************************************************************************/
/*********************************************************************
* INCLUDES
*/
#include "bcomdef.h"
#include "OSAL.h"
#include "OSAL_PwrMgr.h"
#include "OnBoard.h"
#include "hal_led.h"
#include "hal_key.h"
#include "hal_lcd.h"
#include "gatt.h"
#include "ll.h"
#include "hci.h"
#include "gapgattserver.h"
#include "gattservapp.h"
#include "central.h"
#include "gapbondmgr.h"
#include "simpleGATTprofile.h"
#include "simpleBLECentral.h"
#include "npi.h"
#include "stdio.h"
/*
操作步骤
1,主机通过 up按键 搜索从机
2,主机 center键 自动连接,可自动连接最多3个从机,
按屏幕显示当显示 “key S1 = send data ” 时,
按下s1 键即可,之后主机向每个从机的char1 与 char6发送轮流发送数据。
3,从机可以按下s1键 向主机的 notify char6的数据
4,主机可以按down键读取个从机的rssi 或取消。
*/
/*********************************************************************
* MACROS
*/
// Length of bd addr as a string
#define B_ADDR_STR_LEN 15
/*********************************************************************
* CONSTANTS
*/
// 系统定时器间隔时间
#define SBP_PERIODIC_EVT_PERIOD 400//ms 发送数据的定时间隔, 可长可短, 建议 100~10000
#define SBP_PERIODIC_EVT_AUTO_CONNECT 1600//ms 连接从机的间隔, 不能太短, 请勿任意修改
// Maximum number of scan responses
#define DEFAULT_MAX_SCAN_RES 3//8 最大扫描从机个数, 最大为8, 更大的话没验证过
// Scan duration in ms
#define DEFAULT_SCAN_DURATION 1000//4000 开始扫描到返回扫描结果的时间间隔, 不能太小的原因是与从机的广播间隔有关
// Discovey mode (limited, general, all)
#define DEFAULT_DISCOVERY_MODE DEVDISC_MODE_ALL // 扫描所有从机, 当然你可以指定扫描
// TRUE to use active scan
#define DEFAULT_DISCOVERY_ACTIVE_SCAN TRUE
// TRUE to use white list during discovery
#define DEFAULT_DISCOVERY_WHITE_LIST FALSE
// TRUE to use high scan duty cycle when creating link
#define DEFAULT_LINK_HIGH_DUTY_CYCLE FALSE
// TRUE to use white list when creating link
#define DEFAULT_LINK_WHITE_LIST FALSE
// Default RSSI polling period in ms
#define DEFAULT_RSSI_PERIOD 1000 // 这个是使能读取rssi是每次返回结果之间的时间间隔
// Whether to enable automatic parameter update request when a connection is formed
#define DEFAULT_ENABLE_UPDATE_REQUEST FALSE
// Minimum connection interval (units of 1.25ms) if automatic parameter update request is enabled
#define DEFAULT_UPDATE_MIN_CONN_INTERVAL 8// 连接间隔与数据发送量有关, 连接间隔越短, 单位时间内就能发送越多的数据
// Maximum connection interval (units of 1.25ms) if automatic parameter update request is enabled
#define DEFAULT_UPDATE_MAX_CONN_INTERVAL 8//800 连接间隔与数据发送量有关, 连接间隔越短, 单位时间内就能发送越多的数据
// Slave latency to use if automatic parameter update request is enabled
#define DEFAULT_UPDATE_SLAVE_LATENCY 0
// Supervision timeout value (units of 10ms) if automatic parameter update request is enabled
#define DEFAULT_UPDATE_CONN_TIMEOUT 1//300//600 这个是参数更新的定时时间, 不能太长, 否则影响数据发送----请多做实验再修改该值
// Default passcode
#define DEFAULT_PASSCODE 19655 // 密码
// Default GAP pairing mode
#define DEFAULT_PAIRING_MODE GAPBOND_PAIRING_MODE_WAIT_FOR_REQ
// Default MITM mode (TRUE to require passcode or OOB when pairing)
#define DEFAULT_MITM_MODE FALSE
// Default bonding mode, TRUE to bond
#define DEFAULT_BONDING_MODE TRUE
// Default GAP bonding I/O capabilities
#define DEFAULT_IO_CAPABILITIES GAPBOND_IO_CAP_DISPLAY_ONLY
// Default service discovery timer delay in ms
#define DEFAULT_SVC_DISCOVERY_DELAY 1//1000 这个的意思是连接上从机后延时多长时间去获取从机的服务, 为了加快速度,这里我们设置为 1ms
// TRUE to filter discovery results on desired service UUID
#define DEFAULT_DEV_DISC_BY_SVC_UUID TRUE
// Application states
enum
{
BLE_STATE_IDLE,
BLE_STATE_CONNECTING,
BLE_STATE_CONNECTED,
BLE_STATE_DISCONNECTING
};
// Discovery states
enum
{
BLE_DISC_STATE_IDLE, // Idle
BLE_DISC_STATE_SVC, // Service discovery
BLE_DISC_STATE_CHAR1, // 特征值1
BLE_DISC_STATE_CHAR2,
BLE_DISC_STATE_CHAR3,
BLE_DISC_STATE_CHAR4,
BLE_DISC_STATE_CHAR5,
BLE_DISC_STATE_CHAR6, // 我们的主从一体串口透传使用的
};
enum
{
BLE_CHAR1 = 0,
BLE_CHAR2,
BLE_CHAR3,
BLE_CHAR4,
BLE_CHAR5,
BLE_CHAR6,
BLE_CHAR7,
};
/*********************************************************************
* TYPEDEFS
*/
/*********************************************************************
* GLOBAL VARIABLES
*/
/*********************************************************************
* EXTERNAL VARIABLES
*/
/*********************************************************************
* EXTERNAL FUNCTIONS
*/
/*********************************************************************
* LOCAL VARIABLES
*/
// Task ID for internal task/event processing
static uint8 simpleBLETaskId; // 本任务的 id 号
// GAP GATT Attributes
static const uint8 simpleBLEDeviceName[GAP_DEVICE_NAME_LEN] = "Simple BLE Central";
// Number of scan results and scan result index
static uint8 simpleBLEScanRes = 0; // 扫描结果, 表现为个数 ,1,2,3,4 等表示扫描到几个从机
static uint8 simpleBLEScanIdx = 0; // 表示当前处理的是哪一个从机, 0, 1, 2,3,4 等是从机的下标
static uint8 simpleBLEUpdateCnt = 0; // 参数更新计数, 用于控制是否可以提示用户按下 S1 按键去发送数据
static uint8 simpleBLESendValue = 0; // 用于发送的数据, 累加, 方便观察数据
// Scan result list
static gapDevRec_t simpleBLEDevList[DEFAULT_MAX_SCAN_RES];// 扫描结果列表, 内含扫描到的从机地址
// Scanning state
static uint8 simpleBLEScanning = FALSE; // 全局控制, 扫描或停止扫描
// RSSI polling state
//static uint8 simpleBLERssi = FALSE; // 是否查询 rssi 值, 这个查询必须是在连接从机之后才可以查询
#define MAX_PERIPHERAL_NUM DEFAULT_MAX_SCAN_RES // 最大从机个数, 最大为 8, 最小为1, 看你需要的定义了
#define MAX_CHAR_NUM 6 // 最大去搜索的特征值个数-------切勿改动 切勿改动 切勿改动
uint8 connectedPeripheralNum = 0; // 已连接上的从机个数
uint8 flag=0;
//显示用的
char str[32] = {0};
// Connection handle of current connection
//static uint16 simpleBLEConnHandle[MAX_PERIPHERAL_NUM] = {GAP_CONNHANDLE_INIT};
// Application state
//static uint8 simpleBLEState[MAX_PERIPHERAL_NUM] = {BLE_STATE_IDLE};
// Discovery state
//static uint8 simpleBLEDiscState[MAX_PERIPHERAL_NUM] = {BLE_DISC_STATE_IDLE};
// Discovered service start and end handle
//static uint16 simpleBLESvcStartHdl = 0;
//static uint16 simpleBLESvcEndHdl = 0;
// Discovered characteristic handle
//static uint16 simpleBLECharHdl[2] = {0};
// Value to write
//static uint8 simpleBLECharVal = 0;
// Value read/write toggle
//static bool simpleBLEDoWrite = FALSE;
// GATT read/write procedure state
//static bool simpleBLEProcedureInProgress[MAX_PERIPHERAL_NUM] = FALSE;
// amomcu 把上面屏蔽的这些参数放到一个结构体中去, 方便我们做1主3从的连接控制, 相当于每一个连接有一组自己的参数, 若是初学者, 可以好好体会一下这种写法
typedef struct
{
// Connection handle of current connection
uint16 simpleBLEConnHandle; // = {GAP_CONNHANDLE_INIT}; // 连接上后的handle值, 用于对该设备的操作, 这是个源头, 根据这个handle 可以得到很多你需要的参数
uint8 simpleBLEDevIdx; //设备下标 0xff 我无效值
// Application state
uint8 simpleBLEState; // = {BLE_STATE_IDLE}; // 连接状态, 比如空闲、连接中、已连接、连接断开等
// Discovery state
uint8 simpleBLEDiscState; // = {BLE_DISC_STATE_IDLE}; // 发现状态,
// Discovered service start and end handle
uint16 simpleBLESvcStartHdl;// = 0; // 服务的开始handle
uint16 simpleBLESvcEndHdl;// = 0; // 服务的结束handle
// Discovered characteristic handle
uint16 simpleBLECharHdl[MAX_CHAR_NUM];// = {0}; // 特征值handle, 用于读写数据
// Value to write
uint8 simpleBLECharVal;// = 0; // 用于写数据
uint8 simpleBLERssi;// = FALSE; // 是否查询 rssi 值, 这个查询必须是在连接从机之后才可以查询
// Value read/write toggle
bool simpleBLEDoWrite;// = FALSE; // 是否在可写数据, 否则就可以读数据
// GATT read/write procedure state
bool simpleBLEProcedureInProgress;//[MAX_PERIPHERAL_NUM] = FALSE; // 是否正在操作中
int8 rssi;//rssi 信号值
bool updateFlag; // 参数更新
}BLE_DEV;
// 用于 对上面的 BLE_DEV 这个结构体的初始化,
const BLE_DEV gDevInitValue =
{
// Connection handle of current connection
/*int16 simpleBLEConnHandle; // = {GAP_CONNHANDLE_INIT};*/ GAP_CONNHANDLE_INIT,
0xff, // uint8 simpleBLEDevIdx; //设备下标 0xff 我无效值
// Application state
/*nt8 simpleBLEState; // = {BLE_STATE_IDLE};*/ BLE_STATE_IDLE,
// Discovery state
/*nt8 simpleBLEDiscState; // = {BLE_DISC_STATE_IDLE};*/ BLE_DISC_STATE_IDLE,
// Discovered service start and end handle
0,//uint16 simpleBLESvcStartHdl = 0;
0,//uint16 simpleBLESvcEndHdl = 0;
// Discovered characteristic handle
{0, 0, 0, 0, 0, 0},//uint16 simpleBLECharHdl[2];// = {0};
// Value to write
0,//uint8 simpleBLECharVal = 0;
FALSE,//uint8 simpleBLERssi;// = FALSE; // 是否查询 rssi 值, 这个查询必须是在连接从机之后才可以查询
// Value read/write toggle
TRUE,//FALSE,//bool simpleBLEDoWrite = FALSE;
// GATT read/write procedure state
FALSE,//bool simpleBLEProcedureInProgress;//[MAX_PERIPHERAL_NUM] = FALSE;
0,//rssi 信号值
FALSE,// bool updateFlag; // 参数更新
};
static BLE_DEV gDev[MAX_PERIPHERAL_NUM] = {0}; //定义每一个从机连接数组
/*********************************************************************
* LOCAL FUNCTIONS
*/
static void simpleBLECentralProcessGATTMsg( gattMsgEvent_t *pMsg );
static void simpleBLECentralRssiCB( uint16 connHandle, int8 rssi );
static void simpleBLECentralEventCB( gapCentralRoleEvent_t *pEvent );
static void simpleBLECentralPasscodeCB( uint8 *deviceAddr, uint16 connectionHandle,
uint8 uiInputs, uint8 uiOutputs );
static void simpleBLECentralPairStateCB( uint16 connHandle, uint8 state, uint8 status );
static void simpleBLECentral_HandleKeys( uint8 shift, uint8 keys );
static void simpleBLECentral_ProcessOSALMsg( osal_event_hdr_t *pMsg );
static void simpleBLEGATTDiscoveryEvent( gattMsgEvent_t *pMsg );
static void simpleBLECentralStartDiscovery( void );
static bool simpleBLEFindSvcUuid( uint16 uuid, uint8 *pData, uint8 dataLen );
static void simpleBLEAddDeviceInfo( uint8 *pAddr, uint8 addrType );
static BLE_DEV *simpleBLECentralGetDev(uint16 connHandle);
char *bdAddr2Str ( uint8 *pAddr );
static void performPeriodicTask( void ); // 用于发送数据
static void performPeriodicTask_AutoConnect( void ); // 执行动连接
/*********************************************************************
* PROFILE CALLBACKS
*/
// GAP Role Callbacks
static const gapCentralRoleCB_t simpleBLERoleCB =
{
simpleBLECentralRssiCB, // RSSI callback
simpleBLECentralEventCB // Event callback
};
// Bond Manager Callbacks
static const gapBondCBs_t simpleBLEBondCB =
{
simpleBLECentralPasscodeCB,
simpleBLECentralPairStateCB
};
void DLY_ms(unsigned int ms)
{
unsigned int a;
while(ms)
{
a=1800;
while(a--);
ms--;
}
}
/*********************************************************************
* PUBLIC FUNCTIONS
*/
/*********************************************************************
* @fn SimpleBLECentral_Init
*
* @brief Initialization function for the Simple BLE Central App Task.
* This is called during initialization and should contain
* any application specific initialization (ie. hardware
* initialization/setup, table initialization, power up
* notification).
*
* @param task_id - the ID assigned by OSAL. This ID should be
* used to send messages and set timers.
*
* @return none
*/
void SimpleBLECentral_Init( uint8 task_id )
{
simpleBLETaskId = task_id;
//串口初始化
//NPI_InitTransport(NpiSerialCallback);
NPI_InitTransport(NULL);
// 初始化结构体
for(int i = 0; i < MAX_PERIPHERAL_NUM; i++)
{
osal_memcpy(&(gDev[i]), &gDevInitValue, sizeof(BLE_DEV));
}
// Setup Central Profile
{
uint8 scanRes = DEFAULT_MAX_SCAN_RES;
GAPCentralRole_SetParameter ( GAPCENTRALROLE_MAX_SCAN_RES, sizeof( uint8 ), &scanRes );
}
// Setup GAP
GAP_SetParamValue( TGAP_GEN_DISC_SCAN, DEFAULT_SCAN_DURATION );
GAP_SetParamValue( TGAP_LIM_DISC_SCAN, DEFAULT_SCAN_DURATION );
GGS_SetParameter( GGS_DEVICE_NAME_ATT, GAP_DEVICE_NAME_LEN, (uint8 *) simpleBLEDeviceName );
// Setup the GAP Bond Manager
{
uint32 passkey = DEFAULT_PASSCODE;
uint8 pairMode = DEFAULT_PAIRING_MODE;
uint8 mitm = DEFAULT_MITM_MODE;
uint8 ioCap = DEFAULT_IO_CAPABILITIES;
uint8 bonding = DEFAULT_BONDING_MODE;
GAPBondMgr_SetParameter( GAPBOND_DEFAULT_PASSCODE, sizeof( uint32 ), &passkey );
GAPBondMgr_SetParameter( GAPBOND_PAIRING_MODE, sizeof( uint8 ), &pairMode );
GAPBondMgr_SetParameter( GAPBOND_MITM_PROTECTION, sizeof( uint8 ), &mitm );
GAPBondMgr_SetParameter( GAPBOND_IO_CAPABILITIES, sizeof( uint8 ), &ioCap );
GAPBondMgr_SetParameter( GAPBOND_BONDING_ENABLED, sizeof( uint8 ), &bonding );
}
// Initialize GATT Client
VOID GATT_InitClient();
// Register to receive incoming ATT Indications/Notifications
GATT_RegisterForInd( simpleBLETaskId );
// Initialize GATT attributes
GGS_AddService( GATT_ALL_SERVICES ); // GAP
GATTServApp_AddService( GATT_ALL_SERVICES ); // GATT attributes
// Register for all key events - This app will handle all key events
RegisterForKeys( simpleBLETaskId );
// makes sure LEDs are off
HalLedSet( (HAL_LED_1 | HAL_LED_2), HAL_LED_MODE_OFF );
// Setup a delayed profile startup
osal_set_event( simpleBLETaskId, START_DEVICE_EVT );
NPI_PrintString("Ready to Starting\r\n");
}
/*********************************************************************
* @fn SimpleBLECentral_ProcessEvent
*
* @brief Simple BLE Central Application Task event processor. This function
* is called to process all events for the task. Events
* include timers, messages and any other user defined events.
*
* @param task_id - The OSAL assigned task ID.
* @param events - events to process. This is a bit map and can
* contain more than one event.
*
* @return events not processed
*/
uint16 SimpleBLECentral_ProcessEvent( uint8 task_id, uint16 events )
{
VOID task_id; // OSAL required parameter that isn't used in this function
if ( events & SYS_EVENT_MSG )// 系统事件
{
uint8 *pMsg;
if ( (pMsg = osal_msg_receive( simpleBLETaskId )) != NULL )
{
simpleBLECentral_ProcessOSALMsg( (osal_event_hdr_t *)pMsg );
// Release the OSAL message
VOID osal_msg_deallocate( pMsg );
}
// return unprocessed events
return (events ^ SYS_EVENT_MSG);
}
if ( events & START_DEVICE_EVT )// 初始化后就执行这个啦
{
// Start the Device
VOID GAPCentralRole_StartDevice( (gapCentralRoleCB_t *) &simpleBLERoleCB );
// Register with bond manager after starting device
GAPBondMgr_Register( (gapBondCBs_t *) &simpleBLEBondCB );
LCD_WRITE_STRING("Key S1 = Scan device", HAL_LCD_LINE_8);
//osal_start_timerEx( simpleBLETaskId, SBP_PERIODIC_EVT, SBP_PERIODIC_EVT_PERIOD );
return ( events ^ START_DEVICE_EVT );
}
/*
if ( events & SBP_PERIODIC_EVT )
{
// Restart timer
if ( SBP_PERIODIC_EVT_PERIOD )
{
osal_start_timerEx( simpleBLETaskId, SBP_PERIODIC_EVT, SBP_PERIODIC_EVT_PERIOD );
}
// Perform periodic application task
//performPeriodicTask(); //用于发送数据
return (events ^ SBP_PERIODIC_EVT);
}
*/
/*
if ( events & SBP_AUTO_CONNECT_EVT )
{
// 以下都是处理用户按下 CENTER 按键后自动连接每一个扫描到的从机的控制
if ( simpleBLEScanRes > 0
&& simpleBLEScanIdx < simpleBLEScanRes )
{
simpleBLEScanIdx++;
if(simpleBLEScanIdx == simpleBLEScanRes)
{
simpleBLEScanIdx = 0;
}
else
{
performPeriodicTask_AutoConnect(); // 执行动连接
osal_start_timerEx( simpleBLETaskId, SBP_AUTO_CONNECT_EVT, SBP_PERIODIC_EVT_AUTO_CONNECT );
if(simpleBLEScanIdx == 1)
HalLedBlink (HAL_LED_2, 1, 50, 1000);//这个的意思是, 1000ms内,以50%的占空比闪烁1次, 实际就是点亮50ms
else if(simpleBLEScanIdx == 2)
HalLedBlink (HAL_LED_2, 1, 50, 1000);//这个的意思是, 1000ms内,以50%的占空比闪烁1次, 实际就是点亮50ms
}
}
return (events ^ SBP_AUTO_CONNECT_EVT);
}
*/
if ( events & START_DISCOVERY_EVT )
{
simpleBLECentralStartDiscovery( );//寻找特征值 handle
return ( events ^ START_DISCOVERY_EVT );
}
// Discard unknown events
return 0;
}
/*********************************************************************
* @fn simpleBLECentral_ProcessOSALMsg
*
* @brief Process an incoming task message.
*
* @param pMsg - message to process
*
* @return none
*/
static void simpleBLECentral_ProcessOSALMsg( osal_event_hdr_t *pMsg )
{
switch ( pMsg->event )
{
case KEY_CHANGE:// 按键事件
simpleBLECentral_HandleKeys( ((keyChange_t *)pMsg)->state, ((keyChange_t *)pMsg)->keys );
break;
case GATT_MSG_EVENT:// GATT 事件, 比如收到数据, 发送数据后的回应, 都在这个函数里执行
simpleBLECentralProcessGATTMsg( (gattMsgEvent_t *) pMsg );
break;
}
}
/*********************************************************************
* @fn simpleBLECentral_HandleKeys
*
* @brief Handles all key events for this device.
*
* @param shift - true if in shift/alt.
* @param keys - bit field for key events. Valid entries:
* HAL_KEY_SW_2
* HAL_KEY_SW_1
*
* @return none
*/
uint8 gStatus;
// 发送特征值 的函数
/*
uint8 index, 从机标 0, 1, 2 等
uint8 charIdx, 特征值索引 CHAR1~CHAR7
uint8 value[20], 要发送的数据 buffer,
uint8 valueLen 要发送的数据长度, 要注意 CHAR1~CHAR4 都是只有一个字节的,
CHAR5是5个字节, CHAR6是19个字节
*/
void OneConnetedDevice_WriteCharX(uint8 index, uint8 charIdx, uint8 value[20], uint8 valueLen)
{
BLE_DEV *p = &(gDev[index]);
if ( p->simpleBLEState == BLE_STATE_CONNECTED &&
p->simpleBLECharHdl[charIdx] != 0 &&
/*p->simpleBLEProcedureInProgress == FALSE &&*/
p->simpleBLEConnHandle != GAP_CONNHANDLE_INIT)
{
uint8 status;
// Do a read or write as long as no other read or write is in progress
if ( p->simpleBLEDoWrite )
{
// Do a write
attWriteReq_t req;
req.handle = p->simpleBLECharHdl[charIdx];
req.len = valueLen;
//req.value[0] = value;//p->simpleBLECharVal;
osal_memcpy(req.value, value, valueLen);
req.sig = 0;
req.cmd = 0;
//NPI_PrintValue("DoWrite :", p->simpleBLECharVal, 10);
status = GATT_WriteCharValue( p->simpleBLEConnHandle, &req, simpleBLETaskId ); // 发送数据
if(SUCCESS != status)
{
NPI_PrintValue("Write Error :", status, 10);
}
}
else// 以下是读取数据的 函数, 我们没用到, 你加上去就ok
{
// Do a read
attReadReq_t req;
req.handle = p->simpleBLECharHdl[charIdx];
NPI_PrintValue("DoRead :", req.handle, 10);
status = GATT_ReadCharValue( p->simpleBLEConnHandle, &req, simpleBLETaskId );
}
p->simpleBLEProcedureInProgress = TRUE;
// 请注意, 把以下这一句打开, 那么就会执行读数据了, 后面会执行写一次数据, 然后读一次数据
//p->simpleBLEDoWrite = !(p->simpleBLEDoWrite);
}
}
// 按键处理
static void simpleBLECentral_HandleKeys( uint8 shift, uint8 keys )
{
(void)shift; // Intentionally unreferenced parameter
// smartRF开发板上的 S1 对应源码上的 HAL_KEY_SW_6
//S1对应扫描设备的作用
if ( keys & HAL_KEY_SW_6 )
{
// Start or stop discovery
NPI_PrintString(" [KEY S1 pressed!]\r\n");
//if (connectedPeripheralNum < MAX_PERIPHERAL_NUM)
if(flag==0)
{
if ( !simpleBLEScanning )//不在扫描中则进行扫描
{
simpleBLEScanning = TRUE;
simpleBLEScanRes = 0;
LCD_WRITE_STRING( "Discovering...", HAL_LCD_LINE_1 );
LCD_WRITE_STRING( "", HAL_LCD_LINE_2 );
LCD_WRITE_STRING( "", HAL_LCD_LINE_3 );
LCD_WRITE_STRING( "", HAL_LCD_LINE_4 );
GAPCentralRole_StartDiscovery( DEFAULT_DISCOVERY_MODE,
DEFAULT_DISCOVERY_ACTIVE_SCAN,
DEFAULT_DISCOVERY_WHITE_LIST );
}
else // 如果在扫描中,则停止扫描, 这个时候会返回已扫描到的设备
{
GAPCentralRole_CancelDiscovery();
}
flag=1;
}
else{
//自动连接从机
LCD_WRITE_STRING("Connecting......", HAL_LCD_LINE_8);
simpleBLEUpdateCnt = 0;
simpleBLESendValue = 0;
simpleBLEScanIdx = 0;
performPeriodicTask_AutoConnect(); // 执行动连接
osal_start_timerEx( simpleBLETaskId, SBP_AUTO_CONNECT_EVT, SBP_PERIODIC_EVT_AUTO_CONNECT );
HalLedBlink (HAL_LED_1, 1, 50, 1000);//这个的意思是, 1000ms内,以50%的占空比闪烁1次, 实际就是点亮50ms
flag=0;
}
}
if ( keys & HAL_KEY_UP )
{
simpleBLESendValue = 0;
OneConnetedDevice_WriteCharX(simpleBLEScanIdx, BLE_CHAR1, &simpleBLESendValue, 1);
// 发送的数据同样显示在显示屏上
sprintf(str, "Char1: %d", simpleBLESendValue);
HalLcdWriteString(str, HAL_LCD_LINE_6 );
HalLedSet(HAL_LED_1,HAL_LED_MODE_ON);
//HalLedBlink (HAL_LED_1, 1, 50, 1000);
}
if ( keys & HAL_KEY_DOWN )
{
simpleBLESendValue = 1;
OneConnetedDevice_WriteCharX(0, BLE_CHAR1, &simpleBLESendValue, 1);
// 发送的数据同样显示在显示屏上
sprintf(str, "Char1: %d", simpleBLESendValue);
HalLcdWriteString(str, HAL_LCD_LINE_6 );
HalLedSet(HAL_LED_2,HAL_LED_MODE_ON);
//HalLedBlink (HAL_LED_2, 1, 50, 1000);
}
if ( keys & HAL_KEY_LEFT )
{
simpleBLESendValue = 2;
OneConnetedDevice_WriteCharX(0, BLE_CHAR1, &simpleBLESendValue, 1);
// 发送的数据同样显示在显示屏上
sprintf(str, "Char1: %d", simpleBLESendValue);
HalLcdWriteString(str, HAL_LCD_LINE_6 );
HalLedSet(HAL_LED_3,HAL_LED_MODE_ON);
//HalLedBlink (HAL_LED_3, 1, 50, 1000);
}
if ( keys & HAL_KEY_RIGHT )
{
simpleBLESendValue = 3;
OneConnetedDevice_WriteCharX(0, BLE_CHAR1, &simpleBLESendValue, 1);
// 发送的数据同样显示在显示屏上
sprintf(str, "Char1: %d", simpleBLESendValue);
HalLcdWriteString(str, HAL_LCD_LINE_6 );
HalLedSet(HAL_LED_3,HAL_LED_MODE_ON);
//HalLedBlink (HAL_LED_4, 1, 50, 1000);
}
/*之前调试用
if ( keys & HAL_KEY_LEFT )
{
char str[32] = {0};
//串口传数据
sprintf(str, "Sent CHAR to PHER.");
HalLcdWriteString(str, HAL_LCD_LINE_5 );
simpleBLEScanIdx = 0;
// 是否启动定时器发送数据 启动就的话取消注释
osal_start_timerEx( simpleBLETaskId, SBP_PERIODIC_EVT, SBP_PERIODIC_EVT_PERIOD );// 关键
LCD_WRITE_STRING("Key DOWN = Read RSSI", HAL_LCD_LINE_8);
NPI_PrintString(" [KEY LEFT pressed!]\r\n");
// Display discovery results
if ( !simpleBLEScanning && simpleBLEScanRes > 0 )
{
// Increment index of current result (with wraparound)
simpleBLEScanIdx++;
if ( simpleBLEScanIdx >= simpleBLEScanRes )
{
simpleBLEScanIdx = 0;
}
// 显示当前设备号
LCD_WRITE_STRING_VALUE( "Device", simpleBLEScanIdx + 1,
10, HAL_LCD_LINE_1 );
LCD_WRITE_STRING( bdAddr2Str( simpleBLEDevList[simpleBLEScanIdx].addr ),
HAL_LCD_LINE_2 );
if(gDev[simpleBLEScanIdx].simpleBLEState == BLE_STATE_CONNECTED)
{
LCD_WRITE_STRING( "State: Connected", HAL_LCD_LINE_3 );
}
else
{
LCD_WRITE_STRING( "State: UnConnect", HAL_LCD_LINE_3 );
}
}
}
if ( keys & HAL_KEY_RIGHT )
{
BLE_DEV *p = &(gDev[simpleBLEScanIdx]);
NPI_PrintString(" [KEY RIGHT pressed!]\r\n");
// Connection update
if ( p->simpleBLEState == BLE_STATE_CONNECTED )
{
// 更新参数
GAPCentralRole_UpdateLink( p->simpleBLEConnHandle,
DEFAULT_UPDATE_MIN_CONN_INTERVAL,
DEFAULT_UPDATE_MAX_CONN_INTERVAL,
DEFAULT_UPDATE_SLAVE_LATENCY,
DEFAULT_UPDATE_CONN_TIMEOUT );
}
}
*/
if ( keys & HAL_KEY_CENTER )
{
simpleBLESendValue = 7;
OneConnetedDevice_WriteCharX(0, BLE_CHAR1, &simpleBLESendValue, 1);
// 发送的数据同样显示在显示屏上
sprintf(str, "Char1: %d", simpleBLESendValue);
HalLcdWriteString(str, HAL_LCD_LINE_6 );
//发送发射数据的时候led闪烁4次
HalLedBlink(HAL_LED_1|HAL_LED_2|HAL_LED_3,3,50,100);
}
if ( keys == HAL_KEY_STATE_NORMAL ) //中间按键
{
simpleBLESendValue = 6;
OneConnetedDevice_WriteCharX(0, BLE_CHAR1, &simpleBLESendValue, 1);
// 发送的数据同样显示在显示屏上
sprintf(str, "Char1: %d", simpleBLESendValue);
HalLcdWriteString(str, HAL_LCD_LINE_6 );
HalLedSet(HAL_LED_1|HAL_LED_2|HAL_LED_3,HAL_LED_MODE_OFF);
//HalLedBlink (HAL_LED_4, 1, 50, 1000);
/*先前调试用于连接从机使用
#if 1// 连续自动连接已扫描到的从机
LCD_WRITE_STRING("Connecting......", HAL_LCD_LINE_8);
simpleBLEUpdateCnt = 0;
simpleBLESendValue = 0;
simpleBLEScanIdx = 0;
performPeriodicTask_AutoConnect(); // 执行动连接
osal_start_timerEx( simpleBLETaskId, SBP_AUTO_CONNECT_EVT, SBP_PERIODIC_EVT_AUTO_CONNECT );
HalLedBlink (HAL_LED_1, 1, 50, 1000);//这个的意思是, 1000ms内,以50%的占空比闪烁1次, 实际就是点亮50ms
#else
uint8 addrType;
uint8 *peerAddr;
BLE_DEV *p = &(gDev[simpleBLEScanIdx]);
NPI_PrintString(" [KEY_CENTER]\r\n");
NPI_PrintValue("Idx=", simpleBLEScanIdx, 10);
NPI_PrintValue("State=", p->simpleBLEState, 10);
NPI_PrintValue("num=", connectedPeripheralNum, 10);
NPI_PrintValue("res=", simpleBLEScanRes, 10);
// Connect or disconnect
//if ( p->simpleBLEState == BLE_STATE_IDLE
// || connectedPeripheralNum < MAX_PERIPHERAL_NUM)
if ( p->simpleBLEState == BLE_STATE_IDLE )
{
// if there is a scan result
if ( simpleBLEScanRes > 0
&& simpleBLEScanIdx < simpleBLEScanRes )
{
// connect to current device in scan result
peerAddr = simpleBLEDevList[simpleBLEScanIdx].addr;
addrType = simpleBLEDevList[simpleBLEScanIdx].addrType;
p->simpleBLEState = BLE_STATE_CONNECTING;
//osal_pwrmgr_device( PWRMGR_ALWAYS_ON );
GAPCentralRole_EstablishLink( DEFAULT_LINK_HIGH_DUTY_CYCLE,
DEFAULT_LINK_WHITE_LIST,
addrType, peerAddr );
LCD_WRITE_STRING( "Connecting", HAL_LCD_LINE_1 );
LCD_WRITE_STRING( bdAddr2Str( peerAddr ), HAL_LCD_LINE_2 );
}
}
else if ( p->simpleBLEState == BLE_STATE_CONNECTING ||
p->simpleBLEState == BLE_STATE_CONNECTED ||
p->simpleBLEState == BLE_STATE_DISCONNECTING)
{
// disconnect
p->simpleBLEState = BLE_STATE_DISCONNECTING;
gStatus = GAPCentralRole_TerminateLink( p->simpleBLEConnHandle );
LCD_WRITE_STRING( "Disconnecting", HAL_LCD_LINE_1 );
}
#endif
*/
}
/*
if ( keys & HAL_KEY_DOWN )
{
NPI_PrintString(" [KEY_CENTER pressed!]\r\n");
// 注意我们下面是使能 所有设备的rssi 读取, 如果你只需要读取其中一个rssi的, 把这个循环去掉, 并指定从机号即可
for(int i = 0; i < simpleBLEScanRes; i++)
{
BLE_DEV *p = &(gDev[i]);
// Start or cancel RSSI polling
if ( p->simpleBLEState == BLE_STATE_CONNECTED )
{
if ( !p->simpleBLERssi )
{
p->simpleBLERssi = TRUE;
GAPCentralRole_StartRssi( p->simpleBLEConnHandle, DEFAULT_RSSI_PERIOD );// 关键
LCD_WRITE_STRING("Key DOWN = Cancel RSSI", HAL_LCD_LINE_8);
}
else
{
p->simpleBLERssi = FALSE;
GAPCentralRole_CancelRssi( p->simpleBLEConnHandle );// 关键
LCD_WRITE_STRING( "RSSI Cancelled", HAL_LCD_LINE_1 );
LCD_WRITE_STRING("Key DOWN = Read RSSI", HAL_LCD_LINE_8);
}
}
}
}
*/
// smartRF开发板上的 S1 对应源码上的HAL_KEY_SW_6
/*
if ( keys & HAL_KEY_SW_6 )
{
char str[32] = {0};
sprintf(str, "Sent CHAR to PHER.");
HalLcdWriteString(str, HAL_LCD_LINE_5 );
simpleBLEScanIdx = 0;
// 是否启动定时器发送数据 启动就的话取消注释
osal_start_timerEx( simpleBLETaskId, SBP_PERIODIC_EVT, SBP_PERIODIC_EVT_PERIOD );// 关键
LCD_WRITE_STRING("Key DOWN = Read RSSI", HAL_LCD_LINE_8);
}
*/
}
/*********************************************************************
* @fn simpleBLECentralProcessGATTMsg
*
* @brief Process GATT messages
*
* @return none
*/
// 寻找当前的 connHandle (已连接的从机句柄) 对应的设备结构地址
static BLE_DEV *simpleBLECentralGetDev(uint16 connHandle)
{
for(int i = 0; i < MAX_PERIPHERAL_NUM; i++)
{
if(connHandle == gDev[i].simpleBLEConnHandle)
return &(gDev[i]);
}
return NULL;
}
static void simpleBLECentralProcessGATTMsg( gattMsgEvent_t *pMsg )
{
BLE_DEV *p = simpleBLECentralGetDev(pMsg->connHandle);
if(p == NULL)//未找到相应的connHandle (已连接的从机句柄) 对应的设备结构地址
{
NPI_PrintValue("ERROR line=", __LINE__, 10);
return;
}
if ( p->simpleBLEState != BLE_STATE_CONNECTED )
{
// In case a GATT message came after a connection has dropped,
// ignore the message
return;
}
if ( ( pMsg->method == ATT_READ_RSP ) ||
( ( pMsg->method == ATT_ERROR_RSP ) &&
( pMsg->msg.errorRsp.reqOpcode == ATT_READ_REQ ) ) )
{
if ( pMsg->method == ATT_ERROR_RSP )
{
uint8 status = pMsg->msg.errorRsp.errCode;
LCD_WRITE_STRING_VALUE( "Read Error", status, 10, HAL_LCD_LINE_1 );
}
else
{
// After a successful read, display the read value
uint8 valueRead = pMsg->msg.readRsp.value[0];
LCD_WRITE_STRING_VALUE( "Read rsp:", valueRead, 10, HAL_LCD_LINE_1 );
}
p->simpleBLEProcedureInProgress = FALSE;
}
else if ( ( pMsg->method == ATT_WRITE_RSP ) ||
( ( pMsg->method == ATT_ERROR_RSP ) &&
( pMsg->msg.errorRsp.reqOpcode == ATT_WRITE_REQ ) ) )
{
if ( pMsg->method == ATT_ERROR_RSP == ATT_ERROR_RSP )
{
uint8 status = pMsg->msg.errorRsp.errCode;
LCD_WRITE_STRING_VALUE( "Write Error", status, 10, HAL_LCD_LINE_1 );
}
else
{
//写成功后的显示
// After a succesful write, display the value that was written and increment value
//LCD_WRITE_STRING_VALUE( "Write sent:", (p->simpleBLECharVal)++, 10, HAL_LCD_LINE_1 );
LCD_WRITE_STRING_VALUE( "Write sent:", simpleBLESendValue, 10, HAL_LCD_LINE_1 );
}
p->simpleBLEProcedureInProgress = FALSE;
}