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