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