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