xref: /btstack/src/hci_transport_h4.c (revision 9cfcc54d6f7959d68fb9446a04a16f849c54507a)
1 /*
2  * Copyright (C) 2009 by Matthias Ringwald
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  *
17  * THIS SOFTWARE IS PROVIDED BY MATTHIAS RINGWALD AND CONTRIBUTORS
18  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
20  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTHIAS
21  * RINGWALD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
22  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
23  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
24  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
25  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
26  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
27  * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28  * SUCH DAMAGE.
29  *
30  */
31 
32 /*
33  *  hci_h4_transport.c
34  *
35  *  HCI Transport API implementation for basic H4 protocol
36  *
37  *  Created by Matthias Ringwald on 4/29/09.
38  */
39 #include <termios.h>  /* POSIX terminal control definitions */
40 #include <fcntl.h>    /* File control definitions */
41 #include <unistd.h>   /* UNIX standard function definitions */
42 #include <stdio.h>
43 #include <string.h>
44 #include <pthread.h>
45 
46 #include "debug.h"
47 #include "hci.h"
48 #include "hci_transport.h"
49 #include "hci_dump.h"
50 
51 // #define USE_HCI_READER_THREAD
52 
53 typedef enum {
54     H4_W4_PACKET_TYPE,
55     H4_W4_EVENT_HEADER,
56     H4_W4_ACL_HEADER,
57     H4_W4_PAYLOAD,
58     H4_W4_PICKUP
59 } H4_STATE;
60 
61 typedef struct hci_transport_h4 {
62     hci_transport_t transport;
63     data_source_t *ds;
64     int uart_fd;    // different from ds->fd for HCI reader thread
65 
66 #ifdef USE_HCI_READER_THREAD
67     // synchronization facilities for dedicated reader thread
68     int pipe_fds[2];
69     pthread_mutex_t mutex;
70     pthread_cond_t cond;
71 #endif
72 } hci_transport_h4_t;
73 
74 // single instance
75 static hci_transport_h4_t * hci_transport_h4 = NULL;
76 
77 static int  h4_process(struct data_source *ds);
78 static void *h4_reader(void *context);
79 static int  h4_reader_process(struct data_source *ds);
80 static void dummy_handler(uint8_t packet_type, uint8_t *packet, uint16_t size);
81 static      hci_uart_config_t *hci_uart_config;
82 
83 static  void (*packet_handler)(uint8_t packet_type, uint8_t *packet, uint16_t size) = dummy_handler;
84 
85 // packet reader state machine
86 static  H4_STATE h4_state;
87 static int bytes_to_read;
88 static int read_pos;
89 // static uint8_t hci_event_buffer[255+2]; // maximal payload + 2 bytes header
90 static uint8_t hci_packet[1+HCI_ACL_3DH5_SIZE]; // bigger than largest packet
91 
92 
93 // prototypes
94 static int    h4_open(void *transport_config){
95     hci_uart_config = (hci_uart_config_t*) transport_config;
96     struct termios toptions;
97     int flags = O_RDWR | O_NOCTTY;
98 #ifndef USE_HCI_READER_THREAD
99     flags |= O_NONBLOCK;
100 #endif
101     int fd = open(hci_uart_config->device_name, flags);
102     if (fd == -1)  {
103         perror("init_serialport: Unable to open port ");
104         perror(hci_uart_config->device_name);
105         return -1;
106     }
107 
108     if (tcgetattr(fd, &toptions) < 0) {
109         perror("init_serialport: Couldn't get term attributes");
110         return -1;
111     }
112     speed_t brate = hci_uart_config->baudrate; // let you override switch below if needed
113     switch(hci_uart_config->baudrate) {
114         case 57600:  brate=B57600;  break;
115         case 115200: brate=B115200; break;
116 #ifdef B230400
117         case 230400: brate=B230400; break;
118 #endif
119 #ifdef B460800
120         case 460800: brate=B460800; break;
121 #endif
122 #ifdef B921600
123         case 921600: brate=B921600; break;
124 #endif
125     }
126     cfsetispeed(&toptions, brate);
127     cfsetospeed(&toptions, brate);
128 
129     // 8N1
130     toptions.c_cflag &= ~PARENB;
131     toptions.c_cflag &= ~CSTOPB;
132     toptions.c_cflag &= ~CSIZE;
133     toptions.c_cflag |= CS8;
134 
135     if (hci_uart_config->flowcontrol) {
136         // with flow control
137         toptions.c_cflag |= CRTSCTS;
138     } else {
139         // no flow control
140         toptions.c_cflag &= ~CRTSCTS;
141     }
142 
143     toptions.c_cflag |= CREAD | CLOCAL;  // turn on READ & ignore ctrl lines
144     toptions.c_iflag &= ~(IXON | IXOFF | IXANY); // turn off s/w flow ctrl
145 
146     toptions.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); // make raw
147     toptions.c_oflag &= ~OPOST; // make raw
148 
149     // see: http://unixwiz.net/techtips/termios-vmin-vtime.html
150     toptions.c_cc[VMIN]  = 1;
151     toptions.c_cc[VTIME] = 0;
152 
153     if( tcsetattr(fd, TCSANOW, &toptions) < 0) {
154         perror("init_serialport: Couldn't set term attributes");
155         return -1;
156     }
157 
158     // set up data_source
159     hci_transport_h4->ds = malloc(sizeof(data_source_t));
160     if (!hci_transport_h4->ds) return -1;
161     hci_transport_h4->uart_fd = fd;
162 
163 #ifdef USE_HCI_READER_THREAD
164     // init synchronization tools
165     pthread_mutex_init(&hci_transport_h4->mutex, NULL);
166     pthread_cond_init(&hci_transport_h4->cond, NULL);
167 
168 	// create pipe
169 	pipe(hci_transport_h4->pipe_fds);
170 
171 	// create reader thread
172 	pthread_t hci_reader_thread;
173 	pthread_create(&hci_reader_thread, NULL, &h4_reader, NULL);
174 
175     hci_transport_h4->ds->fd = hci_transport_h4->pipe_fds[0];
176     hci_transport_h4->ds->process = h4_reader_process;
177 #else
178     hci_transport_h4->ds->fd = fd;
179     hci_transport_h4->ds->process = h4_process;
180 #endif
181     run_loop_add_data_source(hci_transport_h4->ds);
182 
183     // init state machine
184     bytes_to_read = 1;
185     h4_state = H4_W4_PACKET_TYPE;
186     read_pos = 0;
187 
188     return 0;
189 }
190 
191 static int    h4_close(){
192     // first remove run loop handler
193 	run_loop_remove_data_source(hci_transport_h4->ds);
194 
195     // close device
196     close(hci_transport_h4->ds->fd);
197 
198     // free struct
199     free(hci_transport_h4->ds);
200     hci_transport_h4->ds = NULL;
201     return 0;
202 }
203 
204 static int h4_send_packet(uint8_t packet_type, uint8_t * packet, int size){
205     if (hci_transport_h4->ds == NULL) return -1;
206     if (hci_transport_h4->uart_fd == 0) return -1;
207     hci_dump_packet( (uint8_t) packet_type, 0, packet, size);
208     char *data = (char*) packet;
209     int bytes_written = write(hci_transport_h4->uart_fd, &packet_type, 1);
210     while (bytes_written < 1) {
211         usleep(5000);
212         bytes_written = write(hci_transport_h4->uart_fd, &packet_type, 1);
213     };
214     while (size > 0) {
215         int bytes_written = write(hci_transport_h4->uart_fd, data, size);
216         if (bytes_written < 0) {
217             usleep(5000);
218             continue;
219         }
220         data += bytes_written;
221         size -= bytes_written;
222     }
223     return 0;
224 }
225 
226 static void   h4_register_packet_handler(void (*handler)(uint8_t packet_type, uint8_t *packet, uint16_t size)){
227     packet_handler = handler;
228 }
229 
230 static void   h4_deliver_packet(){
231     if (read_pos < 3) return; // sanity check
232     hci_dump_packet( hci_packet[0], 1, &hci_packet[1], read_pos-1);
233     packet_handler(hci_packet[0], &hci_packet[1], read_pos-1);
234 
235     h4_state = H4_W4_PACKET_TYPE;
236     read_pos = 0;
237     bytes_to_read = 1;
238 }
239 
240 static void h4_statemachine(){
241     switch (h4_state) {
242 
243         case H4_W4_PACKET_TYPE:
244             if (hci_packet[0] == HCI_EVENT_PACKET){
245                 bytes_to_read = HCI_EVENT_PKT_HDR;
246                 h4_state = H4_W4_EVENT_HEADER;
247             } else if (hci_packet[0] == HCI_ACL_DATA_PACKET){
248                 bytes_to_read = HCI_ACL_DATA_PKT_HDR;
249                 h4_state = H4_W4_ACL_HEADER;
250             } else {
251                 log_err("h4_process: invalid packet type 0x%02x\n", hci_packet[0]);
252                 read_pos = 0;
253                 bytes_to_read = 1;
254             }
255             break;
256 
257         case H4_W4_EVENT_HEADER:
258             bytes_to_read = hci_packet[2];
259             h4_state = H4_W4_PAYLOAD;
260             break;
261 
262         case H4_W4_ACL_HEADER:
263             bytes_to_read = READ_BT_16( hci_packet, 3);
264             h4_state = H4_W4_PAYLOAD;
265             break;
266 
267         case H4_W4_PAYLOAD:
268 #ifdef USE_HCI_READER_THREAD
269             h4_state = H4_W4_PICKUP;
270 #else
271             h4_deliver_packet();
272 #endif
273             break;
274     }
275 }
276 
277 static int    h4_process(struct data_source *ds) {
278     if (hci_transport_h4->uart_fd == 0) return -1;
279 
280     int read_now = bytes_to_read;
281     //    if (read_now > 100) {
282     //        read_now = 100;
283     //    }
284 
285     // read up to bytes_to_read data in
286     ssize_t bytes_read = read(hci_transport_h4->uart_fd, &hci_packet[read_pos], read_now);
287     // printf("h4_process: bytes read %u\n", bytes_read);
288     if (bytes_read < 0) {
289         return bytes_read;
290     }
291 
292     // hexdump(&hci_packet[read_pos], bytes_read);
293 
294     bytes_to_read -= bytes_read;
295     read_pos      += bytes_read;
296     if (bytes_to_read > 0) {
297         return 0;
298     }
299 
300     h4_statemachine();
301     return 0;
302 }
303 
304 #ifdef USE_HCI_READER_THREAD
305 static int h4_reader_process(struct data_source *ds) {
306     // get token
307     char token;
308     int tokens_read = read(hci_transport_h4->pipe_fds[0], &token, 1);
309     if (tokens_read < 1) {
310         return 0;
311     }
312 
313     // hci_reader received complete packet, just pick it up
314     h4_deliver_packet();
315 
316     // un-block reader
317     pthread_mutex_lock(&hci_transport_h4->mutex);
318     pthread_cond_signal(&hci_transport_h4->cond);
319     pthread_mutex_unlock(&hci_transport_h4->mutex);
320     return 0;
321 }
322 
323 static void *h4_reader(void *context){
324 	while(1){
325         // read up to bytes_to_read data in
326         int bytes_read = read(hci_transport_h4->uart_fd, &hci_packet[read_pos], bytes_to_read);
327         // error
328         if (bytes_read < 0) {
329             h4_state = H4_W4_PACKET_TYPE;
330             read_pos = 0;
331             bytes_to_read = 1;
332             continue;
333         }
334 
335         bytes_to_read -= bytes_read;
336         read_pos      += bytes_read;
337 
338         if (bytes_to_read > 0) continue;
339 
340         h4_statemachine();
341 
342         if (h4_state != H4_W4_PICKUP) continue;
343 
344 		// notify main thread
345         char data = 'h';
346 		write(hci_transport_h4->pipe_fds[1], &data, 1);
347 
348 		// wait for response
349 		pthread_mutex_lock(&hci_transport_h4->mutex);
350 		pthread_cond_wait(&hci_transport_h4->cond,&hci_transport_h4->mutex);
351 		pthread_mutex_unlock(&hci_transport_h4->mutex);
352 	}
353 }
354 #endif
355 
356 static const char * h4_get_transport_name(){
357     return "H4";
358 }
359 
360 static void dummy_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
361 }
362 
363 // get h4 singleton
364 hci_transport_t * hci_transport_h4_instance() {
365     if (hci_transport_h4 == NULL) {
366         hci_transport_h4 = malloc( sizeof(hci_transport_h4_t));
367         hci_transport_h4->ds                                      = NULL;
368         hci_transport_h4->transport.open                          = h4_open;
369         hci_transport_h4->transport.close                         = h4_close;
370         hci_transport_h4->transport.send_packet                   = h4_send_packet;
371         hci_transport_h4->transport.register_packet_handler       = h4_register_packet_handler;
372         hci_transport_h4->transport.get_transport_name            = h4_get_transport_name;
373     }
374     return (hci_transport_t *) hci_transport_h4;
375 }
376