hc
2024-10-12 a5969cabbb4660eab42b6ef0412cbbd1200cf14d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
/*
 *
 *  BlueZ - Bluetooth protocol stack for Linux
 *
 *  Copyright (C) 2000-2001  Qualcomm Incorporated
 *  Copyright (C) 2002-2003  Maxim Krasnyansky <maxk@qualcomm.com>
 *  Copyright (C) 2002-2010  Marcel Holtmann <marcel@holtmann.org>
 *
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 */
 
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
 
#define _GNU_SOURCE
#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <syslog.h>
#include <termios.h>
#include <time.h>
#include <sys/time.h>
#include <sys/poll.h>
#include <sys/param.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/uio.h>
#include <sys/timerfd.h>
 
#include "hciattach.h"
 
#define RFKILL_NODE    "/sys/class/rfkill/rfkill0/state"
 
#ifdef NEED_PPOLL
#include "ppoll.h"
#endif
 
/* #define SCHED_ENABLE */
 
#ifdef SCHED_ENABLE
#include <sched.h>
#endif
 
struct uart_t {
   char *type;
   int  m_id;
   int  p_id;
   int  proto;
   int  init_speed;
   int  speed;
   int  flags;
   int  pm;
   char *bdaddr;
   int  (*init) (int fd, struct uart_t *u, struct termios *ti);
   int  (*post) (int fd, struct uart_t *u, struct termios *ti);
};
 
#define FLOW_CTL    0x0001
#define ENABLE_PM    1
#define DISABLE_PM    0
 
static volatile sig_atomic_t __io_canceled = 0;
 
static void sig_hup(int sig)
{
   RS_INFO("signal hup.");
}
 
static void sig_term(int sig)
{
   switch (sig) {
   case SIGINT:
       RS_INFO("signal int.");
       break;
   case SIGTERM:
       RS_INFO("signal term.");
       break;
   }
   __io_canceled = 1;
}
 
static void sig_alarm(int sig)
{
   RS_ERR("Initialization timed out.");
   exit(1);
}
 
static int uart_speed(int s)
{
   switch (s) {
   case 9600:
       return B9600;
   case 19200:
       return B19200;
   case 38400:
       return B38400;
   case 57600:
       return B57600;
   case 115200:
       return B115200;
   case 230400:
       return B230400;
   case 460800:
       return B460800;
   case 500000:
       return B500000;
   case 576000:
       return B576000;
   case 921600:
       return B921600;
   case 1000000:
       return B1000000;
   case 1152000:
       return B1152000;
   case 1500000:
       return B1500000;
   case 2000000:
       return B2000000;
#ifdef B2500000
   case 2500000:
       return B2500000;
#endif
#ifdef B3000000
   case 3000000:
       return B3000000;
#endif
#ifdef B3500000
   case 3500000:
       return B3500000;
#endif
#ifdef B4000000
   case 4000000:
       return B4000000;
#endif
   default:
       return B57600;
   }
}
 
int set_speed(int fd, struct termios *ti, int speed)
{
   if (cfsetospeed(ti, uart_speed(speed)) < 0)
       return -errno;
 
   if (cfsetispeed(ti, uart_speed(speed)) < 0)
       return -errno;
 
   if (tcsetattr(fd, TCSANOW, ti) < 0)
       return -errno;
 
   return 0;
}
 
static int realtek_init(int fd, struct uart_t *u, struct termios *ti)
{
 
   RS_INFO("Realtek Bluetooth init uart with init speed:%d, type:HCI UART %s",
       u->init_speed,
       (u->proto == HCI_UART_H4) ? "H4" : "H5");
   return rtb_init(fd, u->proto, u->speed, ti);
}
 
static int realtek_post(int fd, struct uart_t *u, struct termios *ti)
{
   RS_INFO("Realtek Bluetooth post process");
   return rtb_post(fd, u->proto, ti);
}
 
struct uart_t uart[] = {
   { "any",     0x0000, 0x0000, HCI_UART_H4,   115200, 115200, FLOW_CTL, DISABLE_PM, NULL, NULL},
 
