arexxd.c 18 KB

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