]> mj.ucw.cz Git - arexx.git/blob - arexx.c
A brief description of the protocol
[arexx.git] / arexx.c
1 /*
2  *      Linux Interfece for Arexx Data Loggers
3  *
4  *      (c) 2011 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 <math.h>
13 #include <time.h>
14 #include <sys/stat.h>
15 #include <libusb-1.0/libusb.h>
16 #include <rrd.h>
17
18 typedef unsigned char byte;
19 static libusb_context *usb_ctxt;
20 static libusb_device_handle *devh;
21
22 static int debug_packets = 0;
23 static int debug_raw_data = 0;
24
25 #define TIME_OFFSET 946681200           // Timestamp of 2000-01-01 00:00:00
26
27 static void die(char *msg, ...)
28 {
29         va_list args;
30         va_start(args, msg);
31         vfprintf(stderr, msg, args);
32         fputc('\n', stderr);
33         va_end(args);
34         exit(1);
35 }
36
37 /*** RRD interface ***/
38
39 #define RRD_NAME "/tmp/power.rrd"
40 #define SLOT_SIZE 10                                    // 10 seconds per averaging slot
41 #define MAX_ARGS 20
42 #define MAX_ARG_SIZE 1024
43
44 static int arg_cnt;
45 static char *arg_ptr[MAX_ARGS+1];
46 static char arg_buf[MAX_ARG_SIZE];
47 static int arg_pos;
48
49 static void arg_new(void)
50 {
51         arg_cnt = 1;
52         arg_pos = 0;
53         arg_ptr[0] = "rrdtool";
54 }
55
56 static void arg_push(const char *fmt, ...)
57 {
58         if (arg_cnt >= MAX_ARGS)
59                 die("MAX_ARGS exceeded");
60         va_list va;
61         va_start(va, fmt);
62         int len = 1 + vsnprintf(arg_buf + arg_pos, MAX_ARG_SIZE - arg_pos, fmt, va);
63         if (arg_pos + len > MAX_ARG_SIZE)
64                 die("MAX_ARG_SIZE exceeded");
65         arg_ptr[arg_cnt++] = arg_buf + arg_pos;
66         arg_ptr[arg_cnt] = NULL;
67         arg_pos += len;
68 }
69
70 static void rrd_point(time_t t, int id, double val)
71 {
72         char rr_name[256];
73         snprintf(rr_name, sizeof(rr_name), "sensor-%d.rrd", id);
74
75         struct stat st;
76         if (stat(rr_name, &st) < 0 || !st.st_size) {
77                 // We have to create the RRD
78                 printf("### Creating %s\n", rr_name);
79                 arg_new();
80                 arg_push(rr_name);
81                 arg_push("--start");
82                 arg_push("%d", (int) time(NULL) - 28*86400);
83                 arg_push("--step");
84                 arg_push("60");
85                 arg_push("DS:temp:GAUGE:300:0:10000");          // Anything over 10 kW is considered a ghost
86                 arg_push("RRA:AVERAGE:0.25:1:20160");           // Last 14 days with full resolution
87                 arg_push("RRA:AVERAGE:0.25:60:88800");          // Last 10 years with 1h resolution
88                 rrd_create(arg_cnt, arg_ptr);
89                 if (rrd_test_error())
90                         die("rrd_create failed: %s", rrd_get_error());
91         }
92
93         arg_new();
94         arg_push(rr_name);
95         arg_push("%d:%f", t, val);
96         rrd_update(arg_cnt, arg_ptr);
97         if (rrd_test_error())
98                 printf("### rrd_update failed: %s\n", rrd_get_error());
99 }
100
101 /*** Transforms ***/
102
103 static void cooked_point(time_t t, int id, double val, char *unit, int q)
104 {
105         struct tm tm;
106         localtime_r(&t, &tm);
107
108         char tbuf[64];
109         strftime(tbuf, sizeof(tbuf), "%Y-%m-%d %H:%M:%S", &tm);
110
111         printf("== %s id=%d val=%.3f unit=%s q=%d\n", tbuf, id, val, unit, q);
112
113         rrd_point(t, id, val);
114 }
115
116 static void raw_point(int t, int id, int raw, int q)
117 {
118         /*
119          *  The binary blob provided by Arexx contains an embedded XML fragment
120          *  with descriptions of all known sensor types. If you want to see it,
121          *  grep the blob for "<deviceinfo>". The meanings of the parameters are
122          *  as follows:
123          *
124          *      m1, m2          Device type matches if (raw_sensor_id & m1) == m2
125          *      type            Unit measured by the sensor (1=Celsius, 2=RH%, 3=CO2 ppm)
126          *      dm              User-visible sensor ID = raw_sensor_id & dm
127          *      i               1 if the raw value is signed
128          *      p[]             Coefficients of transformation polynomial (x^0 first)
129          *      vLo, vUp        Upper and lower bound on the final value
130          *      scale           Scaling function:
131          *                              0 = identity (default)
132          *                              1 = 10^x
133          *                              2 = exp(x)
134          *                              3 = (x < 0) ? 0 : log10(x)
135          *                              4 = (x < 0) ? 0 : log(x)
136          *
137          *  The raw values are transformed this way:
138          *      - sign-extend if signed
139          *      - apply the transformation polynomial
140          *      - apply the scaling function
141          *      - drop if outside the interval [vLo,vUp]
142          *
143          *  This function applies the necessary transform for sensors we've
144          *  seen in the wild. We deliberately ignore the "dm" parameter as we want
145          *  to report different channels of a single sensor as multiple sensors.
146          */
147
148         double z = raw;
149         double hi, lo;
150         char *unit;
151         int idhi = id & 0xf000;
152
153         if (idhi == 0x1000) {
154                 z = 0.02*z - 273.15;
155                 lo = -200;
156                 hi = 600;
157                 unit = "C";
158         } else if (idhi == 0x2000) {
159                 if (raw >= 0x8000)
160                         z -= 0x10000;
161                 z /= 128;
162                 lo = -60;
163                 hi = 125;
164                 unit = "C";
165         } else if (idhi == 0x4000) {
166                 if (!(id & 1)) {
167                         z = z/100 - 39.6;
168                         lo = -60;
169                         hi = 125;
170                         unit = "C";
171                 } else {
172                         z = -2.8e-6*z*z + 0.0405*z - 4;
173                         lo = 0;
174                         hi = 100.1;
175                         unit = "%RH";
176                 }
177         } else if (idhi == 0x6000) {
178                 if (!(id & 1)) {
179                         if (raw >= 0x8000)
180                                 z -= 0x10000;
181                         z /= 128;
182                         lo = -60;
183                         hi = 125;
184                         unit = "C";
185                 } else {
186                         z = -3.8123e-11*z;
187                         z = (z + 1.9184e-7) * z;
188                         z = (z - 1.0998e-3) * z;
189                         z += 6.56;
190                         z = pow(10, z);
191                         lo = 0;
192                         hi = 1e6;
193                         unit = "ppm";
194                 }
195         } else {
196                 printf("### Unknown sensor type 0x%04x\n", id);
197                 return;
198         }
199
200         if (z < lo || z > hi) {
201                 printf("### Sensor %d: value %f out of range\n", id, z);
202                 return;
203         }
204
205         cooked_point(t + TIME_OFFSET, id, z, unit, q);
206 }
207
208 /*** USB interface ***/
209
210 static void find_device(void)
211 {
212         libusb_device **devlist;
213         ssize_t devn = libusb_get_device_list(usb_ctxt, &devlist);
214         if (devn < 0)
215                 die("Cannot enumerate USB devices: error %d\n", (int) devn);
216
217         for (ssize_t i=0; i<devn; i++) {
218                 struct libusb_device_descriptor desc;
219                 libusb_device *dev = devlist[i];
220                 if (!libusb_get_device_descriptor(dev, &desc)) {
221                         if (desc.idVendor == 0x0451 && desc.idProduct == 0x3211) {
222                                 printf("Arexx USB receiver found at usb%d.%d\n", libusb_get_bus_number(dev), libusb_get_device_address(dev));
223                                 int err;
224                                 if (err = libusb_open(dev, &devh))
225                                         die("libusb_open() failed: error %d\n", err);
226                                 if (err = libusb_claim_interface(devh, 0))
227                                         die("libusb_claim_interface() failed: error %d\n", err);
228                                 libusb_free_device_list(devlist, 1);
229                                 return;
230                         }
231                 }
232         }
233
234         die("No Arexx USB receiver found");
235 }
236
237 static void dump_packet(byte *pkt)
238 {
239         for (int i=0; i<64; i++) {
240                 if (!(i % 16))
241                         printf("\t%02x:", i);
242                 printf(" %02x", pkt[i]);
243                 if (i % 16 == 15)
244                         printf("\n");
245         }
246 }
247
248 static int send_and_receive(byte *req, byte *reply)
249 {
250         int err, transferred;
251         if (err = libusb_bulk_transfer(devh, 0x01, req, 64, &transferred, 200)) {
252                 fprintf(stderr, "Transmit error: %d\n", err);
253                 return 0;
254         }
255         if (debug_packets) {
256                 printf(">> xmit %d bytes\n", transferred);
257                 dump_packet(req);
258         }
259         if (err = libusb_bulk_transfer(devh, 0x81, reply, 64, &transferred, 200)) {
260                 fprintf(stderr, "Receive error: %d\n", err);
261                 return 0;
262         }
263         if (debug_packets)
264                 printf("<< recv %d bytes\n", transferred);
265         while (transferred < 64)
266                 reply[transferred++] = 0xff;
267         if (debug_packets)
268                 dump_packet(reply);
269         return 1;
270 }
271
272 static unsigned int get_be16(byte *p)
273 {
274         return p[1] | (p[0] << 8);
275 }
276
277 static unsigned int get_le16(byte *p)
278 {
279         return p[0] | (p[1] << 8);
280 }
281
282 static unsigned int get_le32(byte *p)
283 {
284         return get_le16(p) | (get_le16(p+2) << 16);
285 }
286
287 static void put_le16(byte *p, unsigned int x)
288 {
289         p[0] = x;
290         p[1] = x >> 8;
291 }
292
293 static void put_le32(byte *p, unsigned int x)
294 {
295         put_le16(p, x);
296         put_le16(p+2, x>>16);
297 }
298
299 static int parse_packet(byte *reply)
300 {
301         if (reply[0]) {
302                 printf("### Unknown packet type %02x\n", reply[0]);
303                 return 0;
304         }
305
306         int pos = 1;
307         int points = 0;
308         while (pos < 64) {
309                 byte *p = reply + pos;
310                 int len = p[0];
311                 if (!len || len == 0xff)
312                         break;
313                 if (len < 9 || len > 10) {
314                         printf("### Unknown tuple length %02x\n", len);
315                         break;
316                 }
317                 if (pos + len > 64) {
318                         printf("### Tuple truncated\n");
319                         break;
320                 }
321                 int id = get_le16(p+1);
322                 int raw = get_be16(p+3);
323                 int t = get_le32(p+5);
324                 int q = (len > 9) ? p[9] : -1;
325                 if (debug_raw_data) {
326                         printf("... %02x: id=%d raw=%d t=%d", len, id, raw, t);
327                         if (len > 9)
328                                 printf(" q=%d", q);
329                         printf("\n");
330                 }
331                 raw_point(t, id, raw, q);
332                 pos += len;
333                 points++;
334         }
335
336         return points;
337 }
338
339 static void set_clock(void)
340 {
341         puts("### Syncing time");
342
343         byte req[64], reply[64];
344         memset(req, 0, 64);
345         req[0] = 4;
346         time_t t = time(NULL);
347         put_le32(req+1, t-TIME_OFFSET);
348         send_and_receive(req, reply);
349
350 #if 0
351         /*
352          *  Original software also sends a packet with type 3 and the timestamp,
353          *  but it does not make any sense, especially as they ignore the sensor
354          *  readings in the answer.
355          */
356         req[0] = 3;
357         send_and_receive(req, reply);
358         parse_packet(reply);
359 #endif
360 }
361
362 int main(void)
363 {
364         int err;
365         if (err = libusb_init(&usb_ctxt))
366                 die("Cannot initialize libusb: error %d", err);
367         libusb_set_debug(usb_ctxt, 3);
368
369         find_device();
370         set_clock();
371
372         for (;;) {
373                 byte req[64], reply[64];
374                 memset(req, 0, sizeof(req));
375                 req[0] = 3;
376                 if (send_and_receive(req, reply)) {
377                         if (parse_packet(reply))
378                                 continue;
379                 }
380                 sleep(4);
381         }
382
383         return 0;
384 }