xref: /btstack/port/libusb/main.c (revision ce6f85e79d1d141c1b45dfa16b2671762457cbb4)
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 // minimal setup for HCI code
43 //
44 // *****************************************************************************
45 
46 #include <getopt.h>
47 #include <stdint.h>
48 #include <stdio.h>
49 #include <stdlib.h>
50 #include <string.h>
51 #include <signal.h>
52 #include <unistd.h>
53 #include <hci_dump_posix_stdout.h>
54 
55 #include "btstack_config.h"
56 
57 #include "ble/le_device_db_tlv.h"
58 #include "bluetooth_company_id.h"
59 #include "btstack_audio.h"
60 #include "btstack_chipset_realtek.h"
61 #include "btstack_chipset_zephyr.h"
62 #include "btstack_debug.h"
63 #include "btstack_event.h"
64 #include "btstack_memory.h"
65 #include "btstack_run_loop.h"
66 #include "btstack_run_loop_posix.h"
67 #include "btstack_signal.h"
68 #include "btstack_stdin.h"
69 #include "btstack_tlv_posix.h"
70 #include "classic/btstack_link_key_db_tlv.h"
71 #include "hal_led.h"
72 #include "hci.h"
73 #include "hci_dump.h"
74 #include "hci_dump_posix_fs.h"
75 #include "hci_transport.h"
76 #include "hci_transport_usb.h"
77 
78 #define TLV_DB_PATH_PREFIX "/tmp/btstack_"
79 #define TLV_DB_PATH_POSTFIX ".tlv"
80 static char tlv_db_path[100];
81 static bool tlv_reset;
82 static const btstack_tlv_t * tlv_impl;
83 static btstack_tlv_posix_t   tlv_context;
84 static bd_addr_t             local_addr;
85 
86 int btstack_main(int argc, const char * argv[]);
87 
88 static const uint8_t read_static_address_command_complete_prefix[] = { 0x0e, 0x1b, 0x01, 0x09, 0xfc };
89 
90 static bd_addr_t static_address;
91 static int using_static_address;
92 
93 static btstack_packet_callback_registration_t hci_event_callback_registration;
94 
95 // shutdown
96 static bool shutdown_triggered;
97 
98 static void local_version_information_handler(uint8_t * packet){
99     printf("Local version information:\n");
100     uint16_t hci_version    = packet[6];
101     uint16_t hci_revision   = little_endian_read_16(packet, 7);
102     uint16_t lmp_version    = packet[9];
103     uint16_t manufacturer   = little_endian_read_16(packet, 10);
104     uint16_t lmp_subversion = little_endian_read_16(packet, 12);
105     printf("- HCI Version    0x%04x\n", hci_version);
106     printf("- HCI Revision   0x%04x\n", hci_revision);
107     printf("- LMP Version    0x%04x\n", lmp_version);
108     printf("- LMP Subversion 0x%04x\n", lmp_subversion);
109     printf("- Manufacturer   0x%04x\n", manufacturer);
110     switch (manufacturer){
111         case BLUETOOTH_COMPANY_ID_THE_LINUX_FOUNDATION:
112             printf("- Linux Foundation - assume Zephyr hci_usb firmware running on nRF52xx\n");
113             // setup Zephyr chipset support
114             hci_set_chipset(btstack_chipset_zephyr_instance());
115             // sm required to setup static random Bluetooth address
116             sm_init();
117             break;
118         case BLUETOOTH_COMPANY_ID_REALTEK_SEMICONDUCTOR_CORPORATION:
119             printf("- Realtek controller - provide firmware and config\n");
120             btstack_chipset_realtek_set_lmp_subversion(lmp_subversion);
121             hci_set_chipset(btstack_chipset_realtek_instance());
122             break;
123         default:
124             break;
125     }
126 }
127 
128 static void packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
129     UNUSED(channel);
130     UNUSED(size);
131     uint8_t i;
132     uint8_t usb_path_len;
133     const uint8_t * usb_path;
134     uint16_t product_id;
135 
136     if (packet_type != HCI_EVENT_PACKET) return;
137 
138     switch (hci_event_packet_get_type(packet)){
139         case HCI_EVENT_TRANSPORT_USB_INFO:
140             usb_path_len = hci_event_transport_usb_info_get_path_len(packet);
141             usb_path = hci_event_transport_usb_info_get_path(packet);
142             // print device path
143             product_id = hci_event_transport_usb_info_get_product_id(packet);
144             printf("USB device 0x%04x/0x%04x, path: ",
145                    hci_event_transport_usb_info_get_vendor_id(packet), product_id);
146             for (i=0;i<usb_path_len;i++){
147                 if (i) printf("-");
148                 printf("%02x", usb_path[i]);
149             }
150             printf("\n");
151             // set Product ID for Realtek Controllers
152             btstack_chipset_realtek_set_product_id(product_id);
153             break;
154         case BTSTACK_EVENT_STATE:
155             switch (btstack_event_state_get_state(packet)){
156                 case HCI_STATE_WORKING:
157                     gap_local_bd_addr(local_addr);
158                     if (using_static_address){
159                         memcpy(local_addr, static_address, 6);
160                     }
161                     btstack_strcpy(tlv_db_path, sizeof(tlv_db_path), TLV_DB_PATH_PREFIX);
162                     btstack_strcat(tlv_db_path, sizeof(tlv_db_path), bd_addr_to_str_with_delimiter(local_addr, '-'));
163                     btstack_strcat(tlv_db_path, sizeof(tlv_db_path), TLV_DB_PATH_POSTFIX);
164                     printf("TLV path: %s", tlv_db_path);
165                     if (tlv_reset){
166                         int rc = unlink(tlv_db_path);
167                         if (rc == 0) {
168                             printf(", reset ok");
169                         } else {
170                             printf(", reset failed with result = %d", rc);
171                         }
172                     }
173                     printf("\n");
174                     tlv_impl = btstack_tlv_posix_init_instance(&tlv_context, tlv_db_path);
175                     btstack_tlv_set_instance(tlv_impl, &tlv_context);
176 #ifdef ENABLE_CLASSIC
177                     hci_set_link_key_db(btstack_link_key_db_tlv_get_instance(tlv_impl, &tlv_context));
178 #endif
179 #ifdef ENABLE_BLE
180                     le_device_db_tlv_configure(tlv_impl, &tlv_context);
181 #endif
182                     printf("BTstack up and running on %s.\n", bd_addr_to_str(local_addr));
183                     break;
184                 case HCI_STATE_OFF:
185                     btstack_tlv_posix_deinit(&tlv_context);
186                     if (!shutdown_triggered) break;
187                     // reset stdin
188                     btstack_stdin_reset();
189                     log_info("Good bye, see you.\n");
190                     exit(0);
191                     break;
192                 default:
193                     break;
194             }
195             break;
196         case HCI_EVENT_COMMAND_COMPLETE:
197             if (hci_event_command_complete_get_command_opcode(packet) == HCI_OPCODE_HCI_READ_LOCAL_VERSION_INFORMATION){
198                 local_version_information_handler(packet);
199             }
200             if (memcmp(packet, read_static_address_command_complete_prefix, sizeof(read_static_address_command_complete_prefix)) == 0){
201                 reverse_48(&packet[7], static_address);
202                 gap_random_address_set(static_address);
203                 using_static_address = 1;
204             }
205             break;
206         default:
207             break;
208     }
209 }
210 
211 static void trigger_shutdown(void){
212     printf("CTRL-C - SIGINT received, shutting down..\n");
213     log_info("sigint_handler: shutting down");
214     shutdown_triggered = true;
215     hci_power_control(HCI_POWER_OFF);
216 }
217 
218 static int led_state = 0;
219 
220 void hal_led_toggle(void){
221     led_state = 1 - led_state;
222     printf("LED State %u\n", led_state);
223 }
224 
225 static char short_options[] = "hu:l:r";
226 
227 static struct option long_options[] = {
228     {"help",        no_argument,        NULL,   'h'},
229     {"logfile",    required_argument,  NULL,   'l'},
230     {"reset-tlv",    no_argument,       NULL,   'r'},
231     {"usbpath",    required_argument,  NULL,   'u'},
232     {0, 0, 0, 0}
233 };
234 
235 static char *help_options[] = {
236     "print (this) help.",
237     "set file to store debug output and HCI trace.",
238     "reset bonding information stored in TLV.",
239     "set USB path to Bluetooth Controller.",
240 };
241 
242 static char *option_arg_name[] = {
243     "",
244     "LOGFILE",
245     "",
246     "USBPATH",
247 };
248 
249 static void usage(const char *name){
250     unsigned int i;
251     printf( "usage:\n\t%s [options]\n", name );
252     printf("valid options:\n");
253     for( i=0; long_options[i].name != 0; i++) {
254         printf("--%-10s| -%c  %-10s\t\t%s\n", long_options[i].name, long_options[i].val, option_arg_name[i], help_options[i] );
255     }
256 }
257 
258 #define USB_MAX_PATH_LEN 7
259 int main(int argc, const char * argv[]){
260 
261     uint8_t usb_path[USB_MAX_PATH_LEN];
262     int usb_path_len = 0;
263     const char * usb_path_string = NULL;
264     const char * log_file_path = NULL;
265 
266     // parse command line parameters
267     while(true){
268         int c = getopt_long( argc, (char* const *)argv, short_options, long_options, NULL );
269         if (c < 0) {
270             break;
271         }
272         if (c == '?'){
273             break;
274         }
275         switch (c) {
276             case 'u':
277                 usb_path_string = optarg;
278                 break;
279             case 'l':
280                 log_file_path = optarg;
281                 break;
282             case 'r':
283                 tlv_reset = true;
284                 break;
285             case 'h':
286             default:
287                 usage(argv[0]);
288                 return EXIT_FAILURE;
289         }
290     }
291 
292     if (usb_path_string != NULL){
293         // parse command line options for "-u 11:22:33"
294         printf("Specified USB Path: ");
295         while (1){
296             char * delimiter;
297             int port = strtol(usb_path_string, &delimiter, 16);
298             usb_path[usb_path_len] = port;
299             usb_path_len++;
300             printf("%02x ", port);
301             if (!delimiter) break;
302             if (*delimiter != ':' && *delimiter != '-') break;
303             usb_path_string = delimiter+1;
304         }
305         printf("\n");
306     }
307 
308 	/// GET STARTED with BTstack ///
309 	btstack_memory_init();
310     btstack_run_loop_init(btstack_run_loop_posix_get_instance());
311 
312     if (usb_path_len){
313         hci_transport_usb_set_path(usb_path_len, usb_path);
314     }
315 
316     // log into file using HCI_DUMP_PACKETLOGGER format
317     char pklg_path[100];
318     if (log_file_path == NULL){
319         btstack_strcpy(pklg_path, sizeof(pklg_path),  "/tmp/hci_dump");
320         if (usb_path_len){
321             btstack_strcat(pklg_path, sizeof(pklg_path),  "_");
322             btstack_strcat(pklg_path, sizeof(pklg_path),  usb_path_string);
323         }
324         btstack_strcat(pklg_path, sizeof(pklg_path), ".pklg");
325         log_file_path = pklg_path;
326     }
327 
328     hci_dump_posix_fs_open(log_file_path, HCI_DUMP_PACKETLOGGER);
329     const hci_dump_t * hci_dump_impl = hci_dump_posix_fs_get_instance();
330     hci_dump_init(hci_dump_impl);
331     printf("Packet Log: %s\n", log_file_path);
332 
333     // init HCI
334 	hci_init(hci_transport_usb_instance(), NULL);
335 
336 #ifdef HAVE_PORTAUDIO
337     btstack_audio_sink_set_instance(btstack_audio_portaudio_sink_get_instance());
338     btstack_audio_source_set_instance(btstack_audio_portaudio_source_get_instance());
339 #endif
340 
341     // inform about BTstack state
342     hci_event_callback_registration.callback = &packet_handler;
343     hci_add_event_handler(&hci_event_callback_registration);
344 
345     // register callback for CTRL-c
346     btstack_signal_register_callback(SIGINT, &trigger_shutdown);
347 
348     // register known Realtek USB Controllers
349     uint16_t realtek_num_controllers = btstack_chipset_realtek_get_num_usb_controllers();
350     uint16_t i;
351     for (i=0;i<realtek_num_controllers;i++){
352         uint16_t vendor_id;
353         uint16_t product_id;
354         btstack_chipset_realtek_get_vendor_product_id(i, &vendor_id, &product_id);
355         hci_transport_usb_add_device(vendor_id, product_id);
356     }
357 
358     // setup app
359     btstack_main(argc, argv);
360 
361     // go
362     btstack_run_loop_execute();
363 
364     return 0;
365 }
366