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