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