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