xref: /btstack/chipset/sx128x/ll_sx1280.c (revision fa529fa70ecd60b9bf447a172e5b96a75741e08d)
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 static void radio_prepare_auto_tx(uint16_t packet_end_ticks, uint8_t rx_len){
715 	// restart supervision timeout
716 	ctx.time_without_any_packets_us = 0;
717 
718 	// check if we can sent a full packet before sync hop
719 	int16_t now_ticks = packet_end_ticks - ctx.anchor_ticks;
720 	if (ctx.synced && (now_ticks > ctx.conn_latest_tx_ticks)){
721 		// disable AutoTX to abort sending of next packet
722 		Radio.SetFs();
723 		log_info("Close before Sync hop: now %u > %u", now_ticks, ctx.conn_latest_tx_ticks);
724 
725 		// get rx pdu and
726 		radio_fetch_rx_pdu();
727 		return;
728 	}
729 
730 	// setup empty packet in ll buffer if no tx packet was preloaded
731 	if (ctx.num_tx_pdus_on_controller == 0) {
732 		ctx.tx_buffer_pdu[ctx.next_tx_buffer] = &ll_tx_packet;
733 		ctx.num_tx_pdus_on_controller++;
734 		ll_tx_packet.header = PDU_DATA_LLID_DATA_CONTINUE;
735 		ll_tx_packet.len = 0;
736 	}
737 
738 	// setup pdu header
739 	uint8_t packet_header[2];
740 	uint8_t md = btstack_linked_queue_empty(&ctx.tx_queue) ? 0 : 1;
741 	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;
742 	packet_header[1] = ctx.tx_buffer_pdu[ctx.next_tx_buffer]->len;
743 
744 	// select outgoing tx buffer and update pdu header
745 	SX1280SetBufferBaseAddresses( tx_buffer_offset[ctx.next_tx_buffer], SX1280_RX0_OFFSET);
746 	SX1280HalWriteBuffer( tx_buffer_offset[ctx.next_tx_buffer], (uint8_t *) packet_header, sizeof(packet_header));
747 
748 	// update operating state
749 	SX1280AutoTxWillStart();
750 
751 	// set anchor on first packet in connection event
752 	if (ctx.packet_nr_in_connection_event == 0){
753 
754 		// preamble (1) + aa (4) + header (1) + len (1) + payload (len) + crc (3) -- ISR handler ca. 35 us
755 		uint16_t timestamp_delay = (10 + rx_len) * 8 - 35;
756 		uint16_t packet_start_ticks = packet_end_ticks - US_TO_TICKS(timestamp_delay);
757 
758 		ctx.anchor_ticks = packet_start_ticks;
759 		ctx.synced = true;
760 		radio_set_timer_ticks(ctx.conn_sync_hop_ticks);
761 	}
762 
763 	ctx.packet_nr_in_connection_event++;
764 
765 	// printf("RX %02x -- tx buffer %u, %02x %02x\n", rx_header, ctx.next_tx_buffer, packet_header[0], packet_header[1]);
766 }
767 
768 static void radio_on_rx_done(void ){
769     uint16_t packet_end_ticks = hal_timer_get_ticks();
770 
771 	if (ll_state == LL_STATE_ADVERTISING){
772 
773 		// fetch reserved rx pdu
774 		ll_pdu_t * rx_packet = ctx.rx_pdu;
775 		btstack_assert(rx_packet != NULL);
776 		ctx.rx_pdu = NULL;
777 
778 		// no data packet
779 		rx_packet->flags = 0;
780 		uint16_t max_packet_len = 2 + LL_MAX_PAYLOAD;
781 
782 		SX1280HalReadBuffer( SX1280_RX0_OFFSET, &rx_packet->header, max_packet_len);
783 
784 		// queue received packet
785 		btstack_linked_queue_enqueue(&ctx.rx_queue, (btstack_linked_item_t *) rx_packet);
786 
787 	} else if (ll_state == LL_STATE_CONNECTED){
788 
789 		// get and parse rx pdu header
790 		uint8_t rx_buffer[2];
791 		SX1280HalReadBuffer( SX1280_RX0_OFFSET, rx_buffer, 2);
792 		uint8_t rx_header = rx_buffer[0];
793 		uint8_t rx_len    = rx_buffer[1];
794         uint8_t next_expected_sequence_number = (rx_header >> 2) & 1;
795         uint8_t sequence_number = (rx_header >> 3) & 1;
796         // more data field not used yet
797         // uint8_t more_data = (rx_packet->header >> 4) & 1;
798 
799         // only accept packets where len <= payload size
800         if (rx_len <= LL_MAX_PAYLOAD){
801 			// update state
802 			ctx.next_expected_sequence_number = 1 - sequence_number;
803 
804 			// register pdu fetch
805 			ctx.rx_pdu_received = true;
806         }
807 
808         // report outgoing packet as ack'ed and free if confirmed by peer
809         bool tx_acked = ctx.transmit_sequence_number != next_expected_sequence_number;
810         if (tx_acked){
811             if (ctx.num_tx_pdus_on_controller > 0){
812             	btstack_assert(ctx.tx_buffer_pdu[ctx.next_tx_buffer] != NULL);
813             	// if non link-layer packet, free buffer and report as completed
814 				if (ctx.tx_buffer_pdu[ctx.next_tx_buffer] != &ll_tx_packet){
815 					btstack_memory_ll_pdu_free(ctx.tx_buffer_pdu[ctx.next_tx_buffer]);
816 					ctx.tx_buffer_pdu[ctx.next_tx_buffer] = NULL;
817 					ctx.num_completed++;
818 				}
819 				// next buffer
820 				ctx.num_tx_pdus_on_controller--;
821 				ctx.next_tx_buffer = (ctx.next_tx_buffer + 1 ) & 1;
822 			}
823             ctx.transmit_sequence_number = next_expected_sequence_number;
824         }
825 
826         // packet received, now prepare for AutoTX
827 		radio_prepare_auto_tx(packet_end_ticks, rx_len);
828     }
829 }
830 
831 static void radio_on_tx_timeout(void ){
832     radio_state = RADIO_TX_TIMEOUT;
833     printf( "<>>>>>>>>TXE\n\r" );
834 }
835 
836 static void radio_on_rx_timeout(void ){
837     switch (ll_state){
838         case LL_STATE_ADVERTISING:
839             radio_state = RADIO_RX_ERROR;
840             break;
841         default:
842             break;
843     }
844 }
845 
846 static void radio_on_rx_error(IrqErrorCode_t errorCode ){
847 	uint16_t packet_end_ticks = hal_timer_get_ticks();
848 	uint8_t rx_buffer[2];
849 	uint8_t rx_len;
850     switch (ll_state){
851         case LL_STATE_ADVERTISING:
852             radio_state = RADIO_RX_ERROR;
853             break;
854 		case LL_STATE_CONNECTED:
855 			// get len from rx pdu header
856 			SX1280HalReadBuffer(SX1280_RX0_OFFSET, rx_buffer, 2);
857 			rx_len = rx_buffer[1];
858 			radio_prepare_auto_tx(packet_end_ticks, rx_len);
859 			break;
860         default:
861             break;
862     }
863 }
864 
865 const static RadioCallbacks_t Callbacks =
866 {
867     &radio_on_tx_done,     // txDone
868     &radio_on_rx_done,     // rxDone
869     NULL,                  // syncWordDone
870     NULL,                  // headerDone
871     &radio_on_tx_timeout,  // txTimeout
872     &radio_on_rx_timeout,  // rxTimeout
873     &radio_on_rx_error,    // rxError
874     NULL,                  // rangingDone
875     NULL,                  // cadDone
876 };
877 
878 // Link Layer
879 
880 static void ll_emit_hci_event(const hci_event_t * event, ...){
881     va_list argptr;
882     va_start(argptr, event);
883     uint16_t length = hci_event_create_from_template_and_arglist(ll_outgoing_hci_event, event, argptr);
884     va_end(argptr);
885     controller_packet_handler(HCI_EVENT_PACKET, ll_outgoing_hci_event, length);
886 }
887 
888 void ll_init(void){
889 
890     // setup memory pools
891     btstack_memory_pool_create(&ll_pdu_pool, ll_pdu_pool_storage, MAX_NUM_LL_PDUS, sizeof(ll_pdu_t));
892 
893     // set test bd addr 33:33:33:33:33:33
894     memset(ctx.bd_addr_le, 0x33, 6);
895 
896     // default channels, advertising interval
897     ctx.adv_map = 0x7;
898     ctx.adv_interval_us = 1280000;
899 
900     // init timer
901     hal_timer_init();
902     hal_timer_set_callback(&radio_timer_handler);
903 }
904 
905 void ll_radio_on(void){
906 
907     Radio.Init( (RadioCallbacks_t *) &Callbacks );
908     Radio.SetRegulatorMode( USE_DCDC ); // Can also be set in LDO mode but consume more power
909     Radio.SetInterruptMode( );
910     Radio.SetDioIrqParams( RX_TX_IRQ_MASK, RX_TX_IRQ_MASK, IRQ_RADIO_NONE, IRQ_RADIO_NONE );
911 
912     ModulationParams_t modulationParams;
913     modulationParams.PacketType = PACKET_TYPE_BLE;
914     modulationParams.Params.Ble.BitrateBandwidth = GFSK_BLE_BR_1_000_BW_1_2;
915     modulationParams.Params.Ble.ModulationIndex = GFSK_BLE_MOD_IND_0_50;
916     modulationParams.Params.Ble.ModulationShaping = RADIO_MOD_SHAPING_BT_0_5;
917 
918     Radio.SetStandby( STDBY_RC );
919     Radio.SetPacketType( modulationParams.PacketType );
920     Radio.SetModulationParams( &modulationParams );
921     Radio.SetBufferBaseAddresses( SX1280_TX0_OFFSET, SX1280_RX0_OFFSET );
922     Radio.SetTxParams( TX_PARAMS_OUTPUT_POWER, TX_PARAMS_RAMP_TIME );
923 
924     // Go back to Frequcency Synthesis Mode, reduces transition time between Rx<->TX
925     Radio.SetAutoFS(1);
926 
927     // quick test
928     uint8_t data[] = { 1, 2, 4, 8, 16, 32, 64, 128 };
929     Radio.WriteBuffer(0, data, sizeof(data));
930     uint8_t check[8];
931     Radio.ReadBuffer(0, check, sizeof(data));
932     if (memcmp(data, check, sizeof(data)) != 0){
933         printf_hexdump(data, sizeof(data));
934         printf_hexdump(check, sizeof(data));
935         btstack_assert(false);
936     }
937 
938     ll_state = LL_STATE_STANDBY;
939 }
940 
941 static void ll_handle_conn_ind(ll_pdu_t * rx_packet){
942     printf("Connect Req: ");
943     printf_hexdump(&rx_packet->header, rx_packet->len + 2);
944 
945     uint8_t * init_addr = &rx_packet->payload[0];
946     uint8_t * adv_addr =  &rx_packet->payload[6];
947     uint8_t   chan_sel = (rx_packet->header >> 5) & 1;
948 
949     // verify AdvA
950     if (memcmp(ctx.bd_addr_le, adv_addr, 6) != 0){
951         // differs, go back to adv sending
952         radio_state = RADIO_LOWPOWER;
953         return;
954     }
955 
956     // TODO: get remote addr type
957     ctx.peer_addr_type = 0;
958     memcpy(ctx.peer_addr, init_addr, 6);
959 
960     // get params for HCI event
961     const uint8_t * ll_data = &rx_packet->payload[12];
962 
963     ctx.aa                        = little_endian_read_32(ll_data, 0);
964     uint8_t crc_init_0            = ll_data[4];
965     uint8_t crc_init_1            = ll_data[5];
966     uint8_t crc_init_2            = ll_data[6];
967     uint8_t win_size              = ll_data[7];
968     uint16_t win_offset           = little_endian_read_16(ll_data, 8);
969     uint16_t conn_interval_1250us = little_endian_read_16(ll_data, 10);
970     ctx.conn_latency              = little_endian_read_16(ll_data, 12);
971     ctx.supervision_timeout_10ms  = little_endian_read_16(ll_data, 14);
972     const uint8_t * channel_map = &ll_data[16];
973     uint8_t hop = ll_data[21] & 0x1f;
974     uint8_t sca = ll_data[21] >> 5;
975 
976     UNUSED(sca);
977     UNUSED(win_offset);
978     UNUSED(win_size);
979 
980 	ctx_set_conn_interval(conn_interval_1250us);
981 
982     // convert to us
983     ctx.supervision_timeout_us  = ctx.supervision_timeout_10ms  * 10000;
984     ctx.connection_event = 0;
985     ctx.packet_nr_in_connection_event = 0;
986     ctx.next_expected_sequence_number = 0;
987     ctx.transmit_sequence_number = 0;
988 
989     // set AA
990     Radio.SetBleAccessAddress(ctx.aa);
991 
992     // set CRC init value
993     Radio.WriteRegister(0x9c7, crc_init_2);
994     Radio.WriteRegister(0x9c8, crc_init_1);
995     Radio.WriteRegister(0x9c9, crc_init_0);
996 
997     printf("Connection interval %u us\n", ctx.conn_interval_us);
998     printf("Connection timeout  %u us\n", ctx.supervision_timeout_us);
999     printf("AA %08x\n", ctx.aa);
1000     printf("CRC Init 0x%02x%02x%02x\n", crc_init_2, crc_init_1, crc_init_0);
1001 
1002     // init hopping
1003     hopping_init( &h );
1004     hopping_set_channel_map( &h, channel_map);
1005     ctx.channel_selection_algorithm = ctx.csa2_support & chan_sel;
1006     switch (ctx.channel_selection_algorithm){
1007         case 0:
1008             hopping_csa1_set_hop_increment(  &h, hop );
1009             break;
1010         case 1:
1011             hopping_csa2_set_access_address( &h, ctx.aa);
1012             break;
1013         default:
1014             break;
1015     }
1016     next_channel();
1017 
1018     start_hopping();
1019 
1020     // Enable Rx->Tx in 150 us for BLE
1021     // Note: Driver subtracts AUTO_RX_TX_OFFSET (33) from it and 150 should be correct, Raccoon reports 181 us then, so -31
1022     // Radio.SetAutoTx(119);
1023 
1024     // SetAutoTX(100) - direct write / ignore compensation
1025     uint8_t buf[2];
1026     big_endian_store_16(buf, 0, AUTO_RX_TX_TIME_US);
1027     SX1280HalWriteCommand( RADIO_SET_AUTOTX, buf, 2 );
1028 
1029 	// pre-load tx pdu
1030 	ctx.num_tx_pdus_on_controller = 0;
1031 	ctx.next_tx_buffer = 0;
1032 	preload_tx_buffer();
1033 
1034     // get next packet
1035     ll_state = LL_STATE_CONNECTED;
1036 
1037     receive_first_master();
1038     ll_send_connection_complete = true;
1039 }
1040 
1041 static void ll_handle_control(ll_pdu_t * rx_packet){
1042     ll_pdu_t * tx_packet = &ll_tx_packet;
1043     uint8_t opcode = rx_packet->payload[0];
1044     switch (opcode){
1045         case PDU_DATA_LLCTRL_TYPE_VERSION_IND:
1046             tx_packet->len = 6;
1047             tx_packet->header = PDU_DATA_LLID_CTRL;
1048             tx_packet->payload[0] = PDU_DATA_LLCTRL_TYPE_VERSION_IND;
1049             tx_packet->payload[1] = 0x06; // VersNr = Bluetooth Core V4.0
1050             little_endian_store_16(tx_packet->payload, 2, BLUETOOTH_COMPANY_ID_BLUEKITCHEN_GMBH);
1051             little_endian_store_16(tx_packet->payload, 4, 0);
1052             btstack_linked_queue_enqueue(&ctx.tx_queue, (btstack_linked_item_t *) tx_packet);
1053             printf("Queue Version Ind\n");
1054             break;
1055         case PDU_DATA_LLCTRL_TYPE_FEATURE_REQ:
1056             tx_packet->len = 9;
1057             tx_packet->header = PDU_DATA_LLID_CTRL;
1058             tx_packet->payload[0] = PDU_DATA_LLCTRL_TYPE_FEATURE_RSP;
1059             // TODO: set features of our controller
1060             memset(&tx_packet->payload[1], 0, 8);
1061             btstack_linked_queue_enqueue(&ctx.tx_queue, (btstack_linked_item_t *) tx_packet);
1062             printf("Queue Feature Rsp\n");
1063             break;
1064         case PDU_DATA_LLCTRL_TYPE_CHAN_MAP_IND:
1065             memcpy((uint8_t *) ctx.channel_map_update_map, &rx_packet->payload[1], 5);
1066             ctx.channel_map_update_instant   = little_endian_read_16(rx_packet->payload, 6);
1067             ctx.channel_map_update_pending   = true;
1068             break;
1069         case PDU_DATA_LLCTRL_TYPE_CONN_UPDATE_IND:
1070             ctx.conn_param_update_win_size        = tx_packet->payload[1];
1071             ctx.conn_param_update_win_offset      = little_endian_read_16(rx_packet->payload, 2);
1072             ctx.conn_param_update_interval_1250us = little_endian_read_16(rx_packet->payload, 4);
1073             ctx.conn_param_update_latency         = little_endian_read_16(rx_packet->payload, 6);
1074             ctx.conn_param_update_timeout_us      = little_endian_read_16(rx_packet->payload, 8) * 10000;
1075             ctx.conn_param_update_instant         = little_endian_read_16(rx_packet->payload, 10);
1076             ctx.conn_param_update_pending         = true;
1077             log_info("PDU_DATA_LLCTRL_TYPE_CONN_UPDATE_IND, conn interval %u 1250us at instant %u",
1078                      (unsigned int) ctx.conn_param_update_interval_1250us, ctx.conn_param_update_instant);
1079             break;
1080         case PDU_DATA_LLCTRL_TYPE_TERMINATE_IND:
1081             printf("Terminate!\n");
1082             ll_terminate();
1083             break;
1084         default:
1085             break;
1086     }
1087 }
1088 
1089 static void ll_handle_data(ll_pdu_t * rx_packet){
1090     if (ll_state != LL_STATE_CONNECTED) return;
1091     btstack_assert(rx_packet->len <= LL_MAX_PAYLOAD);
1092     uint8_t acl_packet[4 + LL_MAX_PAYLOAD];
1093     // ACL Header
1094     uint8_t ll_id = rx_packet->header & 3;
1095     acl_packet[0] = 0x01;
1096     acl_packet[1] = ll_id << 4;
1097     little_endian_store_16(acl_packet, 2, rx_packet->len);
1098     memcpy(&acl_packet[4], rx_packet->payload, rx_packet->len);
1099     (*controller_packet_handler)(HCI_ACL_DATA_PACKET, acl_packet, rx_packet->len + 4);
1100 }
1101 
1102 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){
1103     // TODO .. store other params
1104     ll_scan_interval_us = ((uint32_t) le_scan_interval) * 625;
1105     ll_scan_window_us   = ((uint32_t) le_scan_window)   * 625;
1106     log_info("LE Scan Params: window %lu, interval %lu ms", ll_scan_interval_us, ll_scan_window_us);
1107 }
1108 
1109 static uint8_t ll_start_scanning(uint8_t filter_duplicates){
1110 #if 0
1111     // COMMAND DISALLOWED if wrong state.
1112     if (ll_state != LL_STATE_STANDBY)  return 0x0c;
1113 
1114     ll_state = LL_STATE_SCANNING;
1115 
1116     log_info("LE Scan Start: window %lu, interval %lu ms", ll_scan_interval_us, ll_scan_window_us);
1117 
1118     // reset timer and capature events
1119     NRF_TIMER0->TASKS_CLEAR = 1;
1120     NRF_TIMER0->TASKS_STOP  = 1;
1121     NRF_TIMER0->EVENTS_COMPARE[0] = 0;
1122     NRF_TIMER0->EVENTS_COMPARE[1] = 0;
1123 
1124     // limit scanning
1125     if (ll_scan_window_us < ll_scan_interval_us){
1126         // setup PPI to disable radio after end of scan_window
1127         NRF_TIMER0->CC[1]    = ll_scan_window_us;
1128         NRF_PPI->CHENSET     = 1 << 22; // TIMER0->EVENTS_COMPARE[1] ->  RADIO->TASKS_DISABLE
1129     }
1130 
1131     // set timer to trigger IRQ for next scan interval
1132     NRF_TIMER0->CC[0]    = ll_scan_interval_us;
1133     NRF_TIMER0->INTENSET = TIMER_INTENSET_COMPARE0_Enabled << TIMER_INTENSET_COMPARE0_Pos;
1134 
1135     // next channel to scan
1136     int adv_channel = (random_generator_next() % 3) + 37;
1137     log_debug("LE Scan Channel: %u", adv_channel);
1138 
1139     // start receiving
1140     NRF_TIMER0->TASKS_START = 1;
1141     radio_receive_on_channel(adv_channel);
1142 #endif
1143     return 0;
1144 }
1145 
1146 static uint8_t ll_stop_scanning(void){
1147 #if 0
1148     // COMMAND DISALLOWED if wrong state.
1149     if (ll_state != LL_STATE_SCANNING)  return 0x0c;
1150 
1151     log_info("LE Scan Stop");
1152 
1153     ll_state = LL_STATE_STANDBY;
1154 
1155     // stop radio
1156     radio_disable();
1157 
1158 #endif
1159     return 0;
1160 }
1161 
1162 uint8_t ll_set_scan_enable(uint8_t le_scan_enable, uint8_t filter_duplicates){
1163     if (le_scan_enable){
1164         return ll_start_scanning(filter_duplicates);
1165     } else {
1166         return ll_stop_scanning();
1167     }
1168 }
1169 
1170 static uint8_t ll_start_advertising(void){
1171     // COMMAND DISALLOWED if wrong state.
1172     if (ll_state != LL_STATE_STANDBY) return ERROR_CODE_COMMAND_DISALLOWED;
1173     log_info("Start Advertising on channels 0x%0x, interval %lu us", ctx.adv_map, ctx.adv_interval_us);
1174     start_advertising();
1175     return ERROR_CODE_SUCCESS;
1176 }
1177 
1178 static uint8_t ll_stop_advertising(void){
1179     // COMMAND DISALLOWED if wrong state.
1180     if (ll_state != LL_STATE_ADVERTISING) return ERROR_CODE_COMMAND_DISALLOWED;
1181 
1182     // TODO:
1183     return ERROR_CODE_SUCCESS;
1184 }
1185 
1186 uint8_t ll_set_advertise_enable(uint8_t le_adv_enable){
1187     if (le_adv_enable){
1188         return ll_start_advertising();
1189     } else {
1190         return ll_stop_advertising();
1191     }
1192 }
1193 
1194 uint8_t ll_set_advertising_parameters(uint16_t advertising_interval_min, uint16_t advertising_interval_max,
1195                                       uint8_t advertising_type, uint8_t own_address_type, uint8_t peer_address_types, uint8_t * peer_address,
1196                                       uint8_t advertising_channel_map, uint8_t advertising_filter_policy){
1197 
1198     // validate channel map
1199     if (advertising_channel_map == 0) return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
1200     if ((advertising_channel_map & 0xf8) != 0) return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
1201 
1202     // validate advertising interval
1203     if (advertising_interval_min < 0x20)   return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
1204     if (advertising_interval_min > 0x4000) return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
1205     if (advertising_interval_max < 0x20)   return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
1206     if (advertising_interval_max > 0x4000) return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
1207     if (advertising_interval_min > advertising_interval_max) return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
1208 
1209     ctx.adv_map = advertising_channel_map;
1210     ctx.adv_interval_us = advertising_interval_max * 625;
1211 
1212     // TODO: validate other params
1213     // TODO: process other params
1214 
1215     return ERROR_CODE_SUCCESS;
1216 }
1217 
1218 uint8_t ll_set_advertising_data(uint8_t adv_len, const uint8_t * adv_data){
1219     // COMMAND DISALLOWED if wrong state.
1220     if (ll_state == LL_STATE_ADVERTISING) return ERROR_CODE_COMMAND_DISALLOWED;
1221     if (adv_len > 31) return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
1222     ctx.adv_len = adv_len;
1223     memcpy(ctx.adv_data, adv_data, adv_len);
1224 
1225     // TODO:
1226     return ERROR_CODE_SUCCESS;
1227 }
1228 
1229 void ll_execute_once(void){
1230     // process received packets
1231     while (1){
1232         ll_pdu_t * rx_packet = (ll_pdu_t *) btstack_linked_queue_dequeue(&ctx.rx_queue);
1233         if (rx_packet == NULL) break;
1234         if (rx_packet->len > 0){
1235             if ((rx_packet->flags & LL_PDU_FLAG_DATA_PDU) == 0){
1236                 // ADV PDU
1237                 // connect ind?
1238                 if ((rx_packet->header & 0x0f) == PDU_ADV_TYPE_CONNECT_IND){
1239                     ll_handle_conn_ind(rx_packet);
1240                 }
1241                 else {
1242                     radio_state = RADIO_LOWPOWER;
1243                 }
1244             } else {
1245                 // DATA PDU
1246                 uint8_t ll_id = rx_packet->header & 3;
1247                 if (ll_id == PDU_DATA_LLID_CTRL) {
1248                     ll_handle_control(rx_packet);
1249                 } else {
1250                     ll_handle_data(rx_packet);
1251                 }
1252             }
1253         }
1254         // free packet
1255         btstack_memory_ll_pdu_free(rx_packet);
1256     }
1257 
1258     switch ( ll_state ){
1259         case LL_STATE_ADVERTISING:
1260             ll_advertising_statemachine();
1261             break;
1262         default:
1263             break;
1264     }
1265 
1266     // generate HCI events
1267 
1268     // report num complete packets
1269     /** critical section start */
1270     hal_cpu_disable_irqs();
1271     uint8_t num_completed = ctx.num_completed;
1272     ctx.num_completed = 0;
1273     hal_cpu_enable_irqs();
1274     /** critical section end */
1275     if (num_completed > 0){
1276         ll_emit_hci_event(&hci_event_number_of_completed_packets_1, 1, HCI_CON_HANDLE, num_completed);
1277     }
1278 
1279     // report connection event
1280     if (ll_send_connection_complete){
1281         ll_send_connection_complete = false;
1282         ll_emit_hci_event(&hci_subevent_le_connection_complete,
1283                                  ERROR_CODE_SUCCESS, HCI_CON_HANDLE, 0x01 /* slave */, ctx.peer_addr_type, ctx.peer_addr,
1284                                  ctx.conn_interval_1250us, ctx.conn_latency, ctx.supervision_timeout_10ms, 0 /* master clock accuracy */);
1285     }
1286 
1287     // report disconnection event
1288     if (ll_send_disconnected){
1289         ll_send_disconnected = false;
1290         ll_emit_hci_event(&hci_event_disconnection_complete, ERROR_CODE_SUCCESS, HCI_CON_HANDLE, 0);
1291     }
1292 }
1293 bool ll_reserve_acl_packet(void){
1294     if (ll_reserved_acl_buffer == NULL){
1295         ll_reserved_acl_buffer = btstack_memory_ll_pdu_get();
1296     }
1297     return ll_reserved_acl_buffer != NULL;
1298 }
1299 
1300 void ll_queue_acl_packet(const uint8_t * packet, uint16_t size){
1301     btstack_assert(ll_reserved_acl_buffer != NULL);
1302 
1303     ll_pdu_t * tx_packet = ll_reserved_acl_buffer;
1304     ll_reserved_acl_buffer = NULL;
1305 
1306     switch ((packet[1] >> 4) & 0x03){
1307         case 0:
1308         case 2:
1309             tx_packet->header = PDU_DATA_LLID_DATA_START;
1310             break;
1311         case 1:
1312             tx_packet->header = PDU_DATA_LLID_DATA_CONTINUE;
1313             break;
1314         case 3:
1315             while(1);
1316             break;
1317         default:
1318             break;
1319     }
1320     tx_packet->len = size - 4;
1321     memcpy(tx_packet->payload, &packet[4], size - 4);
1322     btstack_linked_queue_enqueue(&ctx.tx_queue, (btstack_linked_item_t *) tx_packet);
1323 }
1324 
1325 void ll_register_packet_handler(void (*packet_handler)(uint8_t packet_type, uint8_t * packet, uint16_t size)){
1326     controller_packet_handler = packet_handler;
1327 }
1328