   /* Realtek Bluetooth H4 */
   { "rtk_h4",  0x0000, 0x0000, HCI_UART_H4,  115200,  115200, 0, DISABLE_PM, NULL, realtek_init, realtek_post },
 
   /* Realtek Bluetooth H5 */
   { "rtk_h5",  0x0000, 0x0000, HCI_UART_3WIRE, 115200,115200, 0, DISABLE_PM, NULL, realtek_init, realtek_post },
 
   { NULL, 0 }
};
 
static struct uart_t * get_by_id(int m_id, int p_id)
{
   int i;
   for (i = 0; uart[i].type; i++) {
       if (uart[i].m_id == m_id && uart[i].p_id == p_id)
           return &uart[i];
   }
   return NULL;
}
 
static struct uart_t * get_by_type(char *type)
{
   int i;
   for (i = 0; uart[i].type; i++) {
       if (!strcmp(uart[i].type, type))
           return &uart[i];
   }
   return NULL;
}
 
/* Initialize UART driver */
static int init_uart(char *dev, struct uart_t *u, int send_break, int raw)
{
   struct termios ti;
   int fd, i;
   unsigned long flags = 0;
 
   if (raw)
       flags |= 1 << HCI_UART_RAW_DEVICE;
 
   fd = open(dev, O_RDWR | O_NOCTTY);
   if (fd < 0) {
       RS_ERR("Can't open serial port, %d, %s", errno,
              strerror(errno));
       return -1;
   }
 
   tcflush(fd, TCIOFLUSH);
 
   if (tcgetattr(fd, &ti) < 0) {
       RS_ERR("Can't get port settings, %d, %s", errno,
              strerror(errno));
       return -1;
   }
 
   cfmakeraw(&ti);
 
   ti.c_cflag |= CLOCAL;
   if (u->flags & FLOW_CTL)
       ti.c_cflag |= CRTSCTS;
   else
       ti.c_cflag &= ~CRTSCTS;
 
   if (tcsetattr(fd, TCSANOW, &ti) < 0) {
       RS_ERR("Can't set port settings, %d, %s", errno,
              strerror(errno));
       return -1;
   }
 
   /* Set initial baudrate */
   if (set_speed(fd, &ti, u->init_speed) < 0) {
       RS_ERR("Can't set initial baud rate, %d, %s", errno,
              strerror(errno));
       return -1;
   }
 
   tcflush(fd, TCIOFLUSH);
 
   if (send_break) {
       tcsendbreak(fd, 0);
       usleep(500000);
   }
 
   if (u->init && u->init(fd, u, &ti) < 0)
       return -1;
 
   tcflush(fd, TCIOFLUSH);
 
   /* Set actual baudrate
    * There is no need to change baudrate after uart init
    * */
   /* if (set_speed(fd, &ti, u->speed) < 0) {
    *     perror("Can't set baud rate");
    *     return -1;
    * }
    */
 
   /* Set TTY to N_HCI line discipline */
   i = N_HCI;
   if (ioctl(fd, TIOCSETD, &i) < 0) {
       RS_ERR("Can't set line discipline %d, %s", errno,
              strerror(errno));
       return -1;
   }
 
   if (flags && ioctl(fd, HCIUARTSETFLAGS, flags) < 0) {
       RS_ERR("Can't set UART flags %d, %s", errno, strerror(errno));
       return -1;
   }
 
   if (ioctl(fd, HCIUARTSETPROTO, u->proto) < 0) {
       RS_ERR("Can't set device %d, %s", errno, strerror(errno));
       return -1;
   }
 
   if (u->post && u->post(fd, u, &ti) < 0)
       return -1;
 
   return fd;
}
 
