xref: /btstack/src/hci_transport_h5.c (revision d58a1b5f11ada8ddf896c41fff5a35e7f140c37e)
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_prefix_len  = 2;
102 static const uint8_t link_control_config_response_empty[] = { 0x04, 0x7b};
103 static const uint8_t link_control_config_response[] = { 0x04, 0x7b, LINK_CONFIG_FIELD};
104 static const uint8_t link_control_config_response_prefix_len  = 2;
105 static const uint8_t link_control_wakeup[] = { 0x05, 0xfa};
106 static const uint8_t link_control_woken[] =  { 0x06, 0xf9};
107 static const uint8_t link_control_sleep[] =  { 0x07, 0x78};
108 
109 // max size of link control messages
110 #define LINK_CONTROL_MAX_LEN 3
111 
112 // incoming pre-bufffer + 4 bytes H5 header + max(acl header + acl payload, event header + event data) + 2 bytes opt CRC
113 static uint8_t   hci_packet_with_pre_buffer[HCI_INCOMING_PRE_BUFFER_SIZE + 6 + HCI_INCOMING_PACKET_BUFFER_SIZE];
114 
115 // outgoing slip encoded buffer. +4 to assert that DIC fits in buffer. +1 to assert that last SOF fits in buffer.
116 static uint8_t   slip_outgoing_buffer[LINK_SLIP_TX_CHUNK_LEN+4+1];
117 static uint16_t  slip_outgoing_dic;
118 static uint16_t  slip_outgoing_dic_present;
119 static int       slip_write_active;
120 
121 // H5 Link State
122 static hci_transport_link_state_t link_state;
123 static btstack_timer_source_t link_timer;
124 static uint8_t  link_seq_nr;
125 static uint8_t  link_ack_nr;
126 static uint16_t link_resend_timeout_ms;
127 static uint8_t  link_peer_asleep;
128 static uint8_t  link_peer_supports_data_integrity_check;
129 
130 // auto sleep-mode
131 static btstack_timer_source_t inactivity_timer;
132 static uint16_t link_inactivity_timeout_ms; // auto-sleep if set
133 
134 // Outgoing packet
135 static uint8_t   hci_packet_type;
136 static uint16_t  hci_packet_size;
137 static uint8_t * hci_packet;
138 
139 // hci packet handler
140 static  void (*packet_handler)(uint8_t packet_type, uint8_t *packet, uint16_t size);
141 
142 static int hci_transport_link_actions;
143 
144 // UART Driver + Config
145 static const btstack_uart_block_t * btstack_uart;
146 static btstack_uart_config_t uart_config;
147 static btstack_uart_sleep_mode_t btstack_uart_sleep_mode;
148 static int hci_transport_bcsp_mode;
149 
150 // Prototypes
151 static void hci_transport_h5_process_frame(uint16_t frame_size);
152 static int  hci_transport_link_have_outgoing_packet(void);
153 static void hci_transport_link_send_queued_packet(void);
154 static void hci_transport_link_set_timer(uint16_t timeout_ms);
155 static void hci_transport_link_timeout_handler(btstack_timer_source_t * timer);
156 static void hci_transport_link_run(void);
157 static void hci_transport_slip_init(void);
158 
159 // -----------------------------
160 // CRC16-CCITT Calculation - compromise: use 32 byte table - 512 byte table would be faster, but that's too large
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 static uint16_t crc16_ccitt_update (uint16_t crc, uint8_t ch){
170     crc = (crc >> 4) ^ crc16_ccitt_table[(crc ^ ch) & 0x000f];
171     crc = (crc >> 4) ^ crc16_ccitt_table[(crc ^ (ch >> 4)) & 0x000f];
172     return crc;
173 }
174 
175 static uint16_t btstack_reverse_bits_16(uint16_t value){
176     int reverse = 0;
177     int i;
178     for (i = 0; i < 16; i++) {
179         reverse = reverse << 1;
180         reverse |= value & 1;
181         value = value >> 1;
182     }
183     return reverse;
184 }
185 
186 static uint16_t crc16_calc_for_slip_frame(const uint8_t * header, const uint8_t * payload, uint16_t len){
187     int i;
188     uint16_t crc = 0xffff;
189     for (i=0 ; i < 4 ; i++){
190         crc = crc16_ccitt_update(crc, header[i]);
191     }
192     for (i=0 ; i < len ; i++){
193         crc = crc16_ccitt_update(crc, payload[i]);
194     }
195     return btstack_reverse_bits_16(crc);
196 }
197 
198 // -----------------------------
199 static void hci_transport_inactivity_timeout_handler(btstack_timer_source_t * ts){
200     UNUSED(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 // -----------------------------
220 // SLIP Outgoing
221 
222 // Fill chunk and write
223 static void hci_transport_slip_encode_chunk_and_send(int pos){
224     while (btstack_slip_encoder_has_data() & (pos < LINK_SLIP_TX_CHUNK_LEN)) {
225         slip_outgoing_buffer[pos++] = btstack_slip_encoder_get_byte();
226     }
227 
228     if (!btstack_slip_encoder_has_data()){
229         // Payload encoded, append DIC if present.
230         // note: slip_outgoing_buffer is guaranteed to be big enough to add DIC + SOF after LINK_SLIP_TX_CHUNK_LEN
231         if (slip_outgoing_dic_present){
232             uint8_t dic_buffer[2];
233             big_endian_store_16(dic_buffer, 0, slip_outgoing_dic);
234             btstack_slip_encoder_start(dic_buffer, 2);
235             while (btstack_slip_encoder_has_data()){
236                 slip_outgoing_buffer[pos++] = btstack_slip_encoder_get_byte();
237             }
238         }
239         // Start of Frame
240         slip_outgoing_buffer[pos++] = BTSTACK_SLIP_SOF;
241     }
242     slip_write_active = 1;
243     log_debug("slip: send %d bytes", pos);
244     btstack_uart->send_block(slip_outgoing_buffer, pos);
245 }
246 
247 static inline void hci_transport_slip_send_next_chunk(void){
248     hci_transport_slip_encode_chunk_and_send(0);
249 }
250 
251 // format: 0xc0 HEADER PACKET [DIC] 0xc0
252 // @param uint8_t header[4]
253 static void hci_transport_slip_send_frame(const uint8_t * header, const uint8_t * packet, uint16_t packet_size, uint16_t data_integrity_check){
254 
255     int pos = 0;
256 
257     // store data integrity check info
258     slip_outgoing_dic         = data_integrity_check;
259     slip_outgoing_dic_present = header[0] & 0x40;
260 
261     // Start of Frame
262     slip_outgoing_buffer[pos++] = BTSTACK_SLIP_SOF;
263 
264     // Header
265     btstack_slip_encoder_start(header, 4);
266     while (btstack_slip_encoder_has_data()){
267         slip_outgoing_buffer[pos++] = btstack_slip_encoder_get_byte();
268     }
269 
270     // Packet
271     btstack_slip_encoder_start(packet, packet_size);
272 
273     // Fill rest of chunk from packet and send
274     hci_transport_slip_encode_chunk_and_send(pos);
275 }
276 
277 // SLIP Incoming
278 
279 static void hci_transport_slip_init(void){
280     btstack_slip_decoder_init(&hci_packet_with_pre_buffer[HCI_INCOMING_PRE_BUFFER_SIZE], 6 + HCI_INCOMING_PACKET_BUFFER_SIZE);
281 }
282 
283 // H5 Three-Wire Implementation
284 
285 static void hci_transport_link_calc_header(uint8_t * header,
286     uint8_t  sequence_nr,
287     uint8_t  acknowledgement_nr,
288     uint8_t  data_integrity_check_present,
289     uint8_t  reliable_packet,
290     uint8_t  packet_type,
291     uint16_t payload_length){
292 
293     header[0] = sequence_nr | (acknowledgement_nr << 3) | (data_integrity_check_present << 6) | (reliable_packet << 7);
294     header[1] = packet_type | ((payload_length & 0x0f) << 4);
295     header[2] = payload_length >> 4;
296     header[3] = 0xff - (header[0] + header[1] + header[2]);
297 }
298 
299 static void hci_transport_link_send_control(const uint8_t * message, int message_len){
300     uint8_t header[4];
301     hci_transport_link_calc_header(header, 0, 0, link_peer_supports_data_integrity_check, 0, LINK_CONTROL_PACKET_TYPE, message_len);
302     uint16_t data_integrity_check = 0;
303     if (link_peer_supports_data_integrity_check){
304         data_integrity_check = crc16_calc_for_slip_frame(header, message, message_len);
305     }
306     log_debug("hci_transport_link_send_control: size %u, append dic %u", message_len, link_peer_supports_data_integrity_check);
307     log_debug_hexdump(message, message_len);
308     hci_transport_slip_send_frame(header, message, message_len, data_integrity_check);
309 }
310 
311 static void hci_transport_link_send_sync(void){
312     log_debug("link send sync");
313     hci_transport_link_send_control(link_control_sync, sizeof(link_control_sync));
314 }
315 
316 static void hci_transport_link_send_sync_response(void){
317     log_debug("link send sync response");
318     hci_transport_link_send_control(link_control_sync_response, sizeof(link_control_sync_response));
319 }
320 
321 static void hci_transport_link_send_config(void){
322     log_debug("link send config");
323     hci_transport_link_send_control(link_control_config, sizeof(link_control_config));
324 }
325 
326 static void hci_transport_link_send_config_response(void){
327     log_debug("link send config response");
328     hci_transport_link_send_control(link_control_config_response, sizeof(link_control_config_response));
329 }
330 
331 static void hci_transport_link_send_config_response_empty(void){
332     log_debug("link send config response empty");
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_handler(&link_timer, &hci_transport_link_timeout_handler);
440     btstack_run_loop_set_timer(&link_timer, timeout_ms);
441     btstack_run_loop_add_timer(&link_timer);
442 }
443 
444 static void hci_transport_link_timeout_handler(btstack_timer_source_t * ts){
445     UNUSED(ts);
446     switch (link_state){
447         case LINK_UNINITIALIZED:
448             hci_transport_link_actions |= HCI_TRANSPORT_LINK_SEND_SYNC;
449             hci_transport_link_set_timer(LINK_PERIOD_MS);
450             break;
451         case LINK_INITIALIZED:
452             hci_transport_link_actions |= HCI_TRANSPORT_LINK_SEND_CONFIG;
453             hci_transport_link_set_timer(LINK_PERIOD_MS);
454             break;
455         case LINK_ACTIVE:
456             if (!hci_transport_link_have_outgoing_packet()){
457                 log_info("h5 timeout while active, but no outgoing packet");
458                 return;
459             }
460             if (link_peer_asleep){
461                 hci_transport_link_actions |= HCI_TRANSPORT_LINK_SEND_WAKEUP;
462                 hci_transport_link_set_timer(LINK_WAKEUP_MS);
463                 return;
464             }
465             // resend packet
466             hci_transport_link_actions |= HCI_TRANSPORT_LINK_SEND_QUEUED_PACKET;
467             hci_transport_link_set_timer(link_resend_timeout_ms);
468             break;
469         default:
470             break;
471     }
472 
473     hci_transport_link_run();
474 }
475 
476 static void hci_transport_link_init(void){
477     link_state = LINK_UNINITIALIZED;
478     link_peer_asleep = 0;
479     link_peer_supports_data_integrity_check = 0;
480 
481     // get started
482     hci_transport_link_actions |= HCI_TRANSPORT_LINK_SEND_SYNC;
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 != 0;
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) - 2;
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     if (frame_size < 4) return;
522 
523     uint8_t * slip_header  = &hci_packet_with_pre_buffer[HCI_INCOMING_PRE_BUFFER_SIZE];
524     uint8_t * slip_payload = &hci_packet_with_pre_buffer[HCI_INCOMING_PRE_BUFFER_SIZE + 4];
525     int       frame_size_without_header = frame_size - 4;
526 
527     uint8_t  seq_nr =  slip_header[0] & 0x07;
528     uint8_t  ack_nr = (slip_header[0] >> 3)    & 0x07;
529     uint8_t  data_integrity_check_present = (slip_header[0] & 0x40) != 0;
530     uint8_t  reliable_packet  = (slip_header[0] & 0x80) != 0;
531     uint8_t  link_packet_type = slip_header[1] & 0x0f;
532     uint16_t link_payload_len = (slip_header[1] >> 4) | (slip_header[2] << 4);
533 
534     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);
535     log_debug_hexdump(slip_header, 4);
536     log_debug_hexdump(slip_payload, frame_size_without_header);
537 
538     // CSR 8811 does not seem to auto-detect H5 mode and sends data with even parity.
539     // if this byte sequence is detected, just enable even parity
540     const uint8_t sync_response_bcsp[] = {0x01, 0x7a, 0x06, 0x10};
541     if (memcmp(sync_response_bcsp, slip_header, 4) == 0){
542         log_info("detected BSCP SYNC sent with Even Parity -> discard frame and enable Even Parity");
543         btstack_uart->set_parity(1);
544         return;
545     }
546 
547     // validate header checksum
548     uint8_t header_checksum = slip_header[0] + slip_header[1] + slip_header[2] + slip_header[3];
549     if (header_checksum != 0xff){
550         log_info("header checksum 0x%02x (instead of 0xff)", header_checksum);
551         return;
552     }
553 
554     // validate payload length
555     int data_integrity_len = data_integrity_check_present ? 2 : 0;
556     uint16_t received_payload_len = frame_size_without_header - data_integrity_len;
557     if (link_payload_len != received_payload_len){
558         log_info("expected payload len %u but got %u", link_payload_len, received_payload_len);
559         return;
560     }
561 
562     // validate data integrity check
563     if (data_integrity_check_present){
564         uint16_t dic_packet = big_endian_read_16(slip_payload, received_payload_len);
565         uint16_t dic_calculate = crc16_calc_for_slip_frame(slip_header, slip_payload, received_payload_len);
566         if (dic_packet != dic_calculate){
567             log_info("expected dic value 0x%04x but got 0x%04x", dic_calculate, dic_packet);
568             return;
569         }
570     }
571 
572     switch (link_state){
573         case LINK_UNINITIALIZED:
574             if (link_packet_type != LINK_CONTROL_PACKET_TYPE) break;
575             if (memcmp(slip_payload, link_control_sync, sizeof(link_control_sync)) == 0){
576                 log_debug("link received sync");
577                 hci_transport_link_actions |= HCI_TRANSPORT_LINK_SEND_SYNC_RESPONSE;
578                 break;
579             }
580             if (memcmp(slip_payload, link_control_sync_response, sizeof(link_control_sync_response)) == 0){
581                 log_debug("link received sync response");
582                 link_state = LINK_INITIALIZED;
583                 btstack_run_loop_remove_timer(&link_timer);
584                 log_info("link initialized");
585                 //
586                 hci_transport_link_actions |= HCI_TRANSPORT_LINK_SEND_CONFIG;
587                 hci_transport_link_set_timer(LINK_PERIOD_MS);
588                 break;
589             }
590             break;
591         case LINK_INITIALIZED:
592             if (link_packet_type != LINK_CONTROL_PACKET_TYPE) break;
593             if (memcmp(slip_payload, link_control_sync, sizeof(link_control_sync)) == 0){
594                 log_debug("link received sync");
595                 hci_transport_link_actions |= HCI_TRANSPORT_LINK_SEND_SYNC_RESPONSE;
596                 break;
597             }
598             if (memcmp(slip_payload, link_control_config, link_control_config_prefix_len) == 0){
599                 if (link_payload_len == link_control_config_prefix_len){
600                     log_debug("link received config, no config field");
601                     hci_transport_link_actions |= HCI_TRANSPORT_LINK_SEND_CONFIG_RESPONSE_EMPTY;
602                 } else {
603                     log_debug("link received config, 0x%02x", slip_payload[2]);
604                     hci_transport_link_actions |= HCI_TRANSPORT_LINK_SEND_CONFIG_RESPONSE;
605                 }
606                 break;
607             }
608             if (memcmp(slip_payload, link_control_config_response, link_control_config_response_prefix_len) == 0){
609                 uint8_t config = slip_payload[2];
610                 link_peer_supports_data_integrity_check = (config & 0x10) != 0;
611                 log_info("link received config response 0x%02x, data integrity check supported %u", config, link_peer_supports_data_integrity_check);
612                 link_state = LINK_ACTIVE;
613                 btstack_run_loop_remove_timer(&link_timer);
614                 log_info("link activated");
615                 //
616                 link_seq_nr = 0;
617                 link_ack_nr = 0;
618                 // notify upper stack that it can start
619                 uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0};
620                 packet_handler(HCI_EVENT_PACKET, &event[0], sizeof(event));
621                 break;
622             }
623             break;
624         case LINK_ACTIVE:
625 
626             // validate packet sequence nr in reliable packets (check for out of sequence error)
627             if (reliable_packet){
628                 if (seq_nr != link_ack_nr){
629                     log_info("expected seq nr %u, but received %u", link_ack_nr, seq_nr);
630                     hci_transport_link_actions |= HCI_TRANSPORT_LINK_SEND_ACK_PACKET;
631                     break;
632                 }
633                 // ack packet right away
634                 link_ack_nr = hci_transport_link_inc_seq_nr(link_ack_nr);
635                 hci_transport_link_actions |= HCI_TRANSPORT_LINK_SEND_ACK_PACKET;
636             }
637 
638             // Process ACKs in reliable packet and explicit ack packets
639             if (reliable_packet || (link_packet_type == LINK_ACKNOWLEDGEMENT_TYPE)){
640                 // our packet is good if the remote expects our seq nr + 1
641                 int next_seq_nr = hci_transport_link_inc_seq_nr(link_seq_nr);
642                 if (hci_transport_link_have_outgoing_packet() && (next_seq_nr == ack_nr)){
643                     log_debug("outoing packet with seq %u ack'ed", link_seq_nr);
644                     link_seq_nr = next_seq_nr;
645                     hci_transport_link_clear_queue();
646 
647                     // notify upper stack that it can send again
648                     uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0};
649                     packet_handler(HCI_EVENT_PACKET, &event[0], sizeof(event));
650                 }
651             }
652 
653             switch (link_packet_type){
654                 case LINK_CONTROL_PACKET_TYPE:
655                     if (memcmp(slip_payload, link_control_config, sizeof(link_control_config)) == 0){
656                         if (link_payload_len == link_control_config_prefix_len){
657                             log_debug("link received config, no config field");
658                             hci_transport_link_actions |= HCI_TRANSPORT_LINK_SEND_CONFIG_RESPONSE_EMPTY;
659                         } else {
660                             log_debug("link received config, 0x%02x", slip_payload[2]);
661                             hci_transport_link_actions |= HCI_TRANSPORT_LINK_SEND_CONFIG_RESPONSE;
662                         }
663                         break;
664                     }
665                     if (memcmp(slip_payload, link_control_sync, sizeof(link_control_sync)) == 0){
666                         log_debug("link received sync in ACTIVE STATE!");
667                         // TODO sync during active indicates peer reset -> full upper layer reset necessary
668                         break;
669                     }
670                     if (memcmp(slip_payload, link_control_sleep, sizeof(link_control_sleep)) == 0){
671                         if (btstack_uart_sleep_mode){
672                             log_info("link: received sleep message. Enabling UART Sleep.");
673                             btstack_uart->set_sleep(btstack_uart_sleep_mode);
674                             hci_transport_h5_emit_sleep_state(1);
675                         } else {
676                             log_info("link: received sleep message. UART Sleep not supported");
677                         }
678                         link_peer_asleep = 1;
679                         break;
680                     }
681                     if (memcmp(slip_payload, link_control_wakeup, sizeof(link_control_wakeup)) == 0){
682                         log_info("link: received wakupe message -> send woken");
683                         link_peer_asleep = 0;
684                         hci_transport_link_actions |= HCI_TRANSPORT_LINK_SEND_WOKEN;
685                         break;
686                     }
687                     if (memcmp(slip_payload, link_control_woken, sizeof(link_control_woken)) == 0){
688                         log_info("link: received woken message");
689                         link_peer_asleep = 0;
690                         // queued packet will be sent in hci_transport_link_run if needed
691                         break;
692                     }
693                     break;
694                 case HCI_EVENT_PACKET:
695                 case HCI_ACL_DATA_PACKET:
696                 case HCI_SCO_DATA_PACKET:
697                     // seems like peer is awake
698                     link_peer_asleep = 0;
699                     // forward packet to stack
700                     packet_handler(link_packet_type, slip_payload, link_payload_len);
701                     // reset inactvitiy timer
702                     hci_transport_inactivity_timer_set();
703                     break;
704             }
705 
706             break;
707         default:
708             break;
709     }
710 
711     hci_transport_link_run();
712 }
713 
714 // recommendet time until resend: 3 * time of largest packet
715 static uint16_t hci_transport_link_calc_resend_timeout(uint32_t baudrate){
716     uint32_t max_packet_size_in_bit = (HCI_INCOMING_PACKET_BUFFER_SIZE + 6) << 3;
717     uint32_t t_max_x3_ms = max_packet_size_in_bit * 3000 / baudrate;
718 
719     // allow for BTstack logging and other delays
720     t_max_x3_ms += 50;
721 
722     log_info("resend timeout for %"PRIu32" baud: %u ms", baudrate, (int) t_max_x3_ms);
723     return t_max_x3_ms;
724 }
725 
726 static void hci_transport_link_update_resend_timeout(uint32_t baudrate){
727     link_resend_timeout_ms = hci_transport_link_calc_resend_timeout(baudrate);
728 }
729 
730 /// H5 Interface
731 
732 static uint8_t hci_transport_link_read_byte;
733 static int hci_transport_h5_active;
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     if (hci_transport_h5_active == 0) return;
743 
744     // track start time when receiving first byte // a bit hackish
745     if ((hci_transport_h5_receive_start == 0) && (hci_transport_link_read_byte != BTSTACK_SLIP_SOF)){
746         hci_transport_h5_receive_start = btstack_run_loop_get_time_ms();
747     }
748     btstack_slip_decoder_process(hci_transport_link_read_byte);
749     uint16_t frame_size = btstack_slip_decoder_frame_size();
750     if (frame_size) {
751         // track time
752         uint32_t packet_receive_time = btstack_run_loop_get_time_ms() - hci_transport_h5_receive_start;
753         uint32_t nominmal_time = (frame_size + 6) * 10 * 1000 / uart_config.baudrate;
754         log_info("slip frame time %u ms for %u decoded bytes. nomimal time %u ms", (int) packet_receive_time, frame_size, (int) nominmal_time);
755         // reset state
756         hci_transport_h5_receive_start = 0;
757         //
758         hci_transport_h5_process_frame(frame_size);
759         hci_transport_slip_init();
760     }
761     hci_transport_h5_read_next_byte();
762 }
763 
764 static void hci_transport_h5_block_sent(void){
765     if (hci_transport_h5_active == 0) return;
766 
767     // check if more data to send
768     if (btstack_slip_encoder_has_data()){
769         hci_transport_slip_send_next_chunk();
770         return;
771     }
772 
773     // done
774     slip_write_active = 0;
775 
776     // enter sleep mode after sending sleep message
777     if (hci_transport_link_actions & HCI_TRANSPORT_LINK_ENTER_SLEEP){
778         hci_transport_link_actions &= ~HCI_TRANSPORT_LINK_ENTER_SLEEP;
779         if (btstack_uart_sleep_mode){
780             log_info("link: sent sleep message. Enabling UART Sleep.");
781             btstack_uart->set_sleep(btstack_uart_sleep_mode);
782         } else {
783             log_info("link: sent sleep message. UART Sleep not supported");
784         }
785         hci_transport_h5_emit_sleep_state(1);
786     }
787 
788     hci_transport_link_run();
789 }
790 
791 static void hci_transport_h5_init(const void * transport_config){
792     // check for hci_transport_config_uart_t
793     if (!transport_config) {
794         log_error("hci_transport_h5: no config!");
795         return;
796     }
797     if (((hci_transport_config_t*)transport_config)->type != HCI_TRANSPORT_CONFIG_UART) {
798         log_error("hci_transport_h5: config not of type != HCI_TRANSPORT_CONFIG_UART!");
799         return;
800     }
801 
802     hci_transport_h5_active = 0;
803 
804     // extract UART config from transport config
805     hci_transport_config_uart_t * hci_transport_config_uart = (hci_transport_config_uart_t*) transport_config;
806     uart_config.baudrate    = hci_transport_config_uart->baudrate_init;
807     uart_config.flowcontrol = hci_transport_config_uart->flowcontrol;
808     uart_config.device_name = hci_transport_config_uart->device_name;
809 
810     // setup UART driver
811     btstack_uart->init(&uart_config);
812     btstack_uart->set_block_received(&hci_transport_h5_block_received);
813     btstack_uart->set_block_sent(&hci_transport_h5_block_sent);
814 }
815 
816 static int hci_transport_h5_open(void){
817     int res = btstack_uart->open();
818     if (res){
819         return res;
820     }
821 
822     //
823     if (hci_transport_bcsp_mode){
824         log_info("enable even parity for BCSP mode");
825         btstack_uart->set_parity(1);
826     }
827 
828     // check if wake on RX can be used
829     btstack_uart_sleep_mode = BTSTACK_UART_SLEEP_OFF;
830     int supported_sleep_modes = 0;
831     if (btstack_uart->get_supported_sleep_modes){
832         supported_sleep_modes = btstack_uart->get_supported_sleep_modes();
833     }
834     if (supported_sleep_modes & BTSTACK_UART_SLEEP_MASK_RTS_LOW_WAKE_ON_RX_EDGE){
835         log_info("using wake on RX");
836         btstack_uart_sleep_mode = BTSTACK_UART_SLEEP_RTS_LOW_WAKE_ON_RX_EDGE;
837     } else {
838         log_info("UART driver does not provide compatible sleep mode");
839     }
840 
841     // setup resend timeout
842     hci_transport_link_update_resend_timeout(uart_config.baudrate);
843 
844     // init slip parser state machine
845     hci_transport_slip_init();
846 
847     // init link management - already starts syncing
848     hci_transport_link_init();
849 
850     // start receiving
851     hci_transport_h5_active = 1;
852     hci_transport_h5_read_next_byte();
853 
854     return 0;
855 }
856 
857 static int hci_transport_h5_close(void){
858     hci_transport_h5_active = 0;
859     return btstack_uart->close();
860 }
861 
862 static void hci_transport_h5_register_packet_handler(void (*handler)(uint8_t packet_type, uint8_t *packet, uint16_t size)){
863     packet_handler = handler;
864 }
865 
866 static int hci_transport_h5_can_send_packet_now(uint8_t packet_type){
867     int res = !hci_transport_link_have_outgoing_packet() && (link_state == LINK_ACTIVE);
868     // log_info("can_send_packet_now: %u", res);
869     return res;
870 }
871 
872 static int hci_transport_h5_send_packet(uint8_t packet_type, uint8_t *packet, int size){
873     if (!hci_transport_h5_can_send_packet_now(packet_type)){
874         log_error("hci_transport_h5_send_packet called but in state %d", link_state);
875         return -1;
876     }
877 
878     // store request
879     hci_transport_h5_queue_packet(packet_type, packet, size);
880 
881     // send wakeup first
882     if (link_peer_asleep){
883         hci_transport_h5_emit_sleep_state(0);
884         if (btstack_uart_sleep_mode){
885             log_info("disable UART sleep");
886             btstack_uart->set_sleep(BTSTACK_UART_SLEEP_OFF);
887         }
888         hci_transport_link_actions |= HCI_TRANSPORT_LINK_SEND_WAKEUP;
889         hci_transport_link_set_timer(LINK_WAKEUP_MS);
890     } else {
891         hci_transport_link_actions |= HCI_TRANSPORT_LINK_SEND_QUEUED_PACKET;
892         hci_transport_link_set_timer(link_resend_timeout_ms);
893     }
894     hci_transport_link_run();
895     return 0;
896 }
897 
898 static int hci_transport_h5_set_baudrate(uint32_t baudrate){
899 
900     log_info("set_baudrate %"PRIu32, baudrate);
901     int res = btstack_uart->set_baudrate(baudrate);
902 
903     if (res) return res;
904     uart_config.baudrate = baudrate;
905     hci_transport_link_update_resend_timeout(baudrate);
906     return 0;
907 }
908 
909 static void hci_transport_h5_reset_link(void){
910 
911     log_info("reset_link");
912 
913     // clear outgoing queue
914     hci_transport_link_clear_queue();
915 
916     // init slip parser state machine
917     hci_transport_slip_init();
918 
919     // init link management - already starts syncing
920     hci_transport_link_init();
921 }
922 
923 static const hci_transport_t hci_transport_h5 = {
924     /* const char * name; */                                        "H5",
925     /* void   (*init) (const void *transport_config); */            &hci_transport_h5_init,
926     /* int    (*open)(void); */                                     &hci_transport_h5_open,
927     /* int    (*close)(void); */                                    &hci_transport_h5_close,
928     /* void   (*register_packet_handler)(void (*handler)(...); */   &hci_transport_h5_register_packet_handler,
929     /* int    (*can_send_packet_now)(uint8_t packet_type); */       &hci_transport_h5_can_send_packet_now,
930     /* int    (*send_packet)(...); */                               &hci_transport_h5_send_packet,
931     /* int    (*set_baudrate)(uint32_t baudrate); */                &hci_transport_h5_set_baudrate,
932     /* void   (*reset_link)(void); */                               &hci_transport_h5_reset_link,
933     /* void   (*set_sco_config)(uint16_t voice_setting, int num_connections); */ NULL,
934 };
935 
936 // configure and return h5 singleton
937 const hci_transport_t * hci_transport_h5_instance(const btstack_uart_block_t * uart_driver) {
938     btstack_uart = uart_driver;
939     return &hci_transport_h5;
940 }
941 
942 void hci_transport_h5_set_auto_sleep(uint16_t inactivity_timeout_ms){
943     link_inactivity_timeout_ms = inactivity_timeout_ms;
944 }
945 
946 void hci_transport_h5_enable_bcsp_mode(void){
947     hci_transport_bcsp_mode = 1;
948 }
949