arexxd.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  1. /*
  2. * Linux Interfece for Arexx Data Loggers
  3. *
  4. * (c) 2011 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 LOG_PATH "/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 void die(char *fmt, ...)
  29. {
  30. va_list args;
  31. va_start(args, fmt);
  32. if (use_syslog)
  33. vsyslog(LOG_CRIT, fmt, args);
  34. else {
  35. vfprintf(stderr, fmt, args);
  36. fprintf(stderr, "\n");
  37. }
  38. va_end(args);
  39. exit(1);
  40. }
  41. static void log_error(char *fmt, ...)
  42. {
  43. va_list args;
  44. va_start(args, fmt);
  45. if (use_syslog)
  46. vsyslog(LOG_ERR, fmt, args);
  47. else {
  48. vfprintf(stderr, fmt, args);
  49. fprintf(stderr, "\n");
  50. }
  51. va_end(args);
  52. }
  53. static void log_info(char *fmt, ...)
  54. {
  55. va_list args;
  56. va_start(args, fmt);
  57. if (use_syslog)
  58. vsyslog(LOG_INFO, fmt, args);
  59. else {
  60. vfprintf(stderr, fmt, args);
  61. fprintf(stderr, "\n");
  62. }
  63. va_end(args);
  64. }
  65. static void log_pkt(char *fmt, ...)
  66. {
  67. if (!debug_packets)
  68. return;
  69. va_list args;
  70. va_start(args, fmt);
  71. vprintf(fmt, args);
  72. va_end(args);
  73. }
  74. /*** RRD interface ***/
  75. #define SLOT_SIZE 10 // 10 seconds per averaging slot
  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, int id, double val, char *unit)
  102. {
  103. char rr_name[256];
  104. snprintf(rr_name, sizeof(rr_name), "sensor-%d.rrd", id);
  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;
  141. static void cooked_point(time_t t, int id, double val, char *unit, int q)
  142. {
  143. if (debug_raw_data) {
  144. struct tm tm;
  145. localtime_r(&t, &tm);
  146. char tbuf[64];
  147. strftime(tbuf, sizeof(tbuf), "%Y-%m-%d %H:%M:%S", &tm);
  148. printf("== %s id=%d val=%.3f unit=%s q=%d\n", tbuf, id, val, unit, q);
  149. }
  150. data_point_counter++;
  151. rrd_point(t, id, val, unit);
  152. }
  153. static void raw_point(int t, int id, int raw, int q)
  154. {
  155. /*
  156. * The binary blob provided by Arexx contains an embedded XML fragment
  157. * with descriptions of all known sensor types. If you want to see it,
  158. * grep the blob for "<deviceinfo>". The meanings of the parameters are
  159. * as follows:
  160. *
  161. * m1, m2 Device type matches if (raw_sensor_id & m1) == m2
  162. * type Unit measured by the sensor (1=Celsius, 2=RH%, 3=CO2 ppm)
  163. * dm User-visible sensor ID = raw_sensor_id & dm
  164. * i 1 if the raw value is signed
  165. * p[] Coefficients of transformation polynomial (x^0 first)
  166. * vLo, vUp Upper and lower bound on the final value
  167. * scale Scaling function:
  168. * 0 = identity (default)
  169. * 1 = 10^x
  170. * 2 = exp(x)
  171. * 3 = (x < 0) ? 0 : log10(x)
  172. * 4 = (x < 0) ? 0 : log(x)
  173. *
  174. * The raw values are transformed this way:
  175. * - sign-extend if signed
  176. * - apply the transformation polynomial
  177. * - apply the scaling function
  178. * - drop if outside the interval [vLo,vUp]
  179. *
  180. * This function applies the necessary transform for sensors we've
  181. * seen in the wild. We deliberately ignore the "dm" parameter as we want
  182. * to report different channels of a single sensor as multiple sensors.
  183. */
  184. double z = raw;
  185. double hi, lo;
  186. char *unit;
  187. int idhi = id & 0xf000;
  188. if (idhi == 0x1000) {
  189. z = 0.02*z - 273.15;
  190. lo = -200;
  191. hi = 600;
  192. unit = "C";
  193. } else if (idhi == 0x2000) {
  194. if (raw >= 0x8000)
  195. z -= 0x10000;
  196. z /= 128;
  197. lo = -60;
  198. hi = 125;
  199. unit = "C";
  200. } else if (idhi == 0x4000) {
  201. if (!(id & 1)) {
  202. z = z/100 - 39.6;
  203. lo = -60;
  204. hi = 125;
  205. unit = "C";
  206. } else {
  207. z = -2.8e-6*z*z + 0.0405*z - 4;
  208. lo = 0;
  209. hi = 100.1;
  210. unit = "%RH";
  211. }
  212. } else if (idhi == 0x6000) {
  213. if (!(id & 1)) {
  214. if (raw >= 0x8000)
  215. z -= 0x10000;
  216. z /= 128;
  217. lo = -60;
  218. hi = 125;
  219. unit = "C";
  220. } else {
  221. z = -3.8123e-11*z;
  222. z = (z + 1.9184e-7) * z;
  223. z = (z - 1.0998e-3) * z;
  224. z += 6.56;
  225. z = pow(10, z);
  226. lo = 0;
  227. hi = 1e6;
  228. unit = "ppm";
  229. }
  230. } else {
  231. log_error("Unknown sensor type 0x%04x", id);
  232. return;
  233. }
  234. if (z < lo || z > hi) {
  235. log_error("Sensor %d: value %f out of range", id, z);
  236. return;
  237. }
  238. cooked_point(t + TIME_OFFSET, id, z, unit, q);
  239. }
  240. /*** USB interface ***/
  241. static int find_device(void)
  242. {
  243. libusb_device **devlist;
  244. ssize_t devn = libusb_get_device_list(usb_ctxt, &devlist);
  245. if (devn < 0) {
  246. log_error("Cannot enumerate USB devices: error %d", (int) devn);
  247. return 0;
  248. }
  249. for (ssize_t i=0; i<devn; i++) {
  250. struct libusb_device_descriptor desc;
  251. libusb_device *dev = devlist[i];
  252. if (!libusb_get_device_descriptor(dev, &desc)) {
  253. if (desc.idVendor == 0x0451 && desc.idProduct == 0x3211) {
  254. log_info("Arexx data logger found at usb%d.%d", libusb_get_bus_number(dev), libusb_get_device_address(dev));
  255. int err;
  256. if (err = libusb_open(dev, &devh)) {
  257. log_error("libusb_open() failed: error %d", err);
  258. goto failed;
  259. }
  260. if (err = libusb_claim_interface(devh, 0)) {
  261. log_error("libusb_claim_interface() failed: error %d", err);
  262. libusb_close(devh);
  263. goto failed;
  264. }
  265. libusb_free_device_list(devlist, 1);
  266. return 1;
  267. }
  268. }
  269. }
  270. failed:
  271. libusb_free_device_list(devlist, 1);
  272. return 0;
  273. }
  274. static void release_device(void)
  275. {
  276. libusb_close(devh);
  277. devh = NULL;
  278. }
  279. static void dump_packet(byte *pkt)
  280. {
  281. for (int i=0; i<64; i++) {
  282. if (!(i % 16))
  283. log_pkt("\t%02x:", i);
  284. log_pkt(" %02x", pkt[i]);
  285. if (i % 16 == 15)
  286. log_pkt("\n");
  287. }
  288. }
  289. static int send_and_receive(byte *req, byte *reply)
  290. {
  291. if (debug_packets) {
  292. time_t t = time(NULL);
  293. struct tm tm;
  294. localtime_r(&t, &tm);
  295. char tbuf[64];
  296. strftime(tbuf, sizeof(tbuf), "%Y-%m-%d %H:%M:%S", &tm);
  297. log_pkt("## %s\n", tbuf);
  298. }
  299. int err, transferred;
  300. if (err = libusb_bulk_transfer(devh, 0x01, req, 64, &transferred, 200)) {
  301. if (err == LIBUSB_ERROR_TIMEOUT) {
  302. log_pkt(">> xmit timed out\n");
  303. return 0;
  304. }
  305. log_pkt(">> xmit error %d\n", err);
  306. log_error("Transmit error: %d", err);
  307. return err;
  308. }
  309. if (debug_packets) {
  310. log_pkt(">> xmit %d bytes\n", transferred);
  311. dump_packet(req);
  312. }
  313. if (err = libusb_bulk_transfer(devh, 0x81, reply, 64, &transferred, 200)) {
  314. if (err == LIBUSB_ERROR_TIMEOUT) {
  315. log_pkt("<< recv timed out\n");
  316. return 0;
  317. }
  318. log_pkt("<< recv error %d\n", err);
  319. log_error("Receive error: %d", err);
  320. return err;
  321. }
  322. if (debug_packets)
  323. log_pkt("<< recv %d bytes\n", transferred);
  324. while (transferred < 64)
  325. reply[transferred++] = 0xff;
  326. if (debug_packets)
  327. dump_packet(reply);
  328. return 1;
  329. }
  330. static unsigned int get_be16(byte *p)
  331. {
  332. return p[1] | (p[0] << 8);
  333. }
  334. static unsigned int get_le16(byte *p)
  335. {
  336. return p[0] | (p[1] << 8);
  337. }
  338. static unsigned int get_le32(byte *p)
  339. {
  340. return get_le16(p) | (get_le16(p+2) << 16);
  341. }
  342. static void put_le16(byte *p, unsigned int x)
  343. {
  344. p[0] = x;
  345. p[1] = x >> 8;
  346. }
  347. static void put_le32(byte *p, unsigned int x)
  348. {
  349. put_le16(p, x);
  350. put_le16(p+2, x>>16);
  351. }
  352. static int parse_packet(byte *reply)
  353. {
  354. if (reply[0]) {
  355. log_error("Unknown packet type %02x", reply[0]);
  356. return 0;
  357. }
  358. int pos = 1;
  359. int points = 0;
  360. while (pos < 64) {
  361. byte *p = reply + pos;
  362. int len = p[0];
  363. if (!len || len == 0xff)
  364. break;
  365. if (len < 9 || len > 10) {
  366. log_error("Unknown tuple length %02x", len);
  367. break;
  368. }
  369. if (pos + len > 64) {
  370. log_error("Tuple truncated");
  371. break;
  372. }
  373. int id = get_le16(p+1);
  374. int raw = get_be16(p+3);
  375. int t = get_le32(p+5);
  376. int q = (len > 9) ? p[9] : -1;
  377. if (debug_raw_data) {
  378. printf("... %02x: id=%d raw=%d t=%d", len, id, raw, t);
  379. if (len > 9)
  380. printf(" q=%d", q);
  381. printf("\n");
  382. }
  383. raw_point(t, id, raw, q);
  384. pos += len;
  385. points++;
  386. }
  387. return points;
  388. }
  389. static void set_clock(void)
  390. {
  391. byte req[64], reply[64];
  392. memset(req, 0, 64);
  393. req[0] = 4;
  394. time_t t = time(NULL);
  395. put_le32(req+1, t-TIME_OFFSET);
  396. send_and_receive(req, reply);
  397. #if 0
  398. /*
  399. * Original software also sends a packet with type 3 and the timestamp,
  400. * but it does not make any sense, especially as they ignore the sensor
  401. * readings in the answer.
  402. */
  403. req[0] = 3;
  404. send_and_receive(req, reply);
  405. parse_packet(reply);
  406. #endif
  407. }
  408. /*** Main ***/
  409. static volatile sig_atomic_t want_shutdown;
  410. static void sigterm_handler(int sig __attribute__((unused)))
  411. {
  412. want_shutdown = 1;
  413. }
  414. static const struct option long_options[] = {
  415. { "debug", 0, NULL, 'd' },
  416. { "log-packets", 0, NULL, 'p' },
  417. { NULL, 0, NULL, 0 },
  418. };
  419. static void usage(void)
  420. {
  421. fprintf(stderr, "Usage: arexxd [--debug] [--log-packets]\n");
  422. exit(1);
  423. }
  424. int main(int argc, char **argv)
  425. {
  426. int opt;
  427. while ((opt = getopt_long(argc, argv, "dp", long_options, NULL)) >= 0)
  428. switch (opt) {
  429. case 'd':
  430. debug_mode++;
  431. break;
  432. case 'p':
  433. debug_packets++;
  434. debug_raw_data++;
  435. break;
  436. default:
  437. usage();
  438. }
  439. if (optind < argc)
  440. usage();
  441. int err;
  442. if (err = libusb_init(&usb_ctxt))
  443. die("Cannot initialize libusb: error %d", err);
  444. // libusb_set_debug(usb_ctxt, 3);
  445. if (!debug_mode) {
  446. if (chdir(LOG_PATH) < 0)
  447. die("Cannot change directory to %s: %m", LOG_PATH);
  448. if (debug_packets || debug_raw_data) {
  449. close(1);
  450. if (open("debug", O_WRONLY | O_CREAT | O_APPEND, 0666) < 0)
  451. die("Cannot open debug log: %m");
  452. setlinebuf(stdout);
  453. }
  454. openlog("arexxd", LOG_NDELAY, LOG_DAEMON);
  455. pid_t pid = fork();
  456. if (pid < 0)
  457. die("fork() failed: %m");
  458. if (pid)
  459. return 0;
  460. setsid();
  461. use_syslog = 1;
  462. }
  463. struct sigaction sa = { .sa_handler = sigterm_handler };
  464. sigaction(SIGTERM, &sa, NULL);
  465. sigaction(SIGINT, &sa, NULL);
  466. sigset_t term_sigs;
  467. sigemptyset(&term_sigs);
  468. sigaddset(&term_sigs, SIGTERM);
  469. sigaddset(&term_sigs, SIGINT);
  470. sigprocmask(SIG_BLOCK, &term_sigs, NULL);
  471. int inited = 0;
  472. while (!want_shutdown) {
  473. if (!find_device()) {
  474. if (!inited) {
  475. inited = 1;
  476. log_error("Data logger not connected, waiting until it appears");
  477. }
  478. sleep(30);
  479. continue;
  480. }
  481. log_info("Listening");
  482. time_t last_sync = 0;
  483. time_t last_show = 0;
  484. int want_stats = 0;
  485. int want_sleep = 0;
  486. data_point_counter = 0;
  487. while (!want_shutdown) {
  488. time_t now = time(NULL);
  489. if (now > last_sync + 900) {
  490. log_info("Synchronizing data logger time");
  491. set_clock();
  492. last_sync = now;
  493. }
  494. if (want_stats && now > last_show + 300) {
  495. log_info("Stats: received %d data points", data_point_counter);
  496. data_point_counter = 0;
  497. last_show = now;
  498. }
  499. byte req[64], reply[64];
  500. memset(req, 0, sizeof(req));
  501. req[0] = 3;
  502. err = send_and_receive(req, reply);
  503. if (err < 0)
  504. break;
  505. want_sleep = 1;
  506. if (err > 0 && parse_packet(reply))
  507. want_sleep = 0;
  508. sigprocmask(SIG_UNBLOCK, &term_sigs, NULL);
  509. if (want_sleep) {
  510. sleep(4);
  511. want_stats = 1;
  512. }
  513. sigprocmask(SIG_BLOCK, &term_sigs, NULL);
  514. }
  515. log_info("Disconnecting data logger");
  516. release_device();
  517. inited = 0;
  518. }
  519. log_info("Terminated");
  520. return 0;
  521. }