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