xref: /btstack/port/raspi/main.c (revision 80e33422a96c028b3a9c308fc4b9b874712dafb4)
1 /*
2  * Copyright (C) 2014 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__ "main.c"
39 
40 // *****************************************************************************
41 //
42 //   Port for Rasperry Pi with built-in BCM chipset via H4 or H5
43 //
44 // *****************************************************************************
45 
46 #include <errno.h>
47 #include <fcntl.h>
48 #include <inttypes.h>
49 #include <signal.h>
50 #include <stdint.h>
51 #include <stdio.h>
52 #include <stdlib.h>
53 #include <string.h>
54 #include <sys/stat.h>
55 #include <termios.h>
56 #include <unistd.h>
57 
58 #include "btstack_config.h"
59 
60 #include "btstack_debug.h"
61 #include "btstack_event.h"
62 #include "btstack_link_key_db_fs.h"
63 #include "btstack_memory.h"
64 #include "btstack_run_loop.h"
65 #include "btstack_run_loop_posix.h"
66 #include "bluetooth_company_id.h"
67 #include "hci.h"
68 #include "hci_dump.h"
69 #include "btstack_stdin.h"
70 #include "btstack_tlv_posix.h"
71 
72 #include "btstack_chipset_bcm.h"
73 #include "btstack_chipset_bcm_download_firmware.h"
74 #include "btstack_control_raspi.h"
75 
76 #include "raspi_get_model.h"
77 
78 int btstack_main(int argc, const char * argv[]);
79 
80 typedef enum  {
81     UART_INVALID,
82     UART_SOFTWARE_NO_FLOW,
83     UART_HARDWARE_NO_FLOW,
84     UART_HARDWARE_FLOW
85 } uart_type_t;
86 
87 // default config, updated depending on RasperryPi UART configuration
88 static hci_transport_config_uart_t transport_config = {
89     HCI_TRANSPORT_CONFIG_UART,
90     115200,
91     0,       // main baudrate
92     0,       // flow control
93     NULL,
94 };
95 
96 static btstack_uart_config_t uart_config;
97 
98 static int main_argc;
99 static const char ** main_argv;
100 
101 static btstack_packet_callback_registration_t hci_event_callback_registration;
102 
103 #define TLV_DB_PATH_PREFIX "/tmp/btstack_"
104 #define TLV_DB_PATH_POSTFIX ".tlv"
105 static char tlv_db_path[100];
106 static const btstack_tlv_t * tlv_impl;
107 static btstack_tlv_posix_t   tlv_context;
108 
109 
110 static int raspi_speed_to_baud(speed_t baud)
111 {
112     switch (baud) {
113         case B9600:
114             return 9600;
115         case B19200:
116             return 19200;
117         case B38400:
118             return 38400;
119         case B57600:
120             return 57600;
121         case B115200:
122             return 115200;
123         case B230400:
124             return 230400;
125         case B460800:
126             return 460800;
127         case B500000:
128             return 500000;
129         case B576000:
130             return 576000;
131         case B921600:
132             return 921600;
133         case B1000000:
134             return 1000000;
135         case B1152000:
136             return 1152000;
137         case B1500000:
138             return 1500000;
139         case B2000000:
140             return 2000000;
141         case B2500000:
142             return 2500000;
143         case B3000000:
144             return 3000000;
145         case B3500000:
146             return 3500000;
147         case B4000000:
148             return 4000000;
149         default:
150             return -1;
151     }
152 }
153 
154 static void raspi_get_terminal_params( hci_transport_config_uart_t *tc )
155 {
156     // open serial terminal and get parameters
157     int fd = open( tc->device_name, O_RDONLY );
158     if( fd < 0 )
159     {
160         perror( "can't open serial port" );
161         return;
162     }
163     struct termios tios;
164     tcgetattr( fd, &tios );
165     close( fd );
166 
167     speed_t ospeed = cfgetospeed( &tios );
168     int baud = raspi_speed_to_baud( ospeed );
169     printf( "current serial terminal parameter baudrate: %d, flow control: %s\n", baud, (tios.c_cflag&CRTSCTS)?"Hardware":"None" );
170 
171     // overwrites the initial baudrate only in case it was likely to be altered before
172     if( baud > 9600 )
173     {
174         tc->baudrate_init = baud;
175         tc->flowcontrol = (tios.c_cflag & CRTSCTS)?1:0;
176     }
177 }
178 
179 static void sigint_handler(int param){
180     UNUSED(param);
181 
182     printf("CTRL-C - SIGINT received, shutting down..\n");
183     log_info("sigint_handler: shutting down");
184 
185     // reset anyway
186     btstack_stdin_reset();
187 
188     // power down
189     hci_power_control(HCI_POWER_OFF);
190     hci_close();
191     log_info("Good bye, see you.\n");
192     exit(0);
193 }
194 
195 static int led_state = 0;
196 void hal_led_toggle(void){
197     led_state = 1 - led_state;
198     printf("LED State %u\n", led_state);
199 }
200 
201 static void packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
202     bd_addr_t addr;
203     if (packet_type != HCI_EVENT_PACKET) return;
204     switch (hci_event_packet_get_type(packet)){
205         case BTSTACK_EVENT_STATE:
206             if (btstack_event_state_get_state(packet) != HCI_STATE_WORKING) break;
207             gap_local_bd_addr(addr);
208             printf("BTstack up and running at %s\n",  bd_addr_to_str(addr));
209             // setup TLV
210             strcpy(tlv_db_path, TLV_DB_PATH_PREFIX);
211             strcat(tlv_db_path, bd_addr_to_str(addr));
212             strcat(tlv_db_path, TLV_DB_PATH_POSTFIX);
213             tlv_impl = btstack_tlv_posix_init_instance(&tlv_context, tlv_db_path);
214             btstack_tlv_set_instance(tlv_impl, &tlv_context);
215             break;
216         case HCI_EVENT_COMMAND_COMPLETE:
217             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_name)){
218                 if (hci_event_command_complete_get_return_parameters(packet)[0]) break;
219                 // terminate, name 248 chars
220                 packet[6+248] = 0;
221                 printf("Local name: %s\n", &packet[6]);
222 
223                 btstack_chipset_bcm_set_device_name((const char *)&packet[6]);
224             }
225             break;
226         default:
227             break;
228     }
229 }
230 
231 // see https://github.com/RPi-Distro/pi-bluetooth/blob/master/usr/bin/btuart
232 static int raspi_get_bd_addr(bd_addr_t addr){
233 
234     FILE *fd = fopen( "/proc/device-tree/serial-number", "r" );
235     if( fd == NULL ){
236         fprintf(stderr, "can't read serial number, %s\n", strerror( errno ) );
237         return -1;
238     }
239     fscanf( fd, "%*08x" "%*02x" "%02" SCNx8 "%02" SCNx8 "%02" SCNx8, &addr[3], &addr[4], &addr[5] );
240     fclose( fd );
241 
242     addr[0] =  0xb8; addr[1]  = 0x27; addr[2] =  0xeb;
243     addr[3] ^= 0xaa; addr[4] ^= 0xaa; addr[5] ^= 0xaa;
244 
245     return 0;
246 }
247 
248 // see https://github.com/RPi-Distro/pi-bluetooth/blob/master/usr/bin/btuart
249 // on UART_INVALID errno is set
250 static uart_type_t raspi_get_bluetooth_uart_type(void){
251 
252     uint8_t deviceUart0[21] = { 0 };
253     FILE *fd = fopen( "/proc/device-tree/aliases/uart0", "r" );
254     if( fd == NULL ) return UART_INVALID;
255     fscanf( fd, "%20s", deviceUart0 );
256     fclose( fd );
257 
258     uint8_t deviceSerial1[21] = { 0 };
259     fd = fopen( "/proc/device-tree/aliases/serial1", "r" );
260     if( fd == NULL ) return UART_INVALID;
261     fscanf( fd, "%20s", deviceSerial1 );
262     fclose( fd );
263 
264     // test if uart0 is an alias for serial1
265     if( strncmp( (const char *) deviceUart0, (const char *) deviceSerial1, 21 ) == 0 ){
266         // HW uart
267         size_t count = 0;
268         uint8_t buf[16];
269         fd = fopen( "/proc/device-tree/soc/gpio@7e200000/uart0_pins/brcm,pins", "r" );
270         if( fd == NULL ) return UART_INVALID;
271         count = fread( buf, 1, 16, fd );
272         fclose( fd );
273 
274         // contains assigned pins
275         int pins = count / 4;
276         if( pins == 4 ){
277             return UART_HARDWARE_FLOW;
278         } else {
279             return UART_HARDWARE_NO_FLOW;
280         }
281     } else {
282         return UART_SOFTWARE_NO_FLOW;
283     }
284 }
285 
286 static void phase2(int status);
287 int main(int argc, const char * argv[]){
288 
289     /// GET STARTED with BTstack ///
290     btstack_memory_init();
291 
292     // use logger: format HCI_DUMP_PACKETLOGGER, HCI_DUMP_BLUEZ or HCI_DUMP_STDOUT
293     const char * pklg_path = "/tmp/hci_dump.pklg";
294     hci_dump_open(pklg_path, HCI_DUMP_PACKETLOGGER);
295     printf("Packet Log: %s\n", pklg_path);
296 
297     // setup run loop
298     btstack_run_loop_init(btstack_run_loop_posix_get_instance());
299 
300     // pick serial port and configure uart block driver
301     transport_config.device_name = "/dev/serial1";
302 
303     // derive bd_addr from serial number
304     bd_addr_t addr = { 0x11, 0x22, 0x33, 0x44, 0x55, 0x66 };
305     raspi_get_bd_addr(addr);
306 
307     // set UART config based on raspi Bluetooth UART type
308     int bt_reg_en_pin = -1;
309     switch (raspi_get_bluetooth_uart_type()){
310         case UART_INVALID:
311             fprintf(stderr, "can't verify HW uart, %s\n", strerror( errno ) );
312             return -1;
313         case UART_SOFTWARE_NO_FLOW:
314             // ??
315             bt_reg_en_pin = 128;
316             transport_config.baudrate_main = 460800;
317             transport_config.flowcontrol   = 0;
318             break;
319         case UART_HARDWARE_NO_FLOW:
320             // Raspberry Pi 3 A
321             // Raspberry Pi 3 B
322             bt_reg_en_pin = 128;
323             transport_config.baudrate_main = 921600;
324             transport_config.flowcontrol   = 0;
325             break;
326         case UART_HARDWARE_FLOW:
327             // Raspberry Pi Zero W gpio 45
328             // Raspberry Pi 3A+ vgpio 129 but WLAN + BL
329             // Raspberry Pi 3B+ vgpio 129 but WLAN + BL
330             transport_config.baudrate_main = 3000000;
331             transport_config.flowcontrol = 1;
332 
333             // 3 mbps does not work on Zero W (investigation pending)
334             if (raspi_get_model() == MODEL_ZERO_W){
335                 transport_config.baudrate_main = 921600;
336             }
337             break;
338     }
339     printf("%s, %u, BT_REG_EN at GPIO %u\n", transport_config.flowcontrol ? "H4":"H5", transport_config.baudrate_main, bt_reg_en_pin);
340 
341     // get BCM chipset driver
342     const btstack_chipset_t * chipset = btstack_chipset_bcm_instance();
343     chipset->init(&transport_config);
344 
345     // set path to firmware files
346     btstack_chipset_bcm_set_hcd_folder_path("/lib/firmware/brcm");
347 
348     // setup UART driver
349     const btstack_uart_block_t * uart_driver = btstack_uart_block_posix_instance();
350 
351     // extract UART config from transport config
352     uart_config.baudrate    = transport_config.baudrate_init;
353     uart_config.flowcontrol = transport_config.flowcontrol;
354     uart_config.device_name = transport_config.device_name;
355     uart_driver->init(&uart_config);
356 
357     // HW with FlowControl -> we can use regular h4 mode
358     const hci_transport_t * transport;
359     if (transport_config.flowcontrol){
360         transport = hci_transport_h4_instance(uart_driver);
361     } else {
362         transport = hci_transport_h5_instance(uart_driver);
363     }
364 
365     // setup HCI (to be able to use bcm chipset driver)
366     const btstack_link_key_db_t * link_key_db = btstack_link_key_db_fs_instance();
367     hci_init(transport, (void*) &transport_config);
368     hci_set_bd_addr( addr );
369     hci_set_chipset(btstack_chipset_bcm_instance());
370     hci_set_link_key_db(link_key_db);
371 
372     // inform about BTstack state
373     hci_event_callback_registration.callback = &packet_handler;
374     hci_add_event_handler(&hci_event_callback_registration);
375 
376     // handle CTRL-c
377     signal(SIGINT, sigint_handler);
378 
379     main_argc = argc;
380     main_argv = argv;
381 
382     if (transport_config.flowcontrol){
383 
384         // re-use current terminal speed
385         raspi_get_terminal_params( &transport_config );
386 
387         // with flowcontrol, we use h4 and are done
388         btstack_main(main_argc, main_argv);
389 
390     } else {
391 
392         // power cycle Bluetooth controller on older models without flowcontrol
393         printf("Power Cycle Controller\n");
394         btstack_control_raspi_set_bt_reg_en_pin(bt_reg_en_pin);
395         btstack_control_t *control = btstack_control_raspi_get_instance();
396         control->init(NULL);
397         control->off();
398         usleep( 100000 );
399         control->on();
400 
401         // assume BCM4343W used in Pi 3 A/B. Pi 3 A/B+ have a newer controller but support H4 with Flowcontrol
402         btstack_chipset_bcm_set_device_name("BCM43430A1");
403 
404         // phase #1 download firmware
405         printf("Phase 1: Download firmware\n");
406 
407         // phase #2 start main app
408         btstack_chipset_bcm_download_firmware(uart_driver, transport_config.baudrate_main, &phase2);
409     }
410 
411     // go
412     btstack_run_loop_execute();
413     return 0;
414 }
415 
416 static void phase2(int status){
417 
418     if (status){
419         printf("Download firmware failed\n");
420         return;
421     }
422 
423     printf("Phase 2: Main app\n");
424 
425     // setup app
426     btstack_main(main_argc, main_argv);
427 }
428 
429