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;
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.
200 *name = "catarium-rh";
206 #ifdef IGNORE_UNKNOWN_SENSORS
213 static void cooked_point(time_t t, int id, double val, char *unit, int q)
216 snprintf(namebuf, sizeof(namebuf), "%d", id);
217 const char *name = namebuf;
219 double val2 = correct_point(id, val, &name);
221 if (debug_raw_data) {
223 localtime_r(&t, &tm);
225 strftime(tbuf, sizeof(tbuf), "%Y-%m-%d %H:%M:%S", &tm);
226 printf("== %s id=%d name=%s val=%.3f val2=%.3f unit=%s q=%d\n", tbuf, id, name, val, val2, unit, q);
230 log_error("Ignored data from unknown sensor %d", id);
233 if (t < packet_rx_time - MAX_PAST_TIME) {
234 log_error("Data point from sensor %d too far in the past (%d sec)", packet_rx_time - t);
237 if (t > packet_rx_time + MAX_FUTURE_TIME) {
238 log_error("Data point from sensor %d too far in the future (%d sec)", t - packet_rx_time);
242 data_point_counter++;
243 rrd_point(t, name, val2, unit);
246 static void raw_point(int t, int id, int raw, int q)
249 * The binary blob provided by Arexx contains an embedded XML fragment
250 * with descriptions of all known sensor types. If you want to see it,
251 * grep the blob for "<deviceinfo>". The meanings of the parameters are
254 * m1, m2 Device type matches if (raw_sensor_id & m1) == m2
255 * type Unit measured by the sensor (1=Celsius, 2=RH%, 3=CO2 ppm)
256 * dm User-visible sensor ID = raw_sensor_id & dm
257 * i 1 if the raw value is signed
258 * p[] Coefficients of transformation polynomial (x^0 first)
259 * vLo, vUp Upper and lower bound on the final value
260 * scale Scaling function:
261 * 0 = identity (default)
264 * 3 = (x < 0) ? 0 : log10(x)
265 * 4 = (x < 0) ? 0 : log(x)
267 * The raw values are transformed this way:
268 * - sign-extend if signed
269 * - apply the transformation polynomial
270 * - apply the scaling function
271 * - drop if outside the interval [vLo,vUp]
273 * This function applies the necessary transform for sensors we've
274 * seen in the wild. We deliberately ignore the "dm" parameter as we want
275 * to report different channels of a single sensor as multiple sensors.
281 int idhi = id & 0xf000;
283 if (idhi == 0x1000) {
288 } else if (idhi == 0x2000) {
295 } else if (idhi == 0x4000) {
302 z = -2.8e-6*z*z + 0.0405*z - 4;
307 } else if (idhi == 0x6000) {
317 z = (z + 1.9184e-7) * z;
318 z = (z - 1.0998e-3) * z;
326 log_error("Unknown sensor type 0x%04x", id);
330 if (z < lo || z > hi) {
331 log_error("Sensor %d: value %f out of range", id, z);
335 cooked_point(t + TIME_OFFSET, id, z, unit, q);
338 /*** USB interface ***/
340 static int rx_endpoint, tx_endpoint;
342 static int parse_descriptors(libusb_device *dev)
345 struct libusb_config_descriptor *desc;
347 if (err = libusb_get_active_config_descriptor(dev, &desc)) {
348 log_error("libusb_get_config_descriptor failed: error %d", err);
351 if (desc->bNumInterfaces != 1) {
352 log_error("Unexpected number of interfaces: %d", desc->bNumInterfaces);
356 const struct libusb_interface *iface = &desc->interface[0];
357 if (iface->num_altsetting != 1) {
358 log_error("Unexpected number of alternate interface settings: %d", iface->num_altsetting);
362 const struct libusb_interface_descriptor *ifd = &iface->altsetting[0];
363 if (ifd->bNumEndpoints != 2) {
364 log_error("Unexpected number of endpoints: %d", ifd->bNumEndpoints);
368 rx_endpoint = tx_endpoint = -1;
369 for (int i=0; i<2; i++) {
370 const struct libusb_endpoint_descriptor *epd = &ifd->endpoint[i];
371 if (epd->bEndpointAddress & 0x80)
372 rx_endpoint = epd->bEndpointAddress;
374 tx_endpoint = epd->bEndpointAddress;
376 if (rx_endpoint < 0 || tx_endpoint < 0) {
377 log_error("Failed to identify endpoints");
381 log_pkt("Found endpoints: rx==%02x tx=%02x\n", rx_endpoint, tx_endpoint);
382 libusb_free_config_descriptor(desc);
386 libusb_free_config_descriptor(desc);
390 static int find_device(void)
392 libusb_device **devlist;
393 ssize_t devn = libusb_get_device_list(usb_ctxt, &devlist);
395 log_error("Cannot enumerate USB devices: error %d", (int) devn);
399 for (ssize_t i=0; i<devn; i++) {
400 struct libusb_device_descriptor desc;
401 libusb_device *dev = devlist[i];
402 if (!libusb_get_device_descriptor(dev, &desc)) {
403 if (desc.idVendor == 0x0451 && desc.idProduct == 0x3211) {
404 log_info("Arexx data logger found at usb%d.%d", libusb_get_bus_number(dev), libusb_get_device_address(dev));
405 if (!parse_descriptors(dev))
408 if (err = libusb_open(dev, &devh)) {
409 log_error("libusb_open() failed: error %d", err);
412 if (err = libusb_claim_interface(devh, 0)) {
413 log_error("libusb_claim_interface() failed: error %d", err);
417 libusb_free_device_list(devlist, 1);
424 libusb_free_device_list(devlist, 1);
428 static void release_device(void)
430 libusb_release_interface(devh, 0);
431 libusb_reset_device(devh);
436 static void dump_packet(byte *pkt)
438 for (int i=0; i<64; i++) {
440 log_pkt("\t%02x:", i);
441 log_pkt(" %02x", pkt[i]);
447 static void my_msleep(int ms)
449 struct timespec ts = { .tv_sec = ms/1000, .tv_nsec = (ms%1000) * 1000000 };
450 nanosleep(&ts, NULL);
453 static int send_and_receive(byte *req, byte *reply)
456 time_t t = time(NULL);
458 localtime_r(&t, &tm);
461 strftime(tbuf, sizeof(tbuf), "%Y-%m-%d %H:%M:%S", &tm);
462 log_pkt("## %s\n", tbuf);
465 int err, transferred;
466 if (err = libusb_bulk_transfer(devh, tx_endpoint, req, 64, &transferred, 200)) {
467 if (err == LIBUSB_ERROR_TIMEOUT) {
468 log_pkt(">> xmit timed out\n");
471 log_pkt(">> xmit error %d\n", err);
472 log_error("Transmit error: %d", err);
476 log_pkt(">> xmit %d bytes\n", transferred);
480 if (err = libusb_bulk_transfer(devh, rx_endpoint, reply, 64, &transferred, 200)) {
481 if (err == LIBUSB_ERROR_TIMEOUT) {
482 log_pkt("<< recv timed out\n");
485 log_pkt("<< recv error %d\n", err);
486 log_error("Receive error: %d", err);
489 packet_rx_time = time(NULL);
491 log_pkt("<< recv %d bytes\n", transferred);
492 while (transferred < 64)
493 reply[transferred++] = 0xff;
499 static unsigned int get_be16(byte *p)
501 return p[1] | (p[0] << 8);
504 static unsigned int get_le16(byte *p)
506 return p[0] | (p[1] << 8);
509 static unsigned int get_le32(byte *p)
511 return get_le16(p) | (get_le16(p+2) << 16);
514 static void put_le16(byte *p, unsigned int x)
520 static void put_le32(byte *p, unsigned int x)
523 put_le16(p+2, x>>16);
526 static int parse_packet(byte *reply)
529 log_error("Unknown packet type %02x", reply[0]);
536 byte *p = reply + pos;
538 if (!len || len == 0xff)
540 if (len < 9 || len > 10) {
541 log_error("Unknown tuple length %02x", len);
544 if (pos + len > 64) {
545 log_error("Tuple truncated");
548 int id = get_le16(p+1);
549 int raw = get_be16(p+3);
550 int t = get_le32(p+5);
551 int q = (len > 9) ? p[9] : -1;
552 if (debug_raw_data) {
553 printf("... %02x: id=%d raw=%d t=%d", len, id, raw, t);
558 raw_point(t, id, raw, q);
566 static void set_clock(void)
568 byte req[64], reply[64];
571 time_t t = time(NULL);
572 put_le32(req+1, t-TIME_OFFSET);
573 send_and_receive(req, reply);
577 * Original software also sends a packet with type 3 and the timestamp,
578 * but it does not make any sense, especially as they ignore the sensor
579 * readings in the answer.
582 send_and_receive(req, reply);
589 static sigset_t term_sigs;
590 static volatile sig_atomic_t want_shutdown;
592 static void sigterm_handler(int sig __attribute__((unused)))
597 static void interruptible_msleep(int ms)
599 sigprocmask(SIG_UNBLOCK, &term_sigs, NULL);
601 sigprocmask(SIG_BLOCK, &term_sigs, NULL);
604 static const struct option long_options[] = {
605 { "debug", 0, NULL, 'd' },
606 { "log-dir", 1, NULL, 'l' },
607 { "debug-packets", 0, NULL, 'p' },
608 { "debug-raw", 0, NULL, 'r' },
609 { "version", 0, NULL, 'V' },
610 { NULL, 0, NULL, 0 },
613 static void usage(void)
616 Usage: arexxd <options>\n\
619 -d, --debug Debug mode (no chdir, no fork, no syslog)\n\
620 -l, --log-dir=<dir> Directory where all received data should be stored\n\
621 -p, --debug-packets Log all packets sent and received\n\
622 -r, --debug-raw Log conversion from raw values\n\
623 -u, --debug-usb Enable libusb debug messages (to stdout/stderr)\n\
624 -V, --version Show daemon version\n\
629 int main(int argc, char **argv)
632 while ((opt = getopt_long(argc, argv, "dl:pruV", long_options, NULL)) >= 0)
650 printf("arexxd " AREXXD_VERSION "\n");
651 printf("(c) 2011-2012 Martin Mares <mj@ucw.cz>\n");
660 if (err = libusb_init(&usb_ctxt))
661 die("Cannot initialize libusb: error %d", err);
663 libusb_set_debug(usb_ctxt, 3);
666 if (chdir(log_dir) < 0)
667 die("Cannot change directory to %s: %m", log_dir);
668 if (debug_packets || debug_raw_data) {
670 if (open("debug", O_WRONLY | O_CREAT | O_APPEND, 0666) < 0)
671 die("Cannot open debug log: %m");
674 openlog("arexxd", LOG_NDELAY, LOG_DAEMON);
677 die("fork() failed: %m");
684 struct sigaction sa = { .sa_handler = sigterm_handler };
685 sigaction(SIGTERM, &sa, NULL);
686 sigaction(SIGINT, &sa, NULL);
688 sigemptyset(&term_sigs);
689 sigaddset(&term_sigs, SIGTERM);
690 sigaddset(&term_sigs, SIGINT);
691 sigprocmask(SIG_BLOCK, &term_sigs, NULL);
694 while (!want_shutdown) {
695 if (!find_device()) {
698 log_error("Data logger not connected, waiting until it appears");
700 interruptible_msleep(30000);
703 log_info("Listening");
705 time_t last_sync = 0;
706 time_t last_show = 0;
709 data_point_counter = 0;
710 while (!want_shutdown) {
711 time_t now = time(NULL);
712 if (now > last_sync + 900) {
713 log_info("Synchronizing data logger time");
717 if (want_stats && now > last_show + 300) {
718 log_info("Stats: received %d data points", data_point_counter);
719 data_point_counter = 0;
723 byte req[64], reply[64];
724 memset(req, 0, sizeof(req));
726 err = send_and_receive(req, reply);
730 if (err > 0 && parse_packet(reply))
733 interruptible_msleep(4000);
736 interruptible_msleep(5);
739 log_info("Disconnecting data logger");
742 interruptible_msleep(10000);
745 log_info("Terminated");