xref: /btstack/src/hci_transport_h5.c (revision a8d51f092f1b660d0f6921369ad2bc3f9368296c)
1 /*
2  * Copyright (C) 2016 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__ "hci_transport_h5.c"
39 
40 /*
41  *  hci_transport_h5.c
42  *
43  *  HCI Transport API implementation for basic H5 protocol
44  *
45  *  Created by Matthias Ringw ald on 4/29/09.
46  */
47 
48 #include <inttypes.h>
49 
50 #include "hci.h"
51 #include "btstack_slip.h"
52 #include "btstack_debug.h"
53 #include "hci_transport.h"
54 #include "btstack_uart_block.h"
55 
56 typedef enum {
57     LINK_UNINITIALIZED,
58     LINK_INITIALIZED,
59     LINK_ACTIVE
60 } hci_transport_link_state_t;
61 
62 typedef enum {
63     HCI_TRANSPORT_LINK_SEND_SYNC                  = 1 <<  0,
64     HCI_TRANSPORT_LINK_SEND_SYNC_RESPONSE         = 1 <<  1,
65     HCI_TRANSPORT_LINK_SEND_CONFIG                = 1 <<  2,
66     HCI_TRANSPORT_LINK_SEND_CONFIG_RESPONSE_EMPTY = 1 <<  3,
67     HCI_TRANSPORT_LINK_SEND_CONFIG_RESPONSE       = 1 <<  4,
68     HCI_TRANSPORT_LINK_SEND_SLEEP                 = 1 <<  5,
69     HCI_TRANSPORT_LINK_SEND_WOKEN                 = 1 <<  6,
70     HCI_TRANSPORT_LINK_SEND_WAKEUP                = 1 <<  7,
71     HCI_TRANSPORT_LINK_SEND_QUEUED_PACKET         = 1 <<  8,
72     HCI_TRANSPORT_LINK_SEND_ACK_PACKET            = 1 <<  9,
73     HCI_TRANSPORT_LINK_ENTER_SLEEP                = 1 << 10,
74 
75 } hci_transport_link_actions_t;
76 
77 // Configuration Field. No packet buffers -> sliding window = 1, no OOF flow control, support data integrity check
78 #define LINK_CONFIG_SLIDING_WINDOW_SIZE 1
79 #define LINK_CONFIG_OOF_FLOW_CONTROL 0
80 #define LINK_CONFIG_DATA_INTEGRITY_CHECK 1
81 #define LINK_CONFIG_VERSION_NR 0
82 #define LINK_CONFIG_FIELD (LINK_CONFIG_SLIDING_WINDOW_SIZE | (LINK_CONFIG_OOF_FLOW_CONTROL << 3) | (LINK_CONFIG_DATA_INTEGRITY_CHECK << 4) | (LINK_CONFIG_VERSION_NR << 5))
83 
84 // periodic sending during link establishment
85 #define LINK_PERIOD_MS 250
86 
87 // resend wakeup
88 #define LINK_WAKEUP_MS 50
89 
90 // additional packet types
91 #define LINK_ACKNOWLEDGEMENT_TYPE 0x00
92 #define LINK_CONTROL_PACKET_TYPE 0x0f
93 
94 // max size of write requests
95 #define LINK_SLIP_TX_CHUNK_LEN 64
96 
97 // ---
98 static const uint8_t link_control_sync[] =   { 0x01, 0x7e};
99 static const uint8_t link_control_sync_response[] = { 0x02, 0x7d};
100 static const uint8_t link_control_config[] = { 0x03, 0xfc, LINK_CONFIG_FIELD};
101 static const uint8_t link_control_config_response[] = { 0x04, 0x7b, LINK_CONFIG_FIELD};
102 static const uint8_t link_control_wakeup[] = { 0x05, 0xfa};
103 static const uint8_t link_control_woken[] =  { 0x06, 0xf9};
104 static const uint8_t link_control_sleep[] =  { 0x07, 0x78};
105 
106 // max size of link control messages
107 #define LINK_CONTROL_MAX_LEN 3
108 
109 // incoming pre-bufffer + 4 bytes H5 header + max(acl header + acl payload, event header + event data) + 2 bytes opt CRC
110 static uint8_t   hci_packet_with_pre_buffer[HCI_INCOMING_PRE_BUFFER_SIZE + 6 + HCI_INCOMING_PACKET_BUFFER_SIZE];
111 
112 // outgoing slip encoded buffer. +4 to assert that DIC fits in buffer. +1 to assert that last SOF fits in buffer.
113 static uint8_t   slip_outgoing_buffer[LINK_SLIP_TX_CHUNK_LEN+4+1];
114 static uint16_t  slip_outgoing_dic;
115 static uint16_t  slip_outgoing_dic_present;
116 static int       slip_write_active;
117 
118 // H5 Link State
119 static hci_transport_link_state_t link_state;
120 static btstack_timer_source_t link_timer;
121 static uint8_t  link_seq_nr;
122 static uint8_t  link_ack_nr;
123 static uint16_t link_resend_timeout_ms;
124 static uint8_t  link_peer_asleep;
125 static uint8_t  link_peer_supports_data_integrity_check;
126 
127 // auto sleep-mode
128 static btstack_timer_source_t inactivity_timer;
129 static uint16_t link_inactivity_timeout_ms; // auto-sleep if set
130 
131 // Outgoing packet
132 static uint8_t   hci_packet_type;
133 static uint16_t  hci_packet_size;
134 static uint8_t * hci_packet;
135 
136 // hci packet handler
137 static  void (*packet_handler)(uint8_t packet_type, uint8_t *packet, uint16_t size);
138 
139 static int hci_transport_link_actions;
140 
141 // UART Driver + Config
142 static const btstack_uart_block_t * btstack_uart;
143 static btstack_uart_config_t uart_config;
144 static btstack_uart_sleep_mode_t btstack_uart_sleep_mode;
145 static int hci_transport_bcsp_mode;
146 
147 // Prototypes
148 static void hci_transport_h5_process_frame(uint16_t frame_size);
149 static int  hci_transport_link_have_outgoing_packet(void);
150 static void hci_transport_link_send_queued_packet(void);
151 static void hci_transport_link_set_timer(uint16_t timeout_ms);
152 static void hci_transport_link_timeout_handler(btstack_timer_source_t * timer);
153 static void hci_transport_link_run(void);
154 static void hci_transport_slip_init(void);
155 
156 // -----------------------------
157 // CRC16-CCITT Calculation - compromise: use 32 byte table - 512 byte table would be faster, but that's too large
158 
159 
160 static uint16_t crc16_ccitt_update (uint16_t crc, uint8_t ch){
161 
162     static const uint16_t crc16_ccitt_table[] ={
163             0x0000, 0x1081, 0x2102, 0x3183,
164             0x4204, 0x5285, 0x6306, 0x7387,
165             0x8408, 0x9489, 0xa50a, 0xb58b,
166             0xc60c, 0xd68d, 0xe70e, 0xf78f
167     };
168 
169     crc = (crc >> 4u) ^ crc16_ccitt_table[(crc ^ ch) & 0x000fu];
170     crc = (crc >> 4u) ^ crc16_ccitt_table[(crc ^ (ch >> 4u)) & 0x000fu];
171     return crc;
172 }
173 
174 static uint16_t btstack_reverse_bits_16(uint16_t value){
175     int reverse = 0;
176     int i;
177     for (i = 0; i < 16; i++) {
178         reverse = reverse << 1;
179         reverse |= value & 1u;
180         value = value >> 1;
181     }
182     return reverse;
183 }
184 
185 static uint16_t crc16_calc_for_slip_frame(const uint8_t * header, const uint8_t * payload, uint16_t len){
186     int i;
187     uint16_t crc = 0xffff;
188     for (i=0 ; i < 4 ; i++){
189         crc = crc16_ccitt_update(crc, header[i]);
190     }
191     for (i=0 ; i < len ; i++){
192         crc = crc16_ccitt_update(crc, payload[i]);
193     }
194     return btstack_reverse_bits_16(crc);
195 }
196 
197 // -----------------------------
198 static void hci_transport_inactivity_timeout_handler(btstack_timer_source_t * ts){
199     UNUSED(ts);
200     log_info("inactivity timeout. link state %d, peer asleep %u, actions 0x%02x, outgoing packet %u",
201         link_state, link_peer_asleep, hci_transport_link_actions, hci_transport_link_have_outgoing_packet());
202     if (hci_transport_link_have_outgoing_packet()) return;
203     if (link_state != LINK_ACTIVE) return;
204     if (hci_transport_link_actions) return;
205     if (link_peer_asleep) return;
206     hci_transport_link_actions |= HCI_TRANSPORT_LINK_SEND_SLEEP;
207     hci_transport_link_run();
208 }
209 
210 static void hci_transport_inactivity_timer_set(void){
211     if (!link_inactivity_timeout_ms) return;
212     btstack_run_loop_set_timer_handler(&inactivity_timer, &hci_transport_inactivity_timeout_handler);
213     btstack_run_loop_set_timer(&inactivity_timer, link_inactivity_timeout_ms);
214     btstack_run_loop_remove_timer(&inactivity_timer);
215     btstack_run_loop_add_timer(&inactivity_timer);
216 }
217 
218 // -----------------------------
219 // SLIP Outgoing
220 
221 // Fill chunk and write
222 static void hci_transport_slip_encode_chunk_and_send(int pos){
223     while (btstack_slip_encoder_has_data() & (pos < LINK_SLIP_TX_CHUNK_LEN)) {
224         slip_outgoing_buffer[pos++] = btstack_slip_encoder_get_byte();
225     }
226 
227     if (!btstack_slip_encoder_has_data()){
228         // Payload encoded, append DIC if present.
229         // note: slip_outgoing_buffer is guaranteed to be big enough to add DIC + SOF after LINK_SLIP_TX_CHUNK_LEN
230         if (slip_outgoing_dic_present){
231             uint8_t dic_buffer[2];
232             big_endian_store_16(dic_buffer, 0, slip_outgoing_dic);
233             btstack_slip_encoder_start(dic_buffer, 2);
234             while (btstack_slip_encoder_has_data()){
235                 slip_outgoing_buffer[pos++] = btstack_slip_encoder_get_byte();
236             }
237         }
238         // Start of Frame
239         slip_outgoing_buffer[pos++] = BTSTACK_SLIP_SOF;
240     }
241     slip_write_active = 1;
242     log_debug("slip: send %d bytes", pos);
243     btstack_uart->send_block(slip_outgoing_buffer, pos);
244 }
245 
246 static inline void hci_transport_slip_send_next_chunk(void){
247     hci_transport_slip_encode_chunk_and_send(0);
248 }
249 
250 // format: 0xc0 HEADER PACKET [DIC] 0xc0
251 // @param uint8_t header[4]
252 static void hci_transport_slip_send_frame(const uint8_t * header, const uint8_t * packet, uint16_t packet_size, uint16_t data_integrity_check){
253 
254     int pos = 0;
255 
256     // store data integrity check info
257     slip_outgoing_dic         = data_integrity_check;
258     slip_outgoing_dic_present = header[0] & 0x40u;
259 
260     // Start of Frame
261     slip_outgoing_buffer[pos++] = BTSTACK_SLIP_SOF;
262 
263     // Header
264     btstack_slip_encoder_start(header, 4);
265     while (btstack_slip_encoder_has_data()){
266         slip_outgoing_buffer[pos++] = btstack_slip_encoder_get_byte();
267     }
268 
269     // Packet
270     btstack_slip_encoder_start(packet, packet_size);
271 
272     // Fill rest of chunk from packet and send
273     hci_transport_slip_encode_chunk_and_send(pos);
274 }
275 
276 // SLIP Incoming
277 
278 static void hci_transport_slip_init(void){
279     btstack_slip_decoder_init(&hci_packet_with_pre_buffer[HCI_INCOMING_PRE_BUFFER_SIZE], 6 + HCI_INCOMING_PACKET_BUFFER_SIZE);
280 }
281 
282 // H5 Three-Wire Implementation
283 
284 static void hci_transport_link_calc_header(uint8_t * header,
285     uint8_t  sequence_nr,
286     uint8_t  acknowledgement_nr,
287     uint8_t  data_integrity_check_present,
288     uint8_t  reliable_packet,
289     uint8_t  packet_type,
290     uint16_t payload_length){
291 
292     header[0] = sequence_nr | (acknowledgement_nr << 3) | (data_integrity_check_present << 6) | (reliable_packet << 7);
293     header[1] = packet_type | ((payload_length & 0x0fu) << 4u);
294     header[2] = payload_length >> 4;
295     header[3] = 0xffu - (header[0u] + header[1u] + header[2u]);
296 }
297 
298 static void hci_transport_link_send_control(const uint8_t * message, int message_len){
299     uint8_t header[4];
300     hci_transport_link_calc_header(header, 0, 0, link_peer_supports_data_integrity_check, 0, LINK_CONTROL_PACKET_TYPE, message_len);
301     uint16_t data_integrity_check = 0;
302     if (link_peer_supports_data_integrity_check){
303         data_integrity_check = crc16_calc_for_slip_frame(header, message, message_len);
304     }
305     log_debug("hci_transport_link_send_control: size %u, append dic %u", message_len, link_peer_supports_data_integrity_check);
306     log_debug_hexdump(message, message_len);
307     hci_transport_slip_send_frame(header, message, message_len, data_integrity_check);
308 }
309 
310 static void hci_transport_link_send_sync(void){
311     log_debug("link send sync");
312     hci_transport_link_send_control(link_control_sync, sizeof(link_control_sync));
313 }
314 
315 static void hci_transport_link_send_sync_response(void){
316     log_debug("link send sync response");
317     hci_transport_link_send_control(link_control_sync_response, sizeof(link_control_sync_response));
318 }
319 
320 static void hci_transport_link_send_config(void){
321     log_debug("link send config");
322     hci_transport_link_send_control(link_control_config, sizeof(link_control_config));
323 }
324 
325 static void hci_transport_link_send_config_response(void){
326     log_debug("link send config response");
327     hci_transport_link_send_control(link_control_config_response, sizeof(link_control_config_response));
328 }
329 
330 static void hci_transport_link_send_config_response_empty(void){
331     log_debug("link send config response empty");
332     static const uint8_t link_control_config_response_empty[] = { 0x04, 0x7b};
333     hci_transport_link_send_control(link_control_config_response_empty, sizeof(link_control_config_response_empty));
334 }
335 
336 static void hci_transport_link_send_woken(void){
337     log_debug("link send woken");
338     hci_transport_link_send_control(link_control_woken, sizeof(link_control_woken));
339 }
340 
341 static void hci_transport_link_send_wakeup(void){
342     log_debug("link send wakeup");
343     hci_transport_link_send_control(link_control_wakeup, sizeof(link_control_wakeup));
344 }
345 
346 static void hci_transport_link_send_sleep(void){
347     log_debug("link send sleep");
348     hci_transport_link_send_control(link_control_sleep, sizeof(link_control_sleep));
349 }
350 
351 static void hci_transport_link_send_queued_packet(void){
352 
353     uint8_t header[4];
354     hci_transport_link_calc_header(header, link_seq_nr, link_ack_nr, link_peer_supports_data_integrity_check, 1, hci_packet_type, hci_packet_size);
355 
356     uint16_t data_integrity_check = 0;
357     if (link_peer_supports_data_integrity_check){
358         data_integrity_check = crc16_calc_for_slip_frame(header, hci_packet, hci_packet_size);
359     }
360     log_debug("hci_transport_link_send_queued_packet: seq %u, ack %u, size %u. Append dic %u, dic = 0x%04x", link_seq_nr, link_ack_nr, hci_packet_size, link_peer_supports_data_integrity_check, data_integrity_check);
361     log_debug_hexdump(hci_packet, hci_packet_size);
362 
363     hci_transport_slip_send_frame(header, hci_packet, hci_packet_size, data_integrity_check);
364 
365     // reset inactvitiy timer
366     hci_transport_inactivity_timer_set();
367 }
368 
369 static void hci_transport_link_send_ack_packet(void){
370     // Pure ACK package is without DIC as there is no payload either
371     log_debug("send ack %u", link_ack_nr);
372     uint8_t header[4];
373     hci_transport_link_calc_header(header, 0, link_ack_nr, 0, 0, LINK_ACKNOWLEDGEMENT_TYPE, 0);
374     hci_transport_slip_send_frame(header, NULL, 0, 0);
375 }
376 
377 static void hci_transport_link_run(void){
378     // exit if outgoing active
379     if (slip_write_active) return;
380 
381     // process queued requests
382     if (hci_transport_link_actions & HCI_TRANSPORT_LINK_SEND_SYNC){
383         hci_transport_link_actions &= ~HCI_TRANSPORT_LINK_SEND_SYNC;
384         hci_transport_link_send_sync();
385         return;
386     }
387     if (hci_transport_link_actions & HCI_TRANSPORT_LINK_SEND_SYNC_RESPONSE){
388         hci_transport_link_actions &= ~HCI_TRANSPORT_LINK_SEND_SYNC_RESPONSE;
389         hci_transport_link_send_sync_response();
390         return;
391     }
392     if (hci_transport_link_actions & HCI_TRANSPORT_LINK_SEND_CONFIG){
393         hci_transport_link_actions &= ~HCI_TRANSPORT_LINK_SEND_CONFIG;
394         hci_transport_link_send_config();
395         return;
396     }
397     if (hci_transport_link_actions & HCI_TRANSPORT_LINK_SEND_CONFIG_RESPONSE){
398         hci_transport_link_actions &= ~HCI_TRANSPORT_LINK_SEND_CONFIG_RESPONSE;
399         hci_transport_link_send_config_response();
400         return;
401     }
402     if (hci_transport_link_actions & HCI_TRANSPORT_LINK_SEND_CONFIG_RESPONSE_EMPTY){
403         hci_transport_link_actions &= ~HCI_TRANSPORT_LINK_SEND_CONFIG_RESPONSE_EMPTY;
404         hci_transport_link_send_config_response_empty();
405         return;
406     }
407     if (hci_transport_link_actions & HCI_TRANSPORT_LINK_SEND_WOKEN){
408         hci_transport_link_actions &= ~HCI_TRANSPORT_LINK_SEND_WOKEN;
409         hci_transport_link_send_woken();
410         return;
411     }
412     if (hci_transport_link_actions & HCI_TRANSPORT_LINK_SEND_WAKEUP){
413         hci_transport_link_actions &= ~HCI_TRANSPORT_LINK_SEND_WAKEUP;
414         hci_transport_link_send_wakeup();
415         return;
416     }
417     if (hci_transport_link_actions & HCI_TRANSPORT_LINK_SEND_QUEUED_PACKET){
418         hci_transport_link_actions &= ~HCI_TRANSPORT_LINK_SEND_QUEUED_PACKET;
419         // packet already contains ack, no need to send addtitional one
420         hci_transport_link_actions &= ~HCI_TRANSPORT_LINK_SEND_ACK_PACKET;
421         hci_transport_link_send_queued_packet();
422         return;
423     }
424     if (hci_transport_link_actions & HCI_TRANSPORT_LINK_SEND_ACK_PACKET){
425         hci_transport_link_actions &= ~HCI_TRANSPORT_LINK_SEND_ACK_PACKET;
426         hci_transport_link_send_ack_packet();
427         return;
428     }
429     if (hci_transport_link_actions & HCI_TRANSPORT_LINK_SEND_SLEEP){
430         hci_transport_link_actions &= ~HCI_TRANSPORT_LINK_SEND_SLEEP;
431         hci_transport_link_actions |=  HCI_TRANSPORT_LINK_ENTER_SLEEP;
432         link_peer_asleep = 1;
433         hci_transport_link_send_sleep();
434         return;
435     }
436 }
437 
438 static void hci_transport_link_set_timer(uint16_t timeout_ms){
439     btstack_run_loop_set_timer(&link_timer, timeout_ms);
440     btstack_run_loop_add_timer(&link_timer);
441 }
442 
443 static void hci_transport_link_timeout_handler(btstack_timer_source_t * ts){
444     UNUSED(ts);
445     switch (link_state){
446         case LINK_UNINITIALIZED:
447             hci_transport_link_actions |= HCI_TRANSPORT_LINK_SEND_SYNC;
448             hci_transport_link_set_timer(LINK_PERIOD_MS);
449             break;
450         case LINK_INITIALIZED:
451             hci_transport_link_actions |= HCI_TRANSPORT_LINK_SEND_CONFIG;
452             hci_transport_link_set_timer(LINK_PERIOD_MS);
453             break;
454         case LINK_ACTIVE:
455             if (!hci_transport_link_have_outgoing_packet()){
456                 log_info("h5 timeout while active, but no outgoing packet");
457                 return;
458             }
459             if (link_peer_asleep){
460                 hci_transport_link_actions |= HCI_TRANSPORT_LINK_SEND_WAKEUP;
461                 hci_transport_link_set_timer(LINK_WAKEUP_MS);
462                 return;
463             }
464             // resend packet
465             hci_transport_link_actions |= HCI_TRANSPORT_LINK_SEND_QUEUED_PACKET;
466             hci_transport_link_set_timer(link_resend_timeout_ms);
467             break;
468         default:
469             break;
470     }
471 
472     hci_transport_link_run();
473 }
474 
475 static void hci_transport_link_init(void){
476     link_state = LINK_UNINITIALIZED;
477     link_peer_asleep = 0;
478     link_peer_supports_data_integrity_check = 0;
479 
480     // get started
481     hci_transport_link_actions |= HCI_TRANSPORT_LINK_SEND_SYNC;
482     btstack_run_loop_set_timer_handler(&link_timer, &hci_transport_link_timeout_handler);
483     hci_transport_link_set_timer(LINK_PERIOD_MS);
484     hci_transport_link_run();
485 }
486 
487 static int hci_transport_link_inc_seq_nr(int seq_nr){
488     return (seq_nr + 1) & 0x07;
489 }
490 
491 static int hci_transport_link_have_outgoing_packet(void){
492     return hci_packet != NULL;
493 }
494 
495 static void hci_transport_link_clear_queue(void){
496     btstack_run_loop_remove_timer(&link_timer);
497     hci_packet = NULL;
498 }
499 
500 static void hci_transport_h5_queue_packet(uint8_t packet_type, uint8_t *packet, int size){
501     hci_packet = packet;
502     hci_packet_type = packet_type;
503     hci_packet_size = size;
504 }
505 
506 static void hci_transport_h5_emit_sleep_state(int sleep_active){
507     static int last_state = 0;
508     if (sleep_active == last_state) return;
509     last_state = sleep_active;
510 
511     log_info("emit_sleep_state: %u", sleep_active);
512     uint8_t event[3];
513     event[0] = HCI_EVENT_TRANSPORT_SLEEP_MODE;
514     event[1] = sizeof(event) - 2u;
515     event[2] = sleep_active;
516     packet_handler(HCI_EVENT_PACKET, &event[0], sizeof(event));
517 }
518 
519 static void hci_transport_h5_process_frame(uint16_t frame_size){
520 
521     static const uint8_t link_control_config_prefix_len  = 2;
522     static const uint8_t link_control_config_response_prefix_len  = 2;
523 
524     if (frame_size < 4u) return;
525 
526     uint8_t * slip_header  = &hci_packet_with_pre_buffer[HCI_INCOMING_PRE_BUFFER_SIZE];
527     uint8_t * slip_payload = &hci_packet_with_pre_buffer[HCI_INCOMING_PRE_BUFFER_SIZE + 4];
528     int       frame_size_without_header = frame_size - 4u;
529 
530     uint8_t  seq_nr =  slip_header[0u] & 0x07u;
531     uint8_t  ack_nr = (slip_header[0u] >> 3u)    & 0x07u;
532     uint8_t  data_integrity_check_present = (slip_header[0u] & 0x40u) != 0u;
533     uint8_t  reliable_packet  = (slip_header[0u] & 0x80u) != 0u;
534     uint8_t  link_packet_type = slip_header[1u] & 0x0fu;
535     uint16_t link_payload_len = (slip_header[1] >> 4) | (slip_header[2] << 4);
536 
537     log_debug("process_frame, reliable %u, packet type %u, seq_nr %u, ack_nr %u , dic %u, payload 0x%04x bytes", reliable_packet, link_packet_type, seq_nr, ack_nr, data_integrity_check_present, frame_size_without_header);
538     log_debug_hexdump(slip_header, 4);
539     log_debug_hexdump(slip_payload, frame_size_without_header);
540 
541     // CSR 8811 does not seem to auto-detect H5 mode and sends data with even parity.
542     // if this byte sequence is detected, just enable even parity
543     const uint8_t sync_response_bcsp[] = {0x01, 0x7a, 0x06, 0x10};
544     if (memcmp(sync_response_bcsp, slip_header, 4) == 0){
545         log_info("detected BSCP SYNC sent with Even Parity -> discard frame and enable Even Parity");
546         btstack_uart->set_parity(1);
547         return;
548     }
549 
550     // validate header checksum
551     uint8_t header_checksum = slip_header[0] + slip_header[1] + slip_header[2] + slip_header[3];
552     if (header_checksum != 0xffu){
553         log_info("header checksum 0x%02x (instead of 0xff)", header_checksum);
554         return;
555     }
556 
557     // validate payload length
558     int data_integrity_len = data_integrity_check_present ? 2 : 0;
559     uint16_t received_payload_len = frame_size_without_header - data_integrity_len;
560     if (link_payload_len != received_payload_len){
561         log_info("expected payload len %u but got %u", link_payload_len, received_payload_len);
562         return;
563     }
564 
565     // validate data integrity check
566     if (data_integrity_check_present){
567         uint16_t dic_packet = big_endian_read_16(slip_payload, received_payload_len);
568         uint16_t dic_calculate = crc16_calc_for_slip_frame(slip_header, slip_payload, received_payload_len);
569         if (dic_packet != dic_calculate){
570             log_info("expected dic value 0x%04x but got 0x%04x", dic_calculate, dic_packet);
571             return;
572         }
573     }
574 
575     switch (link_state){
576         case LINK_UNINITIALIZED:
577             if (link_packet_type != LINK_CONTROL_PACKET_TYPE) break;
578             if (memcmp(slip_payload, link_control_sync, sizeof(link_control_sync)) == 0){
579                 log_debug("link received sync");
580                 hci_transport_link_actions |= HCI_TRANSPORT_LINK_SEND_SYNC_RESPONSE;
581                 break;
582             }
583             if (memcmp(slip_payload, link_control_sync_response, sizeof(link_control_sync_response)) == 0){
584                 log_debug("link received sync response");
585                 link_state = LINK_INITIALIZED;
586                 btstack_run_loop_remove_timer(&link_timer);
587                 log_info("link initialized");
588                 //
589                 hci_transport_link_actions |= HCI_TRANSPORT_LINK_SEND_CONFIG;
590                 hci_transport_link_set_timer(LINK_PERIOD_MS);
591                 break;
592             }
593             break;
594         case LINK_INITIALIZED:
595             if (link_packet_type != LINK_CONTROL_PACKET_TYPE) break;
596             if (memcmp(slip_payload, link_control_sync, sizeof(link_control_sync)) == 0){
597                 log_debug("link received sync");
598                 hci_transport_link_actions |= HCI_TRANSPORT_LINK_SEND_SYNC_RESPONSE;
599                 break;
600             }
601             if (memcmp(slip_payload, link_control_config, link_control_config_prefix_len) == 0){
602                 if (link_payload_len == link_control_config_prefix_len){
603                     log_debug("link received config, no config field");
604                     hci_transport_link_actions |= HCI_TRANSPORT_LINK_SEND_CONFIG_RESPONSE_EMPTY;
605                 } else {
606                     log_debug("link received config, 0x%02x", slip_payload[2]);
607                     hci_transport_link_actions |= HCI_TRANSPORT_LINK_SEND_CONFIG_RESPONSE;
608                 }
609                 break;
610             }
611             if (memcmp(slip_payload, link_control_config_response, link_control_config_response_prefix_len) == 0){
612                 uint8_t config = slip_payload[2];
613                 link_peer_supports_data_integrity_check = (config & 0x10u) != 0u;
614                 log_info("link received config response 0x%02x, data integrity check supported %u", config, link_peer_supports_data_integrity_check);
615                 link_state = LINK_ACTIVE;
616                 btstack_run_loop_remove_timer(&link_timer);
617                 log_info("link activated");
618                 //
619                 link_seq_nr = 0;
620                 link_ack_nr = 0;
621                 // notify upper stack that it can start
622                 uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0};
623                 packet_handler(HCI_EVENT_PACKET, &event[0], sizeof(event));
624                 break;
625             }
626             break;
627         case LINK_ACTIVE:
628 
629             // validate packet sequence nr in reliable packets (check for out of sequence error)
630             if (reliable_packet){
631                 if (seq_nr != link_ack_nr){
632                     log_info("expected seq nr %u, but received %u", link_ack_nr, seq_nr);
633                     hci_transport_link_actions |= HCI_TRANSPORT_LINK_SEND_ACK_PACKET;
634                     break;
635                 }
636                 // ack packet right away
637                 link_ack_nr = hci_transport_link_inc_seq_nr(link_ack_nr);
638                 hci_transport_link_actions |= HCI_TRANSPORT_LINK_SEND_ACK_PACKET;
639             }
640 
641             // Process ACKs in reliable packet and explicit ack packets
642             if (reliable_packet || (link_packet_type == LINK_ACKNOWLEDGEMENT_TYPE)){
643                 // our packet is good if the remote expects our seq nr + 1
644                 int next_seq_nr = hci_transport_link_inc_seq_nr(link_seq_nr);
645                 if (hci_transport_link_have_outgoing_packet() && (next_seq_nr == ack_nr)){
646                     log_debug("outoing packet with seq %u ack'ed", link_seq_nr);
647                     link_seq_nr = next_seq_nr;
648                     hci_transport_link_clear_queue();
649 
650                     // notify upper stack that it can send again
651                     uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0};
652                     packet_handler(HCI_EVENT_PACKET, &event[0], sizeof(event));
653                 }
654             }
655 
656             switch (link_packet_type){
657                 case LINK_CONTROL_PACKET_TYPE:
658                     if (memcmp(slip_payload, link_control_config, sizeof(link_control_config)) == 0){
659                         if (link_payload_len == link_control_config_prefix_len){
660                             log_debug("link received config, no config field");
661                             hci_transport_link_actions |= HCI_TRANSPORT_LINK_SEND_CONFIG_RESPONSE_EMPTY;
662                         } else {
663                             log_debug("link received config, 0x%02x", slip_payload[2]);
664                             hci_transport_link_actions |= HCI_TRANSPORT_LINK_SEND_CONFIG_RESPONSE;
665                         }
666                         break;
667                     }
668                     if (memcmp(slip_payload, link_control_sync, sizeof(link_control_sync)) == 0){
669                         log_debug("link received sync in ACTIVE STATE!");
670                         // TODO sync during active indicates peer reset -> full upper layer reset necessary
671                         break;
672                     }
673                     if (memcmp(slip_payload, link_control_sleep, sizeof(link_control_sleep)) == 0){
674                         if (btstack_uart_sleep_mode){
675                             log_info("link: received sleep message. Enabling UART Sleep.");
676                             btstack_uart->set_sleep(btstack_uart_sleep_mode);
677                             hci_transport_h5_emit_sleep_state(1);
678                         } else {
679                             log_info("link: received sleep message. UART Sleep not supported");
680                         }
681                         link_peer_asleep = 1;
682                         break;
683                     }
684                     if (memcmp(slip_payload, link_control_wakeup, sizeof(link_control_wakeup)) == 0){
685                         log_info("link: received wakupe message -> send woken");
686                         link_peer_asleep = 0;
687                         hci_transport_link_actions |= HCI_TRANSPORT_LINK_SEND_WOKEN;
688                         break;
689                     }
690                     if (memcmp(slip_payload, link_control_woken, sizeof(link_control_woken)) == 0){
691                         log_info("link: received woken message");
692                         link_peer_asleep = 0;
693                         // queued packet will be sent in hci_transport_link_run if needed
694                         break;
695                     }
696                     break;
697                 case HCI_EVENT_PACKET:
698                 case HCI_ACL_DATA_PACKET:
699                 case HCI_SCO_DATA_PACKET:
700                     // seems like peer is awake
701                     link_peer_asleep = 0;
702                     // forward packet to stack
703                     packet_handler(link_packet_type, slip_payload, link_payload_len);
704                     // reset inactvitiy timer
705                     hci_transport_inactivity_timer_set();
706                     break;
707 				default:
708 					// invalid packet type,  ignore
709 					break;
710             }
711 
712             break;
713         default:
714             break;
715     }
716 
717     hci_transport_link_run();
718 }
719 
720 // recommendet time until resend: 3 * time of largest packet
721 static uint16_t hci_transport_link_calc_resend_timeout(uint32_t baudrate){
722     uint32_t max_packet_size_in_bit = (HCI_INCOMING_PACKET_BUFFER_SIZE + 6) << 3;
723     uint32_t t_max_x3_ms = max_packet_size_in_bit * 3000u / baudrate;
724 
725     // allow for BTstack logging and other delays
726     t_max_x3_ms += 50u;
727 
728     log_info("resend timeout for %"PRIu32" baud: %u ms", baudrate, (int) t_max_x3_ms);
729     return t_max_x3_ms;
730 }
731 
732 static void hci_transport_link_update_resend_timeout(uint32_t baudrate){
733     link_resend_timeout_ms = hci_transport_link_calc_resend_timeout(baudrate);
734 }
735 
736 /// H5 Interface
737 
738 static uint8_t hci_transport_link_read_byte;
739 static int hci_transport_h5_active;
740 
741 static void hci_transport_h5_read_next_byte(void){
742     btstack_uart->receive_block(&hci_transport_link_read_byte, 1);
743 }
744 
745 // track time receiving SLIP frame
746 static uint32_t hci_transport_h5_receive_start;
747 static void hci_transport_h5_block_received(void){
748     if (hci_transport_h5_active == 0) return;
749 
750     // track start time when receiving first byte // a bit hackish
751     if ((hci_transport_h5_receive_start == 0u) && (hci_transport_link_read_byte != BTSTACK_SLIP_SOF)){
752         hci_transport_h5_receive_start = btstack_run_loop_get_time_ms();
753     }
754     btstack_slip_decoder_process(hci_transport_link_read_byte);
755     uint16_t frame_size = btstack_slip_decoder_frame_size();
756     if (frame_size) {
757         // track time
758         uint32_t packet_receive_time = btstack_run_loop_get_time_ms() - hci_transport_h5_receive_start;
759         uint32_t nominal_time = (frame_size + 6u) * 10u * 1000u / uart_config.baudrate;
760         UNUSED(nominal_time);
761         UNUSED(packet_receive_time);
762         log_info("slip frame time %u ms for %u decoded bytes. nomimal time %u ms", (int) packet_receive_time, frame_size, (int) nominal_time);
763         // reset state
764         hci_transport_h5_receive_start = 0;
765         //
766         hci_transport_h5_process_frame(frame_size);
767         hci_transport_slip_init();
768     }
769     hci_transport_h5_read_next_byte();
770 }
771 
772 static void hci_transport_h5_block_sent(void){
773     if (hci_transport_h5_active == 0) return;
774 
775     // check if more data to send
776     if (btstack_slip_encoder_has_data()){
777         hci_transport_slip_send_next_chunk();
778         return;
779     }
780 
781     // done
782     slip_write_active = 0;
783 
784     // enter sleep mode after sending sleep message
785     if (hci_transport_link_actions & HCI_TRANSPORT_LINK_ENTER_SLEEP){
786         hci_transport_link_actions &= ~HCI_TRANSPORT_LINK_ENTER_SLEEP;
787         if (btstack_uart_sleep_mode){
788             log_info("link: sent sleep message. Enabling UART Sleep.");
789             btstack_uart->set_sleep(btstack_uart_sleep_mode);
790         } else {
791             log_info("link: sent sleep message. UART Sleep not supported");
792         }
793         hci_transport_h5_emit_sleep_state(1);
794     }
795 
796     hci_transport_link_run();
797 }
798 
799 static void hci_transport_h5_init(const void * transport_config){
800     // check for hci_transport_config_uart_t
801     if (!transport_config) {
802         log_error("hci_transport_h5: no config!");
803         return;
804     }
805     if (((hci_transport_config_t*)transport_config)->type != HCI_TRANSPORT_CONFIG_UART) {
806         log_error("hci_transport_h5: config not of type != HCI_TRANSPORT_CONFIG_UART!");
807         return;
808     }
809 
810     hci_transport_h5_active = 0;
811 
812     // extract UART config from transport config
813     hci_transport_config_uart_t * hci_transport_config_uart = (hci_transport_config_uart_t*) transport_config;
814     uart_config.baudrate    = hci_transport_config_uart->baudrate_init;
815     uart_config.flowcontrol = hci_transport_config_uart->flowcontrol;
816     uart_config.device_name = hci_transport_config_uart->device_name;
817 
818     // setup UART driver
819     btstack_uart->init(&uart_config);
820     btstack_uart->set_block_received(&hci_transport_h5_block_received);
821     btstack_uart->set_block_sent(&hci_transport_h5_block_sent);
822 }
823 
824 static int hci_transport_h5_open(void){
825     int res = btstack_uart->open();
826     if (res){
827         return res;
828     }
829 
830     //
831     if (hci_transport_bcsp_mode){
832         log_info("enable even parity for BCSP mode");
833         btstack_uart->set_parity(1);
834     }
835 
836     // check if wake on RX can be used
837     btstack_uart_sleep_mode = BTSTACK_UART_SLEEP_OFF;
838     int supported_sleep_modes = 0;
839     if (btstack_uart->get_supported_sleep_modes){
840         supported_sleep_modes = btstack_uart->get_supported_sleep_modes();
841     }
842     if (supported_sleep_modes & BTSTACK_UART_SLEEP_MASK_RTS_LOW_WAKE_ON_RX_EDGE){
843         log_info("using wake on RX");
844         btstack_uart_sleep_mode = BTSTACK_UART_SLEEP_RTS_LOW_WAKE_ON_RX_EDGE;
845     } else {
846         log_info("UART driver does not provide compatible sleep mode");
847     }
848 
849     // setup resend timeout
850     hci_transport_link_update_resend_timeout(uart_config.baudrate);
851 
852     // init slip parser state machine
853     hci_transport_slip_init();
854 
855     // init link management - already starts syncing
856     hci_transport_link_init();
857 
858     // start receiving
859     hci_transport_h5_active = 1;
860     hci_transport_h5_read_next_byte();
861 
862     return 0;
863 }
864 
865 static int hci_transport_h5_close(void){
866     hci_transport_h5_active = 0;
867     return btstack_uart->close();
868 }
869 
870 static void hci_transport_h5_register_packet_handler(void (*handler)(uint8_t packet_type, uint8_t *packet, uint16_t size)){
871     packet_handler = handler;
872 }
873 
874 static int hci_transport_h5_can_send_packet_now(uint8_t packet_type){
875     int res = !hci_transport_link_have_outgoing_packet() && (link_state == LINK_ACTIVE);
876     // log_info("can_send_packet_now: %u", res);
877     return res;
878 }
879 
880 static int hci_transport_h5_send_packet(uint8_t packet_type, uint8_t *packet, int size){
881     if (!hci_transport_h5_can_send_packet_now(packet_type)){
882         log_error("hci_transport_h5_send_packet called but in state %d", link_state);
883         return -1;
884     }
885 
886     // store request
887     hci_transport_h5_queue_packet(packet_type, packet, size);
888 
889     // send wakeup first
890     if (link_peer_asleep){
891         hci_transport_h5_emit_sleep_state(0);
892         if (btstack_uart_sleep_mode){
893             log_info("disable UART sleep");
894             btstack_uart->set_sleep(BTSTACK_UART_SLEEP_OFF);
895         }
896         hci_transport_link_actions |= HCI_TRANSPORT_LINK_SEND_WAKEUP;
897         hci_transport_link_set_timer(LINK_WAKEUP_MS);
898     } else {
899         hci_transport_link_actions |= HCI_TRANSPORT_LINK_SEND_QUEUED_PACKET;
900         hci_transport_link_set_timer(link_resend_timeout_ms);
901     }
902     hci_transport_link_run();
903     return 0;
904 }
905 
906 static int hci_transport_h5_set_baudrate(uint32_t baudrate){
907 
908     log_info("set_baudrate %"PRIu32, baudrate);
909     int res = btstack_uart->set_baudrate(baudrate);
910 
911     if (res) return res;
912     uart_config.baudrate = baudrate;
913     hci_transport_link_update_resend_timeout(baudrate);
914     return 0;
915 }
916 
917 static void hci_transport_h5_reset_link(void){
918 
919     log_info("reset_link");
920 
921     // clear outgoing queue
922     hci_transport_link_clear_queue();
923 
924     // init slip parser state machine
925     hci_transport_slip_init();
926 
927     // init link management - already starts syncing
928     hci_transport_link_init();
929 }
930 
931 // configure and return h5 singleton
932 const hci_transport_t * hci_transport_h5_instance(const btstack_uart_block_t * uart_driver) {
933 
934     static const hci_transport_t hci_transport_h5 = {
935             /* const char * name; */                                        "H5",
936             /* void   (*init) (const void *transport_config); */            &hci_transport_h5_init,
937             /* int    (*open)(void); */                                     &hci_transport_h5_open,
938             /* int    (*close)(void); */                                    &hci_transport_h5_close,
939             /* void   (*register_packet_handler)(void (*handler)(...); */   &hci_transport_h5_register_packet_handler,
940             /* int    (*can_send_packet_now)(uint8_t packet_type); */       &hci_transport_h5_can_send_packet_now,
941             /* int    (*send_packet)(...); */                               &hci_transport_h5_send_packet,
942             /* int    (*set_baudrate)(uint32_t baudrate); */                &hci_transport_h5_set_baudrate,
943             /* void   (*reset_link)(void); */                               &hci_transport_h5_reset_link,
944             /* void   (*set_sco_config)(uint16_t voice_setting, int num_connections); */ NULL,
945     };
946 
947     btstack_uart = uart_driver;
948     return &hci_transport_h5;
949 }
950 
951 void hci_transport_h5_set_auto_sleep(uint16_t inactivity_timeout_ms){
952     link_inactivity_timeout_ms = inactivity_timeout_ms;
953 }
954 
955 void hci_transport_h5_enable_bcsp_mode(void){
956     hci_transport_bcsp_mode = 1;
957 }
958