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