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;
32 static char *log_dir = DEFAULT_LOG_DIR;
34 static void die(char *fmt, ...)
39 vsyslog(LOG_CRIT, fmt, args);
41 vfprintf(stderr, fmt, args);
42 fprintf(stderr, "\n");
48 static void log_error(char *fmt, ...)
53 vsyslog(LOG_ERR, fmt, args);
55 vfprintf(stderr, fmt, args);
56 fprintf(stderr, "\n");
61 static void log_info(char *fmt, ...)
66 vsyslog(LOG_INFO, fmt, args);
68 vfprintf(stderr, fmt, args);
69 fprintf(stderr, "\n");
74 static void log_pkt(char *fmt, ...)
84 /*** RRD interface ***/
87 #define MAX_ARG_SIZE 1024
90 static char *arg_ptr[MAX_ARGS+1];
91 static char arg_buf[MAX_ARG_SIZE];
94 static void arg_new(void)
98 arg_ptr[0] = "rrdtool";
101 static void arg_push(const char *fmt, ...)
103 if (arg_cnt >= MAX_ARGS)
104 die("MAX_ARGS exceeded");
107 int len = 1 + vsnprintf(arg_buf + arg_pos, MAX_ARG_SIZE - arg_pos, fmt, va);
108 if (arg_pos + len > MAX_ARG_SIZE)
109 die("MAX_ARG_SIZE exceeded");
110 arg_ptr[arg_cnt++] = arg_buf + arg_pos;
111 arg_ptr[arg_cnt] = NULL;
115 static void rrd_point(time_t t, const char *name, double val, char *unit)
118 snprintf(rr_name, sizeof(rr_name), "sensor-%s.rrd", name);
121 if (stat(rr_name, &st) < 0 || !st.st_size) {
122 // We have to create the RRD
123 log_info("Creating %s", rr_name);
127 arg_push("%d", (int) time(NULL) - 28*86400);
130 if (!strcmp(unit, "%RH"))
131 arg_push("DS:rh:GAUGE:300:0:100");
132 else if (!strcmp(unit, "ppm"))
133 arg_push("DS:ppm:GAUGE:300:0:1000000");
135 arg_push("DS:temp:GAUGE:300:-200:200");
136 arg_push("RRA:AVERAGE:0.25:1:20160"); // Last 14 days with full resolution
137 arg_push("RRA:AVERAGE:0.25:60:88800"); // Last 10 years with 1h resolution
138 arg_push("RRA:MIN:0.25:60:88800"); // including minima and maxima
139 arg_push("RRA:MAX:0.25:60:88800");
140 rrd_create(arg_cnt, arg_ptr);
141 if (rrd_test_error()) {
142 log_error("rrd_create on %s failed: %s", rr_name, rrd_get_error());
149 arg_push("%d:%f", t, val);
150 rrd_update(arg_cnt, arg_ptr);
151 if (rrd_test_error())
152 log_error("rrd_update on %s failed: %s", rr_name, rrd_get_error());
157 #define TIME_OFFSET 946681200 // Timestamp of 2000-01-01 00:00:00
159 static int data_point_counter; // Since last log message
161 static double correct_point(int id, double val, const char **name)
164 * Manually calculated corrections and renames for my sensors.
165 * Replace with your formulae.
178 *name = "catarium-rh";
188 static void cooked_point(time_t t, int id, double val, char *unit, int q)
191 snprintf(namebuf, sizeof(namebuf), "%d", id);
192 const char *name = namebuf;
194 double val2 = correct_point(id, val, &name);
196 if (debug_raw_data) {
198 localtime_r(&t, &tm);
200 strftime(tbuf, sizeof(tbuf), "%Y-%m-%d %H:%M:%S", &tm);
201 printf("== %s id=%d name=%s val=%.3f val2=%.3f unit=%s q=%d\n", tbuf, id, name, val, val2, unit, q);
204 data_point_counter++;
205 rrd_point(t, name, val2, unit);
208 static void raw_point(int t, int id, int raw, int q)
211 * The binary blob provided by Arexx contains an embedded XML fragment
212 * with descriptions of all known sensor types. If you want to see it,
213 * grep the blob for "<deviceinfo>". The meanings of the parameters are
216 * m1, m2 Device type matches if (raw_sensor_id & m1) == m2
217 * type Unit measured by the sensor (1=Celsius, 2=RH%, 3=CO2 ppm)
218 * dm User-visible sensor ID = raw_sensor_id & dm
219 * i 1 if the raw value is signed
220 * p[] Coefficients of transformation polynomial (x^0 first)
221 * vLo, vUp Upper and lower bound on the final value
222 * scale Scaling function:
223 * 0 = identity (default)
226 * 3 = (x < 0) ? 0 : log10(x)
227 * 4 = (x < 0) ? 0 : log(x)
229 * The raw values are transformed this way:
230 * - sign-extend if signed
231 * - apply the transformation polynomial
232 * - apply the scaling function
233 * - drop if outside the interval [vLo,vUp]
235 * This function applies the necessary transform for sensors we've
236 * seen in the wild. We deliberately ignore the "dm" parameter as we want
237 * to report different channels of a single sensor as multiple sensors.
243 int idhi = id & 0xf000;
245 if (idhi == 0x1000) {
250 } else if (idhi == 0x2000) {
257 } else if (idhi == 0x4000) {
264 z = -2.8e-6*z*z + 0.0405*z - 4;
269 } else if (idhi == 0x6000) {
279 z = (z + 1.9184e-7) * z;
280 z = (z - 1.0998e-3) * z;
288 log_error("Unknown sensor type 0x%04x", id);
292 if (z < lo || z > hi) {
293 log_error("Sensor %d: value %f out of range", id, z);
297 cooked_point(t + TIME_OFFSET, id, z, unit, q);
300 /*** USB interface ***/
302 static int find_device(void)
304 libusb_device **devlist;
305 ssize_t devn = libusb_get_device_list(usb_ctxt, &devlist);
307 log_error("Cannot enumerate USB devices: error %d", (int) devn);
311 for (ssize_t i=0; i<devn; i++) {
312 struct libusb_device_descriptor desc;
313 libusb_device *dev = devlist[i];
314 if (!libusb_get_device_descriptor(dev, &desc)) {
315 if (desc.idVendor == 0x0451 && desc.idProduct == 0x3211) {
316 log_info("Arexx data logger found at usb%d.%d", libusb_get_bus_number(dev), libusb_get_device_address(dev));
318 if (err = libusb_open(dev, &devh)) {
319 log_error("libusb_open() failed: error %d", err);
322 if (err = libusb_claim_interface(devh, 0)) {
323 log_error("libusb_claim_interface() failed: error %d", err);
327 libusb_free_device_list(devlist, 1);
334 libusb_free_device_list(devlist, 1);
338 static void release_device(void)
344 static void dump_packet(byte *pkt)
346 for (int i=0; i<64; i++) {
348 log_pkt("\t%02x:", i);
349 log_pkt(" %02x", pkt[i]);
355 static int send_and_receive(byte *req, byte *reply)
358 time_t t = time(NULL);
360 localtime_r(&t, &tm);
363 strftime(tbuf, sizeof(tbuf), "%Y-%m-%d %H:%M:%S", &tm);
364 log_pkt("## %s\n", tbuf);
367 int err, transferred;
368 if (err = libusb_bulk_transfer(devh, 0x01, req, 64, &transferred, 200)) {
369 if (err == LIBUSB_ERROR_TIMEOUT) {
370 log_pkt(">> xmit timed out\n");
373 log_pkt(">> xmit error %d\n", err);
374 log_error("Transmit error: %d", err);
378 log_pkt(">> xmit %d bytes\n", transferred);
381 if (err = libusb_bulk_transfer(devh, 0x81, reply, 64, &transferred, 200)) {
382 if (err == LIBUSB_ERROR_TIMEOUT) {
383 log_pkt("<< recv timed out\n");
386 log_pkt("<< recv error %d\n", err);
387 log_error("Receive error: %d", err);
391 log_pkt("<< recv %d bytes\n", transferred);
392 while (transferred < 64)
393 reply[transferred++] = 0xff;
399 static unsigned int get_be16(byte *p)
401 return p[1] | (p[0] << 8);
404 static unsigned int get_le16(byte *p)
406 return p[0] | (p[1] << 8);
409 static unsigned int get_le32(byte *p)
411 return get_le16(p) | (get_le16(p+2) << 16);
414 static void put_le16(byte *p, unsigned int x)
420 static void put_le32(byte *p, unsigned int x)
423 put_le16(p+2, x>>16);
426 static int parse_packet(byte *reply)
429 log_error("Unknown packet type %02x", reply[0]);
436 byte *p = reply + pos;
438 if (!len || len == 0xff)
440 if (len < 9 || len > 10) {
441 log_error("Unknown tuple length %02x", len);
444 if (pos + len > 64) {
445 log_error("Tuple truncated");
448 int id = get_le16(p+1);
449 int raw = get_be16(p+3);
450 int t = get_le32(p+5);
451 int q = (len > 9) ? p[9] : -1;
452 if (debug_raw_data) {
453 printf("... %02x: id=%d raw=%d t=%d", len, id, raw, t);
458 raw_point(t, id, raw, q);
466 static void set_clock(void)
468 byte req[64], reply[64];
471 time_t t = time(NULL);
472 put_le32(req+1, t-TIME_OFFSET);
473 send_and_receive(req, reply);
477 * Original software also sends a packet with type 3 and the timestamp,
478 * but it does not make any sense, especially as they ignore the sensor
479 * readings in the answer.
482 send_and_receive(req, reply);
489 static volatile sig_atomic_t want_shutdown;
491 static void sigterm_handler(int sig __attribute__((unused)))
496 static const struct option long_options[] = {
497 { "debug", 0, NULL, 'd' },
498 { "log-dir", 1, NULL, 'l' },
499 { "debug-packets", 0, NULL, 'p' },
500 { "debug-raw", 0, NULL, 'r' },
501 { NULL, 0, NULL, 0 },
504 static void usage(void)
507 Usage: arexxd <options>\n\
510 -d, --debug Debug mode (no chdir, no fork, no syslog)\n\
511 -l, --log-dir=<dir> Directory where all received data should be stored\n\
512 -p, --debug-packets Log all packets sent and received\n\
513 -r, --debug-raw Log conversion from raw values\n\
518 int main(int argc, char **argv)
521 while ((opt = getopt_long(argc, argv, "dl:pr", long_options, NULL)) >= 0)
542 if (err = libusb_init(&usb_ctxt))
543 die("Cannot initialize libusb: error %d", err);
544 // libusb_set_debug(usb_ctxt, 3);
547 if (chdir(log_dir) < 0)
548 die("Cannot change directory to %s: %m", log_dir);
549 if (debug_packets || debug_raw_data) {
551 if (open("debug", O_WRONLY | O_CREAT | O_APPEND, 0666) < 0)
552 die("Cannot open debug log: %m");
555 openlog("arexxd", LOG_NDELAY, LOG_DAEMON);
558 die("fork() failed: %m");
565 struct sigaction sa = { .sa_handler = sigterm_handler };
566 sigaction(SIGTERM, &sa, NULL);
567 sigaction(SIGINT, &sa, NULL);
570 sigemptyset(&term_sigs);
571 sigaddset(&term_sigs, SIGTERM);
572 sigaddset(&term_sigs, SIGINT);
573 sigprocmask(SIG_BLOCK, &term_sigs, NULL);
576 while (!want_shutdown) {
577 if (!find_device()) {
580 log_error("Data logger not connected, waiting until it appears");
585 log_info("Listening");
587 time_t last_sync = 0;
588 time_t last_show = 0;
591 data_point_counter = 0;
592 while (!want_shutdown) {
593 time_t now = time(NULL);
594 if (now > last_sync + 900) {
595 log_info("Synchronizing data logger time");
599 if (want_stats && now > last_show + 300) {
600 log_info("Stats: received %d data points", data_point_counter);
601 data_point_counter = 0;
605 byte req[64], reply[64];
606 memset(req, 0, sizeof(req));
608 err = send_and_receive(req, reply);
612 if (err > 0 && parse_packet(reply))
614 sigprocmask(SIG_UNBLOCK, &term_sigs, NULL);
619 sigprocmask(SIG_BLOCK, &term_sigs, NULL);
622 log_info("Disconnecting data logger");
627 log_info("Terminated");