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