xref: /btstack/chipset/sx128x/ll_sx1280.c (revision cd5f23a3250874824c01a2b3326a9522fea3f99f)
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 	// adv data
329 	uint8_t scan_resp_len;
330 	uint8_t scan_resp_data[31];
331 
332     // next expected sequence number
333     volatile uint8_t next_expected_sequence_number;
334 
335     // transmit sequence number
336     volatile uint8_t transmit_sequence_number;
337 
338     // num completed packets
339     volatile uint8_t num_completed;
340 
341     // rx queue
342     btstack_linked_queue_t rx_queue;
343 
344     // current incoming packet
345     ll_pdu_t * rx_pdu;
346 
347     // rx packet ready
348     bool rx_pdu_received;
349 
350     // tx queue of outgoing pdus
351     btstack_linked_queue_t tx_queue;
352 
353     // pdus transferred into controller tx buffers
354     ll_pdu_t * tx_buffer_pdu[2];
355 
356     // manage tx packets on controller
357     uint8_t num_tx_pdus_on_controller;
358 
359     // index of next tx buffer to send
360     uint8_t next_tx_buffer;
361 
362 } ctx;
363 
364 static radio_state_t radio_state = RADIO_LOWPOWER;
365 
366 // Buffer pool
367 static ll_pdu_t ll_pdu_pool_storage[MAX_NUM_LL_PDUS];
368 static btstack_memory_pool_t ll_pdu_pool;
369 
370 // single ll control response
371 static ll_pdu_t ll_tx_packet;
372 
373 // Link Layer State
374 static ll_state_t ll_state;
375 static uint32_t ll_scan_interval_us;
376 static uint32_t ll_scan_window_us;
377 
378 static ll_pdu_t * ll_reserved_acl_buffer;
379 static void (*controller_packet_handler)(uint8_t packet_type, uint8_t * packet, uint16_t size);
380 
381 static uint8_t ll_outgoing_hci_event[258];
382 static bool ll_send_disconnected;
383 static bool ll_send_connection_complete;
384 
385 // prototypes
386 static void radio_set_timer_ticks(uint32_t anchor_offset_ticks);
387 
388 
389 // memory pool for acl-le pdus
390 static ll_pdu_t * btstack_memory_ll_pdu_get(void){
391     void * buffer = btstack_memory_pool_get(&ll_pdu_pool);
392     if (buffer){
393         memset(buffer, 0, sizeof(ll_pdu_t));
394     }
395     return (ll_pdu_t *) buffer;
396 }
397 
398 static void btstack_memory_ll_pdu_free(ll_pdu_t *acl_le_pdu){
399     btstack_memory_pool_free(&ll_pdu_pool, acl_le_pdu);
400 }
401 
402 static void radio_auto_tx_on(void){
403 	// SetAutoTX(150 ms) - direct write / ignore compensation
404 	uint8_t buf[2];
405 	big_endian_store_16(buf, 0, AUTO_RX_TX_TIME_US);
406 	SX1280HalWriteCommand( RADIO_SET_AUTOTX, buf, 2 );
407 }
408 
409 static void radio_auto_tx_off(void){
410 	// SetAutoTX(0) - direct write / ignore compensation
411 	uint8_t buf[2] = { 0, 0 };
412 	SX1280HalWriteCommand( RADIO_SET_AUTOTX, buf, 2 );
413 }
414 
415 static bool receive_prepare_rx_bufffer(void){
416     if (ctx.rx_pdu == NULL){
417         ctx.rx_pdu = btstack_memory_ll_pdu_get();
418     }
419     if (ctx.rx_pdu == NULL){
420         printf("No free RX buffer\n");
421         return false;
422     } else {
423         return true;
424     }
425 }
426 
427 static void receive_response(void){
428     if (receive_prepare_rx_bufffer()) {
429         // 150 us would be enough, but the timeout seems to apply for AutoTx as well, so we use 250 us
430         Radio.SetRx( ( TickTime_t ) { RADIO_TICK_SIZE_0015_US, 16 } );
431     }
432 }
433 
434 static void receive_first_master(void){
435     if (receive_prepare_rx_bufffer()){
436         Radio.SetRx( ( TickTime_t ) { RADIO_TICK_SIZE_1000_US, 1000 } );
437     }
438 }
439 
440 static void receive_master(void){
441     if (receive_prepare_rx_bufffer()) {
442         Radio.SetRx((TickTime_t) {RADIO_TICK_SIZE_1000_US, 1});
443     }
444 }
445 
446 static void setup_adv_pdu(uint8_t offset, uint8_t header, uint8_t len, const uint8_t * data){
447 	uint8_t buffer[39];
448 	buffer[0] = header;
449 	buffer[1] = 6 + len;
450 	memcpy(&buffer[2], ctx.bd_addr_le, 6);
451 	memcpy(&buffer[8], data, len);
452 	uint16_t packet_size = 2 + buffer[1];
453 	SX1280HalWriteBuffer( offset, buffer, packet_size );
454 }
455 
456 static void send_adv(void){
457 
458 	// enable AutoTX for potential Scan Response
459 	// TODO: only if adv type allows for scanning
460 	radio_auto_tx_on();
461 
462 	SX1280SetBufferBaseAddresses( SX1280_TX0_OFFSET, SX1280_RX0_OFFSET);
463     SX1280SetTx( ( TickTime_t ){ RADIO_TICK_SIZE_1000_US, 1 } );
464 }
465 
466 static void select_channel(uint8_t channel){
467     // Set Whitening seed
468     Radio.SetWhiteningSeed( channel_table[channel].whitening );
469 
470     // Sel Frequency
471     Radio.SetRfFrequency( channel_table[channel].freq_hz );
472 }
473 
474 static void next_channel(void){
475     switch (ctx.channel_selection_algorithm){
476         case 0:
477             ctx.channel = hopping_csa1_get_next_channel( &h );
478             break;
479         case 1:
480             ctx.channel = hopping_csa2_get_channel_for_counter( &h,  ctx.connection_event);
481             break;
482         default:
483             break;
484     }
485     select_channel(ctx.channel);
486 }
487 
488 static void ll_advertising_statemachine(void){
489     switch ( radio_state) {
490         case RADIO_RX_ERROR:
491         case RADIO_LOWPOWER:
492             // find next channel
493             while (ctx.channel < 40){
494                 ctx.channel++;
495                 if ((ctx.adv_map & (1 << (ctx.channel - 37))) != 0) {
496                     // Set Channel
497                     select_channel(ctx.channel);
498                     radio_state = RADIO_W4_TX_DONE_TO_RX;
499                     send_adv();
500                     break;
501                 }
502                 if (ctx.channel >= 40){
503                     // Set timer
504                     radio_state = RADIO_W4_TIMER;
505                     uint32_t adv_interval_ticks = US_TO_TICKS(ctx.adv_interval_us);
506                     radio_set_timer_ticks(adv_interval_ticks);
507                 }
508             }
509             break;
510         default:
511             break;
512     }
513 }
514 
515 static void start_advertising(void){
516 
517     Radio.StopAutoTx();
518 
519     PacketParams_t packetParams;
520     packetParams.PacketType = PACKET_TYPE_BLE;
521     packetParams.Params.Ble.BlePacketType = BLE_EYELONG_1_0;
522     packetParams.Params.Ble.ConnectionState = BLE_PAYLOAD_LENGTH_MAX_37_BYTES;
523     packetParams.Params.Ble.CrcField = BLE_CRC_3B;
524     packetParams.Params.Ble.Whitening = RADIO_WHITENING_ON;
525     Radio.SetPacketParams( &packetParams );
526 
527     // Set CRC init value 0x555555
528     Radio.WriteRegister(0x9c7, 0x55 );
529     Radio.WriteRegister(0x9c8, 0x55 );
530     Radio.WriteRegister(0x9c9, 0x55 );
531 
532     // Set AccessAddress for ADV packets
533     Radio.SetBleAdvertizerAccessAddress( );
534 
535     // prepare adv and scan data in tx0 and tx1
536 	setup_adv_pdu(SX1280_TX0_OFFSET, PDU_ADV_TYPE_ADV_IND,  ctx.adv_len,       ctx.adv_data);
537 	setup_adv_pdu(SX1280_TX1_OFFSET, PDU_ADV_TYPE_SCAN_RSP, ctx.scan_resp_len, ctx.scan_resp_data);
538 
539 	radio_state = RADIO_LOWPOWER;
540     ll_state = LL_STATE_ADVERTISING;
541 
542     // prepare
543     ctx.channel = 36;
544     ctx.anchor_ticks = hal_timer_get_ticks();
545 
546     // and get started
547     ll_advertising_statemachine();
548 }
549 
550 static void start_hopping(void){
551     PacketParams_t packetParams;
552     packetParams.PacketType = PACKET_TYPE_BLE;
553     packetParams.Params.Ble.BlePacketType = BLE_EYELONG_1_0;
554     packetParams.Params.Ble.ConnectionState = BLE_PAYLOAD_LENGTH_MAX_31_BYTES;
555     packetParams.Params.Ble.CrcField = BLE_CRC_3B;
556     packetParams.Params.Ble.Whitening = RADIO_WHITENING_ON;
557     Radio.SetPacketParams( &packetParams );
558 
559 }
560 
561 static void radio_stop_timer(void){
562     hal_timer_stop();
563 }
564 
565 static void radio_set_timer_ticks(uint32_t anchor_offset_ticks){
566     radio_stop_timer();
567     // set timer for next radio event relative to anchor
568     uint16_t timeout_ticks = (uint16_t) (ctx.anchor_ticks + anchor_offset_ticks);
569     hal_timer_start(timeout_ticks);
570 }
571 
572 static void ctx_set_conn_interval(uint16_t conn_interval_1250us){
573 	ctx.conn_interval_1250us = conn_interval_1250us;
574 	ctx.conn_interval_us     = ctx.conn_interval_1250us * 1250;
575 	ctx.conn_interval_ticks  = US_TO_TICKS(ctx.conn_interval_us);
576 	ctx.conn_sync_hop_ticks  = US_TO_TICKS(ctx.conn_interval_us - SYNC_HOP_DELAY_US);
577 
578 	// latest time to send a packet before getting ready for next cnonection event
579 	uint16_t max_packet_time_incl_ifs_us = 500;
580 	ctx.conn_latest_tx_ticks = US_TO_TICKS(ctx.conn_interval_us - SYNC_HOP_DELAY_US - max_packet_time_incl_ifs_us);
581 }
582 
583 static void ll_terminate(void){
584     ll_state = LL_STATE_STANDBY;
585     ctx.conn_param_update_pending = false;
586     ctx.channel_map_update_pending = false;
587     // stop sync hop timer
588     radio_stop_timer();
589     // free outgoing tx packets
590     uint8_t i;
591     for (i=0;i<2;i++){
592         if ((ctx.tx_buffer_pdu[i] != NULL) && (ctx.tx_buffer_pdu[i] != &ll_tx_packet)){
593             btstack_memory_ll_pdu_free(ctx.tx_buffer_pdu[i]);
594             ctx.tx_buffer_pdu[i] = NULL;
595         }
596     }
597     ctx.num_tx_pdus_on_controller = 0;
598     // free queued tx packets
599     while (true){
600         ll_pdu_t * tx_packet = (ll_pdu_t *) btstack_linked_queue_dequeue(&ctx.tx_queue);
601         if (tx_packet != NULL) {
602             btstack_memory_ll_pdu_free(tx_packet);
603         } else {
604             break;
605         }
606     }
607     // disable auto tx
608     Radio.StopAutoTx();
609     // notify host stack
610     ll_send_disconnected = true;
611 }
612 
613 // load queued tx pdu into next free tx buffer
614 static void preload_tx_buffer(void){
615     if (ctx.num_tx_pdus_on_controller >= 2) return;
616 
617     ll_pdu_t * tx_pdu = (ll_pdu_t *) btstack_linked_queue_dequeue(&ctx.tx_queue);
618     if (tx_pdu == NULL) return;
619 
620 	const uint16_t max_packet_len = 2 + 27;
621     uint8_t index = (ctx.next_tx_buffer + ctx.num_tx_pdus_on_controller) & 1;
622     ctx.tx_buffer_pdu[index] = tx_pdu;
623     SX1280HalWriteBuffer( tx_buffer_offset[index], (uint8_t *) &ctx.tx_buffer_pdu[index]->header, max_packet_len);
624 
625     ctx.num_tx_pdus_on_controller++;
626 	// printf("preload %u bytes into %u\n", ctx.tx_buffer_pdu[index]->len, index);
627 }
628 
629 static void radio_timer_handler(void){
630 
631     uint16_t t0 = hal_timer_get_ticks();
632 
633     switch (ll_state){
634         case LL_STATE_CONNECTED:
635             // check supervision timeout
636             ctx.time_without_any_packets_us += ctx.conn_interval_us;
637             if (ctx.time_without_any_packets_us > ctx.supervision_timeout_us) {
638                 printf("Supervision timeout\n\n");
639                 ll_terminate();
640                 return;
641             }
642 
643             // prepare next connection event
644             ctx.connection_event++;
645             ctx.anchor_ticks += ctx.conn_interval_ticks;
646 
647             ctx.packet_nr_in_connection_event = 0;
648             next_channel();
649 
650             if (ctx.channel_map_update_pending && (ctx.channel_map_update_instant == ctx.connection_event)) {
651                 hopping_set_channel_map( &h, (const uint8_t *) &ctx.channel_map_update_map );
652                 ctx.channel_map_update_pending = false;
653             }
654 
655             if (ctx.conn_param_update_pending && ((ctx.conn_param_update_instant) == ctx.connection_event) ) {
656             	ctx_set_conn_interval(ctx.conn_param_update_interval_1250us);
657                 ctx.conn_latency            = ctx.conn_param_update_latency;
658                 ctx.supervision_timeout_us  = ctx.conn_param_update_timeout_us;
659                 ctx.conn_param_update_pending = false;
660 
661                 log_info("Conn param update now");
662 
663                 radio_stop_timer();
664                 ctx.synced = false;
665             }
666 
667             // preload tx pdu
668 			preload_tx_buffer();
669 
670             if (ctx.synced){
671                 // restart radio timer (might get overwritten by first packet)
672                 radio_set_timer_ticks(ctx.conn_sync_hop_ticks);
673 
674                 receive_master();
675             } else {
676                 // just wait longer
677                 receive_first_master();
678             }
679 
680             // printf("--SYNC-Ch %02u-Event %04u - t %08u--\n", ctx.channel, ctx.connection_event, t0);
681             break;
682         case LL_STATE_ADVERTISING:
683             // send adv on all configured channels
684             ctx.channel = 36;
685             ctx.anchor_ticks = t0;
686             radio_stop_timer();
687             ll_advertising_statemachine();
688             radio_state = RADIO_LOWPOWER;
689             break;
690         default:
691             break;
692     }
693 
694 }
695 
696 static void radio_fetch_rx_pdu(void){
697 
698 	if (!ctx.rx_pdu_received) return;
699 	ctx.rx_pdu_received = false;
700 
701 	// fetch reserved rx pdu
702 	ll_pdu_t * rx_packet = ctx.rx_pdu;
703 	btstack_assert(rx_packet != NULL);
704 
705 	// read max packet
706 	uint16_t max_packet_len = 2 + 27;
707 	SX1280HalReadBuffer( SX1280_RX0_OFFSET, &rx_packet->header, max_packet_len);
708 
709 	// queue if not empty
710 	if (rx_packet->len != 0){
711 
712 		// packet used
713 		ctx.rx_pdu = NULL;
714 
715 		// mark as data packet
716 		rx_packet->flags |= LL_PDU_FLAG_DATA_PDU;
717 
718 		// queue received packet
719 		btstack_linked_queue_enqueue(&ctx.rx_queue, (btstack_linked_item_t *) rx_packet);
720 	}
721 }
722 
723 /** Radio IRQ handlers */
724 static void radio_on_tx_done(void ){
725     switch (radio_state){
726         case RADIO_W4_TX_DONE_TO_RX:
727             receive_response();
728             break;
729         default:
730             break;
731     }
732     switch (ll_state){
733         case LL_STATE_CONNECTED:
734             radio_fetch_rx_pdu();
735             preload_tx_buffer();
736             break;
737         default:
738             break;
739     }
740 }
741 static void radio_prepare_auto_tx(uint16_t packet_end_ticks, uint8_t rx_len){
742 	// restart supervision timeout
743 	ctx.time_without_any_packets_us = 0;
744 
745 	// check if we can sent a full packet before sync hop
746 	int16_t now_ticks = packet_end_ticks - ctx.anchor_ticks;
747 	if (ctx.synced && (now_ticks > ctx.conn_latest_tx_ticks)){
748 		// disable AutoTX to abort sending of next packet
749 		Radio.SetFs();
750 		log_info("Close before Sync hop: now %u > %u", now_ticks, ctx.conn_latest_tx_ticks);
751 
752 		// get rx pdu and
753 		radio_fetch_rx_pdu();
754 		return;
755 	}
756 
757 	// setup empty packet in ll buffer if no tx packet was preloaded
758 	if (ctx.num_tx_pdus_on_controller == 0) {
759 		ctx.tx_buffer_pdu[ctx.next_tx_buffer] = &ll_tx_packet;
760 		ctx.num_tx_pdus_on_controller++;
761 		ll_tx_packet.header = PDU_DATA_LLID_DATA_CONTINUE;
762 		ll_tx_packet.len = 0;
763 	}
764 
765 	// setup pdu header
766 	uint8_t packet_header[2];
767 	uint8_t md = btstack_linked_queue_empty(&ctx.tx_queue) ? 0 : 1;
768 	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;
769 	packet_header[1] = ctx.tx_buffer_pdu[ctx.next_tx_buffer]->len;
770 
771 	// select outgoing tx buffer and update pdu header
772 	SX1280SetBufferBaseAddresses( tx_buffer_offset[ctx.next_tx_buffer], SX1280_RX0_OFFSET);
773 	SX1280HalWriteBuffer( tx_buffer_offset[ctx.next_tx_buffer], (uint8_t *) packet_header, sizeof(packet_header));
774 
775 	// update operating state
776 	SX1280AutoTxWillStart();
777 
778 	// set anchor on first packet in connection event
779 	if (ctx.packet_nr_in_connection_event == 0){
780 
781 		// preamble (1) + aa (4) + header (1) + len (1) + payload (len) + crc (3) -- ISR handler ca. 35 us
782 		uint16_t timestamp_delay = (10 + rx_len) * 8 - 35;
783 		uint16_t packet_start_ticks = packet_end_ticks - US_TO_TICKS(timestamp_delay);
784 
785 		ctx.anchor_ticks = packet_start_ticks;
786 		ctx.synced = true;
787 		radio_set_timer_ticks(ctx.conn_sync_hop_ticks);
788 	}
789 
790 	ctx.packet_nr_in_connection_event++;
791 
792 	// printf("RX %02x -- tx buffer %u, %02x %02x\n", rx_header, ctx.next_tx_buffer, packet_header[0], packet_header[1]);
793 }
794 
795 static void radio_on_rx_done(void ){
796     uint16_t packet_end_ticks = hal_timer_get_ticks();
797 
798 	if (ll_state == LL_STATE_ADVERTISING){
799 
800 		// get rx pdu header
801 		uint8_t rx_header;
802 		SX1280HalReadBuffer( SX1280_RX0_OFFSET, &rx_header, 1);
803 
804 		// check for Scan Request
805 		uint8_t pdu_type = rx_header & 0x0f;
806 		if (pdu_type == PDU_ADV_TYPE_SCAN_REQ){
807 			// scan request, select TX1 for active AutoTx
808 			SX1280SetBufferBaseAddresses( SX1280_TX1_OFFSET, SX1280_RX0_OFFSET);
809 		} else {
810 
811 			// fetch reserved rx pdu
812 			ll_pdu_t * rx_packet = ctx.rx_pdu;
813 			btstack_assert(rx_packet != NULL);
814 			ctx.rx_pdu = NULL;
815 
816 			// no data packet
817 			rx_packet->flags = 0;
818 			uint16_t max_packet_len = 2 + LL_MAX_PAYLOAD;
819 
820 			// no scan request, disable auto tx and read complete buffer
821 			radio_auto_tx_off();
822 			SX1280HalReadBuffer( SX1280_RX0_OFFSET, &rx_packet->header, max_packet_len);
823 
824 			// queue received packet
825 			btstack_linked_queue_enqueue(&ctx.rx_queue, (btstack_linked_item_t *) rx_packet);
826 		}
827 
828 	} else if (ll_state == LL_STATE_CONNECTED){
829 
830 		// get and parse rx pdu header
831 		uint8_t rx_buffer[2];
832 		SX1280HalReadBuffer( SX1280_RX0_OFFSET, rx_buffer, 2);
833 		uint8_t rx_header = rx_buffer[0];
834 		uint8_t rx_len    = rx_buffer[1];
835         uint8_t next_expected_sequence_number = (rx_header >> 2) & 1;
836         uint8_t sequence_number = (rx_header >> 3) & 1;
837         // more data field not used yet
838         // uint8_t more_data = (rx_packet->header >> 4) & 1;
839 
840         // only accept packets where len <= payload size
841         if (rx_len <= LL_MAX_PAYLOAD){
842 			// update state
843 			ctx.next_expected_sequence_number = 1 - sequence_number;
844 
845 			// register pdu fetch
846 			ctx.rx_pdu_received = true;
847         }
848 
849         // report outgoing packet as ack'ed and free if confirmed by peer
850         bool tx_acked = ctx.transmit_sequence_number != next_expected_sequence_number;
851         if (tx_acked){
852             if (ctx.num_tx_pdus_on_controller > 0){
853             	btstack_assert(ctx.tx_buffer_pdu[ctx.next_tx_buffer] != NULL);
854             	// if non link-layer packet, free buffer and report as completed
855 				if (ctx.tx_buffer_pdu[ctx.next_tx_buffer] != &ll_tx_packet){
856 					btstack_memory_ll_pdu_free(ctx.tx_buffer_pdu[ctx.next_tx_buffer]);
857 					ctx.tx_buffer_pdu[ctx.next_tx_buffer] = NULL;
858 					ctx.num_completed++;
859 				}
860 				// next buffer
861 				ctx.num_tx_pdus_on_controller--;
862 				ctx.next_tx_buffer = (ctx.next_tx_buffer + 1 ) & 1;
863 			}
864             ctx.transmit_sequence_number = next_expected_sequence_number;
865         }
866 
867         // packet received, now prepare for AutoTX
868 		radio_prepare_auto_tx(packet_end_ticks, rx_len);
869     }
870 }
871 
872 static void radio_on_tx_timeout(void ){
873     radio_state = RADIO_TX_TIMEOUT;
874     printf( "<>>>>>>>>TXE\n\r" );
875 }
876 
877 static void radio_on_rx_timeout(void ){
878     switch (ll_state){
879         case LL_STATE_ADVERTISING:
880             radio_state = RADIO_RX_ERROR;
881             break;
882         default:
883             break;
884     }
885 }
886 
887 static void radio_on_rx_error(IrqErrorCode_t errorCode ){
888 	uint16_t packet_end_ticks = hal_timer_get_ticks();
889 	uint8_t rx_buffer[2];
890 	uint8_t rx_len;
891     switch (ll_state){
892         case LL_STATE_ADVERTISING:
893             radio_state = RADIO_RX_ERROR;
894             break;
895 		case LL_STATE_CONNECTED:
896 			// get len from rx pdu header
897 			SX1280HalReadBuffer(SX1280_RX0_OFFSET, rx_buffer, 2);
898 			rx_len = rx_buffer[1];
899 			radio_prepare_auto_tx(packet_end_ticks, rx_len);
900 			break;
901         default:
902             break;
903     }
904 }
905 
906 const static RadioCallbacks_t Callbacks =
907 {
908     &radio_on_tx_done,     // txDone
909     &radio_on_rx_done,     // rxDone
910     NULL,                  // syncWordDone
911     NULL,                  // headerDone
912     &radio_on_tx_timeout,  // txTimeout
913     &radio_on_rx_timeout,  // rxTimeout
914     &radio_on_rx_error,    // rxError
915     NULL,                  // rangingDone
916     NULL,                  // cadDone
917 };
918 
919 // Link Layer
920 
921 static void ll_emit_hci_event(const hci_event_t * event, ...){
922     va_list argptr;
923     va_start(argptr, event);
924     uint16_t length = hci_event_create_from_template_and_arglist(ll_outgoing_hci_event, event, argptr);
925     va_end(argptr);
926     controller_packet_handler(HCI_EVENT_PACKET, ll_outgoing_hci_event, length);
927 }
928 
929 void ll_init(void){
930 
931     // setup memory pools
932     btstack_memory_pool_create(&ll_pdu_pool, ll_pdu_pool_storage, MAX_NUM_LL_PDUS, sizeof(ll_pdu_t));
933 
934     // set test bd addr 33:33:33:33:33:33
935     memset(ctx.bd_addr_le, 0x33, 6);
936 
937     // default channels, advertising interval
938     ctx.adv_map = 0x7;
939     ctx.adv_interval_us = 1280000;
940 
941     // init timer
942     hal_timer_init();
943     hal_timer_set_callback(&radio_timer_handler);
944 }
945 
946 void ll_radio_on(void){
947 
948     Radio.Init( (RadioCallbacks_t *) &Callbacks );
949     Radio.SetRegulatorMode( USE_DCDC ); // Can also be set in LDO mode but consume more power
950     Radio.SetInterruptMode( );
951     Radio.SetDioIrqParams( RX_TX_IRQ_MASK, RX_TX_IRQ_MASK, IRQ_RADIO_NONE, IRQ_RADIO_NONE );
952 
953     ModulationParams_t modulationParams;
954     modulationParams.PacketType = PACKET_TYPE_BLE;
955     modulationParams.Params.Ble.BitrateBandwidth = GFSK_BLE_BR_1_000_BW_1_2;
956     modulationParams.Params.Ble.ModulationIndex = GFSK_BLE_MOD_IND_0_50;
957     modulationParams.Params.Ble.ModulationShaping = RADIO_MOD_SHAPING_BT_0_5;
958 
959     Radio.SetStandby( STDBY_RC );
960     Radio.SetPacketType( modulationParams.PacketType );
961     Radio.SetModulationParams( &modulationParams );
962     Radio.SetBufferBaseAddresses( SX1280_TX0_OFFSET, SX1280_RX0_OFFSET );
963     Radio.SetTxParams( TX_PARAMS_OUTPUT_POWER, TX_PARAMS_RAMP_TIME );
964 
965     // Go back to Frequcency Synthesis Mode, reduces transition time between Rx<->TX
966     Radio.SetAutoFS(1);
967 
968 	// quick test
969 	uint8_t data[] = {1, 2, 4, 8, 16, 32, 64, 128,  1, 2, 4, 8, 16, 32, 64, 128,  1, 2, 4, 8, 16, 32, 64, 128,  1, 2, 4, 8, 16, 32, 64, 128 };
970 	Radio.WriteBuffer(0, data, sizeof(data));
971 	uint8_t check[32];
972 	Radio.ReadBuffer(0, check, sizeof(data));
973 	if (memcmp(data, check, sizeof(data)) != 0) {
974 		printf("GOOD: "); printf_hexdump(data, sizeof(data));
975 		printf("BAD:  "); printf_hexdump(check, sizeof(data));
976 		btstack_assert(false);
977 	}
978 
979     ll_state = LL_STATE_STANDBY;
980 }
981 
982 static void ll_handle_conn_ind(ll_pdu_t * rx_packet){
983     printf("Connect Req: ");
984     printf_hexdump(&rx_packet->header, rx_packet->len + 2);
985 
986     uint8_t * init_addr = &rx_packet->payload[0];
987     uint8_t * adv_addr =  &rx_packet->payload[6];
988     uint8_t   chan_sel = (rx_packet->header >> 5) & 1;
989 
990     // verify AdvA
991     if (memcmp(ctx.bd_addr_le, adv_addr, 6) != 0){
992         // differs, go back to adv sending
993         radio_state = RADIO_LOWPOWER;
994         return;
995     }
996 
997     // TODO: get remote addr type
998     ctx.peer_addr_type = 0;
999     memcpy(ctx.peer_addr, init_addr, 6);
1000 
1001     // get params for HCI event
1002     const uint8_t * ll_data = &rx_packet->payload[12];
1003 
1004     ctx.aa                        = little_endian_read_32(ll_data, 0);
1005     uint8_t crc_init_0            = ll_data[4];
1006     uint8_t crc_init_1            = ll_data[5];
1007     uint8_t crc_init_2            = ll_data[6];
1008     uint8_t win_size              = ll_data[7];
1009     uint16_t win_offset           = little_endian_read_16(ll_data, 8);
1010     uint16_t conn_interval_1250us = little_endian_read_16(ll_data, 10);
1011     ctx.conn_latency              = little_endian_read_16(ll_data, 12);
1012     ctx.supervision_timeout_10ms  = little_endian_read_16(ll_data, 14);
1013     const uint8_t * channel_map = &ll_data[16];
1014     uint8_t hop = ll_data[21] & 0x1f;
1015     uint8_t sca = ll_data[21] >> 5;
1016 
1017     UNUSED(sca);
1018     UNUSED(win_offset);
1019     UNUSED(win_size);
1020 
1021 	ctx_set_conn_interval(conn_interval_1250us);
1022 
1023     // convert to us
1024     ctx.supervision_timeout_us  = ctx.supervision_timeout_10ms  * 10000;
1025     ctx.connection_event = 0;
1026     ctx.packet_nr_in_connection_event = 0;
1027     ctx.next_expected_sequence_number = 0;
1028     ctx.transmit_sequence_number = 0;
1029 
1030     // set AA
1031     Radio.SetBleAccessAddress(ctx.aa);
1032 
1033     // set CRC init value
1034     Radio.WriteRegister(0x9c7, crc_init_2);
1035     Radio.WriteRegister(0x9c8, crc_init_1);
1036     Radio.WriteRegister(0x9c9, crc_init_0);
1037 
1038     printf("Connection interval %u us\n", ctx.conn_interval_us);
1039     printf("Connection timeout  %u us\n", ctx.supervision_timeout_us);
1040     printf("AA %08x\n", ctx.aa);
1041     printf("CRC Init 0x%02x%02x%02x\n", crc_init_2, crc_init_1, crc_init_0);
1042 
1043     // init hopping
1044     hopping_init( &h );
1045     hopping_set_channel_map( &h, channel_map);
1046     ctx.channel_selection_algorithm = ctx.csa2_support & chan_sel;
1047     switch (ctx.channel_selection_algorithm){
1048         case 0:
1049             hopping_csa1_set_hop_increment(  &h, hop );
1050             break;
1051         case 1:
1052             hopping_csa2_set_access_address( &h, ctx.aa);
1053             break;
1054         default:
1055             break;
1056     }
1057     next_channel();
1058 
1059     start_hopping();
1060 
1061     radio_auto_tx_on();
1062 
1063 	// pre-load tx pdu
1064 	ctx.num_tx_pdus_on_controller = 0;
1065 	ctx.next_tx_buffer = 0;
1066 	preload_tx_buffer();
1067 
1068     // get next packet
1069     ll_state = LL_STATE_CONNECTED;
1070 
1071     receive_first_master();
1072     ll_send_connection_complete = true;
1073 }
1074 
1075 static void ll_handle_control(ll_pdu_t * rx_packet){
1076     ll_pdu_t * tx_packet = &ll_tx_packet;
1077     uint8_t opcode = rx_packet->payload[0];
1078     switch (opcode){
1079         case PDU_DATA_LLCTRL_TYPE_VERSION_IND:
1080             tx_packet->len = 6;
1081             tx_packet->header = PDU_DATA_LLID_CTRL;
1082             tx_packet->payload[0] = PDU_DATA_LLCTRL_TYPE_VERSION_IND;
1083             tx_packet->payload[1] = 0x06; // VersNr = Bluetooth Core V4.0
1084             little_endian_store_16(tx_packet->payload, 2, BLUETOOTH_COMPANY_ID_BLUEKITCHEN_GMBH);
1085             little_endian_store_16(tx_packet->payload, 4, 0);
1086             btstack_linked_queue_enqueue(&ctx.tx_queue, (btstack_linked_item_t *) tx_packet);
1087             printf("Queue Version Ind\n");
1088             break;
1089         case PDU_DATA_LLCTRL_TYPE_FEATURE_REQ:
1090             tx_packet->len = 9;
1091             tx_packet->header = PDU_DATA_LLID_CTRL;
1092             tx_packet->payload[0] = PDU_DATA_LLCTRL_TYPE_FEATURE_RSP;
1093             // TODO: set features of our controller
1094             memset(&tx_packet->payload[1], 0, 8);
1095             btstack_linked_queue_enqueue(&ctx.tx_queue, (btstack_linked_item_t *) tx_packet);
1096             printf("Queue Feature Rsp\n");
1097             break;
1098         case PDU_DATA_LLCTRL_TYPE_CHAN_MAP_IND:
1099             memcpy((uint8_t *) ctx.channel_map_update_map, &rx_packet->payload[1], 5);
1100             ctx.channel_map_update_instant   = little_endian_read_16(rx_packet->payload, 6);
1101             ctx.channel_map_update_pending   = true;
1102             break;
1103         case PDU_DATA_LLCTRL_TYPE_CONN_UPDATE_IND:
1104             ctx.conn_param_update_win_size        = tx_packet->payload[1];
1105             ctx.conn_param_update_win_offset      = little_endian_read_16(rx_packet->payload, 2);
1106             ctx.conn_param_update_interval_1250us = little_endian_read_16(rx_packet->payload, 4);
1107             ctx.conn_param_update_latency         = little_endian_read_16(rx_packet->payload, 6);
1108             ctx.conn_param_update_timeout_us      = little_endian_read_16(rx_packet->payload, 8) * 10000;
1109             ctx.conn_param_update_instant         = little_endian_read_16(rx_packet->payload, 10);
1110             ctx.conn_param_update_pending         = true;
1111             log_info("PDU_DATA_LLCTRL_TYPE_CONN_UPDATE_IND, conn interval %u 1250us at instant %u",
1112                      (unsigned int) ctx.conn_param_update_interval_1250us, ctx.conn_param_update_instant);
1113             break;
1114         case PDU_DATA_LLCTRL_TYPE_TERMINATE_IND:
1115             printf("Terminate!\n");
1116             ll_terminate();
1117             break;
1118         default:
1119             break;
1120     }
1121 }
1122 
1123 static void ll_handle_data(ll_pdu_t * rx_packet){
1124     if (ll_state != LL_STATE_CONNECTED) return;
1125     btstack_assert(rx_packet->len <= LL_MAX_PAYLOAD);
1126     uint8_t acl_packet[4 + LL_MAX_PAYLOAD];
1127     // ACL Header
1128     uint8_t ll_id = rx_packet->header & 3;
1129     acl_packet[0] = 0x01;
1130     acl_packet[1] = ll_id << 4;
1131     little_endian_store_16(acl_packet, 2, rx_packet->len);
1132     memcpy(&acl_packet[4], rx_packet->payload, rx_packet->len);
1133     (*controller_packet_handler)(HCI_ACL_DATA_PACKET, acl_packet, rx_packet->len + 4);
1134 }
1135 
1136 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){
1137     // TODO .. store other params
1138     ll_scan_interval_us = ((uint32_t) le_scan_interval) * 625;
1139     ll_scan_window_us   = ((uint32_t) le_scan_window)   * 625;
1140     log_info("LE Scan Params: window %lu, interval %lu ms", ll_scan_interval_us, ll_scan_window_us);
1141 }
1142 
1143 static uint8_t ll_start_scanning(uint8_t filter_duplicates){
1144 #if 0
1145     // COMMAND DISALLOWED if wrong state.
1146     if (ll_state != LL_STATE_STANDBY)  return 0x0c;
1147 
1148     ll_state = LL_STATE_SCANNING;
1149 
1150     log_info("LE Scan Start: window %lu, interval %lu ms", ll_scan_interval_us, ll_scan_window_us);
1151 
1152     // reset timer and capature events
1153     NRF_TIMER0->TASKS_CLEAR = 1;
1154     NRF_TIMER0->TASKS_STOP  = 1;
1155     NRF_TIMER0->EVENTS_COMPARE[0] = 0;
1156     NRF_TIMER0->EVENTS_COMPARE[1] = 0;
1157 
1158     // limit scanning
1159     if (ll_scan_window_us < ll_scan_interval_us){
1160         // setup PPI to disable radio after end of scan_window
1161         NRF_TIMER0->CC[1]    = ll_scan_window_us;
1162         NRF_PPI->CHENSET     = 1 << 22; // TIMER0->EVENTS_COMPARE[1] ->  RADIO->TASKS_DISABLE
1163     }
1164 
1165     // set timer to trigger IRQ for next scan interval
1166     NRF_TIMER0->CC[0]    = ll_scan_interval_us;
1167     NRF_TIMER0->INTENSET = TIMER_INTENSET_COMPARE0_Enabled << TIMER_INTENSET_COMPARE0_Pos;
1168 
1169     // next channel to scan
1170     int adv_channel = (random_generator_next() % 3) + 37;
1171     log_debug("LE Scan Channel: %u", adv_channel);
1172 
1173     // start receiving
1174     NRF_TIMER0->TASKS_START = 1;
1175     radio_receive_on_channel(adv_channel);
1176 #endif
1177     return 0;
1178 }
1179 
1180 static uint8_t ll_stop_scanning(void){
1181 #if 0
1182     // COMMAND DISALLOWED if wrong state.
1183     if (ll_state != LL_STATE_SCANNING)  return 0x0c;
1184 
1185     log_info("LE Scan Stop");
1186 
1187     ll_state = LL_STATE_STANDBY;
1188 
1189     // stop radio
1190     radio_disable();
1191 
1192 #endif
1193     return 0;
1194 }
1195 
1196 uint8_t ll_set_scan_enable(uint8_t le_scan_enable, uint8_t filter_duplicates){
1197     if (le_scan_enable){
1198         return ll_start_scanning(filter_duplicates);
1199     } else {
1200         return ll_stop_scanning();
1201     }
1202 }
1203 
1204 static uint8_t ll_start_advertising(void){
1205     // COMMAND DISALLOWED if wrong state.
1206     if (ll_state != LL_STATE_STANDBY) return ERROR_CODE_COMMAND_DISALLOWED;
1207     log_info("Start Advertising on channels 0x%0x, interval %lu us", ctx.adv_map, ctx.adv_interval_us);
1208     start_advertising();
1209     return ERROR_CODE_SUCCESS;
1210 }
1211 
1212 static uint8_t ll_stop_advertising(void){
1213     // COMMAND DISALLOWED if wrong state.
1214     if (ll_state != LL_STATE_ADVERTISING) return ERROR_CODE_COMMAND_DISALLOWED;
1215 
1216     // TODO:
1217     return ERROR_CODE_SUCCESS;
1218 }
1219 
1220 uint8_t ll_set_advertise_enable(uint8_t le_adv_enable){
1221     if (le_adv_enable){
1222         return ll_start_advertising();
1223     } else {
1224         return ll_stop_advertising();
1225     }
1226 }
1227 
1228 uint8_t ll_set_advertising_parameters(uint16_t advertising_interval_min, uint16_t advertising_interval_max,
1229                                       uint8_t advertising_type, uint8_t own_address_type, uint8_t peer_address_types, uint8_t * peer_address,
1230                                       uint8_t advertising_channel_map, uint8_t advertising_filter_policy){
1231 
1232     // validate channel map
1233     if (advertising_channel_map == 0) return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
1234     if ((advertising_channel_map & 0xf8) != 0) return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
1235 
1236     // validate advertising interval
1237     if (advertising_interval_min < 0x20)   return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
1238     if (advertising_interval_min > 0x4000) return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
1239     if (advertising_interval_max < 0x20)   return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
1240     if (advertising_interval_max > 0x4000) return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
1241     if (advertising_interval_min > advertising_interval_max) return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
1242 
1243     ctx.adv_map = advertising_channel_map;
1244     ctx.adv_interval_us = advertising_interval_max * 625;
1245 
1246     // TODO: validate other params
1247     // TODO: process other params
1248 
1249     return ERROR_CODE_SUCCESS;
1250 }
1251 
1252 uint8_t ll_set_advertising_data(uint8_t adv_len, const uint8_t * adv_data){
1253     // COMMAND DISALLOWED if wrong state.
1254     if (ll_state == LL_STATE_ADVERTISING) return ERROR_CODE_COMMAND_DISALLOWED;
1255     if (adv_len > 31) return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
1256     ctx.adv_len = adv_len;
1257     memcpy(ctx.adv_data, adv_data, adv_len);
1258 
1259     return ERROR_CODE_SUCCESS;
1260 }
1261 
1262 uint8_t ll_set_scan_response_data(uint8_t adv_len, const uint8_t * adv_data){
1263 	// COMMAND DISALLOWED if wrong state.
1264 	if (ll_state == LL_STATE_ADVERTISING) return ERROR_CODE_COMMAND_DISALLOWED;
1265 	if (adv_len > 31) return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
1266 	ctx.scan_resp_len = adv_len;
1267 	memcpy(ctx.scan_resp_data, adv_data, adv_len);
1268 
1269 	return ERROR_CODE_SUCCESS;
1270 }
1271 
1272 void ll_execute_once(void){
1273     // process received packets
1274     while (1){
1275         ll_pdu_t * rx_packet = (ll_pdu_t *) btstack_linked_queue_dequeue(&ctx.rx_queue);
1276         if (rx_packet == NULL) break;
1277         if (rx_packet->len > 0){
1278             if ((rx_packet->flags & LL_PDU_FLAG_DATA_PDU) == 0){
1279                 // ADV PDU
1280                 // connect ind?
1281                 if ((rx_packet->header & 0x0f) == PDU_ADV_TYPE_CONNECT_IND){
1282                     ll_handle_conn_ind(rx_packet);
1283                 }
1284                 else {
1285                     radio_state = RADIO_LOWPOWER;
1286                 }
1287             } else {
1288                 // DATA PDU
1289                 uint8_t ll_id = rx_packet->header & 3;
1290                 if (ll_id == PDU_DATA_LLID_CTRL) {
1291                     ll_handle_control(rx_packet);
1292                 } else {
1293                     ll_handle_data(rx_packet);
1294                 }
1295             }
1296         }
1297         // free packet
1298         btstack_memory_ll_pdu_free(rx_packet);
1299     }
1300 
1301     switch ( ll_state ){
1302         case LL_STATE_ADVERTISING:
1303             ll_advertising_statemachine();
1304             break;
1305         default:
1306             break;
1307     }
1308 
1309     // generate HCI events
1310 
1311     // report num complete packets
1312     /** critical section start */
1313     hal_cpu_disable_irqs();
1314     uint8_t num_completed = ctx.num_completed;
1315     ctx.num_completed = 0;
1316     hal_cpu_enable_irqs();
1317     /** critical section end */
1318     if (num_completed > 0){
1319         ll_emit_hci_event(&hci_event_number_of_completed_packets_1, 1, HCI_CON_HANDLE, num_completed);
1320     }
1321 
1322     // report connection event
1323     if (ll_send_connection_complete){
1324         ll_send_connection_complete = false;
1325         ll_emit_hci_event(&hci_subevent_le_connection_complete,
1326                                  ERROR_CODE_SUCCESS, HCI_CON_HANDLE, 0x01 /* slave */, ctx.peer_addr_type, ctx.peer_addr,
1327                                  ctx.conn_interval_1250us, ctx.conn_latency, ctx.supervision_timeout_10ms, 0 /* master clock accuracy */);
1328     }
1329 
1330     // report disconnection event
1331     if (ll_send_disconnected){
1332         ll_send_disconnected = false;
1333         ll_emit_hci_event(&hci_event_disconnection_complete, ERROR_CODE_SUCCESS, HCI_CON_HANDLE, 0);
1334     }
1335 }
1336 bool ll_reserve_acl_packet(void){
1337     if (ll_reserved_acl_buffer == NULL){
1338         ll_reserved_acl_buffer = btstack_memory_ll_pdu_get();
1339     }
1340     return ll_reserved_acl_buffer != NULL;
1341 }
1342 
1343 void ll_queue_acl_packet(const uint8_t * packet, uint16_t size){
1344     btstack_assert(ll_reserved_acl_buffer != NULL);
1345 
1346     ll_pdu_t * tx_packet = ll_reserved_acl_buffer;
1347     ll_reserved_acl_buffer = NULL;
1348 
1349     switch ((packet[1] >> 4) & 0x03){
1350         case 0:
1351         case 2:
1352             tx_packet->header = PDU_DATA_LLID_DATA_START;
1353             break;
1354         case 1:
1355             tx_packet->header = PDU_DATA_LLID_DATA_CONTINUE;
1356             break;
1357         case 3:
1358             while(1);
1359             break;
1360         default:
1361             break;
1362     }
1363     tx_packet->len = size - 4;
1364     memcpy(tx_packet->payload, &packet[4], size - 4);
1365     btstack_linked_queue_enqueue(&ctx.tx_queue, (btstack_linked_item_t *) tx_packet);
1366 }
1367 
1368 void ll_register_packet_handler(void (*packet_handler)(uint8_t packet_type, uint8_t * packet, uint16_t size)){
1369     controller_packet_handler = packet_handler;
1370 }
1371