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