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