2 * Linux Interfece for Arexx Data Loggers
4 * (c) 2011-2016 Martin Mares <mj@ucw.cz>
19 #include <libusb-1.0/libusb.h>
22 #define DEFAULT_LOG_DIR "/var/log/arexxd"
25 * Data points received from the logger are sometimes corrupted by noise.
26 * This effects not only the measured values, but also sensor IDs and timestamps.
27 * Since rrdtool cannot skip back in time, a random timestamp in the future can
28 * cause all further measurements to be dropped. To minimize impact of these
29 * problems, we drop data points which are too far in the past or in the future.
31 * Furthermore, you can ignore data from unrecognized sensors, i.e., those
32 * which are not handled by correct_point().
34 #define MAX_PAST_TIME 30*86400
35 #define MAX_FUTURE_TIME 300
36 #define IGNORE_UNKNOWN_SENSORS
38 typedef unsigned char byte;
39 typedef unsigned int uint;
40 static libusb_context *usb_ctxt;
41 static libusb_device_handle *devh;
43 static int use_syslog;
44 static int debug_mode;
45 static int debug_packets;
46 static int debug_raw_data;
48 static char *log_dir = DEFAULT_LOG_DIR;
51 static void die(char *fmt, ...)
56 vsyslog(LOG_CRIT, fmt, args);
58 vfprintf(stderr, fmt, args);
59 fprintf(stderr, "\n");
65 static void log_error(char *fmt, ...)
70 vsyslog(LOG_ERR, fmt, args);
72 vfprintf(stderr, fmt, args);
73 fprintf(stderr, "\n");
78 static void log_info(char *fmt, ...)
83 vsyslog(LOG_INFO, fmt, args);
85 vfprintf(stderr, fmt, args);
86 fprintf(stderr, "\n");
91 static void log_pkt(char *fmt, ...)
101 /*** RRD interface ***/
104 #define MAX_ARG_SIZE 1024
107 static char *arg_ptr[MAX_ARGS+1];
108 static char arg_buf[MAX_ARG_SIZE];
111 static void arg_new(void)
115 arg_ptr[0] = "rrdtool";
118 static void arg_push(const char *fmt, ...)
120 if (arg_cnt >= MAX_ARGS)
121 die("MAX_ARGS exceeded");
124 int len = 1 + vsnprintf(arg_buf + arg_pos, MAX_ARG_SIZE - arg_pos, fmt, va);
125 if (arg_pos + len > MAX_ARG_SIZE)
126 die("MAX_ARG_SIZE exceeded");
127 arg_ptr[arg_cnt++] = arg_buf + arg_pos;
128 arg_ptr[arg_cnt] = NULL;
132 static void rrd_point(time_t t, const char *name, double val, char *unit)
135 snprintf(rr_name, sizeof(rr_name), "sensor-%s.rrd", name);
138 if (stat(rr_name, &st) < 0 || !st.st_size) {
139 // We have to create the RRD
140 log_info("Creating %s", rr_name);
144 arg_push("%d", (int) time(NULL) - 28*86400);
147 if (!strcmp(unit, "%RH"))
148 arg_push("DS:rh:GAUGE:300:0:100");
149 else if (!strcmp(unit, "ppm"))
150 arg_push("DS:ppm:GAUGE:300:0:1000000");
152 arg_push("DS:temp:GAUGE:300:-200:200");
153 arg_push("RRA:AVERAGE:0.25:1:20160"); // Last 14 days with full resolution
154 arg_push("RRA:AVERAGE:0.25:60:88800"); // Last 10 years with 1h resolution
155 arg_push("RRA:MIN:0.25:60:88800"); // including minima and maxima
156 arg_push("RRA:MAX:0.25:60:88800");
157 rrd_create(arg_cnt, arg_ptr);
158 if (rrd_test_error()) {
159 log_error("rrd_create on %s failed: %s", rr_name, rrd_get_error());
167 arg_push("%d:%f", t, val);
168 rrd_update(arg_cnt, arg_ptr);
169 if (rrd_test_error()) {
170 log_error("rrd_update on %s failed: %s", rr_name, rrd_get_error());
177 #define TIME_OFFSET 946681200 // Timestamp of 2000-01-01 00:00:00
179 static int data_point_counter; // Since last log message
180 static time_t packet_rx_time;
182 static double correct_point(uint id, double val, const char **name)
185 * Manually calculated corrections and renames for my sensors.
186 * Replace with your formulae.
196 *name = "machinarium";
208 #ifdef IGNORE_UNKNOWN_SENSORS
215 static void cooked_point(time_t t, uint id, double val, char *unit, int q)
218 snprintf(namebuf, sizeof(namebuf), "%u", id);
219 const char *name = namebuf;
221 double val2 = correct_point(id, val, &name);
223 if (debug_raw_data) {
225 localtime_r(&t, &tm);
227 strftime(tbuf, sizeof(tbuf), "%Y-%m-%d %H:%M:%S", &tm);
228 printf("== %s id=%d name=%s val=%.3f val2=%.3f unit=%s q=%d\n", tbuf, id, name, val, val2, unit, q);
232 log_error("Ignored data from unknown sensor %d", id);
235 if (t < packet_rx_time - MAX_PAST_TIME) {
236 log_error("Data point from sensor %d too far in the past (%d sec)", packet_rx_time - t);
239 if (t > packet_rx_time + MAX_FUTURE_TIME) {
240 log_error("Data point from sensor %d too far in the future (%d sec)", t - packet_rx_time);
244 data_point_counter++;
245 rrd_point(t, name, val2, unit);
248 static void raw_point(uint t, uint id, int raw, int q)
251 * The binary blob provided by Arexx contains an embedded XML fragment
252 * with descriptions of all known sensor types. If you want to see it,
253 * grep the blob for "<deviceinfo>". The meanings of the parameters are
256 * m1, m2 Device type matches if (raw_sensor_id & m1) == m2
257 * type Unit measured by the sensor (1=Celsius, 2=RH%, 3=CO2 ppm)
258 * dm User-visible sensor ID = raw_sensor_id & dm
259 * i 1 if the raw value is signed
260 * p[] Coefficients of transformation polynomial (x^0 first)
261 * vLo, vUp Upper and lower bound on the final value
262 * scale Scaling function:
263 * 0 = identity (default)
266 * 3 = (x < 0) ? 0 : log10(x)
267 * 4 = (x < 0) ? 0 : log(x)
269 * The raw values are transformed this way:
270 * - sign-extend if signed
271 * - apply the transformation polynomial
272 * - apply the scaling function
273 * - drop if outside the interval [vLo,vUp]
275 * This function applies the necessary transform for sensors we've
276 * seen in the wild. We deliberately ignore the "dm" parameter as we want
277 * to report different channels of a single sensor as multiple sensors.
283 uint idhi = id & 0xfffff000;
284 uint idext = id & 0xf0000000;
286 if (idhi == 0x1000) {
291 } else if (idhi == 0x2000 || idext == 0x20000000) {
298 } else if (idhi == 0x4000) {
305 z = -2.8e-6*z*z + 0.0405*z - 4;
310 } else if (idhi == 0x6000) {
320 z = (z + 1.9184e-7) * z;
321 z = (z - 1.0998e-3) * z;
329 log_error("Unknown sensor type 0x%08x", id);
333 if (z < lo || z > hi) {
334 log_error("Sensor %d: value %f out of range", id, z);
338 cooked_point(t + TIME_OFFSET, id & 0x0fffffff, z, unit, q);
341 /*** USB interface ***/
343 static int rx_endpoint, tx_endpoint;
345 static int parse_descriptors(libusb_device *dev)
348 struct libusb_config_descriptor *desc;
350 if (err = libusb_get_active_config_descriptor(dev, &desc)) {
351 log_error("libusb_get_config_descriptor failed: error %d", err);
354 if (desc->bNumInterfaces != 1) {
355 log_error("Unexpected number of interfaces: %d", desc->bNumInterfaces);
359 const struct libusb_interface *iface = &desc->interface[0];
360 if (iface->num_altsetting != 1) {
361 log_error("Unexpected number of alternate interface settings: %d", iface->num_altsetting);
365 const struct libusb_interface_descriptor *ifd = &iface->altsetting[0];
366 if (ifd->bNumEndpoints != 2) {
367 log_error("Unexpected number of endpoints: %d", ifd->bNumEndpoints);
371 rx_endpoint = tx_endpoint = -1;
372 for (int i=0; i<2; i++) {
373 const struct libusb_endpoint_descriptor *epd = &ifd->endpoint[i];
374 if (epd->bEndpointAddress & 0x80)
375 rx_endpoint = epd->bEndpointAddress;
377 tx_endpoint = epd->bEndpointAddress;
379 if (rx_endpoint < 0 || tx_endpoint < 0) {
380 log_error("Failed to identify endpoints");
384 log_pkt("Found endpoints: rx==%02x tx=%02x\n", rx_endpoint, tx_endpoint);
385 libusb_free_config_descriptor(desc);
389 libusb_free_config_descriptor(desc);
393 static int find_device(void)
395 libusb_device **devlist;
396 ssize_t devn = libusb_get_device_list(usb_ctxt, &devlist);
398 log_error("Cannot enumerate USB devices: error %d", (int) devn);
402 for (ssize_t i=0; i<devn; i++) {
403 struct libusb_device_descriptor desc;
404 libusb_device *dev = devlist[i];
405 if (!libusb_get_device_descriptor(dev, &desc)) {
406 if (desc.idVendor == 0x0451 && desc.idProduct == 0x3211) {
407 log_info("Arexx data logger found at usb%d.%d", libusb_get_bus_number(dev), libusb_get_device_address(dev));
408 if (!parse_descriptors(dev))
411 if (err = libusb_open(dev, &devh)) {
412 log_error("libusb_open() failed: error %d", err);
415 if (err = libusb_claim_interface(devh, 0)) {
416 log_error("libusb_claim_interface() failed: error %d", err);
420 libusb_free_device_list(devlist, 1);
427 libusb_free_device_list(devlist, 1);
431 static void release_device(void)
433 libusb_release_interface(devh, 0);
434 libusb_reset_device(devh);
439 static void dump_packet(byte *pkt)
441 for (int i=0; i<64; i++) {
443 log_pkt("\t%02x:", i);
444 log_pkt(" %02x", pkt[i]);
450 static void my_msleep(int ms)
452 struct timespec ts = { .tv_sec = ms/1000, .tv_nsec = (ms%1000) * 1000000 };
453 nanosleep(&ts, NULL);
456 static int send_and_receive(byte *req, byte *reply)
459 time_t t = time(NULL);
461 localtime_r(&t, &tm);
464 strftime(tbuf, sizeof(tbuf), "%Y-%m-%d %H:%M:%S", &tm);
465 log_pkt("## %s\n", tbuf);
468 int err, transferred;
469 if (err = libusb_bulk_transfer(devh, tx_endpoint, req, 64, &transferred, 200)) {
470 if (err == LIBUSB_ERROR_TIMEOUT) {
471 log_pkt(">> xmit timed out\n");
474 log_pkt(">> xmit error %d\n", err);
475 log_error("Transmit error: %d", err);
479 log_pkt(">> xmit %d bytes\n", transferred);
483 if (err = libusb_bulk_transfer(devh, rx_endpoint, reply, 64, &transferred, 200)) {
484 if (err == LIBUSB_ERROR_TIMEOUT) {
485 log_pkt("<< recv timed out\n");
488 log_pkt("<< recv error %d\n", err);
489 log_error("Receive error: %d", err);
492 packet_rx_time = time(NULL);
494 log_pkt("<< recv %d bytes\n", transferred);
495 while (transferred < 64)
496 reply[transferred++] = 0xff;
502 static unsigned int get_be16(byte *p)
504 return p[1] | (p[0] << 8);
507 static unsigned int get_le16(byte *p)
509 return p[0] | (p[1] << 8);
512 static unsigned int get_le32(byte *p)
514 return get_le16(p) | (get_le16(p+2) << 16);
517 static void put_le16(byte *p, unsigned int x)
523 static void put_le32(byte *p, unsigned int x)
526 put_le16(p+2, x>>16);
529 static int parse_packet(byte *reply)
532 log_error("Unknown packet type %02x", reply[0]);
539 byte *p = reply + pos;
541 if (!len || len == 0xff)
543 if (pos + len > 64) {
544 log_error("Tuple truncated");
556 q = (len > 9) ? p[9] : -1;
565 log_error("Unknown tuple length %02x", len);
569 if (debug_raw_data) {
570 printf("... %02x: id=%08x raw=%d t=%u", len, id, raw, t);
575 raw_point(t, id, raw, q);
584 static void set_clock(void)
586 byte req[64], reply[64];
589 time_t t = time(NULL);
590 put_le32(req+1, t-TIME_OFFSET);
591 send_and_receive(req, reply);
595 * Original software also sends a packet with type 3 and the timestamp,
596 * but it does not make any sense, especially as they ignore the sensor
597 * readings in the answer.
600 send_and_receive(req, reply);
607 static sigset_t term_sigs;
608 static volatile sig_atomic_t want_shutdown;
610 static void sigterm_handler(int sig __attribute__((unused)))
615 static void interruptible_msleep(int ms)
617 sigprocmask(SIG_UNBLOCK, &term_sigs, NULL);
619 sigprocmask(SIG_BLOCK, &term_sigs, NULL);
622 static const struct option long_options[] = {
623 { "debug", 0, NULL, 'd' },
624 { "log-dir", 1, NULL, 'l' },
625 { "no-fork", 0, NULL, 'n' },
626 { "debug-packets", 0, NULL, 'p' },
627 { "debug-raw", 0, NULL, 'r' },
628 { "version", 0, NULL, 'V' },
629 { NULL, 0, NULL, 0 },
632 static void usage(void)
635 Usage: arexxd <options>\n\
638 -d, --debug Debug mode (no chdir, no fork, no syslog)\n\
639 -l, --log-dir=<dir> Directory where all received data should be stored\n\
640 -n, --no-fork Do not fork\n\
641 -p, --debug-packets Log all packets sent and received\n\
642 -r, --debug-raw Log conversion from raw values\n\
643 -u, --debug-usb Enable libusb debug messages (to stdout/stderr)\n\
644 -V, --version Show daemon version\n\
649 int main(int argc, char **argv)
652 while ((opt = getopt_long(argc, argv, "dl:npruV", long_options, NULL)) >= 0)
673 printf("arexxd " AREXXD_VERSION "\n");
674 printf("(c) 2011-2012 Martin Mares <mj@ucw.cz>\n");
683 if (err = libusb_init(&usb_ctxt))
684 die("Cannot initialize libusb: error %d", err);
686 libusb_set_debug(usb_ctxt, 3);
689 if (chdir(log_dir) < 0)
690 die("Cannot change directory to %s: %m", log_dir);
691 if (debug_packets || debug_raw_data) {
693 if (open("debug", O_WRONLY | O_CREAT | O_APPEND, 0666) < 0)
694 die("Cannot open debug log: %m");
697 openlog("arexxd", LOG_NDELAY, LOG_DAEMON);
701 die("fork() failed: %m");
709 struct sigaction sa = { .sa_handler = sigterm_handler };
710 sigaction(SIGTERM, &sa, NULL);
711 sigaction(SIGINT, &sa, NULL);
713 sigemptyset(&term_sigs);
714 sigaddset(&term_sigs, SIGTERM);
715 sigaddset(&term_sigs, SIGINT);
716 sigprocmask(SIG_BLOCK, &term_sigs, NULL);
719 while (!want_shutdown) {
720 if (!find_device()) {
723 log_error("Data logger not connected, waiting until it appears");
725 interruptible_msleep(30000);
728 log_info("Listening");
730 time_t last_sync = 0;
731 time_t last_show = 0;
734 data_point_counter = 0;
735 while (!want_shutdown) {
736 time_t now = time(NULL);
737 if (now > last_sync + 900) {
738 log_info("Synchronizing data logger time");
742 if (want_stats && now > last_show + 300) {
743 log_info("Stats: received %d data points", data_point_counter);
744 data_point_counter = 0;
748 byte req[64], reply[64];
749 memset(req, 0, sizeof(req));
751 err = send_and_receive(req, reply);
755 if (err > 0 && parse_packet(reply))
758 interruptible_msleep(4000);
761 interruptible_msleep(5);
764 log_info("Disconnecting data logger");
767 interruptible_msleep(10000);
770 log_info("Terminated");