-
-
Notifications
You must be signed in to change notification settings - Fork 60
/
bluetooth_stm32_cc2640.c
1778 lines (1437 loc) · 62.4 KB
/
bluetooth_stm32_cc2640.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
// SPDX-License-Identifier: MIT
// Copyright (c) 2018-2021 The Pybricks Authors
// Bluetooth for STM32 MCU with TI CC2640
#include <pbdrv/config.h>
#if PBDRV_CONFIG_BLUETOOTH_STM32_CC2640
#include <assert.h>
#include <stdbool.h>
#include <stdint.h>
#include <string.h>
#include <pbdrv/bluetooth.h>
#include <pbdrv/gpio.h>
#include <pbio/error.h>
#include <pbio/protocol.h>
#include <pbio/task.h>
#include <pbio/util.h>
#include <pbio/version.h>
#include <contiki.h>
#include <lego_lwp3.h>
#include <att.h>
#include <gap.h>
#include <gatt.h>
#include <gattservapp.h>
#include <hci_ext.h>
#include <hci_tl.h>
#include <hci.h>
#include <util.h>
#include "./bluetooth_stm32_cc2640.h"
#define DEBUG 0
#if DEBUG == 1
#include <stdio.h>
#include <stm32f0xx.h>
#define DBG(fmt, ...) { \
char dbg[64]; \
snprintf(dbg, 64, fmt "\r\n",##__VA_ARGS__); \
for (char *d = dbg; *d; d++) { \
while (!(USART3->ISR & USART_ISR_TXE)) { } \
USART3->TDR = *d; \
} \
}
#elif DEBUG == 2
#include <stdio.h>
#include <stm32l431xx.h>
#define DBG(fmt, ...) { \
char dbg[64]; \
snprintf(dbg, 64, fmt "\r\n",##__VA_ARGS__); \
for (char *d = dbg; *d; d++) { \
while (!(LPUART1->ISR & USART_ISR_TXE)) { } \
LPUART1->TDR = *d; \
} \
}
#else
#define DBG(...)
#endif
// hub name goes in special section so that it can be modified when flashing firmware
__attribute__((section(".name")))
char pbdrv_bluetooth_hub_name[16] = "Pybricks Hub";
// used to identify which hub - Device Information Service (DIS).
// 0x2A50 - service UUID - PnP ID characteristic UUID
// 0x01 - Vendor ID Source Field - Bluetooth SIG-assigned ID
// 0x0397 - Vendor ID Field - LEGO company identifier
// 0x00XX - Product ID Field - hub device ID
// 0x0000 - Product Version Field - not applicable to most hubs
#define PNP_ID "\x50\x2a\x01\x97\x03" PBDRV_CONFIG_BLUETOOTH_STM32_CC2640_HUB_ID "\x00\x00\x00"
#ifndef PBDRV_CONFIG_BLUETOOTH_STM32_CC2640_HUB_ID
#error "Must define PBDRV_CONFIG_BLUETOOTH_STM32_CC2640_HUB_ID"
#endif
// TI Network Processor Interface (NPI)
#define NPI_SPI_SOF 0xFE // start of frame
#define NPI_SPI_HEADER_LEN 3 // zero pad, SOF, length
#define NO_CONNECTION 0xFFFF
typedef enum {
RESET_STATE_OUT_HIGH, // in reset
RESET_STATE_OUT_LOW, // out of reset
RESET_STATE_INPUT, // ?
} reset_state_t;
// Tx buffer for SPI writes
static uint8_t write_buf[TX_BUFFER_SIZE];
// Rx buffer for SPI reads
static uint8_t read_buf[RX_BUFFER_SIZE];
// size of current SPI xfer Tx data
// value is set to 0 when Tx is complete
static uint8_t write_xfer_size;
// reflects state of SRDY signal
volatile bool spi_srdy;
// set to false when xfer is started and true when xfer is complete
volatile bool spi_xfer_complete;
// set to the pending hci command opcode when a command is sent
static uint16_t hci_command_opcode;
// set to false when hci command is started and true when command status is received
static bool hci_command_status;
// set to false when hci command is started and true when command is completed
static bool hci_command_complete;
// used to synchronize advertising data handler
static bool advertising_data_received;
// handle to connected Bluetooth device
static uint16_t conn_handle = NO_CONNECTION;
// handle to connected remote control
static uint16_t remote_handle = NO_CONNECTION;
// handle to LWP3 characteristic on remote
static uint16_t remote_lwp3_char_handle = NO_CONNECTION;
// GATT service handles
static uint16_t gatt_service_handle, gatt_service_end_handle;
// GAP service handles
static uint16_t gap_service_handle, gap_service_end_handle;
// Device information service handles
static uint16_t dev_info_service_handle, dev_info_service_end_handle;
// Pybricks service handles
static uint16_t pybricks_service_handle, pybricks_service_end_handle, pybricks_char_handle;
// Pybricks tx notifications enabled
static bool pybricks_notify_en;
// Nordic UART service handles
static uint16_t uart_service_handle, uart_service_end_handle, uart_rx_char_handle, uart_tx_char_handle;
// Nordic UART tx notifications enabled
static bool uart_tx_notify_en;
PROCESS(pbdrv_bluetooth_spi_process, "Bluetooth SPI");
LIST(task_queue);
static bool bluetooth_ready;
static pbdrv_bluetooth_on_event_t bluetooth_on_event;
static pbdrv_bluetooth_receive_handler_t receive_handler;
static pbdrv_bluetooth_receive_handler_t notification_handler;
static const pbdrv_bluetooth_stm32_cc2640_platform_data_t *pdata = &pbdrv_bluetooth_stm32_cc2640_platform_data;
/**
* Converts a ble error code to the most appropriate pbio error code.
* @param [in] status The ble error code.
* @return The pbio error code.
*/
static pbio_error_t ble_error_to_pbio_error(HCI_StatusCodes_t status) {
switch (status) {
case bleSUCCESS:
return PBIO_SUCCESS;
case bleInvalidParameter:
return PBIO_ERROR_INVALID_ARG;
case bleNotConnected:
return PBIO_ERROR_NO_DEV;
case bleTimeout:
return PBIO_ERROR_TIMEDOUT;
default:
return PBIO_ERROR_FAILED;
}
}
/**
* Gets a vendor-specific event payload for @p handle.
* @param [in] handle The connection handle.
* @param [out] event The vendor-specific event.
* @param [out] status The event status.
* @return The event payload or NULL if there is no pending
* vendor-specific event or the event is for a different
* connection handle.
*/
static uint8_t *get_vendor_event(uint16_t handle, uint16_t *event, HCI_StatusCodes_t *status) {
if (read_buf[NPI_SPI_HEADER_LEN] != HCI_EVENT_PACKET) {
return NULL;
}
if (read_buf[NPI_SPI_HEADER_LEN + 1] != HCI_EVENT_VENDOR_SPECIFIC) {
return NULL;
}
*event = pbio_get_uint16_le(&read_buf[NPI_SPI_HEADER_LEN + 3]);
*status = read_buf[NPI_SPI_HEADER_LEN + 5];
if (pbio_get_uint16_le(&read_buf[NPI_SPI_HEADER_LEN + 6]) != handle) {
return NULL;
}
return &read_buf[NPI_SPI_HEADER_LEN + 9];
}
/**
* Sets the nRESET line on the Bluetooth chip.
*/
static void bluetooth_reset(reset_state_t reset) {
switch (reset) {
case RESET_STATE_OUT_HIGH:
pbdrv_gpio_out_high(&pdata->reset_gpio);
break;
case RESET_STATE_OUT_LOW:
pbdrv_gpio_out_low(&pdata->reset_gpio);
break;
case RESET_STATE_INPUT:
pbdrv_gpio_input(&pdata->reset_gpio);
break;
}
}
/**
* Sets the MRDY signal.
*/
static void spi_set_mrdy(bool mrdy) {
if (mrdy) {
pbdrv_gpio_out_low(&pdata->mrdy_gpio);
} else {
pbdrv_gpio_out_high(&pdata->mrdy_gpio);
}
}
// Internal Bluetooth driver API implementation
void pbdrv_bluetooth_init(void) {
pbdrv_gpio_set_pull(&pdata->reset_gpio, PBDRV_GPIO_PULL_NONE);
bluetooth_reset(RESET_STATE_OUT_LOW);
pbdrv_gpio_set_pull(&pdata->mrdy_gpio, PBDRV_GPIO_PULL_NONE);
spi_set_mrdy(false);
pdata->spi_init();
}
// Public Bluetooth driver API implementation
void pbdrv_bluetooth_power_on(bool on) {
if (on) {
process_start(&pbdrv_bluetooth_spi_process);
} else {
// REVISIT: should probably gracefully shutdown in case we are in the
// middle of something
process_exit(&pbdrv_bluetooth_spi_process);
}
}
bool pbdrv_bluetooth_is_ready(void) {
return bluetooth_ready;
}
const char *pbdrv_bluetooth_get_hub_name(void) {
return pbdrv_bluetooth_hub_name;
}
/**
* Sets advertising data and enables advertisements.
*/
static PT_THREAD(set_discoverable(struct pt *pt, pbio_task_t *task)) {
uint8_t data[31];
PT_BEGIN(pt);
// Set advertising data
PT_WAIT_WHILE(pt, write_xfer_size);
data[0] = 2; // length
data[1] = GAP_ADTYPE_FLAGS;
data[2] = GAP_ADTYPE_FLAGS_GENERAL | GAP_ADTYPE_FLAGS_BREDR_NOT_SUPPORTED;
data[3] = 17; // length
data[4] = GAP_ADTYPE_128BIT_MORE;
pbio_uuid128_reverse_copy(&data[5], pbio_pybricks_service_uuid);
data[21] = 2; // length
data[22] = GAP_ADTYPE_POWER_LEVEL;
data[23] = 0;
GAP_updateAdvertistigData(GAP_AD_TYPE_ADVERTISEMNT_DATA, 24, data);
PT_WAIT_UNTIL(pt, hci_command_complete);
// ignoring response data
// Set scan response data
PT_WAIT_WHILE(pt, write_xfer_size);
data[0] = sizeof(PNP_ID); // same as 1 + strlen(PNP_ID)
data[1] = GAP_ADTYPE_SERVICE_DATA;
memcpy(&data[2], PNP_ID, sizeof(PNP_ID));
uint8_t hub_name_len = strlen(pbdrv_bluetooth_hub_name);
data[11] = hub_name_len + 1;
data[12] = GAP_ADTYPE_LOCAL_NAME_COMPLETE;
memcpy(&data[13], pbdrv_bluetooth_hub_name, hub_name_len);
_Static_assert(13 + sizeof(pbdrv_bluetooth_hub_name) - 1 <= 31, "scan response is 31 octet max");
GAP_updateAdvertistigData(GAP_AD_TYPE_SCAN_RSP_DATA, 13 + hub_name_len, data);
PT_WAIT_UNTIL(pt, hci_command_complete);
// ignoring response data
// make discoverable
PT_WAIT_WHILE(pt, write_xfer_size);
GAP_makeDiscoverable(ADV_IND, GAP_INITIATOR_ADDR_TYPE_PUBLIC, NULL,
GAP_CHANNEL_MAP_ALL, GAP_FILTER_POLICY_SCAN_ANY_CONNECT_ANY);
PT_WAIT_UNTIL(pt, hci_command_complete);
// ignoring response data
task->status = PBIO_SUCCESS;
PT_END(pt);
}
void pbdrv_bluetooth_start_advertising(void) {
static pbio_task_t task;
pbio_task_init(&task, set_discoverable, NULL);
pbio_task_queue_add(task_queue, &task);
}
static PT_THREAD(set_non_discoverable(struct pt *pt, pbio_task_t *task)) {
PT_BEGIN(pt);
PT_WAIT_WHILE(pt, write_xfer_size);
GAP_endDiscoverable();
PT_WAIT_UNTIL(pt, hci_command_complete);
// ignoring response data
// REVISIT: technically, this isn't complete until GAP_EndDiscoverableDone
// event is received
task->status = PBIO_SUCCESS;
PT_END(pt);
}
void pbdrv_bluetooth_stop_advertising(void) {
static pbio_task_t task;
pbio_task_init(&task, set_non_discoverable, NULL);
pbio_task_queue_add(task_queue, &task);
}
bool pbdrv_bluetooth_is_connected(pbdrv_bluetooth_connection_t connection) {
if (connection == PBDRV_BLUETOOTH_CONNECTION_LE && conn_handle != NO_CONNECTION) {
return true;
}
if (connection == PBDRV_BLUETOOTH_CONNECTION_PYBRICKS && pybricks_notify_en) {
return true;
}
if (connection == PBDRV_BLUETOOTH_CONNECTION_UART && uart_tx_notify_en) {
return true;
}
if (connection == PBDRV_BLUETOOTH_CONNECTION_PERIPHERAL_LWP3 && remote_handle != NO_CONNECTION) {
return true;
}
return false;
}
void pbdrv_bluetooth_set_on_event(pbdrv_bluetooth_on_event_t on_event) {
bluetooth_on_event = on_event;
}
/**
* Handles sending data via a characteristic value notification.
*/
static PT_THREAD(send_value_notification(struct pt *pt, pbio_task_t *task))
{
pbdrv_bluetooth_send_context_t *send = task->context;
PT_BEGIN(pt);
retry:
PT_WAIT_WHILE(pt, write_xfer_size);
uint16_t attr_handle;
if (send->connection == PBDRV_BLUETOOTH_CONNECTION_PYBRICKS) {
if (!pybricks_notify_en) {
task->status = PBIO_ERROR_INVALID_OP;
goto done;
}
attr_handle = pybricks_char_handle;
} else if (send->connection == PBDRV_BLUETOOTH_CONNECTION_UART) {
if (!uart_tx_notify_en) {
task->status = PBIO_ERROR_INVALID_OP;
goto done;
}
attr_handle = uart_tx_char_handle;
} else {
// called with invalid connection
assert(0);
task->status = PBIO_ERROR_INVALID_ARG;
goto done;
}
{
attHandleValueNoti_t req;
req.handle = attr_handle;
req.len = send->size;
req.pValue = send->data;
ATT_HandleValueNoti(conn_handle, &req);
}
PT_WAIT_UNTIL(pt, hci_command_status);
HCI_StatusCodes_t status = read_buf[8];
if (status == blePending) {
goto retry;
}
task->status = PBIO_SUCCESS;
done:
send->done();
PT_END(pt);
}
void pbdrv_bluetooth_send(pbdrv_bluetooth_send_context_t *context) {
static pbio_task_t task;
pbio_task_init(&task, send_value_notification, context);
pbio_task_queue_add(task_queue, &task);
}
void pbdrv_bluetooth_set_receive_handler(pbdrv_bluetooth_receive_handler_t handler) {
receive_handler = handler;
}
void pbdrv_bluetooth_set_notification_handler(pbdrv_bluetooth_receive_handler_t handler) {
notification_handler = handler;
}
static PT_THREAD(scan_and_connect_task(struct pt *pt, pbio_task_t *task)) {
pbdrv_bluetooth_scan_and_connect_context_t *context = task->context;
PT_BEGIN(pt);
// start scanning
PT_WAIT_WHILE(pt, write_xfer_size);
GAP_DeviceDiscoveryRequest(GAP_DEVICE_DISCOVERY_MODE_ALL, 1, GAP_FILTER_POLICY_SCAN_ANY_CONNECT_ANY);
PT_WAIT_UNTIL(pt, hci_command_status);
context->status = read_buf[8]; // debug
try_again:
for (;;) {
advertising_data_received = false;
PT_WAIT_UNTIL(pt, {
if (task->cancel) {
goto cancel_discovery;
}
advertising_data_received;
});
// TODO: Properly parse advertising data. For now, we are assuming that
// the service UUID is at a fixed position and we are getting only
// GAP_ADTYPE_128BIT_COMPLETE and not GAP_ADTYPE_128BIT_MORE
if (
read_buf[9] != ADV_IND /* connectable undirected advertisement */ ||
read_buf[22] != 17 /* length */ || read_buf[23] != GAP_ADTYPE_128BIT_COMPLETE ||
!pbio_uuid128_reverse_compare(&read_buf[24], pbio_lwp3_hub_service_uuid) ||
read_buf[45] != context->hub_kind) {
// if this is not the desired LEGO LWP3 device, keep scanning
continue;
}
if (memcmp(context->bdaddr, &read_buf[11], 6) == 0) {
// This was the same device as last time. If the scan response
// didn't match before, it probably won't match now and we
// should try a different device.
goto try_again;
}
// save the Bluetooth address for later
context->bdaddr_type = read_buf[10];
memcpy(context->bdaddr, &read_buf[11], 6);
break;
}
for (;;) {
advertising_data_received = false;
PT_WAIT_UNTIL(pt, {
if (task->cancel) {
goto cancel_discovery;
}
advertising_data_received;
});
// TODO: Properly parse scan response data. For now, we are assuming
// that the saved Bluetooth address is sufficient to recognize correct device
if (read_buf[9] != SCAN_RSP || memcmp(&read_buf[11], context->bdaddr, 6) != 0) {
continue;
}
// if the name was passed in from the caller, then filter on name
if (context->name[0] != '\0' && strncmp(context->name, (char *)&read_buf[21], sizeof(context->name)) != 0) {
goto try_again;
}
memcpy(context->name, &read_buf[21], sizeof(context->name));
break;
}
// stop scanning
PT_WAIT_WHILE(pt, write_xfer_size);
GAP_DeviceDiscoveryCancel();
PT_WAIT_UNTIL(pt, hci_command_status);
// connect
assert(remote_handle == NO_CONNECTION);
PT_WAIT_WHILE(pt, write_xfer_size);
GAP_EstablishLinkReq(0, 0, context->bdaddr_type, context->bdaddr);
PT_WAIT_UNTIL(pt, hci_command_status);
context->status = read_buf[8]; // debug
PT_WAIT_UNTIL(pt, {
if (task->cancel) {
goto cancel_connect;
}
remote_handle != NO_CONNECTION;
});
// discover LWP3 characteristic to get attribute handle
assert(remote_lwp3_char_handle == NO_CONNECTION);
PT_WAIT_WHILE(pt, write_xfer_size);
{
attReadByTypeReq_t req = {
.startHandle = 0x0001,
.endHandle = 0xFFFF,
.type.len = 16,
};
pbio_uuid128_reverse_copy(req.type.uuid, pbio_lwp3_hub_char_uuid);
GATT_DiscCharsByUUID(remote_handle, &req);
}
PT_WAIT_UNTIL(pt, hci_command_status);
context->status = read_buf[8]; // debug
// GATT_DiscCharsByUUID() sends a "read by type request" so we have to
// wait until we get an error response to the request or we get a "read
// by type response" with status of bleProcedureComplete. There can be
// multiple responses received before the procedure is complete.
// REVISIT: what happens when remote is disconnected while waiting here?
PT_WAIT_UNTIL(pt, {
uint8_t *payload;
uint16_t event;
HCI_StatusCodes_t status;
(payload = get_vendor_event(remote_handle, &event, &status)) && ({
if (event == ATT_EVENT_ERROR_RSP && payload[0] == ATT_READ_BY_TYPE_REQ) {
task->status = PBIO_ERROR_FAILED;
goto disconnect;
}
event == ATT_EVENT_READ_BY_TYPE_RSP;
}) && ({
// hopefully the docs are correct and this is the only possible error
if (status == bleTimeout) {
task->status = PBIO_ERROR_TIMEDOUT;
goto disconnect;
}
// this assumes that there is only one matching characteristic
// (if there is more than one, we will end up with the last)
// it also assumes that it is the only characteristic in the response
if (status == bleSUCCESS) {
remote_lwp3_char_handle = pbio_get_uint16_le(&payload[4]);
}
status == bleProcedureComplete;
});
});
// enable notifications
retry:
PT_WAIT_WHILE(pt, write_xfer_size);
{
static const uint16_t enable = 0x0001;
attWriteReq_t req = {
// assuming that client characteristic configuration descriptor
// is next attribute after the characteristic value attribute
.handle = remote_lwp3_char_handle + 1,
.len = sizeof(enable),
.pValue = (uint8_t *)&enable,
};
// REVISIT: we may want to change this to write with response to ensure
// that the remote device received the message.
GATT_WriteNoRsp(remote_handle, &req);
}
PT_WAIT_UNTIL(pt, hci_command_status);
HCI_StatusCodes_t status = read_buf[8];
if (status == blePending) {
goto retry;
}
context->status = read_buf[8]; // debug
task->status = PBIO_SUCCESS;
PT_EXIT(pt);
disconnect:
PT_WAIT_WHILE(pt, write_xfer_size);
GAP_TerminateLinkReq(remote_handle, 0x13);
PT_WAIT_UNTIL(pt, hci_command_status);
// task->status must be set before goto disconnect!
PT_EXIT(pt);
cancel_connect:
PT_WAIT_WHILE(pt, write_xfer_size);
GAP_TerminateLinkReq(0xFFFE, 0x13);
PT_WAIT_UNTIL(pt, hci_command_status);
goto end_cancel;
cancel_discovery:
PT_WAIT_WHILE(pt, write_xfer_size);
GAP_DeviceDiscoveryCancel();
PT_WAIT_UNTIL(pt, hci_command_status);
end_cancel:
task->status = PBIO_ERROR_CANCELED;
PT_END(pt);
}
void pbdrv_bluetooth_scan_and_connect(pbio_task_t *task, pbdrv_bluetooth_scan_and_connect_context_t *context) {
pbio_task_init(task, scan_and_connect_task, context);
pbio_task_queue_add(task_queue, task);
}
static PT_THREAD(write_remote_task(struct pt *pt, pbio_task_t *task)) {
pbdrv_bluetooth_value_t *value = task->context;
PT_BEGIN(pt);
retry:
PT_WAIT_WHILE(pt, write_xfer_size);
{
GattWriteCharValue_t req = {
.connHandle = remote_handle,
.handle = remote_lwp3_char_handle,
.value = value->data,
.dataSize = value->size,
};
GATT_WriteCharValue(&req);
}
PT_WAIT_UNTIL(pt, hci_command_status);
HCI_StatusCodes_t status = read_buf[8];
if (status != bleSUCCESS) {
if (task->cancel) {
goto cancel;
}
if (status == blePending) {
goto retry;
}
goto exit;
}
// This gets a bit tricky. Once the request has been sent, we can't cancel
// the task, so we have to wait for the response (otherwise the response
// could be confused with the next request). The device could also become
// disconnected, in which case we never receive a response.
PT_WAIT_UNTIL(pt, {
if (remote_handle == NO_CONNECTION) {
task->status = PBIO_ERROR_NO_DEV;
PT_EXIT(pt);
}
uint8_t *payload;
uint16_t event;
(payload = get_vendor_event(remote_handle, &event, &status)) && ({
if (event == ATT_EVENT_ERROR_RSP && payload[0] == ATT_WRITE_REQ
&& pbio_get_uint16_le(&payload[1]) == remote_lwp3_char_handle) {
task->status = PBIO_ERROR_FAILED;
PT_EXIT(pt);
}
event == ATT_EVENT_WRITE_RSP;
});
});
exit:
task->status = ble_error_to_pbio_error(status);
PT_EXIT(pt);
cancel:
task->status = PBIO_ERROR_CANCELED;
PT_END(pt);
}
void pbdrv_bluetooth_write_remote(pbio_task_t *task, pbdrv_bluetooth_value_t *value) {
pbio_task_init(task, write_remote_task, value);
pbio_task_queue_add(task_queue, task);
}
static PT_THREAD(disconnect_remote_task(struct pt *pt, pbio_task_t *task)) {
PT_BEGIN(pt);
if (remote_handle != NO_CONNECTION) {
PT_WAIT_WHILE(pt, write_xfer_size);
GAP_TerminateLinkReq(remote_handle, 0x13);
PT_WAIT_UNTIL(pt, hci_command_status);
}
task->status = PBIO_SUCCESS;
PT_END(pt);
}
void pbdrv_bluetooth_disconnect_remote(void) {
static pbio_task_t task;
pbio_task_init(&task, disconnect_remote_task, NULL);
pbio_task_queue_add(task_queue, &task);
}
// Driver interrupt callbacks
void pbdrv_bluetooth_stm32_cc2640_srdy_irq(bool srdy) {
spi_srdy = srdy;
process_poll(&pbdrv_bluetooth_spi_process);
}
void pbdrv_bluetooth_stm32_cc2640_spi_xfer_irq(void) {
spi_xfer_complete = true;
process_poll(&pbdrv_bluetooth_spi_process);
}
static void read_by_type_response_uuid16(uint16_t connection_handle,
uint16_t attr_handle, uint8_t property_flags, uint16_t uuid) {
attReadByTypeRsp_t rsp;
uint8_t buf[ATT_MTU_SIZE - 2];
pbio_set_uint16_le(&buf[0], attr_handle);
buf[2] = property_flags;
pbio_set_uint16_le(&buf[3], attr_handle + 1);
pbio_set_uint16_le(&buf[5], uuid);
rsp.pDataList = buf;
rsp.dataLen = 7;
ATT_ReadByTypeRsp(connection_handle, &rsp);
}
static void read_by_type_response_uuid128(uint16_t connection_handle,
uint16_t attr_handle, uint8_t property_flags, const uint8_t *uuid) {
attReadByTypeRsp_t rsp;
uint8_t buf[ATT_MTU_SIZE - 2];
pbio_set_uint16_le(&buf[0], attr_handle);
buf[2] = property_flags;
pbio_set_uint16_le(&buf[3], attr_handle + 1);
pbio_uuid128_reverse_copy(&buf[5], uuid);
rsp.pDataList = buf;
rsp.dataLen = 21;
ATT_ReadByTypeRsp(connection_handle, &rsp);
}
// processes an event received from the Bluetooth chip
static void handle_event(uint8_t *packet) {
uint8_t event = packet[0];
uint8_t size = packet[1];
uint8_t *data = &packet[2];
(void)size;
switch (event) {
case HCI_EVENT_COMMAND_COMPLETE:
hci_command_complete = true;
break;
case HCI_EVENT_VENDOR_SPECIFIC: {
uint16_t event_code = (data[1] << 8) | data[0];
HCI_StatusCodes_t status = data[2];
uint16_t connection_handle = (data[4] << 8) | data[3];
uint8_t pdu_len = data[5];
(void)status;
(void)pdu_len;
switch (event_code) {
case ATT_EVENT_EXCHANGE_MTU_REQ: {
attExchangeMTURsp_t rsp;
rsp.serverRxMTU = 158;
ATT_ExchangeMTURsp(connection_handle, &rsp);
}
break;
case ATT_EVENT_FIND_BY_TYPE_VALUE_REQ: {
uint16_t start_handle = (data[7] << 8) | data[6];
uint16_t end_handle = (data[9] << 8) | data[8];
uint16_t type = (data[11] << 8) | data[10];
uint8_t *value = &data[12];
(void)start_handle;
(void)end_handle;
(void)type;
(void)value;
DBG("s %04X t %04X", start_handle, type);
attErrorRsp_t rsp;
rsp.reqOpcode = ATT_FIND_BY_TYPE_VALUE_REQ;
rsp.handle = start_handle;
rsp.errCode = ATT_ERR_UNSUPPORTED_REQ;
ATT_ErrorRsp(connection_handle, &rsp);
}
break;
case ATT_EVENT_READ_BY_TYPE_REQ: {
uint16_t start_handle = (data[7] << 8) | data[6];
uint16_t end_handle = (data[9] << 8) | data[8];
uint16_t type = (data[11] << 8) | data[10];
(void)end_handle;
DBG("s %04X t %04X", start_handle, type);
switch (type) {
case GATT_CHARACTER_UUID:
if (start_handle <= gap_service_handle + 1) {
read_by_type_response_uuid16(connection_handle, gap_service_handle + 1,
GATT_PROP_READ, DEVICE_NAME_UUID);
} else if (start_handle <= gap_service_handle + 3) {
read_by_type_response_uuid16(connection_handle, gap_service_handle + 3,
GATT_PROP_READ, APPEARANCE_UUID);
} else if (start_handle <= gap_service_handle + 5) {
read_by_type_response_uuid16(connection_handle, gap_service_handle + 5,
GATT_PROP_READ, PERI_CONN_PARAM_UUID);
} else if (start_handle <= dev_info_service_handle + 1) {
read_by_type_response_uuid16(connection_handle, dev_info_service_handle + 1,
GATT_PROP_READ, FIRMWARE_REVISION_STRING_UUID);
} else if (start_handle <= dev_info_service_handle + 3) {
read_by_type_response_uuid16(connection_handle, dev_info_service_handle + 3,
GATT_PROP_READ, SOFTWARE_REVISION_STRING_UUID);
} else if (start_handle <= dev_info_service_handle + 5) {
read_by_type_response_uuid16(connection_handle, dev_info_service_handle + 5,
GATT_PROP_READ, PNP_ID_UUID);
} else if (start_handle <= pybricks_service_handle + 1) {
read_by_type_response_uuid128(connection_handle, pybricks_service_handle + 1,
GATT_PROP_WRITE_NO_RSP | GATT_PROP_WRITE | GATT_PROP_NOTIFY,
pbio_pybricks_control_char_uuid);
} else if (start_handle <= uart_service_handle + 1) {
read_by_type_response_uuid128(connection_handle, uart_service_handle + 1,
GATT_PROP_WRITE_NO_RSP, pbio_nus_rx_char_uuid);
} else if (start_handle <= uart_service_handle + 3) {
read_by_type_response_uuid128(connection_handle, uart_service_handle + 3,
GATT_PROP_NOTIFY, pbio_nus_tx_char_uuid);
} else {
attErrorRsp_t rsp;
rsp.reqOpcode = ATT_READ_BY_TYPE_REQ;
rsp.handle = start_handle;
rsp.errCode = ATT_ERR_INVALID_VALUE;
ATT_ErrorRsp(connection_handle, &rsp);
}
break;
case DEVICE_NAME_UUID: {
attReadByTypeRsp_t rsp;
uint8_t buf[ATT_MTU_SIZE - 2];
uint8_t hub_name_len = strlen(pbdrv_bluetooth_hub_name);
pbio_set_uint16_le(&buf[0], gap_service_handle + 2);
memcpy(&buf[2], pbdrv_bluetooth_hub_name, hub_name_len);
rsp.pDataList = buf;
rsp.dataLen = hub_name_len + 2;
ATT_ReadByTypeRsp(connection_handle, &rsp);
}
break;
default: {
attErrorRsp_t rsp;
rsp.reqOpcode = ATT_READ_BY_TYPE_REQ;
rsp.handle = start_handle;
rsp.errCode = ATT_ERR_ATTR_NOT_FOUND;
ATT_ErrorRsp(connection_handle, &rsp);
DBG("unhandled read by type req: %04X", type);
}
break;
}
}
break;
case ATT_EVENT_READ_REQ: {
uint16_t handle = (data[7] << 8) | data[6];
if (handle == gap_service_handle + 2) {
attReadRsp_t rsp;
uint8_t buf[ATT_MTU_SIZE - 1];
uint8_t hub_name_len = strlen(pbdrv_bluetooth_hub_name);
memcpy(&buf[0], pbdrv_bluetooth_hub_name, hub_name_len);
rsp.len = hub_name_len;
rsp.pValue = buf;
ATT_ReadRsp(connection_handle, &rsp);
} else if (handle == gap_service_handle + 4) {
attReadRsp_t rsp;
uint8_t buf[ATT_MTU_SIZE - 1];
pbio_set_uint16_le(&buf[0], GAP_APPEARE_UNKNOWN);
rsp.len = 2;
rsp.pValue = buf;
ATT_ReadRsp(connection_handle, &rsp);
} else if (handle == gap_service_handle + 6) {
attReadRsp_t rsp;
uint8_t buf[ATT_MTU_SIZE - 1];
// FIXME: what should these values be?
pbio_set_uint16_le(&buf[0], 0xFFFF); // intervalMin
pbio_set_uint16_le(&buf[2], 0xFFFF); // intervalMax
pbio_set_uint16_le(&buf[4], 0xFFFF); // latency
pbio_set_uint16_le(&buf[6], 0xFFFF); // timeout
rsp.len = 8;
rsp.pValue = buf;
ATT_ReadRsp(connection_handle, &rsp);
} else if (handle == dev_info_service_handle + 2) {
attReadRsp_t rsp;
uint8_t buf[ATT_MTU_SIZE - 1];
memcpy(&buf[0], PBIO_VERSION_STR, sizeof(PBIO_VERSION_STR) - 1);
rsp.len = sizeof(PBIO_VERSION_STR) - 1;
rsp.pValue = buf;
ATT_ReadRsp(connection_handle, &rsp);
} else if (handle == dev_info_service_handle + 4) {
attReadRsp_t rsp;
uint8_t buf[ATT_MTU_SIZE - 1];
memcpy(&buf[0], PBIO_PROTOCOL_VERSION_STR, sizeof(PBIO_PROTOCOL_VERSION_STR) - 1);
rsp.len = sizeof(PBIO_PROTOCOL_VERSION_STR) - 1;
rsp.pValue = buf;
ATT_ReadRsp(connection_handle, &rsp);
} else if (handle == dev_info_service_handle + 6) {
attReadRsp_t rsp;
uint8_t buf[ATT_MTU_SIZE - 1];
buf[0] = 0x01; // Vendor ID Source Field - Bluetooth SIG-assigned ID
pbio_set_uint16_le(&buf[1], LWP3_LEGO_COMPANY_ID); // Vendor ID Field
pbio_set_uint16_le(&buf[3], PBDRV_CONFIG_BLUETOOTH_STM32_CC2640_HUB_ID[0]); // Product ID Field
pbio_set_uint16_le(&buf[5], 0); // Product Version Field
rsp.len = 7;
rsp.pValue = buf;
ATT_ReadRsp(connection_handle, &rsp);
} else if (handle == pybricks_char_handle + 1) {
attReadRsp_t rsp;
uint8_t buf[ATT_MTU_SIZE - 1];
buf[0] = pybricks_notify_en;
buf[1] = 0;
rsp.len = 2;
rsp.pValue = buf;
ATT_ReadRsp(connection_handle, &rsp);
} else if (handle == uart_tx_char_handle + 1) {
attReadRsp_t rsp;
uint8_t buf[ATT_MTU_SIZE - 1];
buf[0] = uart_tx_notify_en;
buf[1] = 0;
rsp.len = 2;
rsp.pValue = buf;
ATT_ReadRsp(connection_handle, &rsp);
} else {
DBG("unhandled read req: %04X", handle);
}
}
break;
case ATT_EVENT_READ_BY_GRP_TYPE_REQ: {
uint16_t start_handle = (data[7] << 8) | data[6];
uint16_t end_handle = (data[9] << 8) | data[8];
uint16_t group_type = (data[11] << 8) | data[10];
(void)end_handle;
DBG("s %04X g %04X", start_handle, group_type);
switch (group_type) {
case GATT_PRIMARY_SERVICE_UUID:
if (start_handle <= gatt_service_handle) {
attReadByGrpTypeRsp_t rsp;
uint8_t buf[ATT_MTU_SIZE - 2];