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