arexxd.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820
  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 & 0xfffff000;
  279. int userid = id & 0x0FFFFFFF;
  280. if (idhi == 0x1000) {
  281. z = 0.02*z - 273.15;
  282. lo = -200;
  283. hi = 600;
  284. unit = "C";
  285. } else if (idhi == 0x2000) {
  286. if (raw >= 0x8000)
  287. z -= 0x10000;
  288. z /= 128;
  289. lo = -60;
  290. hi = 125;
  291. unit = "C";
  292. } else if (idhi == 0x4000) {
  293. if (!(id & 1)) {
  294. z = z/100 - 39.6;
  295. lo = -60;
  296. hi = 125;
  297. unit = "C";
  298. } else {
  299. z = -2.8e-6*z*z + 0.0405*z - 4;
  300. lo = 0;
  301. hi = 100.1;
  302. unit = "%RH";
  303. }
  304. } else if (idhi == 0x6000) {
  305. if (!(id & 1)) {
  306. if (raw >= 0x8000)
  307. z -= 0x10000;
  308. z /= 128;
  309. lo = -60;
  310. hi = 125;
  311. unit = "C";
  312. } else {
  313. z = -3.8123e-11*z;
  314. z = (z + 1.9184e-7) * z;
  315. z = (z - 1.0998e-3) * z;
  316. z += 6.56;
  317. z = pow(10, z);
  318. lo = 0;
  319. hi = 1e6;
  320. unit = "ppm";
  321. }
  322. } else if ( idhi = 0x40000000) {
  323. if (!(id & 1)) {
  324. // Temperature
  325. z = z/100 - 39.6;
  326. lo = -60;
  327. hi = 125;
  328. unit = "C";
  329. } else {
  330. // Humidity
  331. z = -2.8e-6*z*z + 0.0405*z - 4;
  332. lo = 0;
  333. hi = 100.1;
  334. unit = "%RH";
  335. }
  336. } else {
  337. log_error("Unknown sensor type 0x%04x.%04x/%d", ((id & 0xFFFF0000) >> 16), (id & 0xFFFF), userid);
  338. return;
  339. }
  340. if (z < lo || z > hi) {
  341. log_error("Sensor 0x%04x.%04x/%d: value %f out of range", ((id & 0xFFFF0000) >> 16), (id & 0xFFFF), userid, z);
  342. return;
  343. }
  344. cooked_point(t + TIME_OFFSET, userid, raw, z, unit, q);
  345. }
  346. /*** USB interface ***/
  347. static int rx_endpoint, tx_endpoint;
  348. static int parse_descriptors(libusb_device *dev)
  349. {
  350. int err;
  351. struct libusb_config_descriptor *desc;
  352. if (err = libusb_get_active_config_descriptor(dev, &desc)) {
  353. log_error("libusb_get_config_descriptor failed: error %d", err);
  354. return 0;
  355. }
  356. if (desc->bNumInterfaces != 1) {
  357. log_error("Unexpected number of interfaces: %d", desc->bNumInterfaces);
  358. goto failed;
  359. }
  360. const struct libusb_interface *iface = &desc->interface[0];
  361. if (iface->num_altsetting != 1) {
  362. log_error("Unexpected number of alternate interface settings: %d", iface->num_altsetting);
  363. goto failed;
  364. }
  365. const struct libusb_interface_descriptor *ifd = &iface->altsetting[0];
  366. if (ifd->bNumEndpoints != 2) {
  367. log_error("Unexpected number of endpoints: %d", ifd->bNumEndpoints);
  368. goto failed;
  369. }
  370. rx_endpoint = tx_endpoint = -1;
  371. for (int i=0; i<2; i++) {
  372. const struct libusb_endpoint_descriptor *epd = &ifd->endpoint[i];
  373. if (epd->bEndpointAddress & 0x80)
  374. rx_endpoint = epd->bEndpointAddress;
  375. else
  376. tx_endpoint = epd->bEndpointAddress;
  377. }
  378. if (rx_endpoint < 0 || tx_endpoint < 0) {
  379. log_error("Failed to identify endpoints");
  380. goto failed;
  381. }
  382. log_pkt("Found endpoints: rx==%02x tx=%02x\n", rx_endpoint, tx_endpoint);
  383. libusb_free_config_descriptor(desc);
  384. return 1;
  385. failed:
  386. libusb_free_config_descriptor(desc);
  387. return 0;
  388. }
  389. static int find_device(void)
  390. {
  391. libusb_device **devlist;
  392. ssize_t devn = libusb_get_device_list(usb_ctxt, &devlist);
  393. if (devn < 0) {
  394. log_error("Cannot enumerate USB devices: error %d", (int) devn);
  395. return 0;
  396. }
  397. for (ssize_t i=0; i<devn; i++) {
  398. struct libusb_device_descriptor desc;
  399. libusb_device *dev = devlist[i];
  400. if (!libusb_get_device_descriptor(dev, &desc)) {
  401. if (desc.idVendor == 0x0451 && desc.idProduct == 0x3211) {
  402. log_info("Arexx data logger found at usb%d.%d", libusb_get_bus_number(dev), libusb_get_device_address(dev));
  403. if (!parse_descriptors(dev))
  404. continue;
  405. int err;
  406. if (err = libusb_open(dev, &devh)) {
  407. log_error("libusb_open() failed: error %d", err);
  408. goto failed;
  409. }
  410. if (err = libusb_claim_interface(devh, 0)) {
  411. log_error("libusb_claim_interface() failed: error %d", err);
  412. libusb_close(devh);
  413. goto failed;
  414. }
  415. libusb_free_device_list(devlist, 1);
  416. return 1;
  417. }
  418. }
  419. }
  420. failed:
  421. libusb_free_device_list(devlist, 1);
  422. return 0;
  423. }
  424. static void release_device(void)
  425. {
  426. libusb_release_interface(devh, 0);
  427. libusb_reset_device(devh);
  428. libusb_close(devh);
  429. devh = NULL;
  430. }
  431. static void dump_packet(byte *pkt)
  432. {
  433. for (int i=0; i<64; i++) {
  434. if (!(i % 16))
  435. log_pkt("\t%02x:", i);
  436. log_pkt(" %02x", pkt[i]);
  437. if (i % 16 == 15)
  438. log_pkt("\n");
  439. }
  440. }
  441. static void my_msleep(int ms)
  442. {
  443. struct timespec ts = { .tv_sec = ms/1000, .tv_nsec = (ms%1000) * 1000000 };
  444. nanosleep(&ts, NULL);
  445. }
  446. static int send_and_receive(byte *req, byte *reply)
  447. {
  448. if (debug_packets) {
  449. time_t t = time(NULL);
  450. struct tm tm;
  451. localtime_r(&t, &tm);
  452. char tbuf[64];
  453. strftime(tbuf, sizeof(tbuf), "%Y-%m-%d %H:%M:%S", &tm);
  454. log_pkt("## %s\n", tbuf);
  455. }
  456. int err, transferred;
  457. if (err = libusb_bulk_transfer(devh, tx_endpoint, req, 64, &transferred, 200)) {
  458. if (err == LIBUSB_ERROR_TIMEOUT) {
  459. log_pkt(">> xmit timed out\n");
  460. return 0;
  461. }
  462. log_pkt(">> xmit error %d\n", err);
  463. log_error("Transmit error: %d", err);
  464. return err;
  465. }
  466. if (debug_packets) {
  467. log_pkt(">> xmit %d bytes\n", transferred);
  468. dump_packet(req);
  469. }
  470. my_msleep(1);
  471. if (err = libusb_bulk_transfer(devh, rx_endpoint, reply, 64, &transferred, 200)) {
  472. if (err == LIBUSB_ERROR_TIMEOUT) {
  473. log_pkt("<< recv timed out\n");
  474. return 0;
  475. }
  476. log_pkt("<< recv error %d\n", err);
  477. log_error("Receive error: %d", err);
  478. return err;
  479. }
  480. packet_rx_time = time(NULL);
  481. if (debug_packets)
  482. log_pkt("<< recv %d bytes\n", transferred);
  483. while (transferred < 64)
  484. reply[transferred++] = 0xff;
  485. if (debug_packets)
  486. dump_packet(reply);
  487. return 1;
  488. }
  489. static unsigned int get_be16(byte *p)
  490. {
  491. return p[1] | (p[0] << 8);
  492. }
  493. static unsigned int get_le16(byte *p)
  494. {
  495. return p[0] | (p[1] << 8);
  496. }
  497. static unsigned int get_le32(byte *p)
  498. {
  499. return get_le16(p) | (get_le16(p+2) << 16);
  500. }
  501. static void put_le16(byte *p, unsigned int x)
  502. {
  503. p[0] = x;
  504. p[1] = x >> 8;
  505. }
  506. static void put_le32(byte *p, unsigned int x)
  507. {
  508. put_le16(p, x);
  509. put_le16(p+2, x>>16);
  510. }
  511. static int parse_packet(byte *reply)
  512. {
  513. if (reply[0]) {
  514. log_error("Unknown packet type %02x", reply[0]);
  515. return 0;
  516. }
  517. int pos = 1;
  518. int points = 0;
  519. int len = 0;
  520. int id = 0;
  521. int raw = 0;
  522. int t = 0;
  523. int q = 0;
  524. while (pos < 64) {
  525. byte *p = reply + pos;
  526. len = p[0];
  527. p++;
  528. if (!len || len == 0xff)
  529. break;
  530. if (len < 9 || len > 12) {
  531. log_error("Unknown tuple length %02x", len);
  532. break;
  533. }
  534. if (pos + len > 64) {
  535. log_error("Tuple truncated");
  536. break;
  537. }
  538. if (len < 11) {
  539. id = get_le16(p);
  540. p += 2;
  541. } else {
  542. id = get_le32(p);
  543. p += 4;
  544. }
  545. raw = get_be16(p);
  546. p += 2;
  547. t = get_le32(p);
  548. p += 4;
  549. if (( (byte)*p & 1) == 1) {
  550. q = (byte)*p;
  551. } else {
  552. q = -1;
  553. }
  554. if (debug_raw_data) {
  555. printf("... %02x: id=0x%04x.%04x userid=%d raw=%d t=%d", len, ((id & 0xFFFF0000) >> 16), (id & 0xFFFF), (id & 0x0FFFFFFF), raw, t);
  556. // if (len & 1)
  557. printf(" q=%d", q);
  558. printf("\n");
  559. }
  560. raw_point(t, id, raw, q);
  561. pos += len;
  562. points++;
  563. }
  564. return points;
  565. }
  566. static void set_clock(void)
  567. {
  568. byte req[64], reply[64];
  569. memset(req, 0, 64);
  570. req[0] = 4;
  571. time_t t = time(NULL);
  572. put_le32(req+1, t-TIME_OFFSET);
  573. send_and_receive(req, reply);
  574. #if 0
  575. /*
  576. * Original software also sends a packet with type 3 and the timestamp,
  577. * but it does not make any sense, especially as they ignore the sensor
  578. * readings in the answer.
  579. */
  580. req[0] = 3;
  581. send_and_receive(req, reply);
  582. parse_packet(reply);
  583. #endif
  584. }
  585. /*** Main ***/
  586. static sigset_t term_sigs;
  587. static volatile sig_atomic_t want_shutdown;
  588. static void sigterm_handler(int sig __attribute__((unused)))
  589. {
  590. want_shutdown = 1;
  591. }
  592. static void interruptible_msleep(int ms)
  593. {
  594. sigprocmask(SIG_UNBLOCK, &term_sigs, NULL);
  595. my_msleep(ms);
  596. sigprocmask(SIG_BLOCK, &term_sigs, NULL);
  597. }
  598. static const struct option long_options[] = {
  599. { "rrd", 0, NULL, 'R' },
  600. { "storelatest", 0, NULL, 'S' },
  601. { "debug", 0, NULL, 'd' },
  602. { "log-dir", 1, NULL, 'l' },
  603. { "debug-packets", 0, NULL, 'p' },
  604. { "debug-raw", 0, NULL, 'r' },
  605. { "version", 0, NULL, 'V' },
  606. { NULL, 0, NULL, 0 },
  607. };
  608. static void usage(void)
  609. {
  610. fprintf(stderr, "\n\
  611. Usage: arexxd <options>\n\
  612. \n\
  613. Options:\n\
  614. -R, --rrd Store data in RRD\n\
  615. -S, --storelatest Store latest value in files\n\
  616. -d, --debug Debug mode (no chdir, no fork, no syslog)\n\
  617. -l, --log-dir=<dir> Directory where all received data should be stored\n\
  618. -p, --debug-packets Log all packets sent and received\n\
  619. -r, --debug-raw Log conversion from raw values\n\
  620. -u, --debug-usb Enable libusb debug messages (to stdout/stderr)\n\
  621. -V, --version Show daemon version\n\
  622. ");
  623. exit(1);
  624. }
  625. int main(int argc, char **argv)
  626. {
  627. int opt;
  628. while ((opt = getopt_long(argc, argv, "RSdl:pruV", long_options, NULL)) >= 0)
  629. switch (opt) {
  630. case 'R':
  631. use_rrd++;
  632. break;
  633. case 'S':
  634. use_storelatest++;
  635. break;
  636. case 'd':
  637. debug_mode++;
  638. break;
  639. case 'l':
  640. log_dir = optarg;
  641. break;
  642. case 'p':
  643. debug_packets++;
  644. break;
  645. case 'r':
  646. debug_raw_data++;
  647. break;
  648. case 'u':
  649. debug_usb++;
  650. break;
  651. case 'V':
  652. printf("arexxd " AREXXD_VERSION "\n");
  653. printf("(c) 2011-2012 Martin Mares <mj@ucw.cz>\n");
  654. return 0;
  655. default:
  656. usage();
  657. }
  658. if (optind < argc)
  659. usage();
  660. int err;
  661. if (err = libusb_init(&usb_ctxt))
  662. die("Cannot initialize libusb: error %d", err);
  663. if (debug_usb)
  664. libusb_set_debug(usb_ctxt, 3);
  665. if (!debug_mode) {
  666. if (chdir(log_dir) < 0)
  667. die("Cannot change directory to %s: %m", log_dir);
  668. if (debug_packets || debug_raw_data) {
  669. close(1);
  670. if (open("debug", O_WRONLY | O_CREAT | O_APPEND, 0666) < 0)
  671. die("Cannot open debug log: %m");
  672. setlinebuf(stdout);
  673. }
  674. openlog("arexxd", LOG_NDELAY, LOG_DAEMON);
  675. pid_t pid = fork();
  676. if (pid < 0)
  677. die("fork() failed: %m");
  678. if (pid)
  679. return 0;
  680. setsid();
  681. use_syslog = 1;
  682. }
  683. struct sigaction sa = { .sa_handler = sigterm_handler };
  684. sigaction(SIGTERM, &sa, NULL);
  685. sigaction(SIGINT, &sa, NULL);
  686. sigemptyset(&term_sigs);
  687. sigaddset(&term_sigs, SIGTERM);
  688. sigaddset(&term_sigs, SIGINT);
  689. sigprocmask(SIG_BLOCK, &term_sigs, NULL);
  690. int inited = 0;
  691. while (!want_shutdown) {
  692. if (!find_device()) {
  693. if (!inited) {
  694. inited = 1;
  695. log_error("Data logger not connected, waiting until it appears");
  696. }
  697. interruptible_msleep(30000);
  698. continue;
  699. }
  700. log_info("Listening");
  701. time_t last_sync = 0;
  702. time_t last_show = 0;
  703. int want_stats = 0;
  704. int want_sleep = 0;
  705. data_point_counter = 0;
  706. while (!want_shutdown) {
  707. time_t now = time(NULL);
  708. if (now > last_sync + 900) {
  709. log_info("Synchronizing data logger time");
  710. set_clock();
  711. last_sync = now;
  712. }
  713. if (want_stats && now > last_show + 300) {
  714. log_info("Stats: received %d data points", data_point_counter);
  715. data_point_counter = 0;
  716. last_show = now;
  717. }
  718. byte req[64], reply[64];
  719. memset(req, 0, sizeof(req));
  720. req[0] = 3;
  721. err = send_and_receive(req, reply);
  722. if (err < 0)
  723. break;
  724. want_sleep = 1;
  725. if (err > 0 && parse_packet(reply))
  726. want_sleep = 0;
  727. if (want_sleep) {
  728. interruptible_msleep(4000);
  729. want_stats = 1;
  730. } else
  731. interruptible_msleep(5);
  732. }
  733. log_info("Disconnecting data logger");
  734. release_device();
  735. inited = 0;
  736. interruptible_msleep(10000);
  737. }
  738. log_info("Terminated");
  739. return 0;
  740. }