]> mj.ucw.cz Git - arexx.git/blob - arexxd.c
Added --debug-usb switch
[arexx.git] / arexxd.c
1 /*
2  *      Linux Interfece for Arexx Data Loggers
3  *
4  *      (c) 2011-2012 Martin Mares <mj@ucw.cz>
5  */
6
7 #include <stdio.h>
8 #include <stdarg.h>
9 #include <stdlib.h>
10 #include <string.h>
11 #include <unistd.h>
12 #include <fcntl.h>
13 #include <math.h>
14 #include <time.h>
15 #include <getopt.h>
16 #include <syslog.h>
17 #include <signal.h>
18 #include <sys/stat.h>
19 #include <libusb-1.0/libusb.h>
20 #include <rrd.h>
21
22 #define DEFAULT_LOG_DIR "/var/log/arexxd"
23
24 typedef unsigned char byte;
25 static libusb_context *usb_ctxt;
26 static libusb_device_handle *devh;
27
28 static int use_syslog;
29 static int debug_mode;
30 static int debug_packets;
31 static int debug_raw_data;
32 static int debug_usb;
33 static char *log_dir = DEFAULT_LOG_DIR;
34
35 static void die(char *fmt, ...)
36 {
37         va_list args;
38         va_start(args, fmt);
39         if (use_syslog)
40                 vsyslog(LOG_CRIT, fmt, args);
41         else {
42                 vfprintf(stderr, fmt, args);
43                 fprintf(stderr, "\n");
44         }
45         va_end(args);
46         exit(1);
47 }
48
49 static void log_error(char *fmt, ...)
50 {
51         va_list args;
52         va_start(args, fmt);
53         if (use_syslog)
54                 vsyslog(LOG_ERR, fmt, args);
55         else {
56                 vfprintf(stderr, fmt, args);
57                 fprintf(stderr, "\n");
58         }
59         va_end(args);
60 }
61
62 static void log_info(char *fmt, ...)
63 {
64         va_list args;
65         va_start(args, fmt);
66         if (use_syslog)
67                 vsyslog(LOG_INFO, fmt, args);
68         else {
69                 vfprintf(stderr, fmt, args);
70                 fprintf(stderr, "\n");
71         }
72         va_end(args);
73 }
74
75 static void log_pkt(char *fmt, ...)
76 {
77         if (!debug_packets)
78                 return;
79         va_list args;
80         va_start(args, fmt);
81         vprintf(fmt, args);
82         va_end(args);
83 }
84
85 /*** RRD interface ***/
86
87 #define MAX_ARGS 20
88 #define MAX_ARG_SIZE 1024
89
90 static int arg_cnt;
91 static char *arg_ptr[MAX_ARGS+1];
92 static char arg_buf[MAX_ARG_SIZE];
93 static int arg_pos;
94
95 static void arg_new(void)
96 {
97         arg_cnt = 1;
98         arg_pos = 0;
99         arg_ptr[0] = "rrdtool";
100 }
101
102 static void arg_push(const char *fmt, ...)
103 {
104         if (arg_cnt >= MAX_ARGS)
105                 die("MAX_ARGS exceeded");
106         va_list va;
107         va_start(va, fmt);
108         int len = 1 + vsnprintf(arg_buf + arg_pos, MAX_ARG_SIZE - arg_pos, fmt, va);
109         if (arg_pos + len > MAX_ARG_SIZE)
110                 die("MAX_ARG_SIZE exceeded");
111         arg_ptr[arg_cnt++] = arg_buf + arg_pos;
112         arg_ptr[arg_cnt] = NULL;
113         arg_pos += len;
114 }
115
116 static void rrd_point(time_t t, const char *name, double val, char *unit)
117 {
118         char rr_name[256];
119         snprintf(rr_name, sizeof(rr_name), "sensor-%s.rrd", name);
120
121         struct stat st;
122         if (stat(rr_name, &st) < 0 || !st.st_size) {
123                 // We have to create the RRD
124                 log_info("Creating %s", rr_name);
125                 arg_new();
126                 arg_push(rr_name);
127                 arg_push("--start");
128                 arg_push("%d", (int) time(NULL) - 28*86400);
129                 arg_push("--step");
130                 arg_push("60");
131                 if (!strcmp(unit, "%RH"))
132                         arg_push("DS:rh:GAUGE:300:0:100");
133                 else if (!strcmp(unit, "ppm"))
134                         arg_push("DS:ppm:GAUGE:300:0:1000000");
135                 else
136                         arg_push("DS:temp:GAUGE:300:-200:200");
137                 arg_push("RRA:AVERAGE:0.25:1:20160");           // Last 14 days with full resolution
138                 arg_push("RRA:AVERAGE:0.25:60:88800");          // Last 10 years with 1h resolution
139                 arg_push("RRA:MIN:0.25:60:88800");              // including minima and maxima
140                 arg_push("RRA:MAX:0.25:60:88800");
141                 rrd_create(arg_cnt, arg_ptr);
142                 if (rrd_test_error()) {
143                         log_error("rrd_create on %s failed: %s", rr_name, rrd_get_error());
144                         return;
145                 }
146         }
147
148         arg_new();
149         arg_push(rr_name);
150         arg_push("%d:%f", t, val);
151         rrd_update(arg_cnt, arg_ptr);
152         if (rrd_test_error())
153                 log_error("rrd_update on %s failed: %s", rr_name, rrd_get_error());
154 }
155
156 /*** Transforms ***/
157
158 #define TIME_OFFSET 946681200           // Timestamp of 2000-01-01 00:00:00
159
160 static int data_point_counter;          // Since last log message
161
162 static double correct_point(int id, double val, const char **name)
163 {
164         /*
165          *  Manually calculated corrections and renames for my sensors.
166          *  Replace with your formulae.
167          */
168         switch (id) {
169                 case 10415:
170                         *name = "ursarium";
171                         return val - 0.93;
172                 case 10707:
173                         *name = "balcony";
174                         return val - 0.71;
175                 case 19246:
176                         *name = "catarium";
177                         return val + 0.49;
178                 case 19247:
179                         *name = "catarium-rh";
180                         return val;
181                 case 12133:
182                         *name = "outside";
183                         return val + 0.44;
184                 default:
185                         return val;
186         }
187 }
188
189 static void cooked_point(time_t t, int id, double val, char *unit, int q)
190 {
191         char namebuf[16];
192         snprintf(namebuf, sizeof(namebuf), "%d", id);
193         const char *name = namebuf;
194
195         double val2 = correct_point(id, val, &name);
196
197         if (debug_raw_data) {
198                 struct tm tm;
199                 localtime_r(&t, &tm);
200                 char tbuf[64];
201                 strftime(tbuf, sizeof(tbuf), "%Y-%m-%d %H:%M:%S", &tm);
202                 printf("== %s id=%d name=%s val=%.3f val2=%.3f unit=%s q=%d\n", tbuf, id, name, val, val2, unit, q);
203         }
204
205         data_point_counter++;
206         rrd_point(t, name, val2, unit);
207 }
208
209 static void raw_point(int t, int id, int raw, int q)
210 {
211         /*
212          *  The binary blob provided by Arexx contains an embedded XML fragment
213          *  with descriptions of all known sensor types. If you want to see it,
214          *  grep the blob for "<deviceinfo>". The meanings of the parameters are
215          *  as follows:
216          *
217          *      m1, m2          Device type matches if (raw_sensor_id & m1) == m2
218          *      type            Unit measured by the sensor (1=Celsius, 2=RH%, 3=CO2 ppm)
219          *      dm              User-visible sensor ID = raw_sensor_id & dm
220          *      i               1 if the raw value is signed
221          *      p[]             Coefficients of transformation polynomial (x^0 first)
222          *      vLo, vUp        Upper and lower bound on the final value
223          *      scale           Scaling function:
224          *                              0 = identity (default)
225          *                              1 = 10^x
226          *                              2 = exp(x)
227          *                              3 = (x < 0) ? 0 : log10(x)
228          *                              4 = (x < 0) ? 0 : log(x)
229          *
230          *  The raw values are transformed this way:
231          *      - sign-extend if signed
232          *      - apply the transformation polynomial
233          *      - apply the scaling function
234          *      - drop if outside the interval [vLo,vUp]
235          *
236          *  This function applies the necessary transform for sensors we've
237          *  seen in the wild. We deliberately ignore the "dm" parameter as we want
238          *  to report different channels of a single sensor as multiple sensors.
239          */
240
241         double z = raw;
242         double hi, lo;
243         char *unit;
244         int idhi = id & 0xf000;
245
246         if (idhi == 0x1000) {
247                 z = 0.02*z - 273.15;
248                 lo = -200;
249                 hi = 600;
250                 unit = "C";
251         } else if (idhi == 0x2000) {
252                 if (raw >= 0x8000)
253                         z -= 0x10000;
254                 z /= 128;
255                 lo = -60;
256                 hi = 125;
257                 unit = "C";
258         } else if (idhi == 0x4000) {
259                 if (!(id & 1)) {
260                         z = z/100 - 39.6;
261                         lo = -60;
262                         hi = 125;
263                         unit = "C";
264                 } else {
265                         z = -2.8e-6*z*z + 0.0405*z - 4;
266                         lo = 0;
267                         hi = 100.1;
268                         unit = "%RH";
269                 }
270         } else if (idhi == 0x6000) {
271                 if (!(id & 1)) {
272                         if (raw >= 0x8000)
273                                 z -= 0x10000;
274                         z /= 128;
275                         lo = -60;
276                         hi = 125;
277                         unit = "C";
278                 } else {
279                         z = -3.8123e-11*z;
280                         z = (z + 1.9184e-7) * z;
281                         z = (z - 1.0998e-3) * z;
282                         z += 6.56;
283                         z = pow(10, z);
284                         lo = 0;
285                         hi = 1e6;
286                         unit = "ppm";
287                 }
288         } else {
289                 log_error("Unknown sensor type 0x%04x", id);
290                 return;
291         }
292
293         if (z < lo || z > hi) {
294                 log_error("Sensor %d: value %f out of range", id, z);
295                 return;
296         }
297
298         cooked_point(t + TIME_OFFSET, id, z, unit, q);
299 }
300
301 /*** USB interface ***/
302
303 static int find_device(void)
304 {
305         libusb_device **devlist;
306         ssize_t devn = libusb_get_device_list(usb_ctxt, &devlist);
307         if (devn < 0) {
308                 log_error("Cannot enumerate USB devices: error %d", (int) devn);
309                 return 0;
310         }
311
312         for (ssize_t i=0; i<devn; i++) {
313                 struct libusb_device_descriptor desc;
314                 libusb_device *dev = devlist[i];
315                 if (!libusb_get_device_descriptor(dev, &desc)) {
316                         if (desc.idVendor == 0x0451 && desc.idProduct == 0x3211) {
317                                 log_info("Arexx data logger found at usb%d.%d", libusb_get_bus_number(dev), libusb_get_device_address(dev));
318                                 int err;
319                                 if (err = libusb_open(dev, &devh)) {
320                                         log_error("libusb_open() failed: error %d", err);
321                                         goto failed;
322                                 }
323                                 if (err = libusb_claim_interface(devh, 0)) {
324                                         log_error("libusb_claim_interface() failed: error %d", err);
325                                         libusb_close(devh);
326                                         goto failed;
327                                 }
328                                 libusb_free_device_list(devlist, 1);
329                                 return 1;
330                         }
331                 }
332         }
333
334 failed:
335         libusb_free_device_list(devlist, 1);
336         return 0;
337 }
338
339 static void release_device(void)
340 {
341         libusb_release_interface(devh, 0);
342         libusb_reset_device(devh);
343         libusb_close(devh);
344         devh = NULL;
345 }
346
347 static void dump_packet(byte *pkt)
348 {
349         for (int i=0; i<64; i++) {
350                 if (!(i % 16))
351                         log_pkt("\t%02x:", i);
352                 log_pkt(" %02x", pkt[i]);
353                 if (i % 16 == 15)
354                         log_pkt("\n");
355         }
356 }
357
358 static int send_and_receive(byte *req, byte *reply)
359 {
360         if (debug_packets) {
361                 time_t t = time(NULL);
362                 struct tm tm;
363                 localtime_r(&t, &tm);
364
365                 char tbuf[64];
366                 strftime(tbuf, sizeof(tbuf), "%Y-%m-%d %H:%M:%S", &tm);
367                 log_pkt("## %s\n", tbuf);
368         }
369
370         int err, transferred;
371         if (err = libusb_bulk_transfer(devh, 0x01, req, 64, &transferred, 200)) {
372                 if (err == LIBUSB_ERROR_TIMEOUT) {
373                         log_pkt(">> xmit timed out\n");
374                         return 0;
375                 }
376                 log_pkt(">> xmit error %d\n", err);
377                 log_error("Transmit error: %d", err);
378                 return err;
379         }
380         if (debug_packets) {
381                 log_pkt(">> xmit %d bytes\n", transferred);
382                 dump_packet(req);
383         }
384         if (err = libusb_bulk_transfer(devh, 0x81, reply, 64, &transferred, 200)) {
385                 if (err == LIBUSB_ERROR_TIMEOUT) {
386                         log_pkt("<< recv timed out\n");
387                         return 0;
388                 }
389                 log_pkt("<< recv error %d\n", err);
390                 log_error("Receive error: %d", err);
391                 return err;
392         }
393         if (debug_packets)
394                 log_pkt("<< recv %d bytes\n", transferred);
395         while (transferred < 64)
396                 reply[transferred++] = 0xff;
397         if (debug_packets)
398                 dump_packet(reply);
399         return 1;
400 }
401
402 static unsigned int get_be16(byte *p)
403 {
404         return p[1] | (p[0] << 8);
405 }
406
407 static unsigned int get_le16(byte *p)
408 {
409         return p[0] | (p[1] << 8);
410 }
411
412 static unsigned int get_le32(byte *p)
413 {
414         return get_le16(p) | (get_le16(p+2) << 16);
415 }
416
417 static void put_le16(byte *p, unsigned int x)
418 {
419         p[0] = x;
420         p[1] = x >> 8;
421 }
422
423 static void put_le32(byte *p, unsigned int x)
424 {
425         put_le16(p, x);
426         put_le16(p+2, x>>16);
427 }
428
429 static int parse_packet(byte *reply)
430 {
431         if (reply[0]) {
432                 log_error("Unknown packet type %02x", reply[0]);
433                 return 0;
434         }
435
436         int pos = 1;
437         int points = 0;
438         while (pos < 64) {
439                 byte *p = reply + pos;
440                 int len = p[0];
441                 if (!len || len == 0xff)
442                         break;
443                 if (len < 9 || len > 10) {
444                         log_error("Unknown tuple length %02x", len);
445                         break;
446                 }
447                 if (pos + len > 64) {
448                         log_error("Tuple truncated");
449                         break;
450                 }
451                 int id = get_le16(p+1);
452                 int raw = get_be16(p+3);
453                 int t = get_le32(p+5);
454                 int q = (len > 9) ? p[9] : -1;
455                 if (debug_raw_data) {
456                         printf("... %02x: id=%d raw=%d t=%d", len, id, raw, t);
457                         if (len > 9)
458                                 printf(" q=%d", q);
459                         printf("\n");
460                 }
461                 raw_point(t, id, raw, q);
462                 pos += len;
463                 points++;
464         }
465
466         return points;
467 }
468
469 static void set_clock(void)
470 {
471         byte req[64], reply[64];
472         memset(req, 0, 64);
473         req[0] = 4;
474         time_t t = time(NULL);
475         put_le32(req+1, t-TIME_OFFSET);
476         send_and_receive(req, reply);
477
478 #if 0
479         /*
480          *  Original software also sends a packet with type 3 and the timestamp,
481          *  but it does not make any sense, especially as they ignore the sensor
482          *  readings in the answer.
483          */
484         req[0] = 3;
485         send_and_receive(req, reply);
486         parse_packet(reply);
487 #endif
488 }
489
490 /*** Main ***/
491
492 static sigset_t term_sigs;
493 static volatile sig_atomic_t want_shutdown;
494
495 static void sigterm_handler(int sig __attribute__((unused)))
496 {
497         want_shutdown = 1;
498 }
499
500 static void interruptible_msleep(int ms)
501 {
502         sigprocmask(SIG_UNBLOCK, &term_sigs, NULL);
503         struct timespec ts = { .tv_sec = ms/1000, .tv_nsec = (ms%1000) * 1000000 };
504         nanosleep(&ts, NULL);
505         sigprocmask(SIG_BLOCK, &term_sigs, NULL);
506 }
507
508 static const struct option long_options[] = {
509         { "debug",              0, NULL, 'd' },
510         { "log-dir",            1, NULL, 'l' },
511         { "debug-packets",      0, NULL, 'p' },
512         { "debug-raw",          0, NULL, 'r' },
513         { NULL,                 0, NULL, 0 },
514 };
515
516 static void usage(void)
517 {
518         fprintf(stderr, "\n\
519 Usage: arexxd <options>\n\
520 \n\
521 Options:\n\
522 -d, --debug             Debug mode (no chdir, no fork, no syslog)\n\
523 -l, --log-dir=<dir>     Directory where all received data should be stored\n\
524 -p, --debug-packets     Log all packets sent and received\n\
525 -r, --debug-raw         Log conversion from raw values\n\
526 -u, --debug-usb         Enable libusb debug messages (to stdout/stderr)\n\
527 ");
528         exit(1);
529 }
530
531 int main(int argc, char **argv)
532 {
533         int opt;
534         while ((opt = getopt_long(argc, argv, "dl:pru", long_options, NULL)) >= 0)
535                 switch (opt) {
536                         case 'd':
537                                 debug_mode++;
538                                 break;
539                         case 'l':
540                                 log_dir = optarg;
541                                 break;
542                         case 'p':
543                                 debug_packets++;
544                                 break;
545                         case 'r':
546                                 debug_raw_data++;
547                                 break;
548                         case 'u':
549                                 debug_usb++;
550                                 break;
551                         default:
552                                 usage();
553                 }
554         if (optind < argc)
555                 usage();
556
557         int err;
558         if (err = libusb_init(&usb_ctxt))
559                 die("Cannot initialize libusb: error %d", err);
560         if (debug_usb)
561                 libusb_set_debug(usb_ctxt, 3);
562
563         if (!debug_mode) {
564                 if (chdir(log_dir) < 0)
565                         die("Cannot change directory to %s: %m", log_dir);
566                 if (debug_packets || debug_raw_data) {
567                         close(1);
568                         if (open("debug", O_WRONLY | O_CREAT | O_APPEND, 0666) < 0)
569                                 die("Cannot open debug log: %m");
570                         setlinebuf(stdout);
571                 }
572                 openlog("arexxd", LOG_NDELAY, LOG_DAEMON);
573                 pid_t pid = fork();
574                 if (pid < 0)
575                         die("fork() failed: %m");
576                 if (pid)
577                         return 0;
578                 setsid();
579                 use_syslog = 1;
580         }
581
582         struct sigaction sa = { .sa_handler = sigterm_handler };
583         sigaction(SIGTERM, &sa, NULL);
584         sigaction(SIGINT, &sa, NULL);
585
586         sigemptyset(&term_sigs);
587         sigaddset(&term_sigs, SIGTERM);
588         sigaddset(&term_sigs, SIGINT);
589         sigprocmask(SIG_BLOCK, &term_sigs, NULL);
590
591         int inited = 0;
592         while (!want_shutdown) {
593                 if (!find_device()) {
594                         if (!inited) {
595                                 inited = 1;
596                                 log_error("Data logger not connected, waiting until it appears");
597                         }
598                         interruptible_msleep(30000);
599                         continue;
600                 }
601                 log_info("Listening");
602
603                 time_t last_sync = 0;
604                 time_t last_show = 0;
605                 int want_stats = 0;
606                 int want_sleep = 0;
607                 data_point_counter = 0;
608                 while (!want_shutdown) {
609                         time_t now = time(NULL);
610                         if (now > last_sync + 900) {
611                                 log_info("Synchronizing data logger time");
612                                 set_clock();
613                                 last_sync = now;
614                         }
615                         if (want_stats && now > last_show + 300) {
616                                 log_info("Stats: received %d data points", data_point_counter);
617                                 data_point_counter = 0;
618                                 last_show = now;
619                         }
620
621                         byte req[64], reply[64];
622                         memset(req, 0, sizeof(req));
623                         req[0] = 3;
624                         err = send_and_receive(req, reply);
625                         if (err < 0)
626                                 break;
627                         want_sleep = 1;
628                         if (err > 0 && parse_packet(reply))
629                                 want_sleep = 0;
630                         if (want_sleep) {
631                                 interruptible_msleep(4000);
632                                 want_stats = 1;
633                         } else
634                                 interruptible_msleep(5);
635                 }
636
637                 log_info("Disconnecting data logger");
638                 release_device();
639                 inited = 0;
640                 interruptible_msleep(10000);
641         }
642
643         log_info("Terminated");
644         return 0;
645 }