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