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