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