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