arexxd.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697
  1. /*
  2. * Linux Interfece for Arexx Data Loggers
  3. *
  4. * (c) 2011-2012 Martin Mares <mj@ucw.cz>
  5. */
  6. #include <stdio.h>
  7. #include <stdarg.h>
  8. #include <stdlib.h>
  9. #include <string.h>
  10. #include <unistd.h>
  11. #include <fcntl.h>
  12. #include <math.h>
  13. #include <time.h>
  14. #include <getopt.h>
  15. #include <syslog.h>
  16. #include <signal.h>
  17. #include <sys/stat.h>
  18. #include <libusb-1.0/libusb.h>
  19. #include <rrd.h>
  20. #define DEFAULT_LOG_DIR "/var/log/arexxd"
  21. typedef unsigned char byte;
  22. static libusb_context *usb_ctxt;
  23. static libusb_device_handle *devh;
  24. static int use_syslog;
  25. static int debug_mode;
  26. static int debug_packets;
  27. static int debug_raw_data;
  28. static int debug_usb;
  29. static char *log_dir = DEFAULT_LOG_DIR;
  30. static void die(char *fmt, ...)
  31. {
  32. va_list args;
  33. va_start(args, fmt);
  34. if (use_syslog)
  35. vsyslog(LOG_CRIT, fmt, args);
  36. else {
  37. vfprintf(stderr, fmt, args);
  38. fprintf(stderr, "\n");
  39. }
  40. va_end(args);
  41. exit(1);
  42. }
  43. static void log_error(char *fmt, ...)
  44. {
  45. va_list args;
  46. va_start(args, fmt);
  47. if (use_syslog)
  48. vsyslog(LOG_ERR, fmt, args);
  49. else {
  50. vfprintf(stderr, fmt, args);
  51. fprintf(stderr, "\n");
  52. }
  53. va_end(args);
  54. }
  55. static void log_info(char *fmt, ...)
  56. {
  57. va_list args;
  58. va_start(args, fmt);
  59. if (use_syslog)
  60. vsyslog(LOG_INFO, fmt, args);
  61. else {
  62. vfprintf(stderr, fmt, args);
  63. fprintf(stderr, "\n");
  64. }
  65. va_end(args);
  66. }
  67. static void log_pkt(char *fmt, ...)
  68. {
  69. if (!debug_packets)
  70. return;
  71. va_list args;
  72. va_start(args, fmt);
  73. vprintf(fmt, args);
  74. va_end(args);
  75. }
  76. /*** RRD interface ***/
  77. #define MAX_ARGS 20
  78. #define MAX_ARG_SIZE 1024
  79. static int arg_cnt;
  80. static char *arg_ptr[MAX_ARGS+1];
  81. static char arg_buf[MAX_ARG_SIZE];
  82. static int arg_pos;
  83. static void arg_new(void)
  84. {
  85. arg_cnt = 1;
  86. arg_pos = 0;
  87. arg_ptr[0] = "rrdtool";
  88. }
  89. static void arg_push(const char *fmt, ...)
  90. {
  91. if (arg_cnt >= MAX_ARGS)
  92. die("MAX_ARGS exceeded");
  93. va_list va;
  94. va_start(va, fmt);
  95. int len = 1 + vsnprintf(arg_buf + arg_pos, MAX_ARG_SIZE - arg_pos, fmt, va);
  96. if (arg_pos + len > MAX_ARG_SIZE)
  97. die("MAX_ARG_SIZE exceeded");
  98. arg_ptr[arg_cnt++] = arg_buf + arg_pos;
  99. arg_ptr[arg_cnt] = NULL;
  100. arg_pos += len;
  101. }
  102. static void rrd_point(time_t t, const char *name, double val, char *unit)
  103. {
  104. char rr_name[256];
  105. snprintf(rr_name, sizeof(rr_name), "sensor-%s.rrd", name);
  106. struct stat st;
  107. if (stat(rr_name, &st) < 0 || !st.st_size) {
  108. // We have to create the RRD
  109. log_info("Creating %s", rr_name);
  110. arg_new();
  111. arg_push(rr_name);
  112. arg_push("--start");
  113. arg_push("%d", (int) time(NULL) - 28*86400);
  114. arg_push("--step");
  115. arg_push("60");
  116. if (!strcmp(unit, "%RH"))
  117. arg_push("DS:rh:GAUGE:300:0:100");
  118. else if (!strcmp(unit, "ppm"))
  119. arg_push("DS:ppm:GAUGE:300:0:1000000");
  120. else
  121. arg_push("DS:temp:GAUGE:300:-200:200");
  122. arg_push("RRA:AVERAGE:0.25:1:20160"); // Last 14 days with full resolution
  123. arg_push("RRA:AVERAGE:0.25:60:88800"); // Last 10 years with 1h resolution
  124. arg_push("RRA:MIN:0.25:60:88800"); // including minima and maxima
  125. arg_push("RRA:MAX:0.25:60:88800");
  126. rrd_create(arg_cnt, arg_ptr);
  127. if (rrd_test_error()) {
  128. log_error("rrd_create on %s failed: %s", rr_name, rrd_get_error());
  129. return;
  130. }
  131. }
  132. arg_new();
  133. arg_push(rr_name);
  134. arg_push("%d:%f", t, val);
  135. rrd_update(arg_cnt, arg_ptr);
  136. if (rrd_test_error())
  137. log_error("rrd_update on %s failed: %s", rr_name, rrd_get_error());
  138. }
  139. /*** Transforms ***/
  140. #define TIME_OFFSET 946681200 // Timestamp of 2000-01-01 00:00:00
  141. static int data_point_counter; // Since last log message
  142. static double correct_point(int id, double val, const char **name)
  143. {
  144. /*
  145. * Manually calculated corrections and renames for my sensors.
  146. * Replace with your formulae.
  147. */
  148. switch (id) {
  149. case 10415:
  150. *name = "ursarium";
  151. return val - 0.93;
  152. case 10707:
  153. *name = "balcony";
  154. return val - 0.71;
  155. case 19246:
  156. *name = "catarium";
  157. return val + 0.49;
  158. case 19247:
  159. *name = "catarium-rh";
  160. return val;
  161. case 12133:
  162. *name = "outside";
  163. return val + 0.44;
  164. default:
  165. return val;
  166. }
  167. }
  168. static void cooked_point(time_t t, int id, double val, char *unit, int q)
  169. {
  170. char namebuf[16];
  171. snprintf(namebuf, sizeof(namebuf), "%d", id);
  172. const char *name = namebuf;
  173. double val2 = correct_point(id, val, &name);
  174. if (debug_raw_data) {
  175. struct tm tm;
  176. localtime_r(&t, &tm);
  177. char tbuf[64];
  178. strftime(tbuf, sizeof(tbuf), "%Y-%m-%d %H:%M:%S", &tm);
  179. printf("== %s id=%d name=%s val=%.3f val2=%.3f unit=%s q=%d\n", tbuf, id, name, val, val2, unit, q);
  180. }
  181. data_point_counter++;
  182. rrd_point(t, name, val2, unit);
  183. }
  184. static void raw_point(int t, int id, int raw, int q)
  185. {
  186. /*
  187. * The binary blob provided by Arexx contains an embedded XML fragment
  188. * with descriptions of all known sensor types. If you want to see it,
  189. * grep the blob for "<deviceinfo>". The meanings of the parameters are
  190. * as follows:
  191. *
  192. * m1, m2 Device type matches if (raw_sensor_id & m1) == m2
  193. * type Unit measured by the sensor (1=Celsius, 2=RH%, 3=CO2 ppm)
  194. * dm User-visible sensor ID = raw_sensor_id & dm
  195. * i 1 if the raw value is signed
  196. * p[] Coefficients of transformation polynomial (x^0 first)
  197. * vLo, vUp Upper and lower bound on the final value
  198. * scale Scaling function:
  199. * 0 = identity (default)
  200. * 1 = 10^x
  201. * 2 = exp(x)
  202. * 3 = (x < 0) ? 0 : log10(x)
  203. * 4 = (x < 0) ? 0 : log(x)
  204. *
  205. * The raw values are transformed this way:
  206. * - sign-extend if signed
  207. * - apply the transformation polynomial
  208. * - apply the scaling function
  209. * - drop if outside the interval [vLo,vUp]
  210. *
  211. * This function applies the necessary transform for sensors we've
  212. * seen in the wild. We deliberately ignore the "dm" parameter as we want
  213. * to report different channels of a single sensor as multiple sensors.
  214. */
  215. double z = raw;
  216. double hi, lo;
  217. char *unit;
  218. int idhi = id & 0xf000;
  219. if (idhi == 0x1000) {
  220. z = 0.02*z - 273.15;
  221. lo = -200;
  222. hi = 600;
  223. unit = "C";
  224. } else if (idhi == 0x2000) {
  225. if (raw >= 0x8000)
  226. z -= 0x10000;
  227. z /= 128;
  228. lo = -60;
  229. hi = 125;
  230. unit = "C";
  231. } else if (idhi == 0x4000) {
  232. if (!(id & 1)) {
  233. z = z/100 - 39.6;
  234. lo = -60;
  235. hi = 125;
  236. unit = "C";
  237. } else {
  238. z = -2.8e-6*z*z + 0.0405*z - 4;
  239. lo = 0;
  240. hi = 100.1;
  241. unit = "%RH";
  242. }
  243. } else if (idhi == 0x6000) {
  244. if (!(id & 1)) {
  245. if (raw >= 0x8000)
  246. z -= 0x10000;
  247. z /= 128;
  248. lo = -60;
  249. hi = 125;
  250. unit = "C";
  251. } else {
  252. z = -3.8123e-11*z;
  253. z = (z + 1.9184e-7) * z;
  254. z = (z - 1.0998e-3) * z;
  255. z += 6.56;
  256. z = pow(10, z);
  257. lo = 0;
  258. hi = 1e6;
  259. unit = "ppm";
  260. }
  261. } else {
  262. log_error("Unknown sensor type 0x%04x", id);
  263. return;
  264. }
  265. if (z < lo || z > hi) {
  266. log_error("Sensor %d: value %f out of range", id, z);
  267. return;
  268. }
  269. cooked_point(t + TIME_OFFSET, id, z, unit, q);
  270. }
  271. /*** USB interface ***/
  272. static int rx_endpoint, tx_endpoint;
  273. static int parse_descriptors(libusb_device *dev)
  274. {
  275. int err;
  276. struct libusb_config_descriptor *desc;
  277. if (err = libusb_get_active_config_descriptor(dev, &desc)) {
  278. log_error("libusb_get_config_descriptor failed: error %d", err);
  279. return 0;
  280. }
  281. if (desc->bNumInterfaces != 1) {
  282. log_error("Unexpected number of interfaces: %d", desc->bNumInterfaces);
  283. goto failed;
  284. }
  285. const struct libusb_interface *iface = &desc->interface[0];
  286. if (iface->num_altsetting != 1) {
  287. log_error("Unexpected number of alternate interface settings: %d", iface->num_altsetting);
  288. goto failed;
  289. }
  290. const struct libusb_interface_descriptor *ifd = &iface->altsetting[0];
  291. if (ifd->bNumEndpoints != 2) {
  292. log_error("Unexpected number of endpoints: %d", ifd->bNumEndpoints);
  293. goto failed;
  294. }
  295. rx_endpoint = tx_endpoint = -1;
  296. for (int i=0; i<2; i++) {
  297. const struct libusb_endpoint_descriptor *epd = &ifd->endpoint[i];
  298. if (epd->bEndpointAddress & 0x80)
  299. rx_endpoint = epd->bEndpointAddress;
  300. else
  301. tx_endpoint = epd->bEndpointAddress;
  302. }
  303. if (rx_endpoint < 0 || tx_endpoint < 0) {
  304. log_error("Failed to identify endpoints");
  305. goto failed;
  306. }
  307. log_pkt("Found endpoints: rx==%02x tx=%02x\n", rx_endpoint, tx_endpoint);
  308. libusb_free_config_descriptor(desc);
  309. return 1;
  310. failed:
  311. libusb_free_config_descriptor(desc);
  312. return 0;
  313. }
  314. static int find_device(void)
  315. {
  316. libusb_device **devlist;
  317. ssize_t devn = libusb_get_device_list(usb_ctxt, &devlist);
  318. if (devn < 0) {
  319. log_error("Cannot enumerate USB devices: error %d", (int) devn);
  320. return 0;
  321. }
  322. for (ssize_t i=0; i<devn; i++) {
  323. struct libusb_device_descriptor desc;
  324. libusb_device *dev = devlist[i];
  325. if (!libusb_get_device_descriptor(dev, &desc)) {
  326. if (desc.idVendor == 0x0451 && desc.idProduct == 0x3211) {
  327. log_info("Arexx data logger found at usb%d.%d", libusb_get_bus_number(dev), libusb_get_device_address(dev));
  328. if (!parse_descriptors(dev))
  329. continue;
  330. int err;
  331. if (err = libusb_open(dev, &devh)) {
  332. log_error("libusb_open() failed: error %d", err);
  333. goto failed;
  334. }
  335. if (err = libusb_claim_interface(devh, 0)) {
  336. log_error("libusb_claim_interface() failed: error %d", err);
  337. libusb_close(devh);
  338. goto failed;
  339. }
  340. libusb_free_device_list(devlist, 1);
  341. return 1;
  342. }
  343. }
  344. }
  345. failed:
  346. libusb_free_device_list(devlist, 1);
  347. return 0;
  348. }
  349. static void release_device(void)
  350. {
  351. libusb_release_interface(devh, 0);
  352. libusb_reset_device(devh);
  353. libusb_close(devh);
  354. devh = NULL;
  355. }
  356. static void dump_packet(byte *pkt)
  357. {
  358. for (int i=0; i<64; i++) {
  359. if (!(i % 16))
  360. log_pkt("\t%02x:", i);
  361. log_pkt(" %02x", pkt[i]);
  362. if (i % 16 == 15)
  363. log_pkt("\n");
  364. }
  365. }
  366. static int send_and_receive(byte *req, byte *reply)
  367. {
  368. if (debug_packets) {
  369. time_t t = time(NULL);
  370. struct tm tm;
  371. localtime_r(&t, &tm);
  372. char tbuf[64];
  373. strftime(tbuf, sizeof(tbuf), "%Y-%m-%d %H:%M:%S", &tm);
  374. log_pkt("## %s\n", tbuf);
  375. }
  376. int err, transferred;
  377. if (err = libusb_bulk_transfer(devh, tx_endpoint, req, 64, &transferred, 200)) {
  378. if (err == LIBUSB_ERROR_TIMEOUT) {
  379. log_pkt(">> xmit timed out\n");
  380. return 0;
  381. }
  382. log_pkt(">> xmit error %d\n", err);
  383. log_error("Transmit error: %d", err);
  384. return err;
  385. }
  386. if (debug_packets) {
  387. log_pkt(">> xmit %d bytes\n", transferred);
  388. dump_packet(req);
  389. }
  390. if (err = libusb_bulk_transfer(devh, rx_endpoint, reply, 64, &transferred, 200)) {
  391. if (err == LIBUSB_ERROR_TIMEOUT) {
  392. log_pkt("<< recv timed out\n");
  393. return 0;
  394. }
  395. log_pkt("<< recv error %d\n", err);
  396. log_error("Receive error: %d", err);
  397. return err;
  398. }
  399. if (debug_packets)
  400. log_pkt("<< recv %d bytes\n", transferred);
  401. while (transferred < 64)
  402. reply[transferred++] = 0xff;
  403. if (debug_packets)
  404. dump_packet(reply);
  405. return 1;
  406. }
  407. static unsigned int get_be16(byte *p)
  408. {
  409. return p[1] | (p[0] << 8);
  410. }
  411. static unsigned int get_le16(byte *p)
  412. {
  413. return p[0] | (p[1] << 8);
  414. }
  415. static unsigned int get_le32(byte *p)
  416. {
  417. return get_le16(p) | (get_le16(p+2) << 16);
  418. }
  419. static void put_le16(byte *p, unsigned int x)
  420. {
  421. p[0] = x;
  422. p[1] = x >> 8;
  423. }
  424. static void put_le32(byte *p, unsigned int x)
  425. {
  426. put_le16(p, x);
  427. put_le16(p+2, x>>16);
  428. }
  429. static int parse_packet(byte *reply)
  430. {
  431. if (reply[0]) {
  432. log_error("Unknown packet type %02x", reply[0]);
  433. return 0;
  434. }
  435. int pos = 1;
  436. int points = 0;
  437. while (pos < 64) {
  438. byte *p = reply + pos;
  439. int len = p[0];
  440. if (!len || len == 0xff)
  441. break;
  442. if (len < 9 || len > 10) {
  443. log_error("Unknown tuple length %02x", len);
  444. break;
  445. }
  446. if (pos + len > 64) {
  447. log_error("Tuple truncated");
  448. break;
  449. }
  450. int id = get_le16(p+1);
  451. int raw = get_be16(p+3);
  452. int t = get_le32(p+5);
  453. int q = (len > 9) ? p[9] : -1;
  454. if (debug_raw_data) {
  455. printf("... %02x: id=%d raw=%d t=%d", len, id, raw, t);
  456. if (len > 9)
  457. printf(" q=%d", q);
  458. printf("\n");
  459. }
  460. raw_point(t, id, raw, q);
  461. pos += len;
  462. points++;
  463. }
  464. return points;
  465. }
  466. static void set_clock(void)
  467. {
  468. byte req[64], reply[64];
  469. memset(req, 0, 64);
  470. req[0] = 4;
  471. time_t t = time(NULL);
  472. put_le32(req+1, t-TIME_OFFSET);
  473. send_and_receive(req, reply);
  474. #if 0
  475. /*
  476. * Original software also sends a packet with type 3 and the timestamp,
  477. * but it does not make any sense, especially as they ignore the sensor
  478. * readings in the answer.
  479. */
  480. req[0] = 3;
  481. send_and_receive(req, reply);
  482. parse_packet(reply);
  483. #endif
  484. }
  485. /*** Main ***/
  486. static sigset_t term_sigs;
  487. static volatile sig_atomic_t want_shutdown;
  488. static void sigterm_handler(int sig __attribute__((unused)))
  489. {
  490. want_shutdown = 1;
  491. }
  492. static void interruptible_msleep(int ms)
  493. {
  494. sigprocmask(SIG_UNBLOCK, &term_sigs, NULL);
  495. struct timespec ts = { .tv_sec = ms/1000, .tv_nsec = (ms%1000) * 1000000 };
  496. nanosleep(&ts, NULL);
  497. sigprocmask(SIG_BLOCK, &term_sigs, NULL);
  498. }
  499. static const struct option long_options[] = {
  500. { "debug", 0, NULL, 'd' },
  501. { "log-dir", 1, NULL, 'l' },
  502. { "debug-packets", 0, NULL, 'p' },
  503. { "debug-raw", 0, NULL, 'r' },
  504. { NULL, 0, NULL, 0 },
  505. };
  506. static void usage(void)
  507. {
  508. fprintf(stderr, "\n\
  509. Usage: arexxd <options>\n\
  510. \n\
  511. Options:\n\
  512. -d, --debug Debug mode (no chdir, no fork, no syslog)\n\
  513. -l, --log-dir=<dir> Directory where all received data should be stored\n\
  514. -p, --debug-packets Log all packets sent and received\n\
  515. -r, --debug-raw Log conversion from raw values\n\
  516. -u, --debug-usb Enable libusb debug messages (to stdout/stderr)\n\
  517. ");
  518. exit(1);
  519. }
  520. int main(int argc, char **argv)
  521. {
  522. int opt;
  523. while ((opt = getopt_long(argc, argv, "dl:pru", long_options, NULL)) >= 0)
  524. switch (opt) {
  525. case 'd':
  526. debug_mode++;
  527. break;
  528. case 'l':
  529. log_dir = optarg;
  530. break;
  531. case 'p':
  532. debug_packets++;
  533. break;
  534. case 'r':
  535. debug_raw_data++;
  536. break;
  537. case 'u':
  538. debug_usb++;
  539. break;
  540. default:
  541. usage();
  542. }
  543. if (optind < argc)
  544. usage();
  545. int err;
  546. if (err = libusb_init(&usb_ctxt))
  547. die("Cannot initialize libusb: error %d", err);
  548. if (debug_usb)
  549. libusb_set_debug(usb_ctxt, 3);
  550. if (!debug_mode) {
  551. if (chdir(log_dir) < 0)
  552. die("Cannot change directory to %s: %m", log_dir);
  553. if (debug_packets || debug_raw_data) {
  554. close(1);
  555. if (open("debug", O_WRONLY | O_CREAT | O_APPEND, 0666) < 0)
  556. die("Cannot open debug log: %m");
  557. setlinebuf(stdout);
  558. }
  559. openlog("arexxd", LOG_NDELAY, LOG_DAEMON);
  560. pid_t pid = fork();
  561. if (pid < 0)
  562. die("fork() failed: %m");
  563. if (pid)
  564. return 0;
  565. setsid();
  566. use_syslog = 1;
  567. }
  568. struct sigaction sa = { .sa_handler = sigterm_handler };
  569. sigaction(SIGTERM, &sa, NULL);
  570. sigaction(SIGINT, &sa, NULL);
  571. sigemptyset(&term_sigs);
  572. sigaddset(&term_sigs, SIGTERM);
  573. sigaddset(&term_sigs, SIGINT);
  574. sigprocmask(SIG_BLOCK, &term_sigs, NULL);
  575. int inited = 0;
  576. while (!want_shutdown) {
  577. if (!find_device()) {
  578. if (!inited) {
  579. inited = 1;
  580. log_error("Data logger not connected, waiting until it appears");
  581. }
  582. interruptible_msleep(30000);
  583. continue;
  584. }
  585. log_info("Listening");
  586. time_t last_sync = 0;
  587. time_t last_show = 0;
  588. int want_stats = 0;
  589. int want_sleep = 0;
  590. data_point_counter = 0;
  591. while (!want_shutdown) {
  592. time_t now = time(NULL);
  593. if (now > last_sync + 900) {
  594. log_info("Synchronizing data logger time");
  595. set_clock();
  596. last_sync = now;
  597. }
  598. if (want_stats && now > last_show + 300) {
  599. log_info("Stats: received %d data points", data_point_counter);
  600. data_point_counter = 0;
  601. last_show = now;
  602. }
  603. byte req[64], reply[64];
  604. memset(req, 0, sizeof(req));
  605. req[0] = 3;
  606. err = send_and_receive(req, reply);
  607. if (err < 0)
  608. break;
  609. want_sleep = 1;
  610. if (err > 0 && parse_packet(reply))
  611. want_sleep = 0;
  612. if (want_sleep) {
  613. interruptible_msleep(4000);
  614. want_stats = 1;
  615. } else
  616. interruptible_msleep(5);
  617. }
  618. log_info("Disconnecting data logger");
  619. release_device();
  620. inited = 0;
  621. interruptible_msleep(10000);
  622. }
  623. log_info("Terminated");
  624. return 0;
  625. }