1 /* 2 * Copyright (C) 2020 BlueKitchen GmbH 3 * 4 * Redistribution and use in source and binary forms, with or without 5 * modification, are permitted provided that the following conditions 6 * are met: 7 * 8 * 1. Redistributions of source code must retain the above copyright 9 * notice, this list of conditions and the following disclaimer. 10 * 2. Redistributions in binary form must reproduce the above copyright 11 * notice, this list of conditions and the following disclaimer in the 12 * documentation and/or other materials provided with the distribution. 13 * 3. Neither the name of the copyright holders nor the names of 14 * contributors may be used to endorse or promote products derived 15 * from this software without specific prior written permission. 16 * 4. Any redistribution, use, or modification is done solely for 17 * personal benefit and not for any commercial purpose or for 18 * monetary gain. 19 * 20 * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS 21 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 22 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 23 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTHIAS 24 * RINGWALD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 25 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 26 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS 27 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 28 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 29 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF 30 * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 31 * SUCH DAMAGE. 32 * 33 * Please inquire about commercial licensing options at 34 * [email protected] 35 * 36 */ 37 38 #define BTSTACK_FILE__ "ll_sx1280.c" 39 40 #define DEBUG 41 42 #include <string.h> 43 44 #include "ll.h" 45 46 #include "hw.h" 47 #include "radio.h" 48 #include "sx1280.h" 49 #include "debug.h" 50 #include "btstack_config.h" 51 #include "btstack_debug.h" 52 #include "btstack_memory.h" 53 #include "btstack_memory_pool.h" 54 #include "btstack_linked_queue.h" 55 #include "bluetooth_company_id.h" 56 #include "hal_cpu.h" 57 #include "hci_event.h" 58 #include "hopping.h" 59 #include "hal_timer.h" 60 61 62 // 63 // configuration 64 // 65 66 #define AUTO_RX_TX_TIME_US 86 67 68 #define TX_PARAMS_RAMP_TIME RADIO_RAMP_02_US 69 70 // set output power in dBM, range [-18..+13] dBm - Bluetooth LE max is 10 dBM 71 #define TX_PARAMS_OUTPUT_POWER 10 72 73 74 75 #define ACL_LE_MAX_PAYLOAD 31 76 #define ADV_MAX_PAYLOAD (6+6+22) 77 #define LL_MAX_PAYLOAD 37 78 79 // split 256 bytes data buffer into 2 rx and 2 tx buffers 80 #define SX1280_RX0_OFFSET 0 81 #define SX1280_RX1_OFFSET 64 82 #define SX1280_TX0_OFFSET 128 83 #define SX1280_TX1_OFFSET 192 84 85 86 // Mask of IRQs to listen in tx and rx mode 87 #define RX_TX_IRQ_MASK (IRQ_RX_DONE | IRQ_TX_DONE | IRQ_RX_TX_TIMEOUT | IRQ_CRC_ERROR) 88 89 // sync hop delay - time we prepare for next connection event 90 #define SYNC_HOP_DELAY_US 600 91 92 // num tx buffers for use by link layer 93 #define HCI_NUM_TX_BUFFERS_LL 4 94 95 // num rx buffers 96 #define HCI_NUM_RX_BUFFERS 16 97 98 // total number PDU buffers 99 #define MAX_NUM_LL_PDUS (HCI_NUM_TX_BUFFERS_STACK + HCI_NUM_TX_BUFFERS_LL + HCI_NUM_RX_BUFFERS) 100 101 // HCI Connection Handle used for all HCI events/connections 102 #define HCI_CON_HANDLE 0x0001 103 104 // convert us to ticks, rounding to the closest tick count 105 // @note us must be <= 1000000 us = 1 s 106 #define US_TO_TICKS(US) (((((uint32_t)(US)) * 4096) + 6125) / 125000L) 107 108 // ADV PDU Types 109 enum pdu_adv_type { 110 PDU_ADV_TYPE_ADV_IND = 0x00, 111 PDU_ADV_TYPE_DIRECT_IND = 0x01, 112 PDU_ADV_TYPE_NONCONN_IND = 0x02, 113 PDU_ADV_TYPE_SCAN_REQ = 0x03, 114 PDU_ADV_TYPE_AUX_SCAN_REQ = PDU_ADV_TYPE_SCAN_REQ, 115 PDU_ADV_TYPE_SCAN_RSP = 0x04, 116 PDU_ADV_TYPE_CONNECT_IND = 0x05, 117 PDU_ADV_TYPE_AUX_CONNECT_REQ = PDU_ADV_TYPE_CONNECT_IND, 118 PDU_ADV_TYPE_SCAN_IND = 0x06, 119 PDU_ADV_TYPE_EXT_IND = 0x07, 120 PDU_ADV_TYPE_AUX_ADV_IND = PDU_ADV_TYPE_EXT_IND, 121 PDU_ADV_TYPE_AUX_SCAN_RSP = PDU_ADV_TYPE_EXT_IND, 122 PDU_ADV_TYPE_AUX_SYNC_IND = PDU_ADV_TYPE_EXT_IND, 123 PDU_ADV_TYPE_AUX_CHAIN_IND = PDU_ADV_TYPE_EXT_IND, 124 PDU_ADV_TYPE_AUX_CONNECT_RSP = 0x08, 125 }; 126 127 // DATA PDU Types 128 enum pdu_data_llid { 129 PDU_DATA_LLID_RESV = 0x00, 130 PDU_DATA_LLID_DATA_CONTINUE = 0x01, 131 PDU_DATA_LLID_DATA_START = 0x02, 132 PDU_DATA_LLID_CTRL = 0x03, 133 }; 134 135 // DATA Link Layer Control Types 136 enum pdu_data_llctrl_type { 137 PDU_DATA_LLCTRL_TYPE_CONN_UPDATE_IND = 0x00, 138 PDU_DATA_LLCTRL_TYPE_CHAN_MAP_IND = 0x01, 139 PDU_DATA_LLCTRL_TYPE_TERMINATE_IND = 0x02, 140 PDU_DATA_LLCTRL_TYPE_ENC_REQ = 0x03, 141 PDU_DATA_LLCTRL_TYPE_ENC_RSP = 0x04, 142 PDU_DATA_LLCTRL_TYPE_START_ENC_REQ = 0x05, 143 PDU_DATA_LLCTRL_TYPE_START_ENC_RSP = 0x06, 144 PDU_DATA_LLCTRL_TYPE_UNKNOWN_RSP = 0x07, 145 PDU_DATA_LLCTRL_TYPE_FEATURE_REQ = 0x08, 146 PDU_DATA_LLCTRL_TYPE_FEATURE_RSP = 0x09, 147 PDU_DATA_LLCTRL_TYPE_PAUSE_ENC_REQ = 0x0A, 148 PDU_DATA_LLCTRL_TYPE_PAUSE_ENC_RSP = 0x0B, 149 PDU_DATA_LLCTRL_TYPE_VERSION_IND = 0x0C, 150 PDU_DATA_LLCTRL_TYPE_REJECT_IND = 0x0D, 151 PDU_DATA_LLCTRL_TYPE_SLAVE_FEATURE_REQ = 0x0E, 152 PDU_DATA_LLCTRL_TYPE_CONN_PARAM_REQ = 0x0F, 153 PDU_DATA_LLCTRL_TYPE_CONN_PARAM_RSP = 0x10, 154 PDU_DATA_LLCTRL_TYPE_REJECT_EXT_IND = 0x11, 155 PDU_DATA_LLCTRL_TYPE_PING_REQ = 0x12, 156 PDU_DATA_LLCTRL_TYPE_PING_RSP = 0x13, 157 PDU_DATA_LLCTRL_TYPE_LENGTH_REQ = 0x14, 158 PDU_DATA_LLCTRL_TYPE_LENGTH_RSP = 0x15, 159 PDU_DATA_LLCTRL_TYPE_PHY_REQ = 0x16, 160 PDU_DATA_LLCTRL_TYPE_PHY_RSP = 0x17, 161 PDU_DATA_LLCTRL_TYPE_PHY_UPD_IND = 0x18, 162 PDU_DATA_LLCTRL_TYPE_MIN_USED_CHAN_IND = 0x19, 163 }; 164 165 // Radio State 166 typedef enum { 167 RADIO_LOWPOWER, 168 RADIO_RX_ERROR, 169 RADIO_TX_TIMEOUT, 170 RADIO_W4_TX_DONE_TO_RX, 171 RADIO_W4_TIMER, 172 } radio_state_t; 173 174 // Link Layer State 175 typedef enum { 176 LL_STATE_STANDBY, 177 LL_STATE_SCANNING, 178 LL_STATE_ADVERTISING, 179 LL_STATE_INITIATING, 180 LL_STATE_CONNECTED 181 } ll_state_t; 182 183 // Link Layer PDU Flags 184 typedef enum { 185 LL_PDU_FLAG_DATA_PDU = 1, 186 } ll_pdu_flags; 187 188 // Link Layer PDU, used in linked list 189 typedef struct { 190 // header 191 void * item; 192 hci_con_handle_t con_handle; 193 uint8_t flags; 194 // over the air data 195 uint8_t header; 196 uint8_t len; 197 uint8_t payload[LL_MAX_PAYLOAD]; 198 } ll_pdu_t; 199 200 // channel table: freq in hertz and whitening seed 201 static const struct { 202 uint32_t freq_hz; 203 uint8_t whitening; 204 } channel_table[] = { 205 { 2404000000, 0x01 /* 00000001 */ }, 206 { 2406000000, 0x41 /* 01000001 */ }, 207 { 2408000000, 0x21 /* 00100001 */ }, 208 { 2410000000, 0x61 /* 01100001 */ }, 209 { 2412000000, 0x11 /* 00010001 */ }, 210 { 2414000000, 0x51 /* 01010001 */ }, 211 { 2416000000, 0x31 /* 00110001 */ }, 212 { 2418000000, 0x71 /* 01110001 */ }, 213 { 2420000000, 0x09 /* 00001001 */ }, 214 { 2422000000, 0x49 /* 01001001 */ }, 215 { 2424000000, 0x29 /* 00101001 */ }, 216 { 2428000000, 0x69 /* 01101001 */ }, 217 { 2430000000, 0x19 /* 00011001 */ }, 218 { 2432000000, 0x59 /* 01011001 */ }, 219 { 2434000000, 0x39 /* 00111001 */ }, 220 { 2436000000, 0x79 /* 01111001 */ }, 221 { 2438000000, 0x05 /* 00000101 */ }, 222 { 2440000000, 0x45 /* 01000101 */ }, 223 { 2442000000, 0x25 /* 00100101 */ }, 224 { 2444000000, 0x65 /* 01100101 */ }, 225 { 2446000000, 0x15 /* 00010101 */ }, 226 { 2448000000, 0x55 /* 01010101 */ }, 227 { 2450000000, 0x35 /* 00110101 */ }, 228 { 2452000000, 0x75 /* 01110101 */ }, 229 { 2454000000, 0x0d /* 00001101 */ }, 230 { 2456000000, 0x4d /* 01001101 */ }, 231 { 2458000000, 0x2d /* 00101101 */ }, 232 { 2460000000, 0x6d /* 01101101 */ }, 233 { 2462000000, 0x1d /* 00011101 */ }, 234 { 2464000000, 0x5d /* 01011101 */ }, 235 { 2466000000, 0x3d /* 00111101 */ }, 236 { 2468000000, 0x7d /* 01111101 */ }, 237 { 2470000000, 0x03 /* 00000011 */ }, 238 { 2472000000, 0x43 /* 01000011 */ }, 239 { 2474000000, 0x23 /* 00100011 */ }, 240 { 2476000000, 0x63 /* 01100011 */ }, 241 { 2478000000, 0x13 /* 00010011 */ }, 242 { 2402000000, 0x53 /* 01010011 */ }, 243 { 2426000000, 0x33 /* 00110011 */ }, 244 { 2480000000, 0x73 /* 01110011 */ }, 245 }; 246 247 // tx buffer offset 248 static uint8_t tx_buffer_offset[] = { 249 SX1280_TX0_OFFSET, 250 SX1280_TX1_OFFSET 251 }; 252 253 // hopping context 254 static hopping_t h; 255 256 static struct { 257 258 volatile bool synced; 259 260 volatile uint16_t packet_nr_in_connection_event; 261 262 volatile uint16_t conn_interval_1250us; 263 volatile uint32_t conn_interval_us; 264 volatile uint16_t conn_interval_ticks; 265 266 volatile uint16_t conn_latency; 267 268 volatile uint16_t supervision_timeout_10ms; 269 volatile uint32_t supervision_timeout_us; 270 271 // 272 volatile uint32_t time_without_any_packets_us; 273 274 // access address 275 volatile uint32_t aa; 276 277 // start of current connection event 278 volatile uint16_t anchor_ticks; 279 280 // latest time to send tx packet before sync hop 281 volatile uint16_t conn_latest_tx_ticks; 282 283 // timeout for sync relative to anchor 284 volatile uint16_t conn_sync_hop_ticks; 285 286 // current channel 287 volatile uint8_t channel; 288 289 // CSA #2 supported 290 uint8_t csa2_support; 291 292 // channels selection algorithm index (1 for csa #2) 293 volatile uint8_t channel_selection_algorithm; 294 295 // current connection event, first one starts with 0 296 // - needed for connection param and channel map updates as well as encryption 297 volatile uint16_t connection_event; 298 299 // pending channel map update 300 volatile bool channel_map_update_pending; 301 volatile uint16_t channel_map_update_instant; 302 volatile uint8_t channel_map_update_map[5]; 303 304 // pending connection param update 305 volatile bool conn_param_update_pending; 306 volatile uint16_t conn_param_update_instant; 307 volatile uint8_t conn_param_update_win_size; 308 volatile uint16_t conn_param_update_win_offset; 309 volatile uint16_t conn_param_update_interval_1250us; 310 volatile uint16_t conn_param_update_latency; 311 volatile uint32_t conn_param_update_timeout_us; 312 313 // our bd_addr as little endian 314 uint8_t bd_addr_le[6]; 315 316 // peer addr 317 uint8_t peer_addr_type; 318 uint8_t peer_addr[6]; 319 320 // adv data 321 uint8_t adv_len; 322 uint8_t adv_data[31]; 323 324 // adv param 325 uint8_t adv_map; 326 uint32_t adv_interval_us; 327 328 // next expected sequence number 329 volatile uint8_t next_expected_sequence_number; 330 331 // transmit sequence number 332 volatile uint8_t transmit_sequence_number; 333 334 // num completed packets 335 volatile uint8_t num_completed; 336 337 // rx queue 338 btstack_linked_queue_t rx_queue; 339 340 // current incoming packet 341 ll_pdu_t * rx_pdu; 342 343 // rx packet ready 344 bool rx_pdu_received; 345 346 // tx queue of outgoing pdus 347 btstack_linked_queue_t tx_queue; 348 349 // pdus transferred into controller tx buffers 350 ll_pdu_t * tx_buffer_pdu[2]; 351 352 // manage tx packets on controller 353 uint8_t num_tx_pdus_on_controller; 354 355 // index of next tx buffer to send 356 uint8_t next_tx_buffer; 357 358 } ctx; 359 360 static radio_state_t radio_state = RADIO_LOWPOWER; 361 362 // Buffer pool 363 static ll_pdu_t ll_pdu_pool_storage[MAX_NUM_LL_PDUS]; 364 static btstack_memory_pool_t ll_pdu_pool; 365 366 // single ll control response 367 static ll_pdu_t ll_tx_packet; 368 369 // Link Layer State 370 static ll_state_t ll_state; 371 static uint32_t ll_scan_interval_us; 372 static uint32_t ll_scan_window_us; 373 374 static ll_pdu_t * ll_reserved_acl_buffer; 375 static void (*controller_packet_handler)(uint8_t packet_type, uint8_t * packet, uint16_t size); 376 377 static uint8_t ll_outgoing_hci_event[258]; 378 static bool ll_send_disconnected; 379 static bool ll_send_connection_complete; 380 381 // prototypes 382 static void radio_set_timer_ticks(uint32_t anchor_offset_ticks); 383 384 385 // memory pool for acl-le pdus 386 static ll_pdu_t * btstack_memory_ll_pdu_get(void){ 387 void * buffer = btstack_memory_pool_get(&ll_pdu_pool); 388 if (buffer){ 389 memset(buffer, 0, sizeof(ll_pdu_t)); 390 } 391 return (ll_pdu_t *) buffer; 392 } 393 394 static void btstack_memory_ll_pdu_free(ll_pdu_t *acl_le_pdu){ 395 btstack_memory_pool_free(&ll_pdu_pool, acl_le_pdu); 396 } 397 398 399 static bool receive_prepare_rx_bufffer(void){ 400 if (ctx.rx_pdu == NULL){ 401 ctx.rx_pdu = btstack_memory_ll_pdu_get(); 402 } 403 if (ctx.rx_pdu == NULL){ 404 printf("No free RX buffer\n"); 405 return false; 406 } else { 407 return true; 408 } 409 } 410 411 static void receive_response(void){ 412 if (receive_prepare_rx_bufffer()) { 413 Radio.SetRx( ( TickTime_t ) { RADIO_TICK_SIZE_0015_US, 10 } ); // 220 us 414 } 415 } 416 417 static void receive_first_master(void){ 418 if (receive_prepare_rx_bufffer()){ 419 Radio.SetRx( ( TickTime_t ) { RADIO_TICK_SIZE_1000_US, 1000 } ); 420 } 421 } 422 423 static void receive_master(void){ 424 if (receive_prepare_rx_bufffer()) { 425 Radio.SetRx((TickTime_t) {RADIO_TICK_SIZE_1000_US, 1}); 426 } 427 } 428 429 430 static void send_adv(void){ 431 // setup advertisement: header (2) + addr (6) + data (31) 432 uint8_t adv_buffer[39]; 433 adv_buffer[0] = PDU_ADV_TYPE_ADV_IND; // TODO: also set private address bits 434 adv_buffer[1] = 6 + ctx.adv_len; 435 memcpy(&adv_buffer[2], ctx.bd_addr_le, 6); 436 memcpy(&adv_buffer[8], ctx.adv_data, ctx.adv_len); 437 uint16_t packet_size = 2 + adv_buffer[1]; 438 SX1280HalWriteBuffer( tx_buffer_offset[ctx.next_tx_buffer], adv_buffer, packet_size ); 439 SX1280SetTx( ( TickTime_t ){ RADIO_TICK_SIZE_1000_US, 1 } ); 440 } 441 442 443 static void select_channel(uint8_t channel){ 444 // Set Whitening seed 445 Radio.SetWhiteningSeed( channel_table[channel].whitening ); 446 447 // Sel Frequency 448 Radio.SetRfFrequency( channel_table[channel].freq_hz ); 449 } 450 451 static void next_channel(void){ 452 switch (ctx.channel_selection_algorithm){ 453 case 0: 454 ctx.channel = hopping_csa1_get_next_channel( &h ); 455 break; 456 case 1: 457 ctx.channel = hopping_csa2_get_channel_for_counter( &h, ctx.connection_event); 458 break; 459 default: 460 break; 461 } 462 select_channel(ctx.channel); 463 } 464 465 static void ll_advertising_statemachine(void){ 466 switch ( radio_state) { 467 case RADIO_RX_ERROR: 468 case RADIO_LOWPOWER: 469 // find next channel 470 while (ctx.channel < 40){ 471 ctx.channel++; 472 if ((ctx.adv_map & (1 << (ctx.channel - 37))) != 0) { 473 // Set Channel 474 select_channel(ctx.channel); 475 radio_state = RADIO_W4_TX_DONE_TO_RX; 476 send_adv(); 477 break; 478 } 479 if (ctx.channel >= 40){ 480 // Set timer 481 radio_state = RADIO_W4_TIMER; 482 uint32_t adv_interval_ticks = US_TO_TICKS(ctx.adv_interval_us); 483 radio_set_timer_ticks(adv_interval_ticks); 484 } 485 } 486 break; 487 default: 488 break; 489 } 490 } 491 492 static void start_advertising(void){ 493 494 Radio.StopAutoTx(); 495 496 PacketParams_t packetParams; 497 packetParams.PacketType = PACKET_TYPE_BLE; 498 packetParams.Params.Ble.BlePacketType = BLE_EYELONG_1_0; 499 packetParams.Params.Ble.ConnectionState = BLE_PAYLOAD_LENGTH_MAX_37_BYTES; 500 packetParams.Params.Ble.CrcField = BLE_CRC_3B; 501 packetParams.Params.Ble.Whitening = RADIO_WHITENING_ON; 502 Radio.SetPacketParams( &packetParams ); 503 504 // Set CRC init value 0x555555 505 Radio.WriteRegister(0x9c7, 0x55 ); 506 Radio.WriteRegister(0x9c8, 0x55 ); 507 Radio.WriteRegister(0x9c9, 0x55 ); 508 509 // Set AccessAddress for ADV packets 510 Radio.SetBleAdvertizerAccessAddress( ); 511 512 radio_state = RADIO_LOWPOWER; 513 ll_state = LL_STATE_ADVERTISING; 514 515 // prepare 516 ctx.channel = 36; 517 ctx.anchor_ticks = hal_timer_get_ticks(); 518 519 // and get started 520 ll_advertising_statemachine(); 521 } 522 523 static void start_hopping(void){ 524 PacketParams_t packetParams; 525 packetParams.PacketType = PACKET_TYPE_BLE; 526 packetParams.Params.Ble.BlePacketType = BLE_EYELONG_1_0; 527 packetParams.Params.Ble.ConnectionState = BLE_PAYLOAD_LENGTH_MAX_31_BYTES; 528 packetParams.Params.Ble.CrcField = BLE_CRC_3B; 529 packetParams.Params.Ble.Whitening = RADIO_WHITENING_ON; 530 Radio.SetPacketParams( &packetParams ); 531 532 } 533 534 static void radio_stop_timer(void){ 535 hal_timer_stop(); 536 } 537 538 static void radio_set_timer_ticks(uint32_t anchor_offset_ticks){ 539 radio_stop_timer(); 540 // set timer for next radio event relative to anchor 541 uint16_t timeout_ticks = (uint16_t) (ctx.anchor_ticks + anchor_offset_ticks); 542 hal_timer_start(timeout_ticks); 543 } 544 545 static void ctx_set_conn_interval(uint16_t conn_interval_1250us){ 546 ctx.conn_interval_1250us = conn_interval_1250us; 547 ctx.conn_interval_us = ctx.conn_interval_1250us * 1250; 548 ctx.conn_interval_ticks = US_TO_TICKS(ctx.conn_interval_us); 549 ctx.conn_sync_hop_ticks = US_TO_TICKS(ctx.conn_interval_us - SYNC_HOP_DELAY_US); 550 551 // latest time to send a packet before getting ready for next cnonection event 552 uint16_t max_packet_time_incl_ifs_us = 500; 553 ctx.conn_latest_tx_ticks = US_TO_TICKS(ctx.conn_interval_us - SYNC_HOP_DELAY_US - max_packet_time_incl_ifs_us); 554 } 555 556 static void ll_terminate(void){ 557 ll_state = LL_STATE_STANDBY; 558 ctx.conn_param_update_pending = false; 559 ctx.channel_map_update_pending = false; 560 // stop sync hop timer 561 radio_stop_timer(); 562 // free outgoing tx packets 563 uint8_t i; 564 for (i=0;i<2;i++){ 565 if ((ctx.tx_buffer_pdu[i] != NULL) && (ctx.tx_buffer_pdu[i] != &ll_tx_packet)){ 566 btstack_memory_ll_pdu_free(ctx.tx_buffer_pdu[i]); 567 ctx.tx_buffer_pdu[i] = NULL; 568 } 569 } 570 ctx.num_tx_pdus_on_controller = 0; 571 // free queued tx packets 572 while (true){ 573 ll_pdu_t * tx_packet = (ll_pdu_t *) btstack_linked_queue_dequeue(&ctx.tx_queue); 574 if (tx_packet != NULL) { 575 btstack_memory_ll_pdu_free(tx_packet); 576 } else { 577 break; 578 } 579 } 580 // disable auto tx 581 Radio.StopAutoTx(); 582 // notify host stack 583 ll_send_disconnected = true; 584 } 585 586 // load queued tx pdu into next free tx buffer 587 static void preload_tx_buffer(void){ 588 if (ctx.num_tx_pdus_on_controller >= 2) return; 589 590 ll_pdu_t * tx_pdu = (ll_pdu_t *) btstack_linked_queue_dequeue(&ctx.tx_queue); 591 if (tx_pdu == NULL) return; 592 593 const uint16_t max_packet_len = 2 + 27; 594 uint8_t index = (ctx.next_tx_buffer + ctx.num_tx_pdus_on_controller) & 1; 595 ctx.tx_buffer_pdu[index] = tx_pdu; 596 SX1280HalWriteBuffer( tx_buffer_offset[index], (uint8_t *) &ctx.tx_buffer_pdu[index]->header, max_packet_len); 597 598 ctx.num_tx_pdus_on_controller++; 599 // printf("preload %u bytes into %u\n", ctx.tx_buffer_pdu[index]->len, index); 600 } 601 602 static void radio_timer_handler(void){ 603 604 uint16_t t0 = hal_timer_get_ticks(); 605 606 switch (ll_state){ 607 case LL_STATE_CONNECTED: 608 // check supervision timeout 609 ctx.time_without_any_packets_us += ctx.conn_interval_us; 610 if (ctx.time_without_any_packets_us > ctx.supervision_timeout_us) { 611 printf("Supervision timeout\n\n"); 612 ll_terminate(); 613 return; 614 } 615 616 // prepare next connection event 617 ctx.connection_event++; 618 ctx.anchor_ticks += ctx.conn_interval_ticks; 619 620 ctx.packet_nr_in_connection_event = 0; 621 next_channel(); 622 623 if (ctx.channel_map_update_pending && (ctx.channel_map_update_instant == ctx.connection_event)) { 624 hopping_set_channel_map( &h, (const uint8_t *) &ctx.channel_map_update_map ); 625 ctx.channel_map_update_pending = false; 626 } 627 628 if (ctx.conn_param_update_pending && ((ctx.conn_param_update_instant) == ctx.connection_event) ) { 629 ctx_set_conn_interval(ctx.conn_param_update_interval_1250us); 630 ctx.conn_latency = ctx.conn_param_update_latency; 631 ctx.supervision_timeout_us = ctx.conn_param_update_timeout_us; 632 ctx.conn_param_update_pending = false; 633 634 log_info("Conn param update now"); 635 636 radio_stop_timer(); 637 ctx.synced = false; 638 } 639 640 // preload tx pdu 641 preload_tx_buffer(); 642 643 if (ctx.synced){ 644 // restart radio timer (might get overwritten by first packet) 645 radio_set_timer_ticks(ctx.conn_sync_hop_ticks); 646 647 receive_master(); 648 } else { 649 // just wait longer 650 receive_first_master(); 651 } 652 653 // printf("--SYNC-Ch %02u-Event %04u - t %08u--\n", ctx.channel, ctx.connection_event, t0); 654 break; 655 case LL_STATE_ADVERTISING: 656 // send adv on all configured channels 657 ctx.channel = 36; 658 ctx.anchor_ticks = t0; 659 radio_stop_timer(); 660 ll_advertising_statemachine(); 661 radio_state = RADIO_LOWPOWER; 662 break; 663 default: 664 break; 665 } 666 667 } 668 669 static void radio_fetch_rx_pdu(void){ 670 671 if (!ctx.rx_pdu_received) return; 672 ctx.rx_pdu_received = false; 673 674 // fetch reserved rx pdu 675 ll_pdu_t * rx_packet = ctx.rx_pdu; 676 btstack_assert(rx_packet != NULL); 677 678 // read max packet 679 uint16_t max_packet_len = 2 + 27; 680 SX1280HalReadBuffer( SX1280_RX0_OFFSET, &rx_packet->header, max_packet_len); 681 682 // queue if not empty 683 if (rx_packet->len != 0){ 684 685 // packet used 686 ctx.rx_pdu = NULL; 687 688 // mark as data packet 689 rx_packet->flags |= LL_PDU_FLAG_DATA_PDU; 690 691 // queue received packet 692 btstack_linked_queue_enqueue(&ctx.rx_queue, (btstack_linked_item_t *) rx_packet); 693 } 694 } 695 696 /** Radio IRQ handlers */ 697 static void radio_on_tx_done(void ){ 698 switch (radio_state){ 699 case RADIO_W4_TX_DONE_TO_RX: 700 receive_response(); 701 break; 702 default: 703 break; 704 } 705 switch (ll_state){ 706 case LL_STATE_CONNECTED: 707 radio_fetch_rx_pdu(); 708 preload_tx_buffer(); 709 break; 710 default: 711 break; 712 } 713 } 714 715 static void radio_on_rx_done(void ){ 716 uint16_t packet_end_ticks = hal_timer_get_ticks(); 717 718 if (ll_state == LL_STATE_ADVERTISING){ 719 720 // fetch reserved rx pdu 721 ll_pdu_t * rx_packet = ctx.rx_pdu; 722 btstack_assert(rx_packet != NULL); 723 ctx.rx_pdu = NULL; 724 725 // no data packet 726 rx_packet->flags = 0; 727 uint16_t max_packet_len = 2 + LL_MAX_PAYLOAD; 728 729 SX1280HalReadBuffer( SX1280_RX0_OFFSET, &rx_packet->header, max_packet_len); 730 731 // queue received packet 732 btstack_linked_queue_enqueue(&ctx.rx_queue, (btstack_linked_item_t *) rx_packet); 733 734 } else if (ll_state == LL_STATE_CONNECTED){ 735 736 // get and parse rx pdu header 737 uint8_t rx_buffer[2]; 738 SX1280HalReadBuffer( SX1280_RX0_OFFSET, rx_buffer, 2); 739 uint8_t rx_header = rx_buffer[0]; 740 uint8_t rx_len = rx_buffer[1]; 741 uint8_t next_expected_sequence_number = (rx_header >> 2) & 1; 742 uint8_t sequence_number = (rx_header >> 3) & 1; 743 // more data field not used yet 744 // uint8_t more_data = (rx_packet->header >> 4) & 1; 745 746 // only accept packets where len <= payload size 747 if (rx_len <= LL_MAX_PAYLOAD){ 748 // update state 749 ctx.next_expected_sequence_number = 1 - sequence_number; 750 751 // register pdu fetch 752 ctx.rx_pdu_received = true; 753 } 754 755 // report outgoing packet as ack'ed and free if confirmed by peer 756 bool tx_acked = ctx.transmit_sequence_number != next_expected_sequence_number; 757 if (tx_acked){ 758 if (ctx.num_tx_pdus_on_controller > 0){ 759 btstack_assert(ctx.tx_buffer_pdu[ctx.next_tx_buffer] != NULL); 760 // if non link-layer packet, free buffer and report as completed 761 if (ctx.tx_buffer_pdu[ctx.next_tx_buffer] != &ll_tx_packet){ 762 btstack_memory_ll_pdu_free(ctx.tx_buffer_pdu[ctx.next_tx_buffer]); 763 ctx.tx_buffer_pdu[ctx.next_tx_buffer] = NULL; 764 ctx.num_completed++; 765 } 766 // next buffer 767 ctx.num_tx_pdus_on_controller--; 768 ctx.next_tx_buffer = (ctx.next_tx_buffer + 1 ) & 1; 769 } 770 ctx.transmit_sequence_number = next_expected_sequence_number; 771 } 772 773 // restart supervision timeout 774 ctx.time_without_any_packets_us = 0; 775 776 // check if we can sent a full packet before sync hop 777 int16_t now_ticks = packet_end_ticks - ctx.anchor_ticks; 778 if (ctx.synced && (now_ticks > ctx.conn_latest_tx_ticks)){ 779 // disable AutoTX to abort sending of next packet 780 Radio.SetFs(); 781 log_info("Close before Sync hop: now %u > %u", now_ticks, ctx.conn_latest_tx_ticks); 782 783 // get rx pdu and 784 radio_fetch_rx_pdu(); 785 return; 786 } 787 788 // setup empty packet in ll buffer if no tx packet was preloaded 789 if (ctx.num_tx_pdus_on_controller == 0) { 790 ctx.tx_buffer_pdu[ctx.next_tx_buffer] = &ll_tx_packet; 791 ctx.num_tx_pdus_on_controller++; 792 ll_tx_packet.header = PDU_DATA_LLID_DATA_CONTINUE; 793 ll_tx_packet.len = 0; 794 } 795 796 // setup pdu header 797 uint8_t packet_header[2]; 798 uint8_t md = btstack_linked_queue_empty(&ctx.tx_queue) ? 0 : 1; 799 packet_header[0] = (md << 4) | (ctx.transmit_sequence_number << 3) | (ctx.next_expected_sequence_number << 2) | ctx.tx_buffer_pdu[ctx.next_tx_buffer]->header; 800 packet_header[1] = ctx.tx_buffer_pdu[ctx.next_tx_buffer]->len; 801 802 // select outgoing tx buffer and update pdu header 803 SX1280SetBufferBaseAddresses( tx_buffer_offset[ctx.next_tx_buffer], SX1280_RX0_OFFSET); 804 SX1280HalWriteBuffer( tx_buffer_offset[ctx.next_tx_buffer], (uint8_t *) packet_header, sizeof(packet_header)); 805 806 // update operating state 807 SX1280AutoTxWillStart(); 808 809 // set anchor on first packet in connection event 810 if (ctx.packet_nr_in_connection_event == 0){ 811 812 // preamble (1) + aa (4) + header (1) + len (1) + payload (len) + crc (3) -- ISR handler ca. 35 us 813 uint16_t timestamp_delay = (10 + rx_len) * 8 - 35; 814 uint16_t packet_start_ticks = packet_end_ticks - US_TO_TICKS(timestamp_delay); 815 816 ctx.anchor_ticks = packet_start_ticks; 817 ctx.synced = true; 818 radio_set_timer_ticks(ctx.conn_sync_hop_ticks); 819 } 820 821 ctx.packet_nr_in_connection_event++; 822 823 // printf("RX %02x -- tx buffer %u, %02x %02x\n", rx_header, ctx.next_tx_buffer, packet_header[0], packet_header[1]); 824 } 825 } 826 827 static void radio_on_tx_timeout(void ){ 828 radio_state = RADIO_TX_TIMEOUT; 829 printf( "<>>>>>>>>TXE\n\r" ); 830 } 831 832 static void radio_on_rx_timeout(void ){ 833 switch (ll_state){ 834 case LL_STATE_ADVERTISING: 835 radio_state = RADIO_RX_ERROR; 836 break; 837 default: 838 break; 839 } 840 } 841 842 static void radio_on_rx_error(IrqErrorCode_t errorCode ){ 843 switch (ll_state){ 844 case LL_STATE_ADVERTISING: 845 radio_state = RADIO_RX_ERROR; 846 break; 847 default: 848 break; 849 } 850 } 851 852 const static RadioCallbacks_t Callbacks = 853 { 854 &radio_on_tx_done, // txDone 855 &radio_on_rx_done, // rxDone 856 NULL, // syncWordDone 857 NULL, // headerDone 858 &radio_on_tx_timeout, // txTimeout 859 &radio_on_rx_timeout, // rxTimeout 860 &radio_on_rx_error, // rxError 861 NULL, // rangingDone 862 NULL, // cadDone 863 }; 864 865 // Link Layer 866 867 static void ll_emit_hci_event(const hci_event_t * event, ...){ 868 va_list argptr; 869 va_start(argptr, event); 870 uint16_t length = hci_event_create_from_template_and_arglist(ll_outgoing_hci_event, event, argptr); 871 va_end(argptr); 872 controller_packet_handler(HCI_EVENT_PACKET, ll_outgoing_hci_event, length); 873 } 874 875 void ll_init(void){ 876 877 // setup memory pools 878 btstack_memory_pool_create(&ll_pdu_pool, ll_pdu_pool_storage, MAX_NUM_LL_PDUS, sizeof(ll_pdu_t)); 879 880 // set test bd addr 33:33:33:33:33:33 881 memset(ctx.bd_addr_le, 0x33, 6); 882 883 // default channels, advertising interval 884 ctx.adv_map = 0x7; 885 ctx.adv_interval_us = 1280000; 886 887 // init timer 888 hal_timer_init(); 889 hal_timer_set_callback(&radio_timer_handler); 890 } 891 892 void ll_radio_on(void){ 893 894 Radio.Init( (RadioCallbacks_t *) &Callbacks ); 895 Radio.SetRegulatorMode( USE_DCDC ); // Can also be set in LDO mode but consume more power 896 Radio.SetInterruptMode( ); 897 Radio.SetDioIrqParams( RX_TX_IRQ_MASK, RX_TX_IRQ_MASK, IRQ_RADIO_NONE, IRQ_RADIO_NONE ); 898 899 ModulationParams_t modulationParams; 900 modulationParams.PacketType = PACKET_TYPE_BLE; 901 modulationParams.Params.Ble.BitrateBandwidth = GFSK_BLE_BR_1_000_BW_1_2; 902 modulationParams.Params.Ble.ModulationIndex = GFSK_BLE_MOD_IND_0_50; 903 modulationParams.Params.Ble.ModulationShaping = RADIO_MOD_SHAPING_BT_0_5; 904 905 Radio.SetStandby( STDBY_RC ); 906 Radio.SetPacketType( modulationParams.PacketType ); 907 Radio.SetModulationParams( &modulationParams ); 908 Radio.SetBufferBaseAddresses( SX1280_TX0_OFFSET, SX1280_RX0_OFFSET ); 909 Radio.SetTxParams( TX_PARAMS_OUTPUT_POWER, TX_PARAMS_RAMP_TIME ); 910 911 // Go back to Frequcency Synthesis Mode, reduces transition time between Rx<->TX 912 Radio.SetAutoFS(1); 913 914 // quick test 915 uint8_t data[] = { 1, 2, 4, 8, 16, 32, 64, 128 }; 916 Radio.WriteBuffer(0, data, sizeof(data)); 917 uint8_t check[8]; 918 Radio.ReadBuffer(0, check, sizeof(data)); 919 if (memcmp(data, check, sizeof(data)) != 0){ 920 printf_hexdump(data, sizeof(data)); 921 printf_hexdump(check, sizeof(data)); 922 btstack_assert(false); 923 } 924 925 ll_state = LL_STATE_STANDBY; 926 } 927 928 static void ll_handle_conn_ind(ll_pdu_t * rx_packet){ 929 printf("Connect Req: "); 930 printf_hexdump(&rx_packet->header, rx_packet->len + 2); 931 932 uint8_t * init_addr = &rx_packet->payload[0]; 933 uint8_t * adv_addr = &rx_packet->payload[6]; 934 uint8_t chan_sel = (rx_packet->header >> 5) & 1; 935 936 // verify AdvA 937 if (memcmp(ctx.bd_addr_le, adv_addr, 6) != 0){ 938 // differs, go back to adv sending 939 radio_state = RADIO_LOWPOWER; 940 return; 941 } 942 943 // TODO: get remote addr type 944 ctx.peer_addr_type = 0; 945 memcpy(ctx.peer_addr, init_addr, 6); 946 947 // get params for HCI event 948 const uint8_t * ll_data = &rx_packet->payload[12]; 949 950 ctx.aa = little_endian_read_32(ll_data, 0); 951 uint8_t crc_init_0 = ll_data[4]; 952 uint8_t crc_init_1 = ll_data[5]; 953 uint8_t crc_init_2 = ll_data[6]; 954 uint8_t win_size = ll_data[7]; 955 uint16_t win_offset = little_endian_read_16(ll_data, 8); 956 uint16_t conn_interval_1250us = little_endian_read_16(ll_data, 10); 957 ctx.conn_latency = little_endian_read_16(ll_data, 12); 958 ctx.supervision_timeout_10ms = little_endian_read_16(ll_data, 14); 959 const uint8_t * channel_map = &ll_data[16]; 960 uint8_t hop = ll_data[21] & 0x1f; 961 uint8_t sca = ll_data[21] >> 5; 962 963 UNUSED(sca); 964 UNUSED(win_offset); 965 UNUSED(win_size); 966 967 ctx_set_conn_interval(conn_interval_1250us); 968 969 // convert to us 970 ctx.supervision_timeout_us = ctx.supervision_timeout_10ms * 10000; 971 ctx.connection_event = 0; 972 ctx.packet_nr_in_connection_event = 0; 973 ctx.next_expected_sequence_number = 0; 974 ctx.transmit_sequence_number = 0; 975 976 // set AA 977 Radio.SetBleAccessAddress(ctx.aa); 978 979 // set CRC init value 980 Radio.WriteRegister(0x9c7, crc_init_2); 981 Radio.WriteRegister(0x9c8, crc_init_1); 982 Radio.WriteRegister(0x9c9, crc_init_0); 983 984 printf("Connection interval %u us\n", ctx.conn_interval_us); 985 printf("Connection timeout %u us\n", ctx.supervision_timeout_us); 986 printf("AA %08x\n", ctx.aa); 987 printf("CRC Init 0x%02x%02x%02x\n", crc_init_2, crc_init_1, crc_init_0); 988 989 // init hopping 990 hopping_init( &h ); 991 hopping_set_channel_map( &h, channel_map); 992 ctx.channel_selection_algorithm = ctx.csa2_support & chan_sel; 993 switch (ctx.channel_selection_algorithm){ 994 case 0: 995 hopping_csa1_set_hop_increment( &h, hop ); 996 break; 997 case 1: 998 hopping_csa2_set_access_address( &h, ctx.aa); 999 break; 1000 default: 1001 break; 1002 } 1003 next_channel(); 1004 1005 start_hopping(); 1006 1007 // Enable Rx->Tx in 150 us for BLE 1008 // Note: Driver subtracts AUTO_RX_TX_OFFSET (33) from it and 150 should be correct, Raccoon reports 181 us then, so -31 1009 // Radio.SetAutoTx(119); 1010 1011 // SetAutoTX(100) - direct write / ignore compensation 1012 uint8_t buf[2]; 1013 big_endian_store_16(buf, 0, AUTO_RX_TX_TIME_US); 1014 SX1280HalWriteCommand( RADIO_SET_AUTOTX, buf, 2 ); 1015 1016 // pre-load tx pdu 1017 ctx.num_tx_pdus_on_controller = 0; 1018 ctx.next_tx_buffer = 0; 1019 preload_tx_buffer(); 1020 1021 // get next packet 1022 ll_state = LL_STATE_CONNECTED; 1023 1024 receive_first_master(); 1025 ll_send_connection_complete = true; 1026 } 1027 1028 static void ll_handle_control(ll_pdu_t * rx_packet){ 1029 ll_pdu_t * tx_packet = &ll_tx_packet; 1030 uint8_t opcode = rx_packet->payload[0]; 1031 switch (opcode){ 1032 case PDU_DATA_LLCTRL_TYPE_VERSION_IND: 1033 tx_packet->len = 6; 1034 tx_packet->header = PDU_DATA_LLID_CTRL; 1035 tx_packet->payload[0] = PDU_DATA_LLCTRL_TYPE_VERSION_IND; 1036 tx_packet->payload[1] = 0x06; // VersNr = Bluetooth Core V4.0 1037 little_endian_store_16(tx_packet->payload, 2, BLUETOOTH_COMPANY_ID_BLUEKITCHEN_GMBH); 1038 little_endian_store_16(tx_packet->payload, 4, 0); 1039 btstack_linked_queue_enqueue(&ctx.tx_queue, (btstack_linked_item_t *) tx_packet); 1040 printf("Queue Version Ind\n"); 1041 break; 1042 case PDU_DATA_LLCTRL_TYPE_FEATURE_REQ: 1043 tx_packet->len = 9; 1044 tx_packet->header = PDU_DATA_LLID_CTRL; 1045 tx_packet->payload[0] = PDU_DATA_LLCTRL_TYPE_FEATURE_RSP; 1046 // TODO: set features of our controller 1047 memset(&tx_packet->payload[1], 0, 8); 1048 btstack_linked_queue_enqueue(&ctx.tx_queue, (btstack_linked_item_t *) tx_packet); 1049 printf("Queue Feature Rsp\n"); 1050 break; 1051 case PDU_DATA_LLCTRL_TYPE_CHAN_MAP_IND: 1052 memcpy((uint8_t *) ctx.channel_map_update_map, &rx_packet->payload[1], 5); 1053 ctx.channel_map_update_instant = little_endian_read_16(rx_packet->payload, 6); 1054 ctx.channel_map_update_pending = true; 1055 break; 1056 case PDU_DATA_LLCTRL_TYPE_CONN_UPDATE_IND: 1057 ctx.conn_param_update_win_size = tx_packet->payload[1]; 1058 ctx.conn_param_update_win_offset = little_endian_read_16(rx_packet->payload, 2); 1059 ctx.conn_param_update_interval_1250us = little_endian_read_16(rx_packet->payload, 4); 1060 ctx.conn_param_update_latency = little_endian_read_16(rx_packet->payload, 6); 1061 ctx.conn_param_update_timeout_us = little_endian_read_16(rx_packet->payload, 8) * 10000; 1062 ctx.conn_param_update_instant = little_endian_read_16(rx_packet->payload, 10); 1063 ctx.conn_param_update_pending = true; 1064 log_info("PDU_DATA_LLCTRL_TYPE_CONN_UPDATE_IND, conn interval %u 1250us at instant %u", 1065 (unsigned int) ctx.conn_param_update_interval_1250us, ctx.conn_param_update_instant); 1066 break; 1067 case PDU_DATA_LLCTRL_TYPE_TERMINATE_IND: 1068 printf("Terminate!\n"); 1069 ll_terminate(); 1070 break; 1071 default: 1072 break; 1073 } 1074 } 1075 1076 static void ll_handle_data(ll_pdu_t * rx_packet){ 1077 if (ll_state != LL_STATE_CONNECTED) return; 1078 btstack_assert(rx_packet->len <= LL_MAX_PAYLOAD); 1079 uint8_t acl_packet[4 + LL_MAX_PAYLOAD]; 1080 // ACL Header 1081 uint8_t ll_id = rx_packet->header & 3; 1082 acl_packet[0] = 0x01; 1083 acl_packet[1] = ll_id << 4; 1084 little_endian_store_16(acl_packet, 2, rx_packet->len); 1085 memcpy(&acl_packet[4], rx_packet->payload, rx_packet->len); 1086 (*controller_packet_handler)(HCI_ACL_DATA_PACKET, acl_packet, rx_packet->len + 4); 1087 } 1088 1089 void ll_set_scan_parameters(uint8_t le_scan_type, uint16_t le_scan_interval, uint16_t le_scan_window, uint8_t own_address_type, uint8_t scanning_filter_policy){ 1090 // TODO .. store other params 1091 ll_scan_interval_us = ((uint32_t) le_scan_interval) * 625; 1092 ll_scan_window_us = ((uint32_t) le_scan_window) * 625; 1093 log_info("LE Scan Params: window %lu, interval %lu ms", ll_scan_interval_us, ll_scan_window_us); 1094 } 1095 1096 static uint8_t ll_start_scanning(uint8_t filter_duplicates){ 1097 #if 0 1098 // COMMAND DISALLOWED if wrong state. 1099 if (ll_state != LL_STATE_STANDBY) return 0x0c; 1100 1101 ll_state = LL_STATE_SCANNING; 1102 1103 log_info("LE Scan Start: window %lu, interval %lu ms", ll_scan_interval_us, ll_scan_window_us); 1104 1105 // reset timer and capature events 1106 NRF_TIMER0->TASKS_CLEAR = 1; 1107 NRF_TIMER0->TASKS_STOP = 1; 1108 NRF_TIMER0->EVENTS_COMPARE[0] = 0; 1109 NRF_TIMER0->EVENTS_COMPARE[1] = 0; 1110 1111 // limit scanning 1112 if (ll_scan_window_us < ll_scan_interval_us){ 1113 // setup PPI to disable radio after end of scan_window 1114 NRF_TIMER0->CC[1] = ll_scan_window_us; 1115 NRF_PPI->CHENSET = 1 << 22; // TIMER0->EVENTS_COMPARE[1] -> RADIO->TASKS_DISABLE 1116 } 1117 1118 // set timer to trigger IRQ for next scan interval 1119 NRF_TIMER0->CC[0] = ll_scan_interval_us; 1120 NRF_TIMER0->INTENSET = TIMER_INTENSET_COMPARE0_Enabled << TIMER_INTENSET_COMPARE0_Pos; 1121 1122 // next channel to scan 1123 int adv_channel = (random_generator_next() % 3) + 37; 1124 log_debug("LE Scan Channel: %u", adv_channel); 1125 1126 // start receiving 1127 NRF_TIMER0->TASKS_START = 1; 1128 radio_receive_on_channel(adv_channel); 1129 #endif 1130 return 0; 1131 } 1132 1133 static uint8_t ll_stop_scanning(void){ 1134 #if 0 1135 // COMMAND DISALLOWED if wrong state. 1136 if (ll_state != LL_STATE_SCANNING) return 0x0c; 1137 1138 log_info("LE Scan Stop"); 1139 1140 ll_state = LL_STATE_STANDBY; 1141 1142 // stop radio 1143 radio_disable(); 1144 1145 #endif 1146 return 0; 1147 } 1148 1149 uint8_t ll_set_scan_enable(uint8_t le_scan_enable, uint8_t filter_duplicates){ 1150 if (le_scan_enable){ 1151 return ll_start_scanning(filter_duplicates); 1152 } else { 1153 return ll_stop_scanning(); 1154 } 1155 } 1156 1157 static uint8_t ll_start_advertising(void){ 1158 // COMMAND DISALLOWED if wrong state. 1159 if (ll_state != LL_STATE_STANDBY) return ERROR_CODE_COMMAND_DISALLOWED; 1160 log_info("Start Advertising on channels 0x%0x, interval %lu us", ctx.adv_map, ctx.adv_interval_us); 1161 start_advertising(); 1162 return ERROR_CODE_SUCCESS; 1163 } 1164 1165 static uint8_t ll_stop_advertising(void){ 1166 // COMMAND DISALLOWED if wrong state. 1167 if (ll_state != LL_STATE_ADVERTISING) return ERROR_CODE_COMMAND_DISALLOWED; 1168 1169 // TODO: 1170 return ERROR_CODE_SUCCESS; 1171 } 1172 1173 uint8_t ll_set_advertise_enable(uint8_t le_adv_enable){ 1174 if (le_adv_enable){ 1175 return ll_start_advertising(); 1176 } else { 1177 return ll_stop_advertising(); 1178 } 1179 } 1180 1181 uint8_t ll_set_advertising_parameters(uint16_t advertising_interval_min, uint16_t advertising_interval_max, 1182 uint8_t advertising_type, uint8_t own_address_type, uint8_t peer_address_types, uint8_t * peer_address, 1183 uint8_t advertising_channel_map, uint8_t advertising_filter_policy){ 1184 1185 // validate channel map 1186 if (advertising_channel_map == 0) return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS; 1187 if ((advertising_channel_map & 0xf8) != 0) return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS; 1188 1189 // validate advertising interval 1190 if (advertising_interval_min < 0x20) return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS; 1191 if (advertising_interval_min > 0x4000) return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS; 1192 if (advertising_interval_max < 0x20) return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS; 1193 if (advertising_interval_max > 0x4000) return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS; 1194 if (advertising_interval_min > advertising_interval_max) return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS; 1195 1196 ctx.adv_map = advertising_channel_map; 1197 ctx.adv_interval_us = advertising_interval_max * 625; 1198 1199 // TODO: validate other params 1200 // TODO: process other params 1201 1202 return ERROR_CODE_SUCCESS; 1203 } 1204 1205 uint8_t ll_set_advertising_data(uint8_t adv_len, const uint8_t * adv_data){ 1206 // COMMAND DISALLOWED if wrong state. 1207 if (ll_state == LL_STATE_ADVERTISING) return ERROR_CODE_COMMAND_DISALLOWED; 1208 if (adv_len > 31) return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE; 1209 ctx.adv_len = adv_len; 1210 memcpy(ctx.adv_data, adv_data, adv_len); 1211 1212 // TODO: 1213 return ERROR_CODE_SUCCESS; 1214 } 1215 1216 void ll_execute_once(void){ 1217 // process received packets 1218 while (1){ 1219 ll_pdu_t * rx_packet = (ll_pdu_t *) btstack_linked_queue_dequeue(&ctx.rx_queue); 1220 if (rx_packet == NULL) break; 1221 if (rx_packet->len > 0){ 1222 if ((rx_packet->flags & LL_PDU_FLAG_DATA_PDU) == 0){ 1223 // ADV PDU 1224 // connect ind? 1225 if ((rx_packet->header & 0x0f) == PDU_ADV_TYPE_CONNECT_IND){ 1226 ll_handle_conn_ind(rx_packet); 1227 } 1228 else { 1229 radio_state = RADIO_LOWPOWER; 1230 } 1231 } else { 1232 // DATA PDU 1233 uint8_t ll_id = rx_packet->header & 3; 1234 if (ll_id == PDU_DATA_LLID_CTRL) { 1235 ll_handle_control(rx_packet); 1236 } else { 1237 ll_handle_data(rx_packet); 1238 } 1239 } 1240 } 1241 // free packet 1242 btstack_memory_ll_pdu_free(rx_packet); 1243 } 1244 1245 switch ( ll_state ){ 1246 case LL_STATE_ADVERTISING: 1247 ll_advertising_statemachine(); 1248 break; 1249 default: 1250 break; 1251 } 1252 1253 // generate HCI events 1254 1255 // report num complete packets 1256 /** critical section start */ 1257 hal_cpu_disable_irqs(); 1258 uint8_t num_completed = ctx.num_completed; 1259 ctx.num_completed = 0; 1260 hal_cpu_enable_irqs(); 1261 /** critical section end */ 1262 if (num_completed > 0){ 1263 ll_emit_hci_event(&hci_event_number_of_completed_packets_1, 1, HCI_CON_HANDLE, num_completed); 1264 } 1265 1266 // report connection event 1267 if (ll_send_connection_complete){ 1268 ll_send_connection_complete = false; 1269 ll_emit_hci_event(&hci_subevent_le_connection_complete, 1270 ERROR_CODE_SUCCESS, HCI_CON_HANDLE, 0x01 /* slave */, ctx.peer_addr_type, ctx.peer_addr, 1271 ctx.conn_interval_1250us, ctx.conn_latency, ctx.supervision_timeout_10ms, 0 /* master clock accuracy */); 1272 } 1273 1274 // report disconnection event 1275 if (ll_send_disconnected){ 1276 ll_send_disconnected = false; 1277 ll_emit_hci_event(&hci_event_disconnection_complete, ERROR_CODE_SUCCESS, HCI_CON_HANDLE, 0); 1278 } 1279 } 1280 bool ll_reserve_acl_packet(void){ 1281 if (ll_reserved_acl_buffer == NULL){ 1282 ll_reserved_acl_buffer = btstack_memory_ll_pdu_get(); 1283 } 1284 return ll_reserved_acl_buffer != NULL; 1285 } 1286 1287 void ll_queue_acl_packet(const uint8_t * packet, uint16_t size){ 1288 btstack_assert(ll_reserved_acl_buffer != NULL); 1289 1290 ll_pdu_t * tx_packet = ll_reserved_acl_buffer; 1291 ll_reserved_acl_buffer = NULL; 1292 1293 switch ((packet[1] >> 4) & 0x03){ 1294 case 0: 1295 case 2: 1296 tx_packet->header = PDU_DATA_LLID_DATA_START; 1297 break; 1298 case 1: 1299 tx_packet->header = PDU_DATA_LLID_DATA_CONTINUE; 1300 break; 1301 case 3: 1302 while(1); 1303 break; 1304 default: 1305 break; 1306 } 1307 tx_packet->len = size - 4; 1308 memcpy(tx_packet->payload, &packet[4], size - 4); 1309 btstack_linked_queue_enqueue(&ctx.tx_queue, (btstack_linked_item_t *) tx_packet); 1310 } 1311 1312 void ll_register_packet_handler(void (*packet_handler)(uint8_t packet_type, uint8_t * packet, uint16_t size)){ 1313 controller_packet_handler = packet_handler; 1314 } 1315