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());
151 arg_push("%d:%f", t, val);
152 rrd_update(arg_cnt, arg_ptr);
153 if (rrd_test_error()) {
154 log_error("rrd_update on %s failed: %s", rr_name, rrd_get_error());
161 #define TIME_OFFSET 946681200 // Timestamp of 2000-01-01 00:00:00
163 static int data_point_counter; // Since last log message
165 static double correct_point(int id, double val, const char **name)
168 * Manually calculated corrections and renames for my sensors.
169 * Replace with your formulae.
182 *name = "catarium-rh";
192 static void cooked_point(time_t t, int id, double val, char *unit, int q)
195 snprintf(namebuf, sizeof(namebuf), "%d", id);
196 const char *name = namebuf;
198 double val2 = correct_point(id, val, &name);
200 if (debug_raw_data) {
202 localtime_r(&t, &tm);
204 strftime(tbuf, sizeof(tbuf), "%Y-%m-%d %H:%M:%S", &tm);
205 printf("== %s id=%d name=%s val=%.3f val2=%.3f unit=%s q=%d\n", tbuf, id, name, val, val2, unit, q);
208 data_point_counter++;
209 rrd_point(t, name, val2, unit);
212 static void raw_point(int t, int id, int raw, int q)
215 * The binary blob provided by Arexx contains an embedded XML fragment
216 * with descriptions of all known sensor types. If you want to see it,
217 * grep the blob for "<deviceinfo>". The meanings of the parameters are
220 * m1, m2 Device type matches if (raw_sensor_id & m1) == m2
221 * type Unit measured by the sensor (1=Celsius, 2=RH%, 3=CO2 ppm)
222 * dm User-visible sensor ID = raw_sensor_id & dm
223 * i 1 if the raw value is signed
224 * p[] Coefficients of transformation polynomial (x^0 first)
225 * vLo, vUp Upper and lower bound on the final value
226 * scale Scaling function:
227 * 0 = identity (default)
230 * 3 = (x < 0) ? 0 : log10(x)
231 * 4 = (x < 0) ? 0 : log(x)
233 * The raw values are transformed this way:
234 * - sign-extend if signed
235 * - apply the transformation polynomial
236 * - apply the scaling function
237 * - drop if outside the interval [vLo,vUp]
239 * This function applies the necessary transform for sensors we've
240 * seen in the wild. We deliberately ignore the "dm" parameter as we want
241 * to report different channels of a single sensor as multiple sensors.
247 int idhi = id & 0xf000;
249 if (idhi == 0x1000) {
254 } else if (idhi == 0x2000) {
261 } else if (idhi == 0x4000) {
268 z = -2.8e-6*z*z + 0.0405*z - 4;
273 } else if (idhi == 0x6000) {
283 z = (z + 1.9184e-7) * z;
284 z = (z - 1.0998e-3) * z;
292 log_error("Unknown sensor type 0x%04x", id);
296 if (z < lo || z > hi) {
297 log_error("Sensor %d: value %f out of range", id, z);
301 cooked_point(t + TIME_OFFSET, id, z, unit, q);
304 /*** USB interface ***/
306 static int rx_endpoint, tx_endpoint;
308 static int parse_descriptors(libusb_device *dev)
311 struct libusb_config_descriptor *desc;
313 if (err = libusb_get_active_config_descriptor(dev, &desc)) {
314 log_error("libusb_get_config_descriptor failed: error %d", err);
317 if (desc->bNumInterfaces != 1) {
318 log_error("Unexpected number of interfaces: %d", desc->bNumInterfaces);
322 const struct libusb_interface *iface = &desc->interface[0];
323 if (iface->num_altsetting != 1) {
324 log_error("Unexpected number of alternate interface settings: %d", iface->num_altsetting);
328 const struct libusb_interface_descriptor *ifd = &iface->altsetting[0];
329 if (ifd->bNumEndpoints != 2) {
330 log_error("Unexpected number of endpoints: %d", ifd->bNumEndpoints);
334 rx_endpoint = tx_endpoint = -1;
335 for (int i=0; i<2; i++) {
336 const struct libusb_endpoint_descriptor *epd = &ifd->endpoint[i];
337 if (epd->bEndpointAddress & 0x80)
338 rx_endpoint = epd->bEndpointAddress;
340 tx_endpoint = epd->bEndpointAddress;
342 if (rx_endpoint < 0 || tx_endpoint < 0) {
343 log_error("Failed to identify endpoints");
347 log_pkt("Found endpoints: rx==%02x tx=%02x\n", rx_endpoint, tx_endpoint);
348 libusb_free_config_descriptor(desc);
352 libusb_free_config_descriptor(desc);
356 static int find_device(void)
358 libusb_device **devlist;
359 ssize_t devn = libusb_get_device_list(usb_ctxt, &devlist);
361 log_error("Cannot enumerate USB devices: error %d", (int) devn);
365 for (ssize_t i=0; i<devn; i++) {
366 struct libusb_device_descriptor desc;
367 libusb_device *dev = devlist[i];
368 if (!libusb_get_device_descriptor(dev, &desc)) {
369 if (desc.idVendor == 0x0451 && desc.idProduct == 0x3211) {
370 log_info("Arexx data logger found at usb%d.%d", libusb_get_bus_number(dev), libusb_get_device_address(dev));
371 if (!parse_descriptors(dev))
374 if (err = libusb_open(dev, &devh)) {
375 log_error("libusb_open() failed: error %d", err);
378 if (err = libusb_claim_interface(devh, 0)) {
379 log_error("libusb_claim_interface() failed: error %d", err);
383 libusb_free_device_list(devlist, 1);
390 libusb_free_device_list(devlist, 1);
394 static void release_device(void)
396 libusb_release_interface(devh, 0);
397 libusb_reset_device(devh);
402 static void dump_packet(byte *pkt)
404 for (int i=0; i<64; i++) {
406 log_pkt("\t%02x:", i);
407 log_pkt(" %02x", pkt[i]);
413 static void my_msleep(int ms)
415 struct timespec ts = { .tv_sec = ms/1000, .tv_nsec = (ms%1000) * 1000000 };
416 nanosleep(&ts, NULL);
419 static int send_and_receive(byte *req, byte *reply)
422 time_t t = time(NULL);
424 localtime_r(&t, &tm);
427 strftime(tbuf, sizeof(tbuf), "%Y-%m-%d %H:%M:%S", &tm);
428 log_pkt("## %s\n", tbuf);
431 int err, transferred;
432 if (err = libusb_bulk_transfer(devh, tx_endpoint, req, 64, &transferred, 200)) {
433 if (err == LIBUSB_ERROR_TIMEOUT) {
434 log_pkt(">> xmit timed out\n");
437 log_pkt(">> xmit error %d\n", err);
438 log_error("Transmit error: %d", err);
442 log_pkt(">> xmit %d bytes\n", transferred);
446 if (err = libusb_bulk_transfer(devh, rx_endpoint, reply, 64, &transferred, 200)) {
447 if (err == LIBUSB_ERROR_TIMEOUT) {
448 log_pkt("<< recv timed out\n");
451 log_pkt("<< recv error %d\n", err);
452 log_error("Receive error: %d", err);
456 log_pkt("<< recv %d bytes\n", transferred);
457 while (transferred < 64)
458 reply[transferred++] = 0xff;
464 static unsigned int get_be16(byte *p)
466 return p[1] | (p[0] << 8);
469 static unsigned int get_le16(byte *p)
471 return p[0] | (p[1] << 8);
474 static unsigned int get_le32(byte *p)
476 return get_le16(p) | (get_le16(p+2) << 16);
479 static void put_le16(byte *p, unsigned int x)
485 static void put_le32(byte *p, unsigned int x)
488 put_le16(p+2, x>>16);
491 static int parse_packet(byte *reply)
494 log_error("Unknown packet type %02x", reply[0]);
501 byte *p = reply + pos;
503 if (!len || len == 0xff)
505 if (len < 9 || len > 10) {
506 log_error("Unknown tuple length %02x", len);
509 if (pos + len > 64) {
510 log_error("Tuple truncated");
513 int id = get_le16(p+1);
514 int raw = get_be16(p+3);
515 int t = get_le32(p+5);
516 int q = (len > 9) ? p[9] : -1;
517 if (debug_raw_data) {
518 printf("... %02x: id=%d raw=%d t=%d", len, id, raw, t);
523 raw_point(t, id, raw, q);
531 static void set_clock(void)
533 byte req[64], reply[64];
536 time_t t = time(NULL);
537 put_le32(req+1, t-TIME_OFFSET);
538 send_and_receive(req, reply);
542 * Original software also sends a packet with type 3 and the timestamp,
543 * but it does not make any sense, especially as they ignore the sensor
544 * readings in the answer.
547 send_and_receive(req, reply);
554 static sigset_t term_sigs;
555 static volatile sig_atomic_t want_shutdown;
557 static void sigterm_handler(int sig __attribute__((unused)))
562 static void interruptible_msleep(int ms)
564 sigprocmask(SIG_UNBLOCK, &term_sigs, NULL);
566 sigprocmask(SIG_BLOCK, &term_sigs, NULL);
569 static const struct option long_options[] = {
570 { "debug", 0, NULL, 'd' },
571 { "log-dir", 1, NULL, 'l' },
572 { "debug-packets", 0, NULL, 'p' },
573 { "debug-raw", 0, NULL, 'r' },
574 { "version", 0, NULL, 'V' },
575 { NULL, 0, NULL, 0 },
578 static void usage(void)
581 Usage: arexxd <options>\n\
584 -d, --debug Debug mode (no chdir, no fork, no syslog)\n\
585 -l, --log-dir=<dir> Directory where all received data should be stored\n\
586 -p, --debug-packets Log all packets sent and received\n\
587 -r, --debug-raw Log conversion from raw values\n\
588 -u, --debug-usb Enable libusb debug messages (to stdout/stderr)\n\
589 -V, --version Show daemon version\n\
594 int main(int argc, char **argv)
597 while ((opt = getopt_long(argc, argv, "dl:pruV", long_options, NULL)) >= 0)
615 printf("arexxd " AREXXD_VERSION "\n");
616 printf("(c) 2011-2012 Martin Mares <mj@ucw.cz>\n");
625 if (err = libusb_init(&usb_ctxt))
626 die("Cannot initialize libusb: error %d", err);
628 libusb_set_debug(usb_ctxt, 3);
631 if (chdir(log_dir) < 0)
632 die("Cannot change directory to %s: %m", log_dir);
633 if (debug_packets || debug_raw_data) {
635 if (open("debug", O_WRONLY | O_CREAT | O_APPEND, 0666) < 0)
636 die("Cannot open debug log: %m");
639 openlog("arexxd", LOG_NDELAY, LOG_DAEMON);
642 die("fork() failed: %m");
649 struct sigaction sa = { .sa_handler = sigterm_handler };
650 sigaction(SIGTERM, &sa, NULL);
651 sigaction(SIGINT, &sa, NULL);
653 sigemptyset(&term_sigs);
654 sigaddset(&term_sigs, SIGTERM);
655 sigaddset(&term_sigs, SIGINT);
656 sigprocmask(SIG_BLOCK, &term_sigs, NULL);
659 while (!want_shutdown) {
660 if (!find_device()) {
663 log_error("Data logger not connected, waiting until it appears");
665 interruptible_msleep(30000);
668 log_info("Listening");
670 time_t last_sync = 0;
671 time_t last_show = 0;
674 data_point_counter = 0;
675 while (!want_shutdown) {
676 time_t now = time(NULL);
677 if (now > last_sync + 900) {
678 log_info("Synchronizing data logger time");
682 if (want_stats && now > last_show + 300) {
683 log_info("Stats: received %d data points", data_point_counter);
684 data_point_counter = 0;
688 byte req[64], reply[64];
689 memset(req, 0, sizeof(req));
691 err = send_and_receive(req, reply);
695 if (err > 0 && parse_packet(reply))
698 interruptible_msleep(4000);
701 interruptible_msleep(5);
704 log_info("Disconnecting data logger");
707 interruptible_msleep(10000);
710 log_info("Terminated");