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"
24 typedef unsigned char byte;
25 static libusb_context *usb_ctxt;
26 static libusb_device_handle *devh;
28 static int use_syslog;
29 static int debug_mode;
30 static int debug_packets;
31 static int debug_raw_data;
33 static char *log_dir = DEFAULT_LOG_DIR;
35 static void die(char *fmt, ...)
40 vsyslog(LOG_CRIT, fmt, args);
42 vfprintf(stderr, fmt, args);
43 fprintf(stderr, "\n");
49 static void log_error(char *fmt, ...)
54 vsyslog(LOG_ERR, fmt, args);
56 vfprintf(stderr, fmt, args);
57 fprintf(stderr, "\n");
62 static void log_info(char *fmt, ...)
67 vsyslog(LOG_INFO, fmt, args);
69 vfprintf(stderr, fmt, args);
70 fprintf(stderr, "\n");
75 static void log_pkt(char *fmt, ...)
85 /*** RRD interface ***/
88 #define MAX_ARG_SIZE 1024
91 static char *arg_ptr[MAX_ARGS+1];
92 static char arg_buf[MAX_ARG_SIZE];
95 static void arg_new(void)
99 arg_ptr[0] = "rrdtool";
102 static void arg_push(const char *fmt, ...)
104 if (arg_cnt >= MAX_ARGS)
105 die("MAX_ARGS exceeded");
108 int len = 1 + vsnprintf(arg_buf + arg_pos, MAX_ARG_SIZE - arg_pos, fmt, va);
109 if (arg_pos + len > MAX_ARG_SIZE)
110 die("MAX_ARG_SIZE exceeded");
111 arg_ptr[arg_cnt++] = arg_buf + arg_pos;
112 arg_ptr[arg_cnt] = NULL;
116 static void rrd_point(time_t t, const char *name, double val, char *unit)
119 snprintf(rr_name, sizeof(rr_name), "sensor-%s.rrd", name);
122 if (stat(rr_name, &st) < 0 || !st.st_size) {
123 // We have to create the RRD
124 log_info("Creating %s", rr_name);
128 arg_push("%d", (int) time(NULL) - 28*86400);
131 if (!strcmp(unit, "%RH"))
132 arg_push("DS:rh:GAUGE:300:0:100");
133 else if (!strcmp(unit, "ppm"))
134 arg_push("DS:ppm:GAUGE:300:0:1000000");
136 arg_push("DS:temp:GAUGE:300:-200:200");
137 arg_push("RRA:AVERAGE:0.25:1:20160"); // Last 14 days with full resolution
138 arg_push("RRA:AVERAGE:0.25:60:88800"); // Last 10 years with 1h resolution
139 arg_push("RRA:MIN:0.25:60:88800"); // including minima and maxima
140 arg_push("RRA:MAX:0.25:60:88800");
141 rrd_create(arg_cnt, arg_ptr);
142 if (rrd_test_error()) {
143 log_error("rrd_create on %s failed: %s", rr_name, rrd_get_error());
150 arg_push("%d:%f", t, val);
151 rrd_update(arg_cnt, arg_ptr);
152 if (rrd_test_error())
153 log_error("rrd_update on %s failed: %s", rr_name, rrd_get_error());
158 #define TIME_OFFSET 946681200 // Timestamp of 2000-01-01 00:00:00
160 static int data_point_counter; // Since last log message
162 static double correct_point(int id, double val, const char **name)
165 * Manually calculated corrections and renames for my sensors.
166 * Replace with your formulae.
179 *name = "catarium-rh";
189 static void cooked_point(time_t t, int id, double val, char *unit, int q)
192 snprintf(namebuf, sizeof(namebuf), "%d", id);
193 const char *name = namebuf;
195 double val2 = correct_point(id, val, &name);
197 if (debug_raw_data) {
199 localtime_r(&t, &tm);
201 strftime(tbuf, sizeof(tbuf), "%Y-%m-%d %H:%M:%S", &tm);
202 printf("== %s id=%d name=%s val=%.3f val2=%.3f unit=%s q=%d\n", tbuf, id, name, val, val2, unit, q);
205 data_point_counter++;
206 rrd_point(t, name, val2, unit);
209 static void raw_point(int t, int id, int raw, int q)
212 * The binary blob provided by Arexx contains an embedded XML fragment
213 * with descriptions of all known sensor types. If you want to see it,
214 * grep the blob for "<deviceinfo>". The meanings of the parameters are
217 * m1, m2 Device type matches if (raw_sensor_id & m1) == m2
218 * type Unit measured by the sensor (1=Celsius, 2=RH%, 3=CO2 ppm)
219 * dm User-visible sensor ID = raw_sensor_id & dm
220 * i 1 if the raw value is signed
221 * p[] Coefficients of transformation polynomial (x^0 first)
222 * vLo, vUp Upper and lower bound on the final value
223 * scale Scaling function:
224 * 0 = identity (default)
227 * 3 = (x < 0) ? 0 : log10(x)
228 * 4 = (x < 0) ? 0 : log(x)
230 * The raw values are transformed this way:
231 * - sign-extend if signed
232 * - apply the transformation polynomial
233 * - apply the scaling function
234 * - drop if outside the interval [vLo,vUp]
236 * This function applies the necessary transform for sensors we've
237 * seen in the wild. We deliberately ignore the "dm" parameter as we want
238 * to report different channels of a single sensor as multiple sensors.
244 int idhi = id & 0xf000;
246 if (idhi == 0x1000) {
251 } else if (idhi == 0x2000) {
258 } else if (idhi == 0x4000) {
265 z = -2.8e-6*z*z + 0.0405*z - 4;
270 } else if (idhi == 0x6000) {
280 z = (z + 1.9184e-7) * z;
281 z = (z - 1.0998e-3) * z;
289 log_error("Unknown sensor type 0x%04x", id);
293 if (z < lo || z > hi) {
294 log_error("Sensor %d: value %f out of range", id, z);
298 cooked_point(t + TIME_OFFSET, id, z, unit, q);
301 /*** USB interface ***/
303 static int rx_endpoint, tx_endpoint;
305 static int parse_descriptors(libusb_device *dev)
308 struct libusb_config_descriptor *desc;
310 if (err = libusb_get_active_config_descriptor(dev, &desc)) {
311 log_error("libusb_get_config_descriptor failed: error %d", err);
314 if (desc->bNumInterfaces != 1) {
315 log_error("Unexpected number of interfaces: %d", desc->bNumInterfaces);
319 const struct libusb_interface *iface = &desc->interface[0];
320 if (iface->num_altsetting != 1) {
321 log_error("Unexpected number of alternate interface settings: %d", iface->num_altsetting);
325 const struct libusb_interface_descriptor *ifd = &iface->altsetting[0];
326 if (ifd->bNumEndpoints != 2) {
327 log_error("Unexpected number of endpoints: %d", ifd->bNumEndpoints);
331 rx_endpoint = tx_endpoint = -1;
332 for (int i=0; i<2; i++) {
333 const struct libusb_endpoint_descriptor *epd = &ifd->endpoint[i];
334 if (epd->bEndpointAddress & 0x80)
335 rx_endpoint = epd->bEndpointAddress;
337 tx_endpoint = epd->bEndpointAddress;
339 if (rx_endpoint < 0 || tx_endpoint < 0) {
340 log_error("Failed to identify endpoints");
344 log_pkt("Found endpoints: rx==%02x tx=%02x\n", rx_endpoint, tx_endpoint);
345 libusb_free_config_descriptor(desc);
349 libusb_free_config_descriptor(desc);
353 static int find_device(void)
355 libusb_device **devlist;
356 ssize_t devn = libusb_get_device_list(usb_ctxt, &devlist);
358 log_error("Cannot enumerate USB devices: error %d", (int) devn);
362 for (ssize_t i=0; i<devn; i++) {
363 struct libusb_device_descriptor desc;
364 libusb_device *dev = devlist[i];
365 if (!libusb_get_device_descriptor(dev, &desc)) {
366 if (desc.idVendor == 0x0451 && desc.idProduct == 0x3211) {
367 log_info("Arexx data logger found at usb%d.%d", libusb_get_bus_number(dev), libusb_get_device_address(dev));
368 if (!parse_descriptors(dev))
371 if (err = libusb_open(dev, &devh)) {
372 log_error("libusb_open() failed: error %d", err);
375 if (err = libusb_claim_interface(devh, 0)) {
376 log_error("libusb_claim_interface() failed: error %d", err);
380 libusb_free_device_list(devlist, 1);
387 libusb_free_device_list(devlist, 1);
391 static void release_device(void)
393 libusb_release_interface(devh, 0);
394 libusb_reset_device(devh);
399 static void dump_packet(byte *pkt)
401 for (int i=0; i<64; i++) {
403 log_pkt("\t%02x:", i);
404 log_pkt(" %02x", pkt[i]);
410 static int send_and_receive(byte *req, byte *reply)
413 time_t t = time(NULL);
415 localtime_r(&t, &tm);
418 strftime(tbuf, sizeof(tbuf), "%Y-%m-%d %H:%M:%S", &tm);
419 log_pkt("## %s\n", tbuf);
422 int err, transferred;
423 if (err = libusb_bulk_transfer(devh, tx_endpoint, req, 64, &transferred, 200)) {
424 if (err == LIBUSB_ERROR_TIMEOUT) {
425 log_pkt(">> xmit timed out\n");
428 log_pkt(">> xmit error %d\n", err);
429 log_error("Transmit error: %d", err);
433 log_pkt(">> xmit %d bytes\n", transferred);
436 if (err = libusb_bulk_transfer(devh, rx_endpoint, reply, 64, &transferred, 200)) {
437 if (err == LIBUSB_ERROR_TIMEOUT) {
438 log_pkt("<< recv timed out\n");
441 log_pkt("<< recv error %d\n", err);
442 log_error("Receive error: %d", err);
446 log_pkt("<< recv %d bytes\n", transferred);
447 while (transferred < 64)
448 reply[transferred++] = 0xff;
454 static unsigned int get_be16(byte *p)
456 return p[1] | (p[0] << 8);
459 static unsigned int get_le16(byte *p)
461 return p[0] | (p[1] << 8);
464 static unsigned int get_le32(byte *p)
466 return get_le16(p) | (get_le16(p+2) << 16);
469 static void put_le16(byte *p, unsigned int x)
475 static void put_le32(byte *p, unsigned int x)
478 put_le16(p+2, x>>16);
481 static int parse_packet(byte *reply)
484 log_error("Unknown packet type %02x", reply[0]);
491 byte *p = reply + pos;
493 if (!len || len == 0xff)
495 if (len < 9 || len > 10) {
496 log_error("Unknown tuple length %02x", len);
499 if (pos + len > 64) {
500 log_error("Tuple truncated");
503 int id = get_le16(p+1);
504 int raw = get_be16(p+3);
505 int t = get_le32(p+5);
506 int q = (len > 9) ? p[9] : -1;
507 if (debug_raw_data) {
508 printf("... %02x: id=%d raw=%d t=%d", len, id, raw, t);
513 raw_point(t, id, raw, q);
521 static void set_clock(void)
523 byte req[64], reply[64];
526 time_t t = time(NULL);
527 put_le32(req+1, t-TIME_OFFSET);
528 send_and_receive(req, reply);
532 * Original software also sends a packet with type 3 and the timestamp,
533 * but it does not make any sense, especially as they ignore the sensor
534 * readings in the answer.
537 send_and_receive(req, reply);
544 static sigset_t term_sigs;
545 static volatile sig_atomic_t want_shutdown;
547 static void sigterm_handler(int sig __attribute__((unused)))
552 static void interruptible_msleep(int ms)
554 sigprocmask(SIG_UNBLOCK, &term_sigs, NULL);
555 struct timespec ts = { .tv_sec = ms/1000, .tv_nsec = (ms%1000) * 1000000 };
556 nanosleep(&ts, NULL);
557 sigprocmask(SIG_BLOCK, &term_sigs, NULL);
560 static const struct option long_options[] = {
561 { "debug", 0, NULL, 'd' },
562 { "log-dir", 1, NULL, 'l' },
563 { "debug-packets", 0, NULL, 'p' },
564 { "debug-raw", 0, NULL, 'r' },
565 { NULL, 0, NULL, 0 },
568 static void usage(void)
571 Usage: arexxd <options>\n\
574 -d, --debug Debug mode (no chdir, no fork, no syslog)\n\
575 -l, --log-dir=<dir> Directory where all received data should be stored\n\
576 -p, --debug-packets Log all packets sent and received\n\
577 -r, --debug-raw Log conversion from raw values\n\
578 -u, --debug-usb Enable libusb debug messages (to stdout/stderr)\n\
583 int main(int argc, char **argv)
586 while ((opt = getopt_long(argc, argv, "dl:pru", long_options, NULL)) >= 0)
610 if (err = libusb_init(&usb_ctxt))
611 die("Cannot initialize libusb: error %d", err);
613 libusb_set_debug(usb_ctxt, 3);
616 if (chdir(log_dir) < 0)
617 die("Cannot change directory to %s: %m", log_dir);
618 if (debug_packets || debug_raw_data) {
620 if (open("debug", O_WRONLY | O_CREAT | O_APPEND, 0666) < 0)
621 die("Cannot open debug log: %m");
624 openlog("arexxd", LOG_NDELAY, LOG_DAEMON);
627 die("fork() failed: %m");
634 struct sigaction sa = { .sa_handler = sigterm_handler };
635 sigaction(SIGTERM, &sa, NULL);
636 sigaction(SIGINT, &sa, NULL);
638 sigemptyset(&term_sigs);
639 sigaddset(&term_sigs, SIGTERM);
640 sigaddset(&term_sigs, SIGINT);
641 sigprocmask(SIG_BLOCK, &term_sigs, NULL);
644 while (!want_shutdown) {
645 if (!find_device()) {
648 log_error("Data logger not connected, waiting until it appears");
650 interruptible_msleep(30000);
653 log_info("Listening");
655 time_t last_sync = 0;
656 time_t last_show = 0;
659 data_point_counter = 0;
660 while (!want_shutdown) {
661 time_t now = time(NULL);
662 if (now > last_sync + 900) {
663 log_info("Synchronizing data logger time");
667 if (want_stats && now > last_show + 300) {
668 log_info("Stats: received %d data points", data_point_counter);
669 data_point_counter = 0;
673 byte req[64], reply[64];
674 memset(req, 0, sizeof(req));
676 err = send_and_receive(req, reply);
680 if (err > 0 && parse_packet(reply))
683 interruptible_msleep(4000);
686 interruptible_msleep(5);
689 log_info("Disconnecting data logger");
692 interruptible_msleep(10000);
695 log_info("Terminated");