forked from bjonica/mochad
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmochad.c
706 lines (608 loc) · 18.9 KB
/
mochad.c
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
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
/*
* Copyright 2010-2011 Brian Uechi <buasst@gmail.com>
*
* This file is part of mochad.
*
* mochad 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 3 of the License, or (at your
* option) any later version.
*
* mochad 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 mochad. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* TCP gateway to X10 CM15A X10 RF and PL controller and CM19A RF controller.
* Decode data from CM15A/CM19A ignoring macros and timers. This driver treats
* the CM15A as a transceiver. The CM15A macros, timers, and real-time clock
* (RTC) are ignored. In fact, the CM15A memory should be cleared using
* ActiveHome Pro (AHP) before using the CM15A is with this driver. Batteries
* are not necessary because the RTC is not used. The CM15A RF to PL converter
* should be disabled for all house codes using AHP. The CM19A does not
* supports macros, timers, or RTC so it can be used as-is.
*/
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdarg.h>
#include <stdlib.h>
#include <signal.h>
#include <poll.h>
#include <time.h>
#include <errno.h>
#include <unistd.h>
/**** system log ****/
#include <syslog.h>
/* Multiple On-line Controllers Home Automation Daemon */
#define DAEMON_NAME "mochad"
/**** socket ****/
#include <sys/socket.h>
#include <netinet/in.h>
#include "global.h"
#define SERVER_PORT (1099)
#define MAXCLISOCKETS (32)
#define MAXSOCKETS (1+MAXCLISOCKETS)
/* first socket=listen socket, 20 client sockets */
#define USB_FDS (10) /* libusb file descriptors */
static struct pollfd Clients[(MAXSOCKETS)+USB_FDS];
/* Client sockets */
static struct pollfd Clientsocks[MAXCLISOCKETS];
static size_t NClients; /* # of valid entries in Clientsocks */
/**** USB usblib 1.0 ****/
#include <libusb-1.0/libusb.h>
uint8_t InEndpoint, OutEndpoint;
static struct libusb_device_handle *Devh = NULL;
static struct libusb_transfer *IntrOut_transfer = NULL;
static struct libusb_transfer *IntrIn_transfer = NULL;
static unsigned char IntrOutBuf[8];
static unsigned char IntrInBuf[8];
/*
* Like printf but print to socket without date/time stamp.
* Used to send back result of getstatus command.
*/
int statusprintf(int fd, const char *fmt, ...)
{
va_list args;
char buf[1024];
int buflen;
va_start(args,fmt);
buflen = vsnprintf(buf, sizeof(buf)-2, fmt, args);
va_end(args);
return send(fd, buf, buflen, MSG_NOSIGNAL);
}
/*
* Like printf but prefix each line with date/time stamp.
* If fd == -1, send to all socket clients else send only to fd.
*/
int sockprintf(int fd, const char *fmt, ...)
{
va_list args;
char buf[1024];
int buflen;
int i;
va_start(args,fmt);
buflen = vsnprintf(buf, sizeof(buf), fmt, args);
va_end(args);
if (buflen > 1) {
if (fd != -1) {
return send(fd, buf, buflen, MSG_NOSIGNAL);
}
/* Send to all socket clients */
for (i = 0; i < MAXCLISOCKETS; i++) {
if ((fd = Clientsocks[i].fd) > 0) {
send(fd, buf, buflen, MSG_NOSIGNAL);
}
}
}
return buflen;
}
static void _hexdump(void *p, size_t len, char *outbuf, size_t outlen)
{
unsigned char *ptr = (unsigned char*) p;
size_t l;
if (len == 0) return;
if (len > (outlen / 3))
l = outlen / 3;
else
l = len;
while (l--) {
sprintf(outbuf, "%02X ", *ptr++);
outbuf += 3;
}
}
void hexdump(void *p, size_t len)
{
char buf[(3*100)+1];
_hexdump(p, len, buf, sizeof(buf));
puts(buf);
}
void sockhexdump(int fd, void *p, size_t len)
{
char buf[(3*100)+1];
_hexdump(p, len, buf, sizeof(buf));
sockprintf(fd, "%s\n", buf);
}
// Output Raw data with header for parsing by misterhouse
void mh_sockhexdump(int fd, void *p, size_t len)
{
char buf[(3*100)+1];
_hexdump(p, len, buf, sizeof(buf));
sockprintf(fd, "Raw data received: %s\n", buf);
}
static int Do_exit = 0;
static int Reattach = 0;
static void init_client(void)
{
int i;
for (i = 0; i < MAXCLISOCKETS; i++) {
Clientsocks[i].fd = -1;
}
NClients = 0;
}
/* Add new socket client */
static int add_client(int fd)
{
int i;
for (i = 0; i < MAXCLISOCKETS; i++) {
if (Clientsocks[i].fd == -1) {
Clientsocks[i].fd = fd;
Clientsocks[i].events = POLLIN;
Clientsocks[i].revents = 0;
NClients++;
return 0;
}
}
//dbprintf("max clients exceeded %d\n", i);
return -1;
}
/* Delete socket client */
int del_client(int fd)
{
int i;
for (i = 0; i < MAXCLISOCKETS; i++) {
if (Clientsocks[i].fd == fd) {
Clientsocks[i].fd = -1;
NClients--;
return 0;
}
}
//dbprintf("del_client:fd not found %d\n", fd);
return -1;
}
/* Copy socket client records to array */
static int copy_clients(struct pollfd *Clients)
{
int i;
for (i = 0; i < MAXCLISOCKETS; i++) {
if (Clientsocks[i].fd != -1) {
*Clients++ = Clientsocks[i];
}
}
return NClients;
}
/* Client sockets */
#include "x10state.h"
#include "x10_write.h"
#include "encode.h"
#include "decode.h"
struct binarydata {
size_t binlength;
unsigned char bindata[8];
};
static const struct binarydata initcm15abinary[] = {
#if 0
{8, {0x9b,0x00,0x5b,0x09,0x50,0x90,0x60,0x02}},
{8, {0x9b,0x00,0x5b,0x09,0x50,0x90,0x60,0x02}},
{8, {0xbb,0x00,0x00,0x05,0x00,0x14,0x20,0x28}},
{1, {0x8b}},
{3, {0xdb,0x1f,0xf0}},
{3, {0xdb,0x20,0x00}},
{3, {0xab,0xde,0xaf}},
{1, {0x8b}},
{3, {0xab,0x00,0x00}},
#endif
{0}
};
static const struct binarydata initcm19abinary[] = {
{8, {0x80,0x05,0x1b,0x14,0x28,0x20,0x24,0x29}},
{2, {0x83,0x03}},
{8, {0x84,0x37,0x02,0x60,0x00,0x00,0x00,0x00}},
{8, {0x80,0x01,0x00,0x14,0x20,0x24,0x28,0x29}},
{3, {0x83,0x02,0x0f}},
{8, {0x83,0x37,0x02,0x60,0x00,0x00,0x00,0x00}},
{5, {0x20,0x34,0xcb,0x58,0xa7}},
{8, {0x80,0x05,0x01,0x14,0x20,0x24,0x28,0x29}},
{0}
};
static void initcm1Xa(const struct binarydata *p)
{
dbprintf("initcm1Xa\n");
while (p->binlength) {
x10_write((unsigned char *)p->bindata, p->binlength);
p++;
}
}
/* Find CM15A or CM19A. The EU versions (CM15Pro and CM19Pro) have the same
* vendor and product IDs, respectively.
*/
static int find_cm15a(struct libusb_device_handle **devhptr)
{
int r;
Cm19a = 0;
*devhptr = libusb_open_device_with_vid_pid(NULL, 0x0bc7, 0x0001);
if (!*devhptr) {
*devhptr = libusb_open_device_with_vid_pid(NULL, 0x0bc7, 0x0002);
if (!*devhptr) {
syslog(LOG_EMERG, "libusb_open_device_with_vid_pid failed");
return -EIO;
}
Cm19a = 1;
}
r = libusb_claim_interface(*devhptr, 0);
if (r == 0) {
syslog(LOG_NOTICE, (Cm19a) ? "Found CM19A" : "Found CM15A");
return 0;
}
syslog(LOG_EMERG, "usb_claim_interface failed %d", r);
r = libusb_kernel_driver_active(*devhptr, 0);
if (r < 0) {
syslog(LOG_EMERG, "Kernel driver check failed %d", r);
return -EIO;
}
syslog(LOG_NOTICE, "Found kernel driver %d, trying detach", r);
r = libusb_detach_kernel_driver(*devhptr, 0);
if (r < 0) {
syslog(LOG_EMERG, "Kernel driver detach failed %d", r);
return -EIO;
}
Reattach = 1;
r = libusb_claim_interface(*devhptr, 0);
if (r < 0) {
syslog(LOG_EMERG, "claim interface failed again %d", r);
return -EIO;
}
syslog(LOG_NOTICE, (Cm19a) ? "Found CM19A" : "Found CM15A");
return 0;
}
/* Find the in and out endpoint address in the device descriptors.
* This is required by newer CM19A that have changed endpoint addresses.
*/
static int get_endpoint_address(libusb_device_handle *devh, uint8_t *inendpt, uint8_t *outendpt)
{
int r;
struct libusb_config_descriptor *config;
const struct libusb_interface *interfaces;
const struct libusb_interface_descriptor *interface_desc;
const struct libusb_endpoint_descriptor *endpoint_desc;
struct libusb_device *uDevice;
struct libusb_device_descriptor desc;
int i, j, k;
uDevice = libusb_get_device(devh);
if (!uDevice) return -1;
r = libusb_get_device_descriptor(uDevice, &desc);
if (r < 0) return r;
r = libusb_get_active_config_descriptor(uDevice, &config);
if (r < 0) return r;
interfaces = config->interface;
for (i = 0; i < config->bNumInterfaces; i++) {
interface_desc = interfaces->altsetting;
for (j = 0; j < interfaces->num_altsetting; j++) {
endpoint_desc = interface_desc->endpoint;
for (k = 0; k < interface_desc->bNumEndpoints; k++) {
if (endpoint_desc->bEndpointAddress & 0x80) {
*inendpt = endpoint_desc->bEndpointAddress;
}
else {
*outendpt = endpoint_desc->bEndpointAddress;
}
endpoint_desc++;
}
interface_desc++;
}
interfaces++;
}
libusb_free_config_descriptor(config);
return r;
}
static void IntrOut_cb(struct libusb_transfer *transfer)
{
/* dbprintf("IntrOut callback len %d\n", transfer->actual_length); */
}
static void IntrIn_cb(struct libusb_transfer *transfer)
{
#if 0
int fd, i;
#endif
if (transfer->status != LIBUSB_TRANSFER_COMPLETED) {
dbprintf("IntrIn transfer status %d?\n", transfer->status);
Do_exit = 2;
libusb_free_transfer(transfer);
IntrIn_transfer = NULL;
return;
}
/* dbprintf("IntrIn callback len %d ", transfer->actual_length); */
/* hexdump(transfer->buffer, transfer->actual_length); */
/* if ((transfer->actual_length == 1) && (*transfer->buffer == 0x55)) { */
if (transfer->actual_length == 1) {
send_next_x10out();
}
#if 0
/* Incoming USB data is sent to all sockets */
for (i = 0; i < MAXCLISOCKETS; i++) {
if ((fd = Clientsocks[i].fd) > 0) {
cm15a_decode(fd, transfer->buffer, transfer->actual_length);
}
}
#else
cm15a_decode(-1, transfer->buffer, transfer->actual_length);
#endif
if (libusb_submit_transfer(IntrIn_transfer) < 0)
Do_exit = 2;
}
static int start_transfers(void)
{
int r;
r = libusb_submit_transfer(IntrIn_transfer);
if (r < 0)
return r;
return 0;
}
static int do_init(void)
{
// set clock?
return 0;
}
static int alloc_transfers(void)
{
IntrIn_transfer = libusb_alloc_transfer(0);
if (!IntrIn_transfer)
return -ENOMEM;
libusb_fill_interrupt_transfer(IntrIn_transfer, Devh, InEndpoint,
IntrInBuf, sizeof(IntrInBuf), IntrIn_cb, NULL, 0);
IntrOut_transfer = libusb_alloc_transfer(0);
if (!IntrOut_transfer)
return -ENOMEM;
return 0;
}
int write_usb(unsigned char *buf, size_t len)
{
int r, i;
dbprintf("usb len %lu ", (unsigned long)len);
hexdump(buf, len);
memcpy(IntrOutBuf, buf, len);
libusb_fill_interrupt_transfer(IntrOut_transfer, Devh, OutEndpoint,
IntrOutBuf, len, IntrOut_cb, NULL, 0);
r = libusb_submit_transfer(IntrOut_transfer);
if (r < 0) {
libusb_cancel_transfer(IntrOut_transfer);
i = 100;
while (IntrOut_transfer && i--)
if (libusb_handle_events(NULL) < 0)
break;
return r;
}
return 0;
}
static void sighandler(int signum)
{
Do_exit = 1;
}
static int mydaemon(void)
{
int nready, i;
/**** sockets ****/
socklen_t clilen;
int clifd, listenfd;
unsigned char buf[1024];
int bytesIn;
struct sockaddr_in cliaddr, servaddr;
int rc;
static const int optval=1;
/**** USB ****/
struct sigaction sigact;
int r = 1;
const struct libusb_pollfd **usbfds;
nfds_t nusbfds;
struct timeval timeout;
hua_sec_init();
r = libusb_init(NULL);
if (r < 0) {
syslog(LOG_EMERG, "failed to initialise libusb %d", r);
dbprintf("failed to initialise libusb %d\n", r);
exit(1);
}
libusb_set_debug(NULL, 3);
r = find_cm15a(&Devh);
if (r < 0) {
syslog(LOG_EMERG, "Could not find/open CM15A/CM19A %d", r);
dbprintf("Could not find/open CM15A/CM19A %d\n", r);
goto out;
}
r = get_endpoint_address(Devh, &InEndpoint, &OutEndpoint);
r = do_init();
if (r < 0)
goto out_deinit;
r = alloc_transfers();
if (r < 0)
goto out_deinit;
r = start_transfers();
if (r < 0)
goto out_deinit;
sigact.sa_handler = sighandler;
sigemptyset(&sigact.sa_mask);
sigact.sa_flags = 0;
sigaction(SIGINT, &sigact, NULL);
sigaction(SIGTERM, &sigact, NULL);
sigaction(SIGQUIT, &sigact, NULL);
usbfds = libusb_get_pollfds(NULL);
dbprintf("usbfds %p %p %p %p %p\n", usbfds,
usbfds[0], usbfds[1], usbfds[2], usbfds[3]);
nusbfds = 1; /* Skip over socket listen fd at [0] */
for (i = 0; usbfds[i] != NULL; i++) {
dbprintf(" %lu: %p fd %d %04X\n", nusbfds,
usbfds[i], usbfds[i]->fd, usbfds[i]->events);
Clients[nusbfds].fd = usbfds[i]->fd;
Clients[nusbfds].events = usbfds[i]->events;
Clients[nusbfds].revents = 0;
nusbfds++;
}
nusbfds -= 1; /* Adjust for skipping 0,1,2 */
dbprintf("nusbfds %lu\n", nusbfds);
memset(&timeout, 0, sizeof(timeout));
if (Cm19a)
initcm1Xa(initcm19abinary);
else
initcm1Xa(initcm15abinary);
/**** sockets ****/
listenfd = socket(AF_INET, SOCK_STREAM, 0);
dbprintf("listenfd %d\n", listenfd);
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(SERVER_PORT);
rc = setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval));
dbprintf("setsockopt() %d/%d\n", rc, errno);
rc = bind(listenfd, (struct sockaddr*) &servaddr, sizeof(servaddr));
dbprintf("bind() %d/%d\n", rc, errno);
rc = listen(listenfd, 128);
dbprintf("listen() %d/%d\n", rc, errno);
init_client();
Clients[0].fd = listenfd;
Clients[0].events = POLLIN;
PollTimeOut = -1;
while (!Do_exit) {
int nsockclients;
int npollfds;
/* Start appending records for socket clients to Clients array after
* listen and USB records
*/
nsockclients = copy_clients(&Clients[1+nusbfds]);
/* 1 for listen socket, nusbfds for libusb, nsockclients for socket clients
*/
npollfds = 1 + nusbfds + nsockclients;
nready = poll(Clients, npollfds, PollTimeOut);
/**** Time out ****/
if (nready == 0) {
send_next_x10out();
}
else {
/**** USB ****/
libusb_handle_events_timeout(NULL, &timeout);
/**** listen sockets ****/
if (Clients[0].revents & POLLIN) {
/* new client connection */
clilen = sizeof(cliaddr);
clifd = accept(listenfd, (struct sockaddr *)&cliaddr, &clilen);
dbprintf("accept() %d/%d\n", clifd, errno);
r = add_client(clifd);
if (--nready <= 0) continue;
}
for (i = 1+nusbfds; i < npollfds; i++) {
if ((clifd = Clients[i].fd) >= 0) {
/* dbprintf("client %d revents 0x%X\n", i, Clients[i].revents); */
if (Clients[i].revents & (POLLIN|POLLERR)) {
if ((bytesIn = read(clifd, buf, sizeof(buf))) < 0) {
dbprintf("read err %d\n", errno);
if (errno != ECONNRESET) {
dbprintf("serious error %d\n", errno);
}
close(clifd);
del_client(clifd);
}
else if (bytesIn == 0) {
dbprintf("read EOF %d\n", bytesIn);
close(clifd);
del_client(clifd);
}
else {
cm15a_encode(clifd, buf, (size_t)bytesIn);
}
if (--nready <= 0) break;
}
}
}
}
}
syslog(LOG_NOTICE, (Cm19a) ? "detaching CM19A" : "detaching CM15A");
if (IntrOut_transfer) {
r = libusb_cancel_transfer(IntrOut_transfer);
if (r < 0)
goto out_deinit;
}
if (IntrIn_transfer) {
r = libusb_cancel_transfer(IntrIn_transfer);
if (r < 0)
goto out_deinit;
}
i = 100;
while ((IntrOut_transfer || IntrIn_transfer) && i--)
if (libusb_handle_events(NULL) < 0)
break;
if (Do_exit == 1)
r = 0;
else
r = 1;
out_deinit:
libusb_free_transfer(IntrIn_transfer);
libusb_free_transfer(IntrOut_transfer);
/* out_release: */
libusb_release_interface(Devh, 0);
out:
libusb_close(Devh);
if (Reattach) libusb_attach_kernel_driver(Devh, 0);
libusb_exit(NULL);
return r >= 0 ? r : -r;
}
static void printcopy(void)
{
printf("Copyright (C) 2010-2012 Brian Uechi.\n");
printf("\n");
printf("This program comes with NO WARRANTY.\n");
printf("You may redistribute copies of this program\n");
printf("under the terms of the GNU General Public License.\n");
printf("For more information about these matters, see the file named COPYING.\n");
fflush(NULL);
}
// This affects whether decode.c will show raw frame data for debugging RF connectivity
// as well as providing raw data for parsing by users like misterhouse's X10_CMxx module.
int raw_data = 0;
int main(int argc, char *argv[])
{
int rc, i;
int foreground=0;
/* Initialize logging */
openlog(DAEMON_NAME, LOG_PID, LOG_LOCAL5);
syslog(LOG_NOTICE, "starting");
/* Process command line args */
for (i = 1; i < argc; i++) {
if (strcmp(argv[i], "-d") == 0)
foreground = 1;
else if (strcmp(argv[i], "--raw-data") == 0)
raw_data = 1;
else if (strcmp(argv[i], "--version") == 0) {
printf("%s\n", PACKAGE_STRING);
printcopy();
exit(0);
}
else {
printf("unknown option %s\n", argv[i]);
exit(-1);
}
}
/* Daemonize */
if (!foreground) {
rc = daemon(0, 0);
dbprintf("daemon() => %d\n", rc);
}
/* Do real work */
rc = mydaemon();
/* Finish up */
syslog(LOG_NOTICE, "terminated");
closelog();
return rc;
}