arexxd.c 17 KB

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