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