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 #include <getopt.h>
46 #include <errno.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
54 #include "btstack_config.h"
55
56 #include "bluetooth_company_id.h"
57 #include "btstack_debug.h"
58 #include "btstack_event.h"
59 #include "ble/le_device_db_tlv.h"
60 #include "classic/btstack_link_key_db_tlv.h"
61 #include "btstack_memory.h"
62 #include "btstack_run_loop.h"
63 #include "btstack_run_loop_posix.h"
64 #include "hal_led.h"
65 #include "hci.h"
66 #include "hci_transport.h"
67 #include "hci_transport_usb.h"
68 #include "hci_dump.h"
69 #include "hci_dump_posix_fs.h"
70 #include "btstack_stdin.h"
71 #include "btstack_audio.h"
72 #include "btstack_tlv_posix.h"
73 #include "btstack_chipset_zephyr.h"
74
75 #define TLV_DB_PATH_PREFIX "/tmp/btstack_"
76 #define TLV_DB_PATH_POSTFIX ".tlv"
77 static char tlv_db_path[100];
78 static bool tlv_clear = false;
79 static const btstack_tlv_t * tlv_impl;
80 static btstack_tlv_posix_t tlv_context;
81 static bd_addr_t local_addr;
82
83 #define MAX_CMD_LINE_ITEMS 100
84 static int app_argc = 0;
85 static const char *app_argv[MAX_CMD_LINE_ITEMS] = { NULL };
86
87 int btstack_main(int argc, const char * argv[]);
88
89 static bd_addr_t static_address;
90 static int using_static_address;
91
92 static btstack_packet_callback_registration_t hci_event_callback_registration;
93
local_version_information_handler(uint8_t * packet)94 static void local_version_information_handler(uint8_t * packet){
95 printf("Local version information:\n");
96 uint16_t hci_version = packet[6];
97 uint16_t hci_revision = little_endian_read_16(packet, 7);
98 uint16_t lmp_version = packet[9];
99 uint16_t manufacturer = little_endian_read_16(packet, 10);
100 uint16_t lmp_subversion = little_endian_read_16(packet, 12);
101 printf("- HCI Version 0x%04x\n", hci_version);
102 printf("- HCI Revision 0x%04x\n", hci_revision);
103 printf("- LMP Version 0x%04x\n", lmp_version);
104 printf("- LMP Subversion 0x%04x\n", lmp_subversion);
105 printf("- Manufacturer 0x%04x\n", manufacturer);
106 switch (manufacturer){
107 case BLUETOOTH_COMPANY_ID_THE_LINUX_FOUNDATION:
108 printf("Linux Foundation - assume Zephyr hci_usb example running on nRF52xx\n");
109 hci_set_chipset(btstack_chipset_zephyr_instance());
110 break;
111 default:
112 break;
113 }
114 }
115
packet_handler(uint8_t packet_type,uint16_t channel,uint8_t * packet,uint16_t size)116 static void packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
117 UNUSED(channel);
118 UNUSED(size);
119 uint8_t usb_path_len;
120 const uint8_t * usb_path;
121 uint16_t product_id;
122 uint8_t i;
123 const uint8_t *params;
124
125 if (packet_type != HCI_EVENT_PACKET) return;
126 switch (hci_event_packet_get_type(packet)){
127 case BTSTACK_EVENT_STATE:
128 switch (btstack_event_state_get_state(packet)){
129 case HCI_STATE_WORKING:
130 gap_local_bd_addr(local_addr);
131 if (using_static_address){
132 memcpy(local_addr, static_address, 6);
133 }
134 printf("BTstack up and running on %s.\n", bd_addr_to_str(local_addr));
135 btstack_strcpy(tlv_db_path, sizeof(tlv_db_path), TLV_DB_PATH_PREFIX);
136 btstack_strcat(tlv_db_path, sizeof(tlv_db_path), bd_addr_to_str(local_addr));
137 btstack_strcat(tlv_db_path, sizeof(tlv_db_path), TLV_DB_PATH_POSTFIX);
138 printf("TLV path: %s", tlv_db_path);
139 if (tlv_clear){
140 int rc = unlink(tlv_db_path);
141 if (rc == 0) {
142 printf(", reset ok");
143 } else {
144 printf(", reset failed with result = %d", rc);
145 }
146 }
147 printf("\n");
148 tlv_impl = btstack_tlv_posix_init_instance(&tlv_context, tlv_db_path);
149 btstack_tlv_set_instance(tlv_impl, &tlv_context);
150 #ifdef ENABLE_CLASSIC
151 hci_set_link_key_db(btstack_link_key_db_tlv_get_instance(tlv_impl, &tlv_context));
152 #endif
153 #ifdef ENABLE_BLE
154 le_device_db_tlv_configure(tlv_impl, &tlv_context);
155 #endif
156 break;
157 case HCI_STATE_OFF:
158 btstack_tlv_posix_deinit(&tlv_context);
159 break;
160 default:
161 break;
162 }
163 if (btstack_event_state_get_state(packet) != HCI_STATE_WORKING) return;
164 break;
165 case HCI_EVENT_COMMAND_COMPLETE:
166 switch (hci_event_command_complete_get_command_opcode(packet)){
167 case HCI_OPCODE_HCI_READ_LOCAL_VERSION_INFORMATION:
168 local_version_information_handler(packet);
169 break;
170 case HCI_OPCODE_HCI_ZEPHYR_READ_STATIC_ADDRESS:
171 params = hci_event_command_complete_get_return_parameters(packet);
172 if(params[0] != 0)
173 break;
174 if(size < 13)
175 break;
176 reverse_48(¶ms[2], static_address);
177 gap_random_address_set(static_address);
178 using_static_address = 1;
179 break;
180 default:
181 break;
182 }
183 break;
184 case HCI_EVENT_TRANSPORT_USB_INFO:
185 usb_path_len = hci_event_transport_usb_info_get_path_len(packet);
186 usb_path = hci_event_transport_usb_info_get_path(packet);
187 // print device path
188 product_id = hci_event_transport_usb_info_get_product_id(packet);
189 printf("USB device 0x%04x/0x%04x, path: ",
190 hci_event_transport_usb_info_get_vendor_id(packet), product_id);
191 for (i=0;i<usb_path_len;i++){
192 if (i) printf("-");
193 printf("%02x", usb_path[i]);
194 }
195 printf("\n");
196 break;
197
198 default:
199 break;
200 }
201 }
202
sigint_handler(int param)203 static void sigint_handler(int param){
204 UNUSED(param);
205
206 printf("CTRL-C - SIGINT received, shutting down..\n");
207 log_info("sigint_handler: shutting down");
208
209 // reset anyway
210 btstack_stdin_reset();
211
212 // power down
213 hci_power_control(HCI_POWER_OFF);
214 hci_close();
215 log_info("Good bye, see you.\n");
216 exit(0);
217 }
218
219 static int led_state = 0;
hal_led_toggle(void)220 void hal_led_toggle(void){
221 led_state = 1 - led_state;
222 printf("LED State %u\n", led_state);
223 }
224
btstack_log_cmd_line(int argc,const char * args[])225 static void btstack_log_cmd_line( int argc, const char *args[] )
226 {
227 char buf[2048] = "command line:";
228 char *ptr = buf+strlen(buf);
229 size_t len = sizeof(buf);
230 for( int i=0; i<argc; ++i )
231 {
232 int ret = snprintf(ptr, len, " %s", args[i]);
233 // avoid overflow
234 if((ret < 0) || ( (size_t)ret >= len ))
235 {
236 log_error("command line truncated!");
237 break;
238 }
239 // terminate string
240 ptr[ret] = 0;
241 len -= ret;
242 ptr += ret;
243 }
244 log_info("%s", buf);
245
246 }
247
248 static const char short_options[] = "-hu:l:c";
249
250 static const struct option long_options[] = {
251 {"help", no_argument, NULL, 'h'},
252 {"logfile", required_argument, NULL, 'l'},
253 {"clear-tlv", no_argument, NULL, 'c'},
254 {"usbpath", required_argument, NULL, 'u'},
255 {0, 0, 0, 0}
256 };
257
258 static const char *help_options[] = {
259 "print (this) help.",
260 "set file to store debug output and HCI trace.",
261 "clear bonding information stored in TLV.",
262 "set USB path to Bluetooth Controller.",
263 };
264
265 static const char *option_arg_name[] = {
266 "",
267 "LOGFILE",
268 "",
269 "USBPATH",
270 };
271
usage(const char * name)272 static void usage(const char *name){
273 unsigned int i;
274 printf( "usage:\n\t%s [options]\n", name );
275 printf("valid options:\n");
276 for( i=0; long_options[i].name != 0; i++) {
277 printf("--%-10s| -%c %-10s\t\t%s\n", long_options[i].name, long_options[i].val, option_arg_name[i], help_options[i] );
278 }
279 }
280
clear_argv(int idx)281 static void clear_argv(int idx){
282 app_argv[idx] = NULL;
283 }
284
shift_argv(int idx)285 static void shift_argv(int idx){
286 for( int i=idx; i<app_argc-1; ++i )
287 {
288 app_argv[i] = app_argv[i+1];
289 }
290 app_argc--;
291 }
292
cleanup_argv(void)293 static void cleanup_argv(void){
294 for( int i=0; i<app_argc; ){
295 if( app_argv[i] == NULL )
296 shift_argv( i );
297 else{
298 ++i;
299 }
300 }
301 }
302
303 #define USB_MAX_PATH_LEN 7
main(int argc,const char * argv[])304 int main(int argc, const char * argv[]){
305
306 uint8_t usb_path[USB_MAX_PATH_LEN];
307 int usb_path_len = 0;
308 const char * usb_path_string = NULL;
309 const char * log_file_path = NULL;
310
311 btstack_assert( argc < MAX_CMD_LINE_ITEMS );
312 app_argc = argc;
313 for( int i=0; i<argc; ++i ){
314 app_argv[i] = argv[i];
315 }
316
317 opterr = 0; // disable error message on unknown options
318 // parse command line parameters
319 while(true){
320 int c = getopt_long( argc, (char* const *)argv, short_options, long_options, NULL );
321 if (c < 0) {
322 break;
323 }
324 switch (c) {
325 case 'u':
326 usb_path_string = optarg;
327 clear_argv( optind - 1 );
328 clear_argv( optind - 2 );
329 break;
330 case 'l':
331 log_file_path = optarg;
332 clear_argv( optind - 1 );
333 clear_argv( optind - 2 );
334 break;
335 case 'c':
336 tlv_clear = true;
337 clear_argv( optind - 1 );
338 break;
339 case '?':
340 case 1:
341 break;
342 case 'h':
343 default:
344 usage(argv[0]);
345 return EXIT_FAILURE;
346 }
347 }
348
349 if (usb_path_string != NULL){
350 // parse command line options for "-u 11:22:33"
351 printf("Specified USB Path: ");
352 while (1){
353 char * delimiter;
354 int port = strtol(usb_path_string, &delimiter, 16);
355 usb_path[usb_path_len] = port;
356 usb_path_len++;
357 printf("%02x ", port);
358 if (!delimiter) break;
359 if (*delimiter != ':' && *delimiter != '-') break;
360 usb_path_string = delimiter+1;
361 }
362 printf("\n");
363 }
364
365 // remove used up command line args
366 cleanup_argv();
367
368 /// GET STARTED with BTstack ///
369 btstack_memory_init();
370 btstack_run_loop_init(btstack_run_loop_posix_get_instance());
371
372 if (usb_path_len){
373 hci_transport_usb_set_path(usb_path_len, usb_path);
374 }
375
376 // use logger: format HCI_DUMP_PACKETLOGGER, HCI_DUMP_BLUEZ or HCI_DUMP_STDOUT
377 char pklg_path[100];
378 btstack_strcpy(pklg_path, sizeof(pklg_path), "/tmp/hci_dump");
379 if (usb_path_len){
380 btstack_strcat(pklg_path, sizeof(pklg_path), "_");
381 btstack_strcat(pklg_path, sizeof(pklg_path), usb_path_string);
382 }
383 btstack_strcat(pklg_path, sizeof(pklg_path), ".pklg");
384
385 // use path from command line if given
386 if( log_file_path != NULL ){
387 btstack_strcpy(pklg_path, sizeof(pklg_path), log_file_path );
388 }
389
390 // log into file using HCI_DUMP_PACKETLOGGER format
391 hci_dump_posix_fs_open(pklg_path, HCI_DUMP_PACKETLOGGER);
392 hci_dump_init(hci_dump_posix_fs_get_instance());
393 printf("Packet Log: %s\n", pklg_path);
394
395 // let the log contain the calling parameters
396 btstack_log_cmd_line( app_argc, app_argv );
397
398 // init HCI
399 hci_init(hci_transport_usb_instance(), NULL);
400
401 #ifdef HAVE_PORTAUDIO
402 btstack_audio_sink_set_instance(btstack_audio_portaudio_sink_get_instance());
403 btstack_audio_source_set_instance(btstack_audio_portaudio_source_get_instance());
404 #endif
405
406 // inform about BTstack state
407 hci_event_callback_registration.callback = &packet_handler;
408 hci_add_event_handler(&hci_event_callback_registration);
409
410 // handle CTRL-c
411 signal(SIGINT, sigint_handler);
412
413 // setup app
414 btstack_main(app_argc, app_argv);
415
416 // go
417 btstack_run_loop_execute();
418
419 return 0;
420 }
421