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