static int reset_bluetooth(void)
{
 
   int fd;
   char state[2];
   int result;
 
   /* power off and power on BT */
   fd = open(RFKILL_NODE, O_RDWR);
   if (fd < 0) {
       RS_ERR("Cannot open %s, %d %s", RFKILL_NODE, errno,
               strerror(errno));
       return -1;
   }
   state[0] = '0';
   state[1] = '\0';
   result = write(fd, state, strlen(state) + 1);
   if (result != (strlen(state) + 1)) {
       RS_ERR("Cannot write 0 to rfkill state %d %s", errno,
               strerror(errno));
       close(fd);
       return -1;
   }
 
   usleep(500000);
 
   state[0] = '1';
   state[1] = '\0';
   result = write(fd, state, strlen(state) + 1);
   if (result != (strlen(state) + 1)) {
       RS_ERR("Cannot write 1 to rfkill state %d %s", errno,
               strerror(errno));
       close(fd);
       return -1;
   }
 
   usleep(500000);
   close(fd);
 
   return 0;
}
 
static void usage(void)
{
   RS_INFO("hciattach - HCI UART driver initialization utility");
   RS_INFO("Usage:");
   RS_INFO("\thciattach [-n] [-p] [-b] [-r] [-t timeout] [-s initial_speed] <tty> <type | id> [speed] [flow|noflow] [bdaddr]");
   RS_INFO("\thciattach -l");
}
 
int main(int argc, char *argv[])
{
   struct uart_t *u = NULL;
   int detach, printpid, raw, opt, i, n, ld, err;
   int to = 10;
   int init_speed = 0;
   int send_break = 0;
   pid_t pid;
   struct sigaction sa;
   struct pollfd p;
   sigset_t sigs;
   char dev[PATH_MAX];
#ifdef SCHED_ENABLE
   struct sched_param sched_par;
#endif
 
   detach = 1;
   printpid = 0;
   raw = 0;
 
   while ((opt=getopt(argc, argv, "bnpt:s:lr")) != EOF) {
       switch(opt) {
       case 'b':
           send_break = 1;
           break;
 
       case 'n':
           detach = 0;
           break;
 
       case 'p':
           printpid = 1;
           break;
 
       case 't':
           to = atoi(optarg);
           break;
 
       case 's':
           init_speed = atoi(optarg);
           break;
 
       case 'l':
           for (i = 0; uart[i].type; i++) {
               RS_INFO("%-10s0x%04x,0x%04x", uart[i].type,
                           uart[i].m_id, uart[i].p_id);
           }
           exit(0);
 
       case 'r':
           raw = 1;
           break;
 
       default:
           usage();
           exit(1);
       }
   }
 
   n = argc - optind;
   if (n < 2) {
       usage();
       exit(1);
   }
 
   for (n = 0; optind < argc; n++, optind++) {
       char *opt;
 
       opt = argv[optind];
 
       switch(n) {
       case 0:
           dev[0] = 0;
           if (!strchr(opt, '/'))
               strcpy(dev, "/dev/");
           strcat(dev, opt);
           break;
 
       case 1:
           if (strchr(argv[optind], ',')) {
               int m_id, p_id;
               sscanf(argv[optind], "%x,%x", &m_id, &p_id);
               u = get_by_id(m_id, p_id);
           } else {
               u = get_by_type(opt);
           }
 
           if (!u) {
               RS_ERR("Unknown device type or id");
               exit(1);
           }
 
           break;
 
       case 2:
           u->speed = atoi(argv[optind]);
           break;
 
       case 3:
           if (!strcmp("flow", argv[optind]))
               u->flags |=  FLOW_CTL;
           else
               u->flags &= ~FLOW_CTL;
           break;
 
       case 4:
           if (!strcmp("sleep", argv[optind]))
               u->pm = ENABLE_PM;
           else
               u->pm = DISABLE_PM;
           break;
 
       case 5:
           u->bdaddr = argv[optind];
           break;
       }
   }
 
   if (!u) {
       RS_ERR("Unknown device type or id");
       exit(1);
   }
 
start:
 
#ifdef SCHED_ENABLE
   RS_INFO("Increase the priority of the process with set sched");
   memset(&sched_par, 0, sizeof(sched_par));
   sched_par.sched_priority = 99;
   err = sched_setscheduler(0, SCHED_FIFO, &sched_par);
   if (err == -1) {
       RS_ERR("Call sched_setscheduler error, %s",
           strerror(errno));
   }
/* #else
 *     RS_INFO("Increase the priority of the process with nice");
 *     err = nice(-20);
 *     if (err == -1) {
 *         RS_ERR("Call nice error, %s", strerror(errno));
 *     }
 */
#endif
 
   /* If user specified a initial speed, use that instead of
      the hardware's default */
   if (init_speed)
       u->init_speed = init_speed;
 
   memset(&sa, 0, sizeof(sa));
   sa.sa_flags   = SA_NOCLDSTOP;
   sa.sa_handler = sig_alarm;
   sigaction(SIGALRM, &sa, NULL);
 
   /* 10 seconds should be enough for initialization */
   alarm(to);
 
   n = init_uart(dev, u, send_break, raw);
   if (n < 0) {
       RS_ERR("Can't initialize device %d, %s", errno,
              strerror(errno));
       exit(1);
   }
 
   RS_INFO("Device setup complete");
 
   alarm(0);
 
   memset(&sa, 0, sizeof(sa));
   sa.sa_flags   = SA_NOCLDSTOP;
   sa.sa_handler = SIG_IGN;
   sigaction(SIGCHLD, &sa, NULL);
   sigaction(SIGPIPE, &sa, NULL);
 
   sa.sa_handler = sig_term;
   sigaction(SIGTERM, &sa, NULL);
   sigaction(SIGINT,  &sa, NULL);
 
   sa.sa_handler = sig_hup;
   sigaction(SIGHUP, &sa, NULL);
 
   if (detach) {
       if ((pid = fork())) {
           if (printpid)
               RS_INFO("%d", pid);
           return 0;
       }
 
       for (i = 0; i < 20; i++)
           if (i != n)
               close(i);
   }
 
   p.fd = n;
   p.events = POLLERR | POLLHUP;
 
   sigfillset(&sigs);
   sigdelset(&sigs, SIGCHLD);
   sigdelset(&sigs, SIGPIPE);
   sigdelset(&sigs, SIGTERM);
   sigdelset(&sigs, SIGINT);
   sigdelset(&sigs, SIGHUP);
 
   while (!__io_canceled) {
       p.revents = 0;
       err = ppoll(&p, 1, NULL, &sigs);
       if (err < 0 && errno == EINTR) {
           RS_INFO("Got EINTR.");
           continue;
       } if (err)
           break;
   }
 
   RS_INFO("err %d, p->revents %04x", err, p.revents);
 
   /* Restore TTY line discipline */
   RS_INFO("Restore TTY line discipline");
   ld = N_TTY;
   if (ioctl(n, TIOCSETD, &ld) < 0) {
       RS_ERR("Can't restore line discipline %d, %s", errno,
              strerror(errno));
       exit(1);
   }
 
   if (p.revents & (POLLERR | POLLHUP)) {
       RS_INFO("Recover...");
       reset_bluetooth();
       goto start;
   }
 
   return 0;
}
 
