arexxd.c 18 KB

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