-
Notifications
You must be signed in to change notification settings - Fork 229
/
Copy pathBluetoothHelper.cpp
1689 lines (1467 loc) · 56.7 KB
/
BluetoothHelper.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* BluetoothHelper.cpp
* Copyright (C) 2019-2025 Linar Yusupov
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#if defined(ESP32)
#include "sdkconfig.h"
#endif
#if defined(ESP32) && !defined(CONFIG_IDF_TARGET_ESP32S2)
#include "Platform_ESP32.h"
#include "SoCHelper.h"
#include "EEPROMHelper.h"
#include "BluetoothHelper.h"
#include "NMEAHelper.h"
#include "GDL90Helper.h"
#include "SkyView.h"
#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)
#error Bluetooth is not enabled!
#endif
#if defined(CONFIG_IDF_TARGET_ESP32)
#include <BluetoothSerial.h>
BluetoothSerial SerialBT;
#endif /* CONFIG_IDF_TARGET_ESP32 */
#include <BLEDevice.h>
#include "WiFiHelper.h" // HOSTNAME
String BT_name = HOSTNAME;
Bluetooth_ctl_t ESP32_BT_ctl = {
.mutex = portMUX_INITIALIZER_UNLOCKED,
.command = BT_CMD_NONE,
.status = BT_STATUS_NC
};
/* LE */
static BLERemoteCharacteristic* pRemoteCharacteristic;
static BLEAdvertisedDevice* AppDevice;
static BLEClient* pClient;
static BLEUUID serviceUUID(SERVICE_UUID16);
static BLEUUID charUUID(CHARACTERISTIC_UUID16);
cbuf *BLE_FIFO_RX, *BLE_FIFO_TX;
static unsigned long BT_TimeMarker = 0;
static unsigned long BLE_Notify_TimeMarker = 0;
static void AppNotifyCallback(
BLERemoteCharacteristic* pBLERemoteCharacteristic,
uint8_t* pData,
size_t length,
bool isNotify) {
if (length > 0) {
BLE_FIFO_RX->write((char *) pData, (BLE_FIFO_RX->room() > length ?
length : BLE_FIFO_RX->room()));
}
}
class AppClientCallback : public BLEClientCallbacks {
void onConnect(BLEClient* pclient) {
}
void onDisconnect(BLEClient* pclient) {
ESP32_BT_ctl.status = BT_STATUS_NC;
Serial.println(F("BLE: disconnected from Server."));
}
};
class AppAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks {
void onResult(BLEAdvertisedDevice advertisedDevice) {
if (advertisedDevice.haveServiceUUID() && advertisedDevice.isAdvertisingService(serviceUUID)) {
BLEDevice::getScan()->stop();
if (AppDevice) {
AppDevice->~BLEAdvertisedDevice();
}
AppDevice = new BLEAdvertisedDevice(advertisedDevice);
ESP32_BT_ctl.command = BT_CMD_CONNECT;
}
}
};
#if defined(CONFIG_IDF_TARGET_ESP32)
static void ESP32_BT_SPP_Connection_Manager(void *parameter)
{
int command;
int status;
while (true) {
delay(1000);
if (strnlen(settings->server, sizeof(settings->server)) == 0) continue;
portENTER_CRITICAL(&ESP32_BT_ctl.mutex);
command = ESP32_BT_ctl.command;
portEXIT_CRITICAL(&ESP32_BT_ctl.mutex);
switch (command)
{
case BT_CMD_CONNECT:
portENTER_CRITICAL(&ESP32_BT_ctl.mutex);
status = ESP32_BT_ctl.status;
portEXIT_CRITICAL(&ESP32_BT_ctl.mutex);
if (status == BT_STATUS_CON) {
portENTER_CRITICAL(&ESP32_BT_ctl.mutex);
ESP32_BT_ctl.command = BT_CMD_NONE;
portEXIT_CRITICAL(&ESP32_BT_ctl.mutex);
break;
}
// connect(address) is fast (upto 10 secs max), connect(name) is slow (upto 30 secs max) as it needs
// to resolve name to address first, but it allows to connect to different devices with the same name.
// Set CoreDebugLevel to Info to view devices bluetooth address and device names
if (SerialBT.connect(settings->server)) {
portENTER_CRITICAL(&ESP32_BT_ctl.mutex);
ESP32_BT_ctl.status = BT_STATUS_CON;
ESP32_BT_ctl.command = BT_CMD_NONE;
portEXIT_CRITICAL(&ESP32_BT_ctl.mutex);
Serial.print(F("BT SPP: Connected to "));
} else {
portENTER_CRITICAL(&ESP32_BT_ctl.mutex);
ESP32_BT_ctl.status = BT_STATUS_NC;
portEXIT_CRITICAL(&ESP32_BT_ctl.mutex);
Serial.print(F("BT SPP: Unable to connect to "));
}
Serial.println(settings->server);
break;
case BT_CMD_DISCONNECT:
portENTER_CRITICAL(&ESP32_BT_ctl.mutex);
status = ESP32_BT_ctl.status;
portEXIT_CRITICAL(&ESP32_BT_ctl.mutex);
if (status != BT_STATUS_CON) {
portENTER_CRITICAL(&ESP32_BT_ctl.mutex);
ESP32_BT_ctl.command = BT_CMD_NONE;
portEXIT_CRITICAL(&ESP32_BT_ctl.mutex);
break;
}
// disconnect() may take upto 10 secs max
if (SerialBT.disconnect()) {
Serial.print(F("BT SPP: Disconnected from "));
} else {
Serial.print(F("BT SPP: Unable to disconnect from "));
}
Serial.println(settings->server);
portENTER_CRITICAL(&ESP32_BT_ctl.mutex);
ESP32_BT_ctl.status = BT_STATUS_NC;
ESP32_BT_ctl.command = BT_CMD_NONE;
portEXIT_CRITICAL(&ESP32_BT_ctl.mutex);
break;
case BT_CMD_SHUTDOWN:
vTaskDelete(NULL);
break;
default:
break;
}
}
}
#endif /* CONFIG_IDF_TARGET_ESP32 */
static bool ESP32_BLEConnectToServer() {
pClient->connect(AppDevice);
BLERemoteService* pRemoteService = pClient->getService(serviceUUID);
if (pRemoteService == nullptr) {
Serial.print(F("BLE: Failed to find our service UUID: "));
Serial.println(serviceUUID.toString().c_str());
pClient->disconnect();
return false;
}
pRemoteCharacteristic = pRemoteService->getCharacteristic(charUUID);
if (pRemoteCharacteristic == nullptr) {
Serial.print(F("BLE: Failed to find our characteristic UUID: "));
Serial.println(charUUID.toString().c_str());
pClient->disconnect();
return false;
}
if(pRemoteCharacteristic->canNotify())
pRemoteCharacteristic->registerForNotify(AppNotifyCallback);
ESP32_BT_ctl.status = BT_STATUS_CON;
return true;
}
static void ESP32_Bluetooth_setup()
{
switch(settings->connection)
{
#if defined(CONFIG_IDF_TARGET_ESP32)
case CON_BLUETOOTH_SPP:
{
esp_bt_controller_mem_release(ESP_BT_MODE_BLE);
char id_06x[8];
snprintf(id_06x, sizeof(id_06x),"%06x", SoC->getChipId() & 0x00FFFFFFU);
BT_name += String(id_06x);
#if !defined(ESP_IDF_VERSION_MAJOR) || ESP_IDF_VERSION_MAJOR < 5
SerialBT.setPin(settings->key);
#elif !defined(CONFIG_BT_SSP_ENABLED)
SerialBT.setPin(settings->key);
#endif /* ESP_IDF_VERSION_MAJOR */
SerialBT.begin(BT_name.c_str(), true);
xTaskCreate(ESP32_BT_SPP_Connection_Manager, "BT SPP ConMgr Task", 2048, NULL, tskIDLE_PRIORITY, NULL);
BT_TimeMarker = millis();
}
break;
#endif /* CONFIG_IDF_TARGET_ESP32 */
case CON_BLUETOOTH_LE:
{
BLE_FIFO_RX = new cbuf(BLE_FIFO_RX_SIZE);
BLE_FIFO_TX = new cbuf(BLE_FIFO_TX_SIZE);
#if defined(CONFIG_IDF_TARGET_ESP32)
esp_bt_controller_mem_release(ESP_BT_MODE_CLASSIC_BT);
#endif /* CONFIG_IDF_TARGET_ESP32 */
BLEDevice::init("");
pClient = BLEDevice::createClient();
pClient->setClientCallbacks(new AppClientCallback());
BLEScan* pBLEScan = BLEDevice::getScan();
pBLEScan->setAdvertisedDeviceCallbacks(new AppAdvertisedDeviceCallbacks());
pBLEScan->setInterval(1349);
pBLEScan->setWindow(449);
pBLEScan->setActiveScan(true);
pBLEScan->start(3, false);
BLE_Notify_TimeMarker = millis();
}
break;
default:
break;
}
}
static void ESP32_Bluetooth_loop()
{
bool hasData = false;
switch(settings->connection)
{
#if defined(CONFIG_IDF_TARGET_ESP32)
case CON_BLUETOOTH_SPP:
{
portENTER_CRITICAL(&ESP32_BT_ctl.mutex);
int command = ESP32_BT_ctl.command;
int status = ESP32_BT_ctl.status;
portEXIT_CRITICAL(&ESP32_BT_ctl.mutex);
if (status == BT_STATUS_NC && command == BT_CMD_NONE) {
portENTER_CRITICAL(&ESP32_BT_ctl.mutex);
ESP32_BT_ctl.command = BT_CMD_CONNECT;
portEXIT_CRITICAL(&ESP32_BT_ctl.mutex);
} else {
switch (settings->protocol)
{
case PROTOCOL_GDL90:
hasData = GDL90_isConnected();
break;
case PROTOCOL_NMEA:
default:
hasData = NMEA_isConnected();
break;
}
if (hasData) {
BT_TimeMarker = millis();
} else if (millis() - BT_TimeMarker > BT_NODATA_TIMEOUT &&
command == BT_CMD_NONE) {
portENTER_CRITICAL(&ESP32_BT_ctl.mutex);
ESP32_BT_ctl.command = BT_CMD_DISCONNECT;
portEXIT_CRITICAL(&ESP32_BT_ctl.mutex);
BT_TimeMarker = millis();
}
}
}
break;
#endif /* CONFIG_IDF_TARGET_ESP32 */
case CON_BLUETOOTH_LE:
{
if (ESP32_BT_ctl.command == BT_CMD_CONNECT) {
if (ESP32_BLEConnectToServer()) {
Serial.println(F("BLE: connected to Server."));
}
ESP32_BT_ctl.command = BT_CMD_NONE;
}
switch (settings->protocol)
{
case PROTOCOL_GDL90:
hasData = GDL90_isConnected();
break;
case PROTOCOL_NMEA:
default:
hasData = NMEA_isConnected();
break;
}
if (hasData) {
BT_TimeMarker = millis();
} else if (millis() - BT_TimeMarker > BT_NODATA_TIMEOUT) {
Serial.println(F("BLE: attempt to (re)connect..."));
if (pClient) {
if (pClient->isConnected()) {
pClient->disconnect();
}
}
BLEDevice::getScan()->start(3, false);
#if 0
/* approx. 170 bytes memory leak still remains */
Serial.print("Free Heap: ");
Serial.println(ESP.getFreeHeap());
#endif
BT_TimeMarker = millis();
}
// notify changed value
// bluetooth stack will go into congestion, if too many packets are sent
if (ESP32_BT_ctl.status == BT_STATUS_CON &&
(millis() - BLE_Notify_TimeMarker > 10)) { /* < 18000 baud */
uint8_t chunk[BLE_MAX_WRITE_CHUNK_SIZE];
size_t size = (BLE_FIFO_TX->available() < BLE_MAX_WRITE_CHUNK_SIZE ?
BLE_FIFO_TX->available() : BLE_MAX_WRITE_CHUNK_SIZE);
if (size > 0) {
BLE_FIFO_TX->read((char *) chunk, size);
pRemoteCharacteristic->writeValue(chunk, size);
BLE_Notify_TimeMarker = millis();
}
}
}
break;
default:
break;
}
}
static void ESP32_Bluetooth_fini()
{
switch(settings->connection)
{
#if defined(CONFIG_IDF_TARGET_ESP32)
case CON_BLUETOOTH_SPP:
{
portENTER_CRITICAL(&ESP32_BT_ctl.mutex);
ESP32_BT_ctl.command = BT_CMD_SHUTDOWN;
portEXIT_CRITICAL(&ESP32_BT_ctl.mutex);
delay(100);
SerialBT.end();
}
break;
#endif /* CONFIG_IDF_TARGET_ESP32 */
case CON_BLUETOOTH_LE:
{
BLEDevice::deinit();
}
break;
default:
break;
}
}
static int ESP32_Bluetooth_available()
{
int rval = 0;
switch(settings->connection)
{
#if defined(CONFIG_IDF_TARGET_ESP32)
case CON_BLUETOOTH_SPP:
{
portENTER_CRITICAL(&ESP32_BT_ctl.mutex);
int status = ESP32_BT_ctl.status;
portEXIT_CRITICAL(&ESP32_BT_ctl.mutex);
if (status == BT_STATUS_CON) {
rval = SerialBT.available();
}
}
break;
#endif /* CONFIG_IDF_TARGET_ESP32 */
case CON_BLUETOOTH_LE:
{
rval = BLE_FIFO_RX->available();
}
break;
default:
break;
}
return rval;
}
static int ESP32_Bluetooth_read()
{
int rval = -1;
switch(settings->connection)
{
#if defined(CONFIG_IDF_TARGET_ESP32)
case CON_BLUETOOTH_SPP:
{
portENTER_CRITICAL(&ESP32_BT_ctl.mutex);
int status = ESP32_BT_ctl.status;
portEXIT_CRITICAL(&ESP32_BT_ctl.mutex);
if (status == BT_STATUS_CON) {
rval = SerialBT.read();
}
}
break;
#endif /* CONFIG_IDF_TARGET_ESP32 */
case CON_BLUETOOTH_LE:
{
rval = BLE_FIFO_RX->read();
break;
}
break;
default:
break;
}
return rval;
}
static size_t ESP32_Bluetooth_write(const uint8_t *buffer, size_t size)
{
int rval = 0;
switch(settings->connection)
{
#if defined(CONFIG_IDF_TARGET_ESP32)
case CON_BLUETOOTH_SPP:
{
portENTER_CRITICAL(&ESP32_BT_ctl.mutex);
int status = ESP32_BT_ctl.status;
portEXIT_CRITICAL(&ESP32_BT_ctl.mutex);
if (status == BT_STATUS_CON) {
rval = SerialBT.write(buffer, size);
}
}
break;
#endif /* CONFIG_IDF_TARGET_ESP32 */
case CON_BLUETOOTH_LE:
{
rval = BLE_FIFO_TX->write((char *) buffer,
(BLE_FIFO_TX->room() > size ? size : BLE_FIFO_TX->room()));
}
break;
default:
break;
}
return rval;
}
IODev_ops_t ESP32_Bluetooth_ops = {
"ESP32 Bluetooth",
ESP32_Bluetooth_setup,
ESP32_Bluetooth_loop,
ESP32_Bluetooth_fini,
ESP32_Bluetooth_available,
ESP32_Bluetooth_read,
ESP32_Bluetooth_write
};
#elif defined(ARDUINO_ARCH_RP2040)
#include "SoCHelper.h"
#if !defined(EXCLUDE_BLUETOOTH)
#include <queue>
#include <pico/cyw43_arch.h>
#include <pico/btstack_cyw43.h>
#include <CoreMutex.h>
#include <btstack.h>
#include <api/RingBuffer.h>
#include "EEPROMHelper.h"
#include "WiFiHelper.h" // HOSTNAME
#include "BluetoothHelper.h"
/* ------- SPP BEGIN ------ */
#define INQUIRY_INTERVAL 5
#define NUM_SERVICES 10
//#define SPP_USE_COD
#define SPP_USE_NAME
#if defined(SPP_USE_COD)
#define SOFTRF_SPP_COD 0x02c110
//#define SOFTRF_SPP_COD 0x001f00 /* HC-05 */
#endif /* SPP_USE_COD */
//#define DEBUG_SPP Serial.printf
#define DEBUG_SPP
typedef enum {
#if defined(SPP_USE_COD)
W4_PEER_COD,
#else
W4_PEER_NAME,
#endif /* SPP_USE_COD */
W4_SCAN_COMPLETE,
W4_SDP_RESULT,
W2_SEND_SDP_QUERY,
W4_RFCOMM_CHANNEL,
SENDING,
DONE
} state_t;
static bool _running = false;
static bool _overflow = false;
static volatile bool _connected = false;
static size_t _fifoSize = 512;
static uint16_t _channelID = 0;
static volatile int _writeLen = 0;
static uint8_t rfcomm_server_channel = 1;
static char *pin_code = (char *) "0000";
static uint8_t service_index = 0;
static mutex_t _mutex;
static uint32_t _writer;
static uint32_t _reader;
static uint8_t *_queue = NULL;
static uint16_t _mtu;
static bd_addr_t peer_addr;
static state_t spp_state;
static const void *_writeBuff;
static btstack_packet_callback_registration_t _hci_event_callback_registration;
static btstack_context_callback_registration_t _handle_sdp_client_query_request;
// prototypes
static void hci_spp_event_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
RingBufferN<BLE_FIFO_TX_SIZE> BLE_FIFO_TX = RingBufferN<BLE_FIFO_TX_SIZE>();
RingBufferN<BLE_FIFO_RX_SIZE> BLE_FIFO_RX = RingBufferN<BLE_FIFO_RX_SIZE>();
String BT_name = HOSTNAME;
static struct {
uint8_t channel_nr;
char service_name[SDP_SERVICE_NAME_LEN+1];
} services[NUM_SERVICES];
static void start_scan(void){
DEBUG_SPP("Starting inquiry scan..\r\n");
#if defined(SPP_USE_COD)
spp_state = W4_PEER_COD;
#else
spp_state = W4_PEER_NAME,
#endif /* SPP_USE_COD */
gap_inquiry_start(INQUIRY_INTERVAL);
}
static void stop_scan(void){
DEBUG_SPP("Stopping inquiry scan..\r\n");
spp_state = W4_SCAN_COMPLETE;
gap_inquiry_stop();
}
#if defined(SPP_USE_NAME)
#define MAX_DEVICES 20
#define MAX_NAMELEN 18 /* matches EEPROMHelper.h value */
enum DEVICE_STATE { REMOTE_NAME_REQUEST, REMOTE_NAME_INQUIRED, REMOTE_NAME_FETCHED };
struct device {
bd_addr_t address;
uint8_t pageScanRepetitionMode;
uint16_t clockOffset;
enum DEVICE_STATE state;
char name[MAX_NAMELEN];
};
struct device devices[MAX_DEVICES];
int deviceCount = 0;
static void CYW43_Bluetooth_setup();
static void CYW43_Bluetooth_fini();
static int getDeviceIndexForAddress( bd_addr_t addr){
int j;
for (j=0; j< deviceCount; j++){
if (bd_addr_cmp(addr, devices[j].address) == 0){
return j;
}
}
return -1;
}
static int has_more_remote_name_requests(void){
int i;
for (i=0;i<deviceCount;i++) {
if (devices[i].state == REMOTE_NAME_REQUEST) return 1;
}
return 0;
}
static void do_next_remote_name_request(void){
int i;
for (i=0;i<deviceCount;i++) {
// remote name request
if (devices[i].state == REMOTE_NAME_REQUEST){
devices[i].state = REMOTE_NAME_INQUIRED;
DEBUG_SPP("Get remote name of %s...\r\n", bd_addr_to_str(devices[i].address));
gap_remote_name_request( devices[i].address, devices[i].pageScanRepetitionMode, devices[i].clockOffset | 0x8000);
return;
}
}
}
static void continue_remote_names(void){
if (has_more_remote_name_requests()){
do_next_remote_name_request();
return;
}
start_scan();
}
#endif /* SPP_USE_NAME */
static void store_found_service(const char * name, uint8_t port){
DEBUG_SPP("APP: Service name: '%s', RFCOMM port %u\r\n", name, port);
if (service_index < NUM_SERVICES){
services[service_index].channel_nr = port;
btstack_strcpy(services[service_index].service_name, SDP_SERVICE_NAME_LEN + 1, name);
service_index++;
} else {
DEBUG_SPP("APP: list full - ignore\r\n");
return;
}
}
static void report_found_services(void){
DEBUG_SPP("Client query response done. ");
if (service_index == 0) {
DEBUG_SPP("No service found.\r\n");
} else {
DEBUG_SPP("Found following %d services:\r\n", service_index);
}
int i;
for (i=0; i<service_index; i++) {
DEBUG_SPP(" Service name %s, RFCOMM port %u\r\n", services[i].service_name, services[i].channel_nr);
}
}
/*
* @section SDP Query Packet Handler
*
* @text Store RFCOMM Channel for SPP service and initiates RFCOMM connection
*/
static void handle_query_rfcomm_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
UNUSED(packet_type);
UNUSED(channel);
UNUSED(size);
switch (hci_event_packet_get_type(packet)){
case SDP_EVENT_QUERY_RFCOMM_SERVICE:
store_found_service(sdp_event_query_rfcomm_service_get_name(packet),
sdp_event_query_rfcomm_service_get_rfcomm_channel(packet));
rfcomm_server_channel = sdp_event_query_rfcomm_service_get_rfcomm_channel(packet);
break;
case SDP_EVENT_QUERY_COMPLETE:
if (sdp_event_query_complete_get_status(packet)){
DEBUG_SPP("SDP query failed 0x%02x\r\n", sdp_event_query_complete_get_status(packet));
break;
}
report_found_services();
if (rfcomm_server_channel == 0) {
DEBUG_SPP("No SPP service found\r\n");
break;
}
DEBUG_SPP("SDP query done, channel %u.\r\n", rfcomm_server_channel);
rfcomm_create_channel(hci_spp_event_handler, peer_addr, rfcomm_server_channel, NULL);
break;
default:
break;
}
}
static void handle_start_sdp_client_query(void * context){
UNUSED(context);
if (spp_state != W2_SEND_SDP_QUERY) return;
spp_state = W4_RFCOMM_CHANNEL;
sdp_client_query_rfcomm_channel_and_name_for_uuid(&handle_query_rfcomm_event, peer_addr, BLUETOOTH_ATTRIBUTE_PUBLIC_BROWSE_ROOT);
}
static void hci_spp_event_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size) {
UNUSED(channel);
bd_addr_t event_addr;
uint8_t rfcomm_channel_nr;
uint32_t class_of_device;
int i;
#if defined(SPP_USE_NAME)
int index;
#endif /* SPP_USE_NAME */
switch (packet_type) {
case HCI_EVENT_PACKET:
switch (hci_event_packet_get_type(packet)) {
case BTSTACK_EVENT_STATE:
if (btstack_event_state_get_state(packet) != HCI_STATE_WORKING) return;
start_scan();
break;
#if defined(SPP_USE_COD)
case GAP_EVENT_INQUIRY_RESULT:
if (spp_state != W4_PEER_COD) break;
class_of_device = gap_event_inquiry_result_get_class_of_device(packet);
gap_event_inquiry_result_get_bd_addr(packet, event_addr);
if (class_of_device == SOFTRF_SPP_COD){
memcpy(peer_addr, event_addr, 6);
DEBUG_SPP("Peer found: %s\r\n", bd_addr_to_str(peer_addr));
stop_scan();
} else {
DEBUG_SPP("Device found: %s with COD: 0x%06x\r\n", bd_addr_to_str(event_addr), (int) class_of_device);
}
break;
#endif /* SPP_USE_COD */
#if defined(SPP_USE_NAME)
case HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE:
reverse_bd_addr(&packet[3], event_addr);
index = getDeviceIndexForAddress(event_addr);
if (index >= 0) {
if (packet[2] == 0) {
// fix for invalid remote names - terminate on 0xff
for (i=0; i<248;i++){
if (packet[9+i] == 0xff){
packet[9+i] = 0;
break;
}
}
packet[9+248] = 0;
DEBUG_SPP("Name: '%s'\r\n", &packet[9]);
memcpy(devices[index].name, &packet[9], MAX_NAMELEN);
devices[index].state = REMOTE_NAME_FETCHED;
} else {
DEBUG_SPP("Failed to get name: page timeout\r\n");
}
}
continue_remote_names();
break;
case GAP_EVENT_INQUIRY_RESULT:
if (spp_state != W4_PEER_NAME) break;
if (deviceCount >= MAX_DEVICES) break; // already full
gap_event_inquiry_result_get_bd_addr(packet, event_addr);
index = getDeviceIndexForAddress(event_addr);
// already in our list
if (index >= 0) {
size_t name_len = strnlen(settings->server, sizeof(settings->server));
if (name_len > 0 && devices[index].state == REMOTE_NAME_FETCHED &&
memcmp(settings->server, devices[index].name, name_len) == 0) {
memcpy(peer_addr, event_addr, 6);
DEBUG_SPP("Peer found: %s\r\n", bd_addr_to_str(peer_addr));
stop_scan();
}
break;
}
memcpy(devices[deviceCount].address, event_addr, 6);
devices[deviceCount].pageScanRepetitionMode = gap_event_inquiry_result_get_page_scan_repetition_mode(packet);
devices[deviceCount].clockOffset = gap_event_inquiry_result_get_clock_offset(packet);
// print info
DEBUG_SPP("Device found: %s ", bd_addr_to_str(event_addr));
DEBUG_SPP("with COD: 0x%06x, ", (unsigned int) gap_event_inquiry_result_get_class_of_device(packet));
DEBUG_SPP("pageScan %d, ", devices[deviceCount].pageScanRepetitionMode);
DEBUG_SPP("clock offset 0x%04x",devices[deviceCount].clockOffset);
if (gap_event_inquiry_result_get_rssi_available(packet)){
DEBUG_SPP(", rssi %d dBm", (int8_t) gap_event_inquiry_result_get_rssi(packet));
}
if (gap_event_inquiry_result_get_name_available(packet)){
char name_buffer[240];
int name_len = gap_event_inquiry_result_get_name_len(packet);
memcpy(name_buffer, gap_event_inquiry_result_get_name(packet), name_len);
name_buffer[name_len] = 0;
DEBUG_SPP(", name '%s'", name_buffer);
size_t srv_name_len = strnlen(settings->server, sizeof(settings->server));
if (srv_name_len > 0 &&
memcmp(settings->server, name_buffer, srv_name_len) == 0) {
memcpy(peer_addr, event_addr, 6);
DEBUG_SPP("Peer found: %s\r\n", bd_addr_to_str(peer_addr));
stop_scan();
}
devices[deviceCount].state = REMOTE_NAME_FETCHED;
} else {
devices[deviceCount].state = REMOTE_NAME_REQUEST;
}
DEBUG_SPP("\r\n");
deviceCount++;
break;
#endif /* SPP_USE_NAME */
case GAP_EVENT_INQUIRY_COMPLETE:
switch (spp_state){
#if defined(SPP_USE_COD)
case W4_PEER_COD:
DEBUG_SPP("Inquiry complete\r\n");
DEBUG_SPP("Peer not found, starting scan again\r\n");
start_scan();
break;
#endif /* SPP_USE_COD */
#if defined(SPP_USE_NAME)
case W4_PEER_NAME:
for (i=0;i<deviceCount;i++) {
// retry remote name request
if (devices[i].state == REMOTE_NAME_INQUIRED)
devices[i].state = REMOTE_NAME_REQUEST;
}
continue_remote_names();
break;
#endif /* SPP_USE_NAME */
case W4_SCAN_COMPLETE:
DEBUG_SPP("Start to connect and query for SPP service\r\n");
spp_state = W2_SEND_SDP_QUERY;
_handle_sdp_client_query_request.callback = &handle_start_sdp_client_query;
(void) sdp_client_register_query_callback(&_handle_sdp_client_query_request);
break;
default:
break;
}
break;
case HCI_EVENT_PIN_CODE_REQUEST:
// inform about pin code request
if (strnlen(settings->key, sizeof(settings->key)) > 0) {
pin_code = settings->key;
}
DEBUG_SPP("Pin code request - using '%s'\r\n", pin_code);
hci_event_pin_code_request_get_bd_addr(packet, event_addr);
gap_pin_code_response(event_addr, pin_code);
break;
case HCI_EVENT_USER_CONFIRMATION_REQUEST:
// inform about user confirmation request
DEBUG_SPP("SSP User Confirmation Request with numeric value '%06"PRIu32"'\r\n", little_endian_read_32(packet, 8));
DEBUG_SPP("SSP User Confirmation Auto accept\r\n");
break;
case RFCOMM_EVENT_INCOMING_CONNECTION:
rfcomm_event_incoming_connection_get_bd_addr(packet, event_addr);
rfcomm_channel_nr = rfcomm_event_incoming_connection_get_server_channel(packet);
_channelID = rfcomm_event_incoming_connection_get_rfcomm_cid(packet);
DEBUG_SPP("RFCOMM channel %u requested for %s\r\n", rfcomm_channel_nr, bd_addr_to_str(event_addr));
rfcomm_accept_connection(_channelID);
break;
case RFCOMM_EVENT_CHANNEL_OPENED:
if (rfcomm_event_channel_opened_get_status(packet)) {
DEBUG_SPP("RFCOMM channel open failed, status %u\r\n", rfcomm_event_channel_opened_get_status(packet));
} else {
_channelID = rfcomm_event_channel_opened_get_rfcomm_cid(packet);
_mtu = rfcomm_event_channel_opened_get_max_frame_size(packet);
DEBUG_SPP("RFCOMM channel open succeeded. New RFCOMM Channel ID %u, max frame size %u\r\n", _channelID, _mtu);
_connected = true;
// disable page/inquiry scan to get max performance
gap_discoverable_control(0);
gap_connectable_control(0);
}
break;
case RFCOMM_EVENT_CAN_SEND_NOW:
rfcomm_send(_channelID, (uint8_t *)_writeBuff, _writeLen);
_writeLen = 0;
break;
case RFCOMM_EVENT_CHANNEL_CLOSED:
DEBUG_SPP("RFCOMM channel closed\r\n");
_channelID = 0;
_connected = false;
#if defined(SPP_USE_COD)
spp_state = W4_PEER_COD;
#else
spp_state = W4_PEER_NAME,
deviceCount = 0;
#endif /* SPP_USE_COD */
service_index = 0;
rfcomm_server_channel = 1;
CYW43_Bluetooth_fini();
//rfcomm_deinit();
btstack_cyw43_init(cyw43_arch_async_context());
CYW43_Bluetooth_setup();
break;
default:
break;
}
break;
case RFCOMM_DATA_PACKET:
for (i = 0; i < size; i++) {
auto next_writer = _writer + 1;
if (next_writer == _fifoSize) {
next_writer = 0;
}
if (next_writer != _reader) {
_queue[_writer] = packet[i];
asm volatile("" ::: "memory"); // Ensure the queue is written before the written count advances
// Avoid using division or mod because the HW divider could be in use
_writer = next_writer;
} else {
_overflow = true;
}
}
break;
default:
break;
}
}
/* ------- SPP END ------ */
/* ------- BLE BEGIN------ */
#define TEST_MODE_WRITE_WITHOUT_RESPONSE 1
#define TEST_MODE_ENABLE_NOTIFICATIONS 2
#define TEST_MODE_DUPLEX 3
// configure test mode: send only, receive only, full duplex
#define TEST_MODE TEST_MODE_ENABLE_NOTIFICATIONS
#define REPORT_INTERVAL_MS 3000
#define DEBUG_BLE 0
// prototypes
static void handle_gatt_client_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
typedef enum {
TC_OFF,
TC_IDLE,
TC_W4_SCAN_RESULT,
TC_W4_CONNECT,
TC_W4_SERVICE_RESULT,
TC_W4_CHARACTERISTIC_RXTX_RESULT,
TC_W4_ENABLE_NOTIFICATIONS_COMPLETE,
TC_W4_TEST_DATA