-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathxplr_bluetooth.c
1609 lines (1449 loc) · 57.5 KB
/
xplr_bluetooth.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
/*
* Copyright 2019-2022 u-blox
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* Only #includes of u_* and the C standard library are allowed here,
* no platform stuff and no OS stuff. Anything required from
* the platform/OS must be brought in through u_port* to maintain
* portability.
*/
#include "./../../xplr_hpglib_cfg.h"
#if XPLRBLUETOOTH_MODE != XPLRBLUETOOTH_MODE_OFF
#include "xplr_bluetooth.h"
#include "xplr_bluetooth_types.h"
#include <string.h>
#include "freertos/ringbuf.h"
#if XPLRBLUETOOTH_MODE == XPLRBLUETOOTH_MODE_BT_CLASSIC
#include "esp_bt.h"
#include "esp_bt_main.h"
#include "esp_gap_bt_api.h"
#include "esp_bt_device.h"
#include "esp_spp_api.h"
#elif XPLRBLUETOOTH_MODE == XPLRBLUETOOTH_MODE_BLE
#include "esp_nimble_hci.h"
#include "host/ble_hs.h"
#include "nimble/nimble_port.h"
#include "nimble/nimble_port_freertos.h"
#include "services/gap/ble_svc_gap.h"
#include "services/gatt/ble_svc_gatt.h"
#else
#error "Wrong XPLR_BLUETOOTH mode"
#endif
/* ----------------------------------------------------------------
* COMPILE-TIME MACROS
* -------------------------------------------------------------- */
#if (1 == XPLRBLUETOOTH_DEBUG_ACTIVE) && (1 == XPLR_HPGLIB_SERIAL_DEBUG_ENABLED) && ((0 == XPLR_HPGLIB_LOG_ENABLED) || (0 == XPLRBLUETOOTH_LOG_ACTIVE))
#define XPLRBLUETOOTH_CONSOLE(tag, message, ...) XPLRLOG(logIndex, XPLR_LOG_PRINT_ONLY, XPLR_HPGLIB_LOG_FORMAT(tag, message), esp_log_timestamp(), "hpgBluetooth", __FUNCTION__, __LINE__, ##__VA_ARGS__)
#elif (1 == XPLRBLUETOOTH_DEBUG_ACTIVE) && (1 == XPLR_HPGLIB_SERIAL_DEBUG_ENABLED) && (1 == XPLR_HPGLIB_LOG_ENABLED) && (1 == XPLRBLUETOOTH_LOG_ACTIVE)
#define XPLRBLUETOOTH_CONSOLE(tag, message, ...) XPLRLOG(logIndex, XPLR_LOG_SD_AND_PRINT, XPLR_HPGLIB_LOG_FORMAT(tag, message), esp_log_timestamp(), "hpgBluetooth", __FUNCTION__, __LINE__, ##__VA_ARGS__)
#elif ((0 == XPLRBLUETOOTH_DEBUG_ACTIVE) || (0 == XPLR_HPGLIB_SERIAL_DEBUG_ENABLED)) && (1 == XPLR_HPGLIB_LOG_ENABLED) && (1 == XPLRBLUETOOTH_LOG_ACTIVE)
#define XPLRBLUETOOTH_CONSOLE(tag, message, ...) XPLRLOG(logIndex, XPLR_LOG_SD_ONLY, XPLR_HPGLIB_LOG_FORMAT(tag, message), esp_log_timestamp(), "hpgBluetooth", __FUNCTION__, __LINE__, ##__VA_ARGS__)
#else
#define XPLRBLUETOOTH_CONSOLE(message, ...) do{} while(0)
#endif
#define XPLR_BLUETOOTH_MAX_DELAY (TickType_t)pdMS_TO_TICKS(100)
/* ----------------------------------------------------------------
* STATIC TYPES
* -------------------------------------------------------------- */
/* ----------------------------------------------------------------
* STATIC VARIABLES
* -------------------------------------------------------------- */
static int8_t logIndex = -1;
xplrBluetooth_client_t *btClient;
SemaphoreHandle_t btSemaphore;
#if XPLRBLUETOOTH_MODE == XPLRBLUETOOTH_MODE_BLE
#if XPLRBLUETOOTH_BLE_CHARS == XPLRBLUETOOTH_BLE_NORDIC
// BLE UUIDs for Nordic UART Service (NUS)
static const ble_uuid128_t xplrBleServiceUuid = UUID128_CONST(0x6E400001,
0xB5A3,
0xF393,
0xE0A9,
0xE50E24DCCA9E);
static const ble_uuid128_t xplrBleCharRxUuid = UUID128_CONST(0x6E400002,
0xB5A3,
0xF393,
0xE0A9,
0xE50E24DCCA9E);
static const ble_uuid128_t xplrBleCharTxUuid = UUID128_CONST(0x6E400003,
0xB5A3,
0xF393,
0xE0A9,
0xE50E24DCCA9E);
#elif XPLRBLUETOOTH_BLE_CHARS == XPLRBLUETOOTH_BLE_CHARS_CUSTOM
// BLE UUIDs for custom Service
static const ble_uuid128_t xplrBleServiceUuid = UUID128_CONST(0x00000000,
0x0000,
0x0000,
0x0000,
0x000000000000);
static const ble_uuid128_t xplrBleCharRxUuid = UUID128_CONST(0x00000000,
0x0000,
0x0000,
0x0000,
0x000000000000);
static const ble_uuid128_t xplrBleCharTxUuid = UUID128_CONST(0x00000000,
0x0000,
0x0000,
0x0000,
0x000000000000);
#endif
// BLE address used for advertising
static uint8_t bleAddr;
// BLE attribute handle for notifying
static uint16_t bleNotifyCharAttrHandle;
#endif
/* ----------------------------------------------------------------
* STATIC FUNCTION PROTOTYPES
* -------------------------------------------------------------- */
static void btInitDeviceTable(void);
static void btDeInitDeviceTable(void);
static xplrBluetooth_error_t btInitDeviceBuffers(char *xplrBluetoothDeviceMessageBuffer,
size_t xplrBluetoothDeviceMessageBufferSize);
static void btRemoveDevice(uint32_t handle);
static uint8_t btGetNumOfConnectedDevices(void);
static void btSetAvailableMessage(uint32_t handle);
static int8_t btDeviceHandleToIndex(uint32_t handle);
static xplrBluetooth_connected_device_t *btDeviceHandleToDeviceStructHelper(uint32_t handle);
static void btCacheMsg(uint32_t handle, uint8_t *incomingMsg, uint32_t incomingMsgLen);
static void btPlaceMessageBackInBufferHelper(uint8_t items, uint8_t *writeBackBuffer);
static int32_t btRead(xplrBluetooth_connected_device_t **dvc, bool readFirstAvailableMsg);
static xplrBluetooth_connected_device_t *btReadFirstAvailableMsgHelper(uint8_t *message,
size_t messageSize,
int32_t *size,
bool *correctMsgRead);
static void btUpdateStateHelper(UBaseType_t *itemsRemainingInBuffer);
#if XPLRBLUETOOTH_MODE == XPLRBLUETOOTH_MODE_BT_CLASSIC
static xplrBluetooth_error_t btClassicInit(void);
static xplrBluetooth_error_t btClassicControllerInit(void);
static xplrBluetooth_error_t btClassicBluedroidInit(void);
static xplrBluetooth_error_t btClassicCbInit(void);
static xplrBluetooth_error_t btClassicDeInit(void);
static void btClassicDisconnectDevice(xplrBluetooth_connected_device_t *dvc);
static xplrBluetooth_error_t btClassicWrite(xplrBluetooth_connected_device_t *dvc,
char *msg,
uint32_t msgSize);
static void btClassicGAPcb(esp_bt_gap_cb_event_t event, esp_bt_gap_cb_param_t *param);
static void BtClassicSPPcb(esp_spp_cb_event_t event, esp_spp_cb_param_t *param);
static void btClassicDiagnostics(uint32_t handle, bool disconnected);
static void btClassicAddDevice(uint32_t handle, esp_bd_addr_t address);
static int8_t btClassicDeviceAddressToIndex(esp_bd_addr_t address);
#elif XPLRBLUETOOTH_MODE == XPLRBLUETOOTH_MODE_BLE
static xplrBluetooth_error_t bleInit(void);
static xplrBluetooth_error_t bleDeInit(void);
static void bleDisconnectDevice(xplrBluetooth_connected_device_t *dvc);
static xplrBluetooth_error_t bleWrite(xplrBluetooth_connected_device_t *dvc, char *msg,
uint32_t msgSize);
static int bleReceiveMsgCb(uint16_t conn_handle,
uint16_t attr_handle,
struct ble_gatt_access_ctxt *ctxt,
void *arg);
static int bleDummyCb(uint16_t conn_handle,
uint16_t attr_handle,
struct ble_gatt_access_ctxt *ctxt,
void *arg);
static int bleGapEventCb(struct ble_gap_event *event, void *arg);
static void bleAppOnSyncCb(void);
static void bleAppAdvertise(void);
static void bleTask(void *param);
static void bleAddDevice(uint32_t handle, ble_addr_t address);
static void bleDiagnostics(uint32_t handle, bool disconnected);
#else
#error "Wrong XPLR_BLUETOOTH mode"
#endif
/* ----------------------------------------------------------------
* PUBLIC FUNCTION DEFINITIONS
* -------------------------------------------------------------- */
xplrBluetooth_error_t xplrBluetoothInit(xplrBluetooth_client_t *client,
SemaphoreHandle_t xplrBluetoothSemaphore,
char *xplrBluetoothDeviceMessageBuffer,
size_t xplrBluetoothDeviceMessageBufferSize)
{
xplrBluetooth_error_t ret;
btClient = client;
btSemaphore = xplrBluetoothSemaphore;
btClient->configuration.ringBuffer = xRingbufferCreateStatic(XPLRBLUETOOTH_RX_BUFFER_SIZE,
RINGBUF_TYPE_NOSPLIT,
btClient->buffer,
&(btClient->configuration.staticBufHandle));
if (btClient->configuration.ringBuffer == NULL) {
XPLRBLUETOOTH_CONSOLE(E, "Failed to create ring buffer");
ret = XPLR_BLUETOOTH_ERROR;
} else {
btInitDeviceTable();
ret = btInitDeviceBuffers(xplrBluetoothDeviceMessageBuffer, xplrBluetoothDeviceMessageBufferSize);
if (ret != XPLR_BLUETOOTH_ERROR) {
#if (XPLRBLUETOOTH_MODE == XPLRBLUETOOTH_MODE_BT_CLASSIC)
ret = btClassicInit();
#elif (XPLRBLUETOOTH_MODE == XPLRBLUETOOTH_MODE_BLE)
ret = bleInit();
#else
#error "hpglib Bluetooth module not configured correctly"
ret = XPLR_BLUETOOTH_ERROR;
#endif
} else {
// Do nothing
}
}
return ret;
}
xplrBluetooth_error_t xplrBluetoothDeInit(void)
{
xplrBluetooth_error_t ret;
BaseType_t semaphoreRet;
xplrBluetoothDisconnectAllDevices();
#if (XPLRBLUETOOTH_MODE == XPLRBLUETOOTH_MODE_BT_CLASSIC)
ret = btClassicDeInit();
#elif (XPLRBLUETOOTH_MODE == XPLRBLUETOOTH_MODE_BLE)
ret = bleDeInit();
#else
#error "hpglib Bluetooth module not configured correctly"
ret = XPLR_BLUETOOTH_ERROR;
#endif
btDeInitDeviceTable();
semaphoreRet = xSemaphoreTake(btSemaphore, XPLR_BLUETOOTH_MAX_DELAY);
if (semaphoreRet == pdTRUE) {
vRingbufferDelete(btClient->configuration.ringBuffer);
xSemaphoreGive(btSemaphore);
} else {
XPLRBLUETOOTH_CONSOLE(W, "Couldn't get semaphore");
}
return ret;
}
void xplrBluetoothDisconnectAllDevices(void)
{
int i;
BaseType_t semaphoreRet;
semaphoreRet = xSemaphoreTake(btSemaphore, XPLR_BLUETOOTH_MAX_DELAY);
if (semaphoreRet == pdTRUE) {
for (i = 0; i < XPLRBLUETOOTH_NUMOF_DEVICES; i++) {
if (btClient->devices[i].connected) {
#if (XPLRBLUETOOTH_MODE == XPLRBLUETOOTH_MODE_BT_CLASSIC)
btClassicDisconnectDevice(&btClient->devices[i]);
#elif (XPLRBLUETOOTH_MODE == XPLRBLUETOOTH_MODE_BLE)
bleDisconnectDevice(&btClient->devices[i]);
#else
#error "hpglib Bluetooth module not configured correctly"
#endif
} else {
// No need to disconnect
}
}
xSemaphoreGive(btSemaphore);
} else {
// Do nothing
}
}
void xplrBluetoothDisconnectDevice(xplrBluetooth_connected_device_t *dvc)
{
BaseType_t semaphoreRet;
semaphoreRet = xSemaphoreTake(btSemaphore, XPLR_BLUETOOTH_MAX_DELAY);
if (semaphoreRet == pdTRUE) {
#if (XPLRBLUETOOTH_MODE == XPLRBLUETOOTH_MODE_BT_CLASSIC)
btClassicDisconnectDevice(dvc);
#elif (XPLRBLUETOOTH_MODE == XPLRBLUETOOTH_MODE_BLE)
bleDisconnectDevice(dvc);
#else
#error "hpglib Bluetooth module not configured correctly"
#endif
xSemaphoreGive(btSemaphore);
} else {
// Do nothing
}
}
xplrBluetooth_conn_state_t xplrBluetoothGetState(void)
{
xplrBluetooth_conn_state_t ret;
BaseType_t semaphoreRet;
semaphoreRet = xSemaphoreTake(btSemaphore, XPLR_BLUETOOTH_MAX_DELAY);
if (semaphoreRet == pdTRUE) {
ret = btClient->state;
xSemaphoreGive(btSemaphore);
} else {
// BUSY state is only returned here and it signals that some other task
// is accessing the btClient struct
ret = XPLR_BLUETOOTH_CONN_STATE_BUSY;
}
return ret;
}
int32_t xplrBluetoothRead(xplrBluetooth_connected_device_t *dvc)
{
int32_t ret = btRead(&dvc, false);
return ret;
}
int32_t xplrBluetoothReadFirstAvailableMsg(xplrBluetooth_connected_device_t **dvc)
{
int32_t ret = btRead(dvc, true);
return ret;
}
xplrBluetooth_error_t xplrBluetoothWrite(xplrBluetooth_connected_device_t *dvc,
char *msg,
size_t msgSize)
{
xplrBluetooth_error_t ret;
#if (XPLRBLUETOOTH_MODE == XPLRBLUETOOTH_MODE_BT_CLASSIC)
ret = btClassicWrite(dvc, msg, msgSize);
#elif (XPLRBLUETOOTH_MODE == XPLRBLUETOOTH_MODE_BLE)
ret = bleWrite(dvc, msg, msgSize);
#else
#error "hpglib Bluetooth module not configured correctly"
ret = XPLR_BLUETOOTH_ERROR;
#endif
return ret;
}
void xplrBluetoothPrintDiagnostics(xplrBluetooth_connected_device_t *dvc)
{
#if (XPLRBLUETOOTH_MODE == XPLRBLUETOOTH_MODE_BT_CLASSIC)
btClassicDiagnostics(dvc->handle, false);
#elif (XPLRBLUETOOTH_MODE == XPLRBLUETOOTH_MODE_BLE)
bleDiagnostics(dvc->handle, false);
#else
#error "hpglib Bluetooth module not configured correctly"
ret = XPLR_BLUETOOTH_ERROR;
#endif
}
xplrBluetooth_connected_device_t *xplrBluetoothPrintConnectedDevices(void)
{
uint8_t devices, i;
devices = btGetNumOfConnectedDevices();
XPLRBLUETOOTH_CONSOLE(I, "There are %d connected devices", devices);
for (i = 0; i < XPLRBLUETOOTH_NUMOF_DEVICES; i++) {
if (btClient->devices[i].connected == true) {
xplrBluetoothPrintDiagnostics(&btClient->devices[i]);
}
}
return btClient->devices;
}
int8_t xplrBluetoothInitLogModule(xplr_cfg_logInstance_t *logCfg)
{
int8_t ret;
xplrLog_error_t logErr;
if (logIndex < 0) {
/* logIndex is negative so logging has not been initialized before */
if (logCfg == NULL) {
/* logCfg is NULL so we will use the default module settings */
logIndex = xplrLogInit(XPLR_LOG_DEVICE_INFO,
XPLR_BLUETOOTH_DEFAULT_FILENAME,
XPLRLOG_FILE_SIZE_INTERVAL,
XPLRLOG_NEW_FILE_ON_BOOT);
} else {
/* logCfg contains the instance settings */
logIndex = xplrLogInit(XPLR_LOG_DEVICE_INFO,
logCfg->filename,
logCfg->sizeInterval,
logCfg->erasePrev);
}
ret = logIndex;
} else {
/* logIndex is positive so logging has been initialized before */
logErr = xplrLogEnable(logIndex);
if (logErr != XPLR_LOG_OK) {
ret = -1;
} else {
ret = logIndex;
}
}
return ret;
}
esp_err_t xplrBluetoothStopLogModule(void)
{
esp_err_t ret;
xplrLog_error_t logErr;
logErr = xplrLogDisable(logIndex);
if (logErr != XPLR_LOG_OK) {
ret = ESP_FAIL;
} else {
ret = ESP_OK;
}
return ret;
}
/* ----------------------------------------------------------------
* STATIC FUNCTION DEFINITIONS
* -------------------------------------------------------------- */
void btInitDeviceTable(void)
{
int i;
BaseType_t semaphoreRet;
semaphoreRet = xSemaphoreTake(btSemaphore, XPLR_BLUETOOTH_MAX_DELAY);
if (semaphoreRet == pdTRUE) {
for (i = 0; i < XPLRBLUETOOTH_NUMOF_DEVICES; i++) {
btClient->devices[i].handle = -999;
btClient->devices[i].connected = false;
btClient->devices[i].msgAvailable = false;
}
xSemaphoreGive(btSemaphore);
} else {
XPLRBLUETOOTH_CONSOLE(W, "Couldn't get semaphore");
}
}
void btDeInitDeviceTable(void)
{
int i;
BaseType_t semaphoreRet;
semaphoreRet = xSemaphoreTake(btSemaphore, XPLR_BLUETOOTH_MAX_DELAY);
if (semaphoreRet == pdTRUE) {
for (i = 0; i < XPLRBLUETOOTH_NUMOF_DEVICES; i++) {
btClient->devices[i].handle = -999;
btClient->devices[i].connected = false;
btClient->devices[i].msgAvailable = false;
}
xSemaphoreGive(btSemaphore);
} else {
XPLRBLUETOOTH_CONSOLE(W, "Couldn't get semaphore");
}
}
xplrBluetooth_error_t btInitDeviceBuffers(char *xplrBluetoothDeviceMessageBuffer,
size_t xplrBluetoothDeviceMessageBufferSize)
{
xplrBluetooth_error_t ret;
int i;
BaseType_t semaphoreRet;
semaphoreRet = xSemaphoreTake(btSemaphore, XPLR_BLUETOOTH_MAX_DELAY);
if (semaphoreRet == pdTRUE) {
if (xplrBluetoothDeviceMessageBufferSize < XPLRBLUETOOTH_MAX_MSG_SIZE *
XPLRBLUETOOTH_NUMOF_DEVICES) {
XPLRBLUETOOTH_CONSOLE(E, "Insufficient device buffer");
ret = XPLR_BLUETOOTH_ERROR;
} else {
for (i = 0; i < XPLRBLUETOOTH_NUMOF_DEVICES; i++) {
btClient->devices[i].msg = &(xplrBluetoothDeviceMessageBuffer[i * XPLRBLUETOOTH_MAX_MSG_SIZE]);
}
ret = XPLR_BLUETOOTH_OK;
}
xSemaphoreGive(btSemaphore);
} else {
XPLRBLUETOOTH_CONSOLE(W, "Couldn't get semaphore");
ret = XPLR_BLUETOOTH_ERROR;
}
return ret;
}
void btRemoveDevice(uint32_t handle)
{
uint8_t index, connectedDevices;
BaseType_t semaphoreRet;
// Find the device's index in the table
index = btDeviceHandleToIndex(handle);
// Mark device as disconnected
semaphoreRet = xSemaphoreTake(btSemaphore, XPLR_BLUETOOTH_MAX_DELAY);
if (semaphoreRet == pdTRUE) {
btClient->devices[index].connected = false;
xSemaphoreGive(btSemaphore);
} else {
XPLRBLUETOOTH_CONSOLE(W, "Couldn't get semaphore");
}
// Store the number of connected devices after the disconnection
connectedDevices = btGetNumOfConnectedDevices();
// If there is no connected device change the client's state
if (!connectedDevices) {
semaphoreRet = xSemaphoreTake(btSemaphore, XPLR_BLUETOOTH_MAX_DELAY);
if (semaphoreRet == pdTRUE) {
btClient->state = XPLR_BLUETOOTH_CONN_STATE_READY;
xSemaphoreGive(btSemaphore);
} else {
XPLRBLUETOOTH_CONSOLE(W, "Couldn't get semaphore");
}
} else {
// Do nothing
}
}
uint8_t btGetNumOfConnectedDevices(void)
{
uint8_t i;
uint8_t counter = 0;
BaseType_t semaphoreRet;
semaphoreRet = xSemaphoreTake(btSemaphore, XPLR_BLUETOOTH_MAX_DELAY);
if (semaphoreRet == pdTRUE) {
for (i = 0; i < XPLRBLUETOOTH_NUMOF_DEVICES; i++) {
if (btClient->devices[i].connected) {
counter++;
}
}
xSemaphoreGive(btSemaphore);
} else {
// Couldn't get semaphore
}
return counter;
}
void btSetAvailableMessage(uint32_t handle)
{
uint8_t i;
BaseType_t semaphoreRet;
semaphoreRet = xSemaphoreTake(btSemaphore, XPLR_BLUETOOTH_MAX_DELAY);
if (semaphoreRet == pdTRUE) {
for (i = 0; i < XPLRBLUETOOTH_NUMOF_DEVICES; i++) {
// Find the corresponding slot
if (btClient->devices[i].handle == handle && btClient->devices[i].connected) {
// If the device exists and is connected
btClient->devices[i].msgAvailable = true;
break;
}
}
btClient->state = XPLR_BLUETOOTH_CONN_STATE_MSG_AVAILABLE;
xSemaphoreGive(btSemaphore);
} else {
XPLRBLUETOOTH_CONSOLE(E, "Couldn't get semaphore");
}
}
int8_t btDeviceHandleToIndex(uint32_t handle)
{
uint8_t i;
int8_t ret = -1;
BaseType_t semaphoreRet;
semaphoreRet = xSemaphoreTake(btSemaphore, XPLR_BLUETOOTH_MAX_DELAY);
if (semaphoreRet == pdTRUE) {
for (i = 0; i < XPLRBLUETOOTH_NUMOF_DEVICES; i++) {
// Find the corresponding slot
if (btClient->devices[i].handle == handle && btClient->devices[i].connected) {
// If the device exists and is connected
ret = i;
break;
}
}
xSemaphoreGive(btSemaphore);
} else {
XPLRBLUETOOTH_CONSOLE(W, "Couldn't get semaphore");
}
if (ret == -1) {
XPLRBLUETOOTH_CONSOLE(E, "Cannot find device");
} else {
// Do nothing
}
return ret;
}
xplrBluetooth_connected_device_t *btDeviceHandleToDeviceStructHelper(uint32_t handle)
{
xplrBluetooth_connected_device_t *ret = &(btClient->devices[btDeviceHandleToIndex(handle)]);
return ret;
}
void btCacheMsg(uint32_t handle, uint8_t *message, size_t messageSize)
{
BaseType_t bufRet, semaphoreRet;
if (messageSize <= XPLRBLUETOOTH_MAX_MSG_SIZE) {
uint8_t buf[4 + messageSize];
// The first 4 bytes of every message are the device handle from which the message was received
memcpy(buf, &handle, 4);
memcpy(&buf[4], message, messageSize);
semaphoreRet = xSemaphoreTake(btSemaphore, XPLR_BLUETOOTH_MAX_DELAY);
if (semaphoreRet == pdTRUE) {
bufRet = xRingbufferSendFromISR(btClient->configuration.ringBuffer, buf, 4 + messageSize, NULL);
if (bufRet != pdTRUE) {
XPLRBLUETOOTH_CONSOLE(E, "Buffer full cannot store message");
btClient->state = XPLR_BLUETOOTH_CONN_STATE_RX_BUFFER_FULL;
} else {
btClient->state = XPLR_BLUETOOTH_CONN_STATE_MSG_AVAILABLE;
}
xSemaphoreGive(btSemaphore);
} else {
XPLRBLUETOOTH_CONSOLE(E, "Couldn't get semaphore");
}
} else {
XPLRBLUETOOTH_CONSOLE(E, "Message larger than configured max message size, discarding...");
}
}
void btPlaceMessageBackInBufferHelper(uint8_t items, uint8_t *writeBackBuffer)
{
uint8_t remainingItems = items;
size_t messageSize;
uint8_t *message = NULL;
BaseType_t bufRet;
BaseType_t semaphoreRet;
semaphoreRet = xSemaphoreTake(btSemaphore, XPLR_BLUETOOTH_MAX_DELAY);
if (semaphoreRet == pdTRUE) {
while (remainingItems > 0) {
message = xRingbufferReceiveFromISR(btClient->configuration.ringBuffer, &messageSize);
memcpy(writeBackBuffer, message, messageSize);
bufRet = xRingbufferSendFromISR(btClient->configuration.ringBuffer, writeBackBuffer, messageSize,
NULL);
if (bufRet != pdTRUE) {
XPLRBLUETOOTH_CONSOLE(E, "Buffer full cannot store message");
btClient->state = XPLR_BLUETOOTH_CONN_STATE_RX_BUFFER_FULL;
} else {
remainingItems--;
}
}
xSemaphoreGive(btSemaphore);
} else {
XPLRBLUETOOTH_CONSOLE(W, "Couldn't get semaphore");
}
}
int32_t btRead(xplrBluetooth_connected_device_t **dvc,
bool readFirstAvailableMsg)
{
int32_t ret, handleBuf, initialItemsRemainingInBuffer;
size_t messageSize;
uint8_t *message = NULL;
UBaseType_t itemsRemainingInBuffer;
BaseType_t semaphoreRet, bufRet;
uint8_t writeBackBuffer[4 + XPLRBLUETOOTH_MAX_MSG_SIZE];
bool correctMsgRead = false;
uint8_t repCounter = 0;
semaphoreRet = xSemaphoreTake(btSemaphore, XPLR_BLUETOOTH_MAX_DELAY);
if (semaphoreRet == pdTRUE) {
vRingbufferGetInfo(btClient->configuration.ringBuffer,
NULL,
NULL,
NULL,
NULL,
&itemsRemainingInBuffer);
xSemaphoreGive(btSemaphore);
} else {
XPLRBLUETOOTH_CONSOLE(W, "Couldn't get semaphore");
}
initialItemsRemainingInBuffer = itemsRemainingInBuffer;
if (itemsRemainingInBuffer != 0) {
if (readFirstAvailableMsg) {
// Read the first available message in the buffer (from any device)
*dvc = btReadFirstAvailableMsgHelper(message,
messageSize,
&ret,
&correctMsgRead);
} else {
do {
// Keep reading messages until you find the first from the requested device
repCounter++;
semaphoreRet = xSemaphoreTake(btSemaphore, XPLR_BLUETOOTH_MAX_DELAY);
if (semaphoreRet == pdTRUE) {
message = xRingbufferReceiveFromISR(btClient->configuration.ringBuffer, &messageSize);
xSemaphoreGive(btSemaphore);
} else {
XPLRBLUETOOTH_CONSOLE(W, "Couldn't get semaphore");
}
memcpy(&handleBuf, message, 4);
semaphoreRet = xSemaphoreTake(btSemaphore, XPLR_BLUETOOTH_MAX_DELAY);
if (semaphoreRet == pdTRUE) {
// If the device handle is the same as requested in the function call
if ((*dvc)->handle == handleBuf) {
// Keep the message in the device buffer
memset((*dvc)->msg, '\0', XPLRBLUETOOTH_MAX_MSG_SIZE);
memcpy((*dvc)->msg, &message[4], messageSize - 4);
vRingbufferReturnItemFromISR(btClient->configuration.ringBuffer, message, NULL);
xSemaphoreGive(btSemaphore);
} else {
XPLRBLUETOOTH_CONSOLE(W, "Couldn't get semaphore");
}
ret = messageSize - 4;
correctMsgRead = true;
itemsRemainingInBuffer--;
} else {
// If the read message is from a different device then return it to the buffer
memcpy(writeBackBuffer, message, messageSize);
semaphoreRet = xSemaphoreTake(btSemaphore, XPLR_BLUETOOTH_MAX_DELAY);
if (semaphoreRet == pdTRUE) {
vRingbufferReturnItemFromISR(btClient->configuration.ringBuffer, message, NULL);
bufRet = xRingbufferSendFromISR(btClient->configuration.ringBuffer, writeBackBuffer, messageSize,
NULL);
if (bufRet != pdTRUE) {
XPLRBLUETOOTH_CONSOLE(E, "Buffer full cannot store message");
btClient->state = XPLR_BLUETOOTH_CONN_STATE_RX_BUFFER_FULL;
} else {
itemsRemainingInBuffer--;
}
xSemaphoreGive(btSemaphore);
} else {
XPLRBLUETOOTH_CONSOLE(W, "Couldn't get semaphore");
}
ret = -1;
}
if (initialItemsRemainingInBuffer == repCounter && !correctMsgRead) {
// Checked all the messages in the buffer and didn't find one from the requested device
XPLRBLUETOOTH_CONSOLE(W, "No message from requested device");
ret = 0;
break;
}
} while (!correctMsgRead);
// Arrange the messages in the buffer in the correct order (if needed)
if (repCounter == 1 && correctMsgRead) {
// Do nothing
} else if (repCounter != 1 && correctMsgRead) {
// Place all the remaining messages in the right order
btPlaceMessageBackInBufferHelper(itemsRemainingInBuffer, writeBackBuffer);
}
}
} else {
// No message to read
XPLRBLUETOOTH_CONSOLE(I, "No message to read");
ret = 0;
}
btUpdateStateHelper(&itemsRemainingInBuffer);
return ret;
}
xplrBluetooth_connected_device_t *btReadFirstAvailableMsgHelper(uint8_t *message,
size_t messageSize,
int32_t *size,
bool *correctMsgRead)
{
xplrBluetooth_connected_device_t *ret;
int32_t handle;
BaseType_t semaphoreRet;
semaphoreRet = xSemaphoreTake(btSemaphore, XPLR_BLUETOOTH_MAX_DELAY);
if (semaphoreRet == pdTRUE) {
message = xRingbufferReceiveFromISR(btClient->configuration.ringBuffer, &messageSize);
xSemaphoreGive(btSemaphore);
} else {
XPLRBLUETOOTH_CONSOLE(W, "Couldn't get semaphore");
}
// Keep the pointer to the device struct
memcpy(&handle, message, 4);
ret = btDeviceHandleToDeviceStructHelper(handle);
// Keep the message in the user provided buffer
semaphoreRet = xSemaphoreTake(btSemaphore, XPLR_BLUETOOTH_MAX_DELAY);
if (semaphoreRet == pdTRUE) {
memset(ret->msg, '\0', XPLRBLUETOOTH_MAX_MSG_SIZE);
memcpy(ret->msg, &message[4], messageSize - 4);
vRingbufferReturnItemFromISR(btClient->configuration.ringBuffer, message, NULL);
xSemaphoreGive(btSemaphore);
} else {
XPLRBLUETOOTH_CONSOLE(W, "Couldn't get semaphore");
}
*size = messageSize - 4;
*correctMsgRead = true;
return ret;
}
void btUpdateStateHelper(UBaseType_t *itemsRemainingInBuffer)
{
BaseType_t semaphoreRet;
semaphoreRet = xSemaphoreTake(btSemaphore, XPLR_BLUETOOTH_MAX_DELAY);
if (semaphoreRet == pdTRUE) {
vRingbufferGetInfo(btClient->configuration.ringBuffer,
NULL,
NULL,
NULL,
NULL,
itemsRemainingInBuffer);
if (*itemsRemainingInBuffer) {
btClient->state = XPLR_BLUETOOTH_CONN_STATE_MSG_AVAILABLE;
} else {
btClient->state = XPLR_BLUETOOTH_CONN_STATE_CONNECTED;
}
xSemaphoreGive(btSemaphore);
} else {
XPLRBLUETOOTH_CONSOLE(W, "Couldn't get semaphore");
}
}
#if XPLRBLUETOOTH_MODE == XPLRBLUETOOTH_MODE_BT_CLASSIC
xplrBluetooth_error_t btClassicInit(void)
{
xplrBluetooth_error_t ret;
ret = btClassicControllerInit();
if (ret == XPLR_BLUETOOTH_OK) {
ret = btClassicBluedroidInit();
} else {
btClient->state = XPLR_BLUETOOTH_CONN_STATE_ERROR;
}
if (ret == XPLR_BLUETOOTH_OK) {
ret = btClassicCbInit();
if (ret == XPLR_BLUETOOTH_OK) {
btClient->state = XPLR_BLUETOOTH_CONN_STATE_READY;
} else {
btClient->state = XPLR_BLUETOOTH_CONN_STATE_ERROR;
}
} else {
btClient->state = XPLR_BLUETOOTH_CONN_STATE_ERROR;
}
/*
* Set default parameters for Legacy Pairing
* Use variable pin, input pin code when pairing
*/
esp_bt_pin_type_t pin_type = ESP_BT_PIN_TYPE_VARIABLE;
esp_bt_pin_code_t pin_code;
esp_bt_gap_set_pin(pin_type, 0, pin_code);
const uint8_t *bda = esp_bt_dev_get_address();
XPLRBLUETOOTH_CONSOLE(I,
"xplr-hpg address:[%02x:%02x:%02x:%02x:%02x:%02x]",
bda[0],
bda[1],
bda[2],
bda[3],
bda[4],
bda[5]);
return ret;
}
xplrBluetooth_error_t btClassicControllerInit(void)
{
esp_err_t espRet;
xplrBluetooth_error_t ret;
esp_bt_controller_config_t bt_cfg = BT_CONTROLLER_INIT_CONFIG_DEFAULT();
espRet = esp_bt_controller_init(&bt_cfg);
if (espRet != ESP_OK) {
XPLRBLUETOOTH_CONSOLE(E, "initialize controller failed: %s", esp_err_to_name(espRet));
ret = XPLR_BLUETOOTH_ERROR;
} else {
espRet = esp_bt_controller_enable(ESP_BT_MODE_CLASSIC_BT);
if (espRet != ESP_OK) {
XPLRBLUETOOTH_CONSOLE(E, "enable controller failed: %s", esp_err_to_name(espRet));
ret = XPLR_BLUETOOTH_ERROR;
} else {
ret = XPLR_BLUETOOTH_OK;
}
}
return ret;
}
xplrBluetooth_error_t btClassicBluedroidInit(void)
{
esp_err_t espRet;
xplrBluetooth_error_t ret;
espRet = esp_bluedroid_init();
if (espRet != ESP_OK) {
XPLRBLUETOOTH_CONSOLE(E, "initialize bluedroid failed: %s", esp_err_to_name(espRet));
ret = XPLR_BLUETOOTH_ERROR;
} else {
espRet = esp_bluedroid_enable();
if (espRet != ESP_OK) {
XPLRBLUETOOTH_CONSOLE(E, "enable bluedroid failed: %s", esp_err_to_name(espRet));
ret = XPLR_BLUETOOTH_ERROR;
} else {
ret = XPLR_BLUETOOTH_OK;
}
}
return ret;
}
xplrBluetooth_error_t btClassicCbInit(void)
{
esp_err_t espRet;
xplrBluetooth_error_t ret;
espRet = esp_spp_register_callback(BtClassicSPPcb);
if (espRet != ESP_OK) {
XPLRBLUETOOTH_CONSOLE(E, "spp register failed: %s", esp_err_to_name(espRet));
ret = XPLR_BLUETOOTH_ERROR;
} else {
espRet = esp_bt_gap_register_callback(btClassicGAPcb);
if (espRet != ESP_OK) {
XPLRBLUETOOTH_CONSOLE(E, "gap register failed: %s", esp_err_to_name(espRet));
ret = XPLR_BLUETOOTH_ERROR;
} else {
espRet = esp_spp_init(ESP_SPP_MODE_CB);
if (espRet != ESP_OK) {
XPLRBLUETOOTH_CONSOLE(E, "spp init failed: %s", esp_err_to_name(espRet));
ret = XPLR_BLUETOOTH_ERROR;
} else {
ret = XPLR_BLUETOOTH_OK;
}
}
}
return ret;
}
xplrBluetooth_error_t btClassicDeInit(void)
{
esp_err_t espRet[6];
int i;
xplrBluetooth_error_t ret;
esp_bt_controller_deinit();
espRet[0] = esp_spp_stop_srv();
espRet[1] = esp_spp_deinit();
espRet[2] = esp_bluedroid_disable();
espRet[3] = esp_bluedroid_deinit();
espRet[4] = esp_bt_controller_disable();
espRet[5] = esp_bt_controller_deinit();
for (i = 0; i < 6; i++) {
if (espRet[i] != ESP_OK) {
ret = XPLR_BLUETOOTH_ERROR;
break;
}
}
return ret;
}
void btClassicDisconnectDevice(xplrBluetooth_connected_device_t *dvc)
{
esp_err_t espRet;
espRet = esp_spp_disconnect(dvc->handle);
if (espRet != ESP_OK) {
XPLRBLUETOOTH_CONSOLE(E,
"Couldn't disconnect device with handle: [%d]",
dvc->handle);
} else {
// Do nothing
}
}
xplrBluetooth_error_t btClassicWrite(xplrBluetooth_connected_device_t *dvc,
char *msg,
size_t msgSize)
{
xplrBluetooth_error_t ret;
esp_err_t espRet;
BaseType_t semaphoreRet;
semaphoreRet = xSemaphoreTake(btSemaphore, XPLR_BLUETOOTH_MAX_DELAY);
if (semaphoreRet == pdTRUE) {
if (msgSize == 0) {
ret = XPLR_BLUETOOTH_ERROR;
XPLRBLUETOOTH_CONSOLE(E, "msgSize is 0");
} else {
espRet = esp_spp_write(dvc->handle, msgSize, (uint8_t *)msg);
if (espRet == ESP_OK) {
ret = XPLR_BLUETOOTH_OK;
} else {
XPLRBLUETOOTH_CONSOLE(E, "esp_spp_write fail");
btClient->state = XPLR_BLUETOOTH_CONN_STATE_ERROR;
ret = XPLR_BLUETOOTH_ERROR;
}
}
xSemaphoreGive(btSemaphore);
} else {
// Couldn't get semaphore returning error
ret = XPLR_BLUETOOTH_ERROR;
}
return ret;