void util_hexdump(const uint8_t *buf, size_t len)
{
   static const char hexdigits[] = "0123456789abcdef";
   char str[16 * 3];
   size_t i;
 
   if (!buf || !len)
       return;
 
   for (i = 0; i < len; i++) {
       str[((i % 16) * 3)] = hexdigits[buf[i] >> 4];
       str[((i % 16) * 3) + 1] = hexdigits[buf[i] & 0xf];
       str[((i % 16) * 3) + 2] = ' ';
       if ((i + 1) % 16 == 0) {
           str[16 * 3 - 1] = '\0';
           RS_INFO("%s", str);
       }
   }
 
   if (i % 16 > 0) {
       str[(i % 16) * 3 - 1] = '\0';
       RS_INFO("%s", str);
   }
}
 
int timeout_set(int fd, unsigned int msec)
{
   struct itimerspec itimer;
   unsigned int sec = msec / 1000;
 
   memset(&itimer, 0, sizeof(itimer));
   itimer.it_interval.tv_sec = 0;
   itimer.it_interval.tv_nsec = 0;
   itimer.it_value.tv_sec = sec;
   itimer.it_value.tv_nsec = (msec - (sec * 1000)) * 1000 * 1000;
 
   return timerfd_settime(fd, 0, &itimer, NULL);
}