2 * Linux Interfece for Arexx Data Loggers
4 * (c) 2011 Martin Mares <mj@ucw.cz>
20 #include <libusb-1.0/libusb.h>
23 #define LOG_PATH "/var/log/arexxd"
25 typedef unsigned char byte;
26 static libusb_context *usb_ctxt;
27 static libusb_device_handle *devh;
29 static int use_syslog;
30 static int debug_mode;
31 static int debug_packets;
32 static int debug_raw_data;
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 ***/
86 #define SLOT_SIZE 10 // 10 seconds per averaging slot
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, int id, double val)
119 snprintf(rr_name, sizeof(rr_name), "sensor-%d.rrd", id);
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 arg_push("DS:temp:GAUGE:300:0:10000"); // Anything over 10 kW is considered a ghost
132 arg_push("RRA:AVERAGE:0.25:1:20160"); // Last 14 days with full resolution
133 arg_push("RRA:AVERAGE:0.25:60:88800"); // Last 10 years with 1h resolution
134 rrd_create(arg_cnt, arg_ptr);
135 if (rrd_test_error()) {
136 log_error("rrd_create on %s failed: %s", rr_name, rrd_get_error());
143 arg_push("%d:%f", t, val);
144 rrd_update(arg_cnt, arg_ptr);
145 if (rrd_test_error())
146 log_error("rrd_update on %s failed: %s", rr_name, rrd_get_error());
151 #define TIME_OFFSET 946681200 // Timestamp of 2000-01-01 00:00:00
153 static void cooked_point(time_t t, int id, double val, char *unit, int q)
156 localtime_r(&t, &tm);
159 strftime(tbuf, sizeof(tbuf), "%Y-%m-%d %H:%M:%S", &tm);
162 printf("== %s id=%d val=%.3f unit=%s q=%d\n", tbuf, id, val, unit, q);
164 rrd_point(t, id, val);
167 static void raw_point(int t, int id, int raw, int q)
170 * The binary blob provided by Arexx contains an embedded XML fragment
171 * with descriptions of all known sensor types. If you want to see it,
172 * grep the blob for "<deviceinfo>". The meanings of the parameters are
175 * m1, m2 Device type matches if (raw_sensor_id & m1) == m2
176 * type Unit measured by the sensor (1=Celsius, 2=RH%, 3=CO2 ppm)
177 * dm User-visible sensor ID = raw_sensor_id & dm
178 * i 1 if the raw value is signed
179 * p[] Coefficients of transformation polynomial (x^0 first)
180 * vLo, vUp Upper and lower bound on the final value
181 * scale Scaling function:
182 * 0 = identity (default)
185 * 3 = (x < 0) ? 0 : log10(x)
186 * 4 = (x < 0) ? 0 : log(x)
188 * The raw values are transformed this way:
189 * - sign-extend if signed
190 * - apply the transformation polynomial
191 * - apply the scaling function
192 * - drop if outside the interval [vLo,vUp]
194 * This function applies the necessary transform for sensors we've
195 * seen in the wild. We deliberately ignore the "dm" parameter as we want
196 * to report different channels of a single sensor as multiple sensors.
202 int idhi = id & 0xf000;
204 if (idhi == 0x1000) {
209 } else if (idhi == 0x2000) {
216 } else if (idhi == 0x4000) {
223 z = -2.8e-6*z*z + 0.0405*z - 4;
228 } else if (idhi == 0x6000) {
238 z = (z + 1.9184e-7) * z;
239 z = (z - 1.0998e-3) * z;
247 log_error("Unknown sensor type 0x%04x", id);
251 if (z < lo || z > hi) {
252 log_error("Sensor %d: value %f out of range", id, z);
256 cooked_point(t + TIME_OFFSET, id, z, unit, q);
259 /*** USB interface ***/
261 static int find_device(void)
263 libusb_device **devlist;
264 ssize_t devn = libusb_get_device_list(usb_ctxt, &devlist);
266 log_error("Cannot enumerate USB devices: error %d", (int) devn);
270 for (ssize_t i=0; i<devn; i++) {
271 struct libusb_device_descriptor desc;
272 libusb_device *dev = devlist[i];
273 if (!libusb_get_device_descriptor(dev, &desc)) {
274 if (desc.idVendor == 0x0451 && desc.idProduct == 0x3211) {
275 log_info("Arexx USB receiver found at usb%d.%d", libusb_get_bus_number(dev), libusb_get_device_address(dev));
277 if (err = libusb_open(dev, &devh)) {
278 log_error("libusb_open() failed: error %d", err);
281 if (err = libusb_claim_interface(devh, 0)) {
282 log_error("libusb_claim_interface() failed: error %d", err);
286 libusb_free_device_list(devlist, 1);
293 libusb_free_device_list(devlist, 1);
297 static void release_device(void)
303 static void dump_packet(byte *pkt)
305 for (int i=0; i<64; i++) {
307 log_pkt("\t%02x:", i);
308 log_pkt(" %02x", pkt[i]);
314 static int send_and_receive(byte *req, byte *reply)
316 int err, transferred;
317 if (err = libusb_bulk_transfer(devh, 0x01, req, 64, &transferred, 200)) {
318 if (err == LIBUSB_ERROR_TIMEOUT) {
319 log_pkt(">> xmit timed out\n");
322 log_error("Transmit error: %d", err);
326 log_pkt(">> xmit %d bytes\n", transferred);
329 if (err = libusb_bulk_transfer(devh, 0x81, reply, 64, &transferred, 200)) {
330 if (err == LIBUSB_ERROR_TIMEOUT) {
331 log_pkt(">> recv timed out\n");
334 log_error("Receive error: %d", err);
338 log_pkt("<< recv %d bytes\n", transferred);
339 while (transferred < 64)
340 reply[transferred++] = 0xff;
346 static unsigned int get_be16(byte *p)
348 return p[1] | (p[0] << 8);
351 static unsigned int get_le16(byte *p)
353 return p[0] | (p[1] << 8);
356 static unsigned int get_le32(byte *p)
358 return get_le16(p) | (get_le16(p+2) << 16);
361 static void put_le16(byte *p, unsigned int x)
367 static void put_le32(byte *p, unsigned int x)
370 put_le16(p+2, x>>16);
373 static int parse_packet(byte *reply)
376 log_error("Unknown packet type %02x", reply[0]);
383 byte *p = reply + pos;
385 if (!len || len == 0xff)
387 if (len < 9 || len > 10) {
388 log_error("Unknown tuple length %02x", len);
391 if (pos + len > 64) {
392 log_error("Tuple truncated");
395 int id = get_le16(p+1);
396 int raw = get_be16(p+3);
397 int t = get_le32(p+5);
398 int q = (len > 9) ? p[9] : -1;
399 if (debug_raw_data) {
400 printf("... %02x: id=%d raw=%d t=%d", len, id, raw, t);
405 raw_point(t, id, raw, q);
413 static void set_clock(void)
415 log_info("Synchronizing receiver time");
417 byte req[64], reply[64];
420 time_t t = time(NULL);
421 put_le32(req+1, t-TIME_OFFSET);
422 send_and_receive(req, reply);
426 * Original software also sends a packet with type 3 and the timestamp,
427 * but it does not make any sense, especially as they ignore the sensor
428 * readings in the answer.
431 send_and_receive(req, reply);
438 static const struct option long_options[] = {
439 { "debug", 0, NULL, 'd' },
440 { "log-packets", 0, NULL, 'p' },
441 { NULL, 0, NULL, 0 },
444 static void usage(void)
446 fprintf(stderr, "Usage: arexxd [--debug] [--log-packets]\n");
450 int main(int argc, char **argv)
453 while ((opt = getopt_long(argc, argv, "dp", long_options, NULL)) >= 0)
469 if (err = libusb_init(&usb_ctxt))
470 die("Cannot initialize libusb: error %d", err);
471 // libusb_set_debug(usb_ctxt, 3);
474 if (chdir(LOG_PATH) < 0)
475 die("Cannot change directory to %s: %m", LOG_PATH);
476 if (debug_packets || debug_raw_data) {
478 if (open("debug", O_WRONLY | O_CREAT | O_APPEND, 0666) < 0)
479 die("Cannot open debug log: %m");
482 openlog("arexxd", LOG_NDELAY, LOG_DAEMON);
485 die("fork() failed: %m");
494 if (!find_device()) {
497 log_error("Receiver not connected, waiting until it appears");
511 byte req[64], reply[64];
512 memset(req, 0, sizeof(req));
514 err = send_and_receive(req, reply);
517 if (err > 0 && parse_packet(reply))
523 log_info("Disconnecting receiver");