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