arexxd.c 14 KB

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