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 #undef 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;
49 static void die(char *fmt, ...)
54 vsyslog(LOG_CRIT, fmt, args);
56 vfprintf(stderr, fmt, args);
57 fprintf(stderr, "\n");
63 static void log_error(char *fmt, ...)
68 vsyslog(LOG_ERR, fmt, args);
70 vfprintf(stderr, fmt, args);
71 fprintf(stderr, "\n");
76 static void log_info(char *fmt, ...)
81 vsyslog(LOG_INFO, fmt, args);
83 vfprintf(stderr, fmt, args);
84 fprintf(stderr, "\n");
89 static void log_pkt(char *fmt, ...)
99 /*** RRD interface ***/
102 #define MAX_ARG_SIZE 1024
105 static char *arg_ptr[MAX_ARGS+1];
106 static char arg_buf[MAX_ARG_SIZE];
109 static void arg_new(void)
113 arg_ptr[0] = "rrdtool";
116 static void arg_push(const char *fmt, ...)
118 if (arg_cnt >= MAX_ARGS)
119 die("MAX_ARGS exceeded");
122 int len = 1 + vsnprintf(arg_buf + arg_pos, MAX_ARG_SIZE - arg_pos, fmt, va);
123 if (arg_pos + len > MAX_ARG_SIZE)
124 die("MAX_ARG_SIZE exceeded");
125 arg_ptr[arg_cnt++] = arg_buf + arg_pos;
126 arg_ptr[arg_cnt] = NULL;
130 static void rrd_point(time_t t, const char *name, double val, char *unit)
133 snprintf(rr_name, sizeof(rr_name), "sensor-%s.rrd", name);
136 if (stat(rr_name, &st) < 0 || !st.st_size) {
137 // We have to create the RRD
138 log_info("Creating %s", rr_name);
142 arg_push("%d", (int) time(NULL) - 28*86400);
145 if (!strcmp(unit, "%RH"))
146 arg_push("DS:rh:GAUGE:300:0:100");
147 else if (!strcmp(unit, "ppm"))
148 arg_push("DS:ppm:GAUGE:300:0:1000000");
150 arg_push("DS:temp:GAUGE:300:-200:200");
151 arg_push("RRA:AVERAGE:0.25:1:20160"); // Last 14 days with full resolution
152 arg_push("RRA:AVERAGE:0.25:60:88800"); // Last 10 years with 1h resolution
153 arg_push("RRA:MIN:0.25:60:88800"); // including minima and maxima
154 arg_push("RRA:MAX:0.25:60:88800");
155 rrd_create(arg_cnt, arg_ptr);
156 if (rrd_test_error()) {
157 log_error("rrd_create on %s failed: %s", rr_name, rrd_get_error());
165 arg_push("%d:%f", t, val);
166 rrd_update(arg_cnt, arg_ptr);
167 if (rrd_test_error()) {
168 log_error("rrd_update on %s failed: %s", rr_name, rrd_get_error());
175 #define TIME_OFFSET 946681200 // Timestamp of 2000-01-01 00:00:00
177 static int data_point_counter; // Since last log message
178 static time_t packet_rx_time;
180 static double correct_point(int id, double val, const char **name)
183 * Manually calculated corrections and renames for my sensors.
184 * Replace with your formulae.
197 *name = "catarium-rh";
203 #ifdef IGNORE_UNKNOWN_SENSORS
210 static void cooked_point(time_t t, int id, double val, char *unit, int q)
213 snprintf(namebuf, sizeof(namebuf), "%d", id);
214 const char *name = namebuf;
216 double val2 = correct_point(id, val, &name);
218 if (debug_raw_data) {
220 localtime_r(&t, &tm);
222 strftime(tbuf, sizeof(tbuf), "%Y-%m-%d %H:%M:%S", &tm);
223 printf("== %s id=%d name=%s val=%.3f val2=%.3f unit=%s q=%d\n", tbuf, id, name, val, val2, unit, q);
227 log_error("Ignored data from unknown sensor %d", id);
230 if (t < packet_rx_time - MAX_PAST_TIME) {
231 log_error("Data point from sensor %d too far in the past (%d sec)", packet_rx_time - t);
234 if (t > packet_rx_time + MAX_FUTURE_TIME) {
235 log_error("Data point from sensor %d too far in the future (%d sec)", t - packet_rx_time);
239 data_point_counter++;
240 rrd_point(t, name, val2, unit);
243 static void raw_point(int t, int id, int raw, int q)
246 * The binary blob provided by Arexx contains an embedded XML fragment
247 * with descriptions of all known sensor types. If you want to see it,
248 * grep the blob for "<deviceinfo>". The meanings of the parameters are
251 * m1, m2 Device type matches if (raw_sensor_id & m1) == m2
252 * type Unit measured by the sensor (1=Celsius, 2=RH%, 3=CO2 ppm)
253 * dm User-visible sensor ID = raw_sensor_id & dm
254 * i 1 if the raw value is signed
255 * p[] Coefficients of transformation polynomial (x^0 first)
256 * vLo, vUp Upper and lower bound on the final value
257 * scale Scaling function:
258 * 0 = identity (default)
261 * 3 = (x < 0) ? 0 : log10(x)
262 * 4 = (x < 0) ? 0 : log(x)
264 * The raw values are transformed this way:
265 * - sign-extend if signed
266 * - apply the transformation polynomial
267 * - apply the scaling function
268 * - drop if outside the interval [vLo,vUp]
270 * This function applies the necessary transform for sensors we've
271 * seen in the wild. We deliberately ignore the "dm" parameter as we want
272 * to report different channels of a single sensor as multiple sensors.
278 int idhi = id & 0xf000;
280 if (idhi == 0x1000) {
285 } else if (idhi == 0x2000) {
292 } else if (idhi == 0x4000) {
299 z = -2.8e-6*z*z + 0.0405*z - 4;
304 } else if (idhi == 0x6000) {
314 z = (z + 1.9184e-7) * z;
315 z = (z - 1.0998e-3) * z;
323 log_error("Unknown sensor type 0x%04x", id);
327 if (z < lo || z > hi) {
328 log_error("Sensor %d: value %f out of range", id, z);
332 cooked_point(t + TIME_OFFSET, id, z, unit, q);
335 /*** USB interface ***/
337 static int rx_endpoint, tx_endpoint;
339 static int parse_descriptors(libusb_device *dev)
342 struct libusb_config_descriptor *desc;
344 if (err = libusb_get_active_config_descriptor(dev, &desc)) {
345 log_error("libusb_get_config_descriptor failed: error %d", err);
348 if (desc->bNumInterfaces != 1) {
349 log_error("Unexpected number of interfaces: %d", desc->bNumInterfaces);
353 const struct libusb_interface *iface = &desc->interface[0];
354 if (iface->num_altsetting != 1) {
355 log_error("Unexpected number of alternate interface settings: %d", iface->num_altsetting);
359 const struct libusb_interface_descriptor *ifd = &iface->altsetting[0];
360 if (ifd->bNumEndpoints != 2) {
361 log_error("Unexpected number of endpoints: %d", ifd->bNumEndpoints);
365 rx_endpoint = tx_endpoint = -1;
366 for (int i=0; i<2; i++) {
367 const struct libusb_endpoint_descriptor *epd = &ifd->endpoint[i];
368 if (epd->bEndpointAddress & 0x80)
369 rx_endpoint = epd->bEndpointAddress;
371 tx_endpoint = epd->bEndpointAddress;
373 if (rx_endpoint < 0 || tx_endpoint < 0) {
374 log_error("Failed to identify endpoints");
378 log_pkt("Found endpoints: rx==%02x tx=%02x\n", rx_endpoint, tx_endpoint);
379 libusb_free_config_descriptor(desc);
383 libusb_free_config_descriptor(desc);
387 static int find_device(void)
389 libusb_device **devlist;
390 ssize_t devn = libusb_get_device_list(usb_ctxt, &devlist);
392 log_error("Cannot enumerate USB devices: error %d", (int) devn);
396 for (ssize_t i=0; i<devn; i++) {
397 struct libusb_device_descriptor desc;
398 libusb_device *dev = devlist[i];
399 if (!libusb_get_device_descriptor(dev, &desc)) {
400 if (desc.idVendor == 0x0451 && desc.idProduct == 0x3211) {
401 log_info("Arexx data logger found at usb%d.%d", libusb_get_bus_number(dev), libusb_get_device_address(dev));
402 if (!parse_descriptors(dev))
405 if (err = libusb_open(dev, &devh)) {
406 log_error("libusb_open() failed: error %d", err);
409 if (err = libusb_claim_interface(devh, 0)) {
410 log_error("libusb_claim_interface() failed: error %d", err);
414 libusb_free_device_list(devlist, 1);
421 libusb_free_device_list(devlist, 1);
425 static void release_device(void)
427 libusb_release_interface(devh, 0);
428 libusb_reset_device(devh);
433 static void dump_packet(byte *pkt)
435 for (int i=0; i<64; i++) {
437 log_pkt("\t%02x:", i);
438 log_pkt(" %02x", pkt[i]);
444 static void my_msleep(int ms)
446 struct timespec ts = { .tv_sec = ms/1000, .tv_nsec = (ms%1000) * 1000000 };
447 nanosleep(&ts, NULL);
450 static int send_and_receive(byte *req, byte *reply)
453 time_t t = time(NULL);
455 localtime_r(&t, &tm);
458 strftime(tbuf, sizeof(tbuf), "%Y-%m-%d %H:%M:%S", &tm);
459 log_pkt("## %s\n", tbuf);
462 int err, transferred;
463 if (err = libusb_bulk_transfer(devh, tx_endpoint, req, 64, &transferred, 200)) {
464 if (err == LIBUSB_ERROR_TIMEOUT) {
465 log_pkt(">> xmit timed out\n");
468 log_pkt(">> xmit error %d\n", err);
469 log_error("Transmit error: %d", err);
473 log_pkt(">> xmit %d bytes\n", transferred);
477 if (err = libusb_bulk_transfer(devh, rx_endpoint, reply, 64, &transferred, 200)) {
478 if (err == LIBUSB_ERROR_TIMEOUT) {
479 log_pkt("<< recv timed out\n");
482 log_pkt("<< recv error %d\n", err);
483 log_error("Receive error: %d", err);
486 packet_rx_time = time(NULL);
488 log_pkt("<< recv %d bytes\n", transferred);
489 while (transferred < 64)
490 reply[transferred++] = 0xff;
496 static unsigned int get_be16(byte *p)
498 return p[1] | (p[0] << 8);
501 static unsigned int get_le16(byte *p)
503 return p[0] | (p[1] << 8);
506 static unsigned int get_le32(byte *p)
508 return get_le16(p) | (get_le16(p+2) << 16);
511 static void put_le16(byte *p, unsigned int x)
517 static void put_le32(byte *p, unsigned int x)
520 put_le16(p+2, x>>16);
523 static int parse_packet(byte *reply)
526 log_error("Unknown packet type %02x", reply[0]);
533 byte *p = reply + pos;
535 if (!len || len == 0xff)
537 if (len < 9 || len > 10) {
538 log_error("Unknown tuple length %02x", len);
541 if (pos + len > 64) {
542 log_error("Tuple truncated");
545 int id = get_le16(p+1);
546 int raw = get_be16(p+3);
547 int t = get_le32(p+5);
548 int q = (len > 9) ? p[9] : -1;
549 if (debug_raw_data) {
550 printf("... %02x: id=%d raw=%d t=%d", len, id, raw, t);
555 raw_point(t, id, raw, q);
563 static void set_clock(void)
565 byte req[64], reply[64];
568 time_t t = time(NULL);
569 put_le32(req+1, t-TIME_OFFSET);
570 send_and_receive(req, reply);
574 * Original software also sends a packet with type 3 and the timestamp,
575 * but it does not make any sense, especially as they ignore the sensor
576 * readings in the answer.
579 send_and_receive(req, reply);
586 static sigset_t term_sigs;
587 static volatile sig_atomic_t want_shutdown;
589 static void sigterm_handler(int sig __attribute__((unused)))
594 static void interruptible_msleep(int ms)
596 sigprocmask(SIG_UNBLOCK, &term_sigs, NULL);
598 sigprocmask(SIG_BLOCK, &term_sigs, NULL);
601 static const struct option long_options[] = {
602 { "debug", 0, NULL, 'd' },
603 { "log-dir", 1, NULL, 'l' },
604 { "debug-packets", 0, NULL, 'p' },
605 { "debug-raw", 0, NULL, 'r' },
606 { "version", 0, NULL, 'V' },
607 { NULL, 0, NULL, 0 },
610 static void usage(void)
613 Usage: arexxd <options>\n\
616 -d, --debug Debug mode (no chdir, no fork, no syslog)\n\
617 -l, --log-dir=<dir> Directory where all received data should be stored\n\
618 -p, --debug-packets Log all packets sent and received\n\
619 -r, --debug-raw Log conversion from raw values\n\
620 -u, --debug-usb Enable libusb debug messages (to stdout/stderr)\n\
621 -V, --version Show daemon version\n\
626 int main(int argc, char **argv)
629 while ((opt = getopt_long(argc, argv, "dl:pruV", long_options, NULL)) >= 0)
647 printf("arexxd " AREXXD_VERSION "\n");
648 printf("(c) 2011-2012 Martin Mares <mj@ucw.cz>\n");
657 if (err = libusb_init(&usb_ctxt))
658 die("Cannot initialize libusb: error %d", err);
660 libusb_set_debug(usb_ctxt, 3);
663 if (chdir(log_dir) < 0)
664 die("Cannot change directory to %s: %m", log_dir);
665 if (debug_packets || debug_raw_data) {
667 if (open("debug", O_WRONLY | O_CREAT | O_APPEND, 0666) < 0)
668 die("Cannot open debug log: %m");
671 openlog("arexxd", LOG_NDELAY, LOG_DAEMON);
674 die("fork() failed: %m");
681 struct sigaction sa = { .sa_handler = sigterm_handler };
682 sigaction(SIGTERM, &sa, NULL);
683 sigaction(SIGINT, &sa, NULL);
685 sigemptyset(&term_sigs);
686 sigaddset(&term_sigs, SIGTERM);
687 sigaddset(&term_sigs, SIGINT);
688 sigprocmask(SIG_BLOCK, &term_sigs, NULL);
691 while (!want_shutdown) {
692 if (!find_device()) {
695 log_error("Data logger not connected, waiting until it appears");
697 interruptible_msleep(30000);
700 log_info("Listening");
702 time_t last_sync = 0;
703 time_t last_show = 0;
706 data_point_counter = 0;
707 while (!want_shutdown) {
708 time_t now = time(NULL);
709 if (now > last_sync + 900) {
710 log_info("Synchronizing data logger time");
714 if (want_stats && now > last_show + 300) {
715 log_info("Stats: received %d data points", data_point_counter);
716 data_point_counter = 0;
720 byte req[64], reply[64];
721 memset(req, 0, sizeof(req));
723 err = send_and_receive(req, reply);
727 if (err > 0 && parse_packet(reply))
730 interruptible_msleep(4000);
733 interruptible_msleep(5);
736 log_info("Disconnecting data logger");
739 interruptible_msleep(10000);
742 log_info("Terminated");