2 * Linux Interfece for Arexx Data Loggers
4 * (c) 2011-2012 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 static libusb_context *usb_ctxt;
40 static libusb_device_handle *devh;
42 static int use_syslog;
43 static int debug_mode;
44 static int debug_packets;
45 static int debug_raw_data;
47 static char *log_dir = DEFAULT_LOG_DIR;
50 static void die(char *fmt, ...)
55 vsyslog(LOG_CRIT, fmt, args);
57 vfprintf(stderr, fmt, args);
58 fprintf(stderr, "\n");
64 static void log_error(char *fmt, ...)
69 vsyslog(LOG_ERR, fmt, args);
71 vfprintf(stderr, fmt, args);
72 fprintf(stderr, "\n");
77 static void log_info(char *fmt, ...)
82 vsyslog(LOG_INFO, fmt, args);
84 vfprintf(stderr, fmt, args);
85 fprintf(stderr, "\n");
90 static void log_pkt(char *fmt, ...)
100 /*** RRD interface ***/
103 #define MAX_ARG_SIZE 1024
106 static char *arg_ptr[MAX_ARGS+1];
107 static char arg_buf[MAX_ARG_SIZE];
110 static void arg_new(void)
114 arg_ptr[0] = "rrdtool";
117 static void arg_push(const char *fmt, ...)
119 if (arg_cnt >= MAX_ARGS)
120 die("MAX_ARGS exceeded");
123 int len = 1 + vsnprintf(arg_buf + arg_pos, MAX_ARG_SIZE - arg_pos, fmt, va);
124 if (arg_pos + len > MAX_ARG_SIZE)
125 die("MAX_ARG_SIZE exceeded");
126 arg_ptr[arg_cnt++] = arg_buf + arg_pos;
127 arg_ptr[arg_cnt] = NULL;
131 static void rrd_point(time_t t, const char *name, double val, char *unit)
134 snprintf(rr_name, sizeof(rr_name), "sensor-%s.rrd", name);
137 if (stat(rr_name, &st) < 0 || !st.st_size) {
138 // We have to create the RRD
139 log_info("Creating %s", rr_name);
143 arg_push("%d", (int) time(NULL) - 28*86400);
146 if (!strcmp(unit, "%RH"))
147 arg_push("DS:rh:GAUGE:300:0:100");
148 else if (!strcmp(unit, "ppm"))
149 arg_push("DS:ppm:GAUGE:300:0:1000000");
151 arg_push("DS:temp:GAUGE:300:-200:200");
152 arg_push("RRA:AVERAGE:0.25:1:20160"); // Last 14 days with full resolution
153 arg_push("RRA:AVERAGE:0.25:60:88800"); // Last 10 years with 1h resolution
154 arg_push("RRA:MIN:0.25:60:88800"); // including minima and maxima
155 arg_push("RRA:MAX:0.25:60:88800");
156 rrd_create(arg_cnt, arg_ptr);
157 if (rrd_test_error()) {
158 log_error("rrd_create on %s failed: %s", rr_name, rrd_get_error());
166 arg_push("%d:%f", t, val);
167 rrd_update(arg_cnt, arg_ptr);
168 if (rrd_test_error()) {
169 log_error("rrd_update on %s failed: %s", rr_name, rrd_get_error());
176 #define TIME_OFFSET 946681200 // Timestamp of 2000-01-01 00:00:00
178 static int data_point_counter; // Since last log message
179 static time_t packet_rx_time;
181 static double correct_point(int id, double val, const char **name)
184 * Manually calculated corrections and renames for my sensors.
185 * Replace with your formulae.
201 *name = "catarium-rh";
207 #ifdef IGNORE_UNKNOWN_SENSORS
214 static void cooked_point(time_t t, int id, double val, char *unit, int q)
217 snprintf(namebuf, sizeof(namebuf), "%d", id);
218 const char *name = namebuf;
220 double val2 = correct_point(id, val, &name);
222 if (debug_raw_data) {
224 localtime_r(&t, &tm);
226 strftime(tbuf, sizeof(tbuf), "%Y-%m-%d %H:%M:%S", &tm);
227 printf("== %s id=%d name=%s val=%.3f val2=%.3f unit=%s q=%d\n", tbuf, id, name, val, val2, unit, q);
231 log_error("Ignored data from unknown sensor %d", id);
234 if (t < packet_rx_time - MAX_PAST_TIME) {
235 log_error("Data point from sensor %d too far in the past (%d sec)", packet_rx_time - t);
238 if (t > packet_rx_time + MAX_FUTURE_TIME) {
239 log_error("Data point from sensor %d too far in the future (%d sec)", t - packet_rx_time);
243 data_point_counter++;
244 rrd_point(t, name, val2, unit);
247 static void raw_point(int t, int id, int raw, int q)
250 * The binary blob provided by Arexx contains an embedded XML fragment
251 * with descriptions of all known sensor types. If you want to see it,
252 * grep the blob for "<deviceinfo>". The meanings of the parameters are
255 * m1, m2 Device type matches if (raw_sensor_id & m1) == m2
256 * type Unit measured by the sensor (1=Celsius, 2=RH%, 3=CO2 ppm)
257 * dm User-visible sensor ID = raw_sensor_id & dm
258 * i 1 if the raw value is signed
259 * p[] Coefficients of transformation polynomial (x^0 first)
260 * vLo, vUp Upper and lower bound on the final value
261 * scale Scaling function:
262 * 0 = identity (default)
265 * 3 = (x < 0) ? 0 : log10(x)
266 * 4 = (x < 0) ? 0 : log(x)
268 * The raw values are transformed this way:
269 * - sign-extend if signed
270 * - apply the transformation polynomial
271 * - apply the scaling function
272 * - drop if outside the interval [vLo,vUp]
274 * This function applies the necessary transform for sensors we've
275 * seen in the wild. We deliberately ignore the "dm" parameter as we want
276 * to report different channels of a single sensor as multiple sensors.
282 int idhi = id & 0xf000;
284 if (idhi == 0x1000) {
289 } else if (idhi == 0x2000) {
296 } else if (idhi == 0x4000) {
303 z = -2.8e-6*z*z + 0.0405*z - 4;
308 } else if (idhi == 0x6000) {
318 z = (z + 1.9184e-7) * z;
319 z = (z - 1.0998e-3) * z;
327 log_error("Unknown sensor type 0x%04x", id);
331 if (z < lo || z > hi) {
332 log_error("Sensor %d: value %f out of range", id, z);
336 cooked_point(t + TIME_OFFSET, id, z, unit, q);
339 /*** USB interface ***/
341 static int rx_endpoint, tx_endpoint;
343 static int parse_descriptors(libusb_device *dev)
346 struct libusb_config_descriptor *desc;
348 if (err = libusb_get_active_config_descriptor(dev, &desc)) {
349 log_error("libusb_get_config_descriptor failed: error %d", err);
352 if (desc->bNumInterfaces != 1) {
353 log_error("Unexpected number of interfaces: %d", desc->bNumInterfaces);
357 const struct libusb_interface *iface = &desc->interface[0];
358 if (iface->num_altsetting != 1) {
359 log_error("Unexpected number of alternate interface settings: %d", iface->num_altsetting);
363 const struct libusb_interface_descriptor *ifd = &iface->altsetting[0];
364 if (ifd->bNumEndpoints != 2) {
365 log_error("Unexpected number of endpoints: %d", ifd->bNumEndpoints);
369 rx_endpoint = tx_endpoint = -1;
370 for (int i=0; i<2; i++) {
371 const struct libusb_endpoint_descriptor *epd = &ifd->endpoint[i];
372 if (epd->bEndpointAddress & 0x80)
373 rx_endpoint = epd->bEndpointAddress;
375 tx_endpoint = epd->bEndpointAddress;
377 if (rx_endpoint < 0 || tx_endpoint < 0) {
378 log_error("Failed to identify endpoints");
382 log_pkt("Found endpoints: rx==%02x tx=%02x\n", rx_endpoint, tx_endpoint);
383 libusb_free_config_descriptor(desc);
387 libusb_free_config_descriptor(desc);
391 static int find_device(void)
393 libusb_device **devlist;
394 ssize_t devn = libusb_get_device_list(usb_ctxt, &devlist);
396 log_error("Cannot enumerate USB devices: error %d", (int) devn);
400 for (ssize_t i=0; i<devn; i++) {
401 struct libusb_device_descriptor desc;
402 libusb_device *dev = devlist[i];
403 if (!libusb_get_device_descriptor(dev, &desc)) {
404 if (desc.idVendor == 0x0451 && desc.idProduct == 0x3211) {
405 log_info("Arexx data logger found at usb%d.%d", libusb_get_bus_number(dev), libusb_get_device_address(dev));
406 if (!parse_descriptors(dev))
409 if (err = libusb_open(dev, &devh)) {
410 log_error("libusb_open() failed: error %d", err);
413 if (err = libusb_claim_interface(devh, 0)) {
414 log_error("libusb_claim_interface() failed: error %d", err);
418 libusb_free_device_list(devlist, 1);
425 libusb_free_device_list(devlist, 1);
429 static void release_device(void)
431 libusb_release_interface(devh, 0);
432 libusb_reset_device(devh);
437 static void dump_packet(byte *pkt)
439 for (int i=0; i<64; i++) {
441 log_pkt("\t%02x:", i);
442 log_pkt(" %02x", pkt[i]);
448 static void my_msleep(int ms)
450 struct timespec ts = { .tv_sec = ms/1000, .tv_nsec = (ms%1000) * 1000000 };
451 nanosleep(&ts, NULL);
454 static int send_and_receive(byte *req, byte *reply)
457 time_t t = time(NULL);
459 localtime_r(&t, &tm);
462 strftime(tbuf, sizeof(tbuf), "%Y-%m-%d %H:%M:%S", &tm);
463 log_pkt("## %s\n", tbuf);
466 int err, transferred;
467 if (err = libusb_bulk_transfer(devh, tx_endpoint, req, 64, &transferred, 200)) {
468 if (err == LIBUSB_ERROR_TIMEOUT) {
469 log_pkt(">> xmit timed out\n");
472 log_pkt(">> xmit error %d\n", err);
473 log_error("Transmit error: %d", err);
477 log_pkt(">> xmit %d bytes\n", transferred);
481 if (err = libusb_bulk_transfer(devh, rx_endpoint, reply, 64, &transferred, 200)) {
482 if (err == LIBUSB_ERROR_TIMEOUT) {
483 log_pkt("<< recv timed out\n");
486 log_pkt("<< recv error %d\n", err);
487 log_error("Receive error: %d", err);
490 packet_rx_time = time(NULL);
492 log_pkt("<< recv %d bytes\n", transferred);
493 while (transferred < 64)
494 reply[transferred++] = 0xff;
500 static unsigned int get_be16(byte *p)
502 return p[1] | (p[0] << 8);
505 static unsigned int get_le16(byte *p)
507 return p[0] | (p[1] << 8);
510 static unsigned int get_le32(byte *p)
512 return get_le16(p) | (get_le16(p+2) << 16);
515 static void put_le16(byte *p, unsigned int x)
521 static void put_le32(byte *p, unsigned int x)
524 put_le16(p+2, x>>16);
527 static int parse_packet(byte *reply)
530 log_error("Unknown packet type %02x", reply[0]);
537 byte *p = reply + pos;
539 if (!len || len == 0xff)
541 if (len < 9 || len > 10) {
542 log_error("Unknown tuple length %02x", len);
545 if (pos + len > 64) {
546 log_error("Tuple truncated");
549 int id = get_le16(p+1);
550 int raw = get_be16(p+3);
551 int t = get_le32(p+5);
552 int q = (len > 9) ? p[9] : -1;
553 if (debug_raw_data) {
554 printf("... %02x: id=%d raw=%d t=%d", len, id, raw, t);
559 raw_point(t, id, raw, q);
567 static void set_clock(void)
569 byte req[64], reply[64];
572 time_t t = time(NULL);
573 put_le32(req+1, t-TIME_OFFSET);
574 send_and_receive(req, reply);
578 * Original software also sends a packet with type 3 and the timestamp,
579 * but it does not make any sense, especially as they ignore the sensor
580 * readings in the answer.
583 send_and_receive(req, reply);
590 static sigset_t term_sigs;
591 static volatile sig_atomic_t want_shutdown;
593 static void sigterm_handler(int sig __attribute__((unused)))
598 static void interruptible_msleep(int ms)
600 sigprocmask(SIG_UNBLOCK, &term_sigs, NULL);
602 sigprocmask(SIG_BLOCK, &term_sigs, NULL);
605 static const struct option long_options[] = {
606 { "debug", 0, NULL, 'd' },
607 { "log-dir", 1, NULL, 'l' },
608 { "no-fork", 0, NULL, 'n' },
609 { "debug-packets", 0, NULL, 'p' },
610 { "debug-raw", 0, NULL, 'r' },
611 { "version", 0, NULL, 'V' },
612 { NULL, 0, NULL, 0 },
615 static void usage(void)
618 Usage: arexxd <options>\n\
621 -d, --debug Debug mode (no chdir, no fork, no syslog)\n\
622 -l, --log-dir=<dir> Directory where all received data should be stored\n\
623 -n, --no-fork Do not fork\n\
624 -p, --debug-packets Log all packets sent and received\n\
625 -r, --debug-raw Log conversion from raw values\n\
626 -u, --debug-usb Enable libusb debug messages (to stdout/stderr)\n\
627 -V, --version Show daemon version\n\
632 int main(int argc, char **argv)
635 while ((opt = getopt_long(argc, argv, "dl:npruV", long_options, NULL)) >= 0)
656 printf("arexxd " AREXXD_VERSION "\n");
657 printf("(c) 2011-2012 Martin Mares <mj@ucw.cz>\n");
666 if (err = libusb_init(&usb_ctxt))
667 die("Cannot initialize libusb: error %d", err);
669 libusb_set_debug(usb_ctxt, 3);
672 if (chdir(log_dir) < 0)
673 die("Cannot change directory to %s: %m", log_dir);
674 if (debug_packets || debug_raw_data) {
676 if (open("debug", O_WRONLY | O_CREAT | O_APPEND, 0666) < 0)
677 die("Cannot open debug log: %m");
680 openlog("arexxd", LOG_NDELAY, LOG_DAEMON);
684 die("fork() failed: %m");
692 struct sigaction sa = { .sa_handler = sigterm_handler };
693 sigaction(SIGTERM, &sa, NULL);
694 sigaction(SIGINT, &sa, NULL);
696 sigemptyset(&term_sigs);
697 sigaddset(&term_sigs, SIGTERM);
698 sigaddset(&term_sigs, SIGINT);
699 sigprocmask(SIG_BLOCK, &term_sigs, NULL);
702 while (!want_shutdown) {
703 if (!find_device()) {
706 log_error("Data logger not connected, waiting until it appears");
708 interruptible_msleep(30000);
711 log_info("Listening");
713 time_t last_sync = 0;
714 time_t last_show = 0;
717 data_point_counter = 0;
718 while (!want_shutdown) {
719 time_t now = time(NULL);
720 if (now > last_sync + 900) {
721 log_info("Synchronizing data logger time");
725 if (want_stats && now > last_show + 300) {
726 log_info("Stats: received %d data points", data_point_counter);
727 data_point_counter = 0;
731 byte req[64], reply[64];
732 memset(req, 0, sizeof(req));
734 err = send_and_receive(req, reply);
738 if (err > 0 && parse_packet(reply))
741 interruptible_msleep(4000);
744 interruptible_msleep(5);
747 log_info("Disconnecting data logger");
750 interruptible_msleep(10000);
753 log_info("Terminated");