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