818473fa81d9f87057623c5fffff29b2d50e70ca
[visomat-utils.git] / src / visomat-data-downloader.c
1 /*
2  * visomat-data-downloader - download data from Visomat Double Comfort
3  *
4  * The Visomat Double Comfort is a blood pressure meter with a USB port.
5  *
6  * Copyright (C) 2013  Antonio Ospite <ospite@studenti.unina.it>
7  *
8  * This program is free software: you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation, either version 3 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
20  */
21
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <errno.h>
26 #include <unistd.h>
27 #include <libusb.h>
28
29 #define VISOMAT_DEVICE_VID    0x1247
30 #define VISOMAT_DEVICE_PID    0x00f8
31 #define VISOMAT_CONFIGURATION 1
32 #define VISOMAT_INTERFACE     1
33 #define VISOMAT_EP_IN         0x82
34 #define VISOMAT_EP_OUT        0x03
35
36 #define STX 0x02
37 #define ETX 0x03
38
39 #define BASE_YEAR 2000
40
41 typedef enum {
42         VISOMAT_CMD_DUMP_EEPROM,
43         VISOMAT_CMD_UNKNOWN1, /* maybe the firmware revision */
44         VISOMAT_CMD_GET_DATETIME,
45         VISOMAT_CMD_START_MEASURE1,
46         VISOMAT_CMD_UNKNOWN2, /* XXX transmission hangs */
47         VISOMAT_CMD_UNKNOWN3,
48 } visomat_command;
49
50 static char command_codes[][3] = {
51         [VISOMAT_CMD_DUMP_EEPROM]    = "R00",
52         [VISOMAT_CMD_UNKNOWN1]       = "R01",
53         [VISOMAT_CMD_GET_DATETIME]   = "R02",
54         [VISOMAT_CMD_START_MEASURE1] = "R03",
55         [VISOMAT_CMD_UNKNOWN2]       = "R04",
56         [VISOMAT_CMD_UNKNOWN3]       = "R05",
57 };
58
59 struct datetime  {
60         unsigned int year;
61         unsigned int month;
62         unsigned int day;
63         unsigned int hour;
64         unsigned int minute;
65 };
66
67 struct pressure  {
68         unsigned int flag; /* XXX Maybe this means arrhythmia? */
69         unsigned int systolic;
70         unsigned int diastolic;
71         unsigned int pulses;
72 };
73
74 static inline int extract_datetime(unsigned char *buffer, struct datetime *d)
75 {
76         int ret;
77
78         ret = sscanf((char *)buffer, "%02u%02u%02u%02u%02u",
79                      &d->year,
80                      &d->month,
81                      &d->day,
82                      &d->hour,
83                      &d->minute);
84         if (ret != 5)
85                 return -EINVAL;
86
87         d->year += BASE_YEAR;
88
89         return 0;
90 }
91
92 /* 
93  * NOTE: the CSV output is meant to be compatible with one from the Windows
94  * program, which uses the %d/%m/%Y date format, so that's not my fault.
95  */
96 static void print_record_csv_compat(struct datetime *d, struct pressure *p)
97 {
98         unsigned int pulse_pressure;
99
100         printf("%02u/%02u/%04u;%02u.%02u;",
101                d->day, d->month, d->year, d->hour, d->minute);
102
103         printf("%u;%u;%u;", p->systolic, p->diastolic, p->pulses);
104
105         pulse_pressure = p->systolic - p->diastolic;
106         printf("%u;", pulse_pressure);
107
108         if (p->flag)
109                 printf("x");
110
111 #if 0
112         /* The original software does not seem to be doing that */
113         if (p->pulses > 100)
114                 printf("tachycardia");
115         else if (p->pulses < 60)
116                 printf("bradycardia");
117 #endif
118
119         printf("\n");
120 }
121
122 /* TODO separate better decoding data from printing it */
123 static int decode_eeprom(unsigned char *buffer,
124                          unsigned int len,
125                          unsigned int user_mask)
126 {
127         int ret;
128         unsigned int n;
129         unsigned int i;
130         unsigned int j;
131         unsigned int user_id;
132         unsigned int num_records;
133         struct datetime d;
134         struct pressure p;
135
136         if (buffer[0] != STX || buffer[1] != 'M' || buffer[len - 1] != ETX)
137                 return -EINVAL;
138
139         /* skip the initial STX */
140         i = 1;
141
142         /* and the final ETX */
143         n = len - 1;
144
145         while (i < n) {
146                 /* Each user record begins with 'M', maybe for "Memory" */
147                 if (buffer[i] == 'M') {
148                         /* i tracks the bytes consumed */
149                         i += 1;
150
151                         ret = sscanf((char *)(buffer + i), "%1u%02u",
152                                      &user_id, &num_records);
153                         if (ret != 2)
154                                 return -EINVAL;
155
156                         /* user_id and num_records take 3 bytes */
157                         i += 3;
158
159                         for (j = 0; j < num_records; j++) {
160                                 ret = extract_datetime(buffer + i, &d);
161                                 if (ret < 0)
162                                         return ret;
163
164                                 /* datetime takes 10 bytes */
165                                 i += 10;
166
167                                 ret = sscanf((char *)(buffer + i),
168                                              "%1u%03u%03u%03u",
169                                              &p.flag,
170                                              &p.systolic,
171                                              &p.diastolic,
172                                              &p.pulses);
173                                 if (ret != 4)
174                                         return -EINVAL;
175
176                                 /* pressure data is 10 bytes */
177                                 i += 10;
178
179                                 /* TODO: split out the printing part */
180                                 if (user_id & user_mask) {
181                                         if (j == 0)
182                                                 printf("# User: %d\n", user_id);
183                                         print_record_csv_compat(&d, &p);
184                                 }
185                         }
186                 }
187         }
188
189         return 0;
190 }
191
192 static int decode_datetime(unsigned char *buffer, unsigned int len)
193 {
194         int ret;
195         unsigned char code[4] = { 0 };
196         struct datetime d;
197         unsigned char *pbuffer = buffer;
198
199         if (len != 15)
200                 return -EINVAL;
201
202         code[0] = buffer[1];
203         code[1] = buffer[2];
204         code[2] = buffer[3];
205
206         ret = extract_datetime(pbuffer + 4, &d);
207         if (ret < 0)
208                 return ret;
209
210         printf("# (%s) Date: %04d/%02d/%02d %02d:%02d\n",
211                code, d.year, d.month, d.day, d.hour, d.minute);
212
213         return 0;
214 }
215
216 static int send_command(libusb_device_handle *dev, visomat_command cmd)
217 {
218         int ret;
219         int transferred;
220         unsigned char request[5];
221
222         request[0] = STX;
223         request[1] = command_codes[cmd][0];
224         request[2] = command_codes[cmd][1];
225         request[3] = command_codes[cmd][2];
226         request[4] = ETX;
227
228         transferred = 0;
229         ret = libusb_bulk_transfer(dev, VISOMAT_EP_OUT, request, sizeof(request), &transferred, 0);
230         if (ret != 0 || transferred != sizeof(request)) {
231                 fprintf(stderr, "Error: sending request: %d (%s)\ttransferred: %d (expected %zu)\n",
232                         ret, libusb_error_name(ret), transferred, sizeof(request));
233                 return ret;
234         }
235         return 0;
236 }
237
238 static int get_response(libusb_device_handle *dev,
239                         unsigned char *buffer,
240                         unsigned int len)
241 {
242         int ret;
243         int transferred;
244         unsigned char response[64] = { 0 };
245         unsigned int i;
246
247         i = 0;
248         do {
249                 unsigned int j;
250
251                 transferred = 0;
252                 ret = libusb_bulk_transfer(dev, VISOMAT_EP_IN, response, sizeof(response), &transferred, 5000);
253                 if (ret != 0) {
254                         fprintf(stderr, "Error getting response: %d (%s)\ttransferred: %d (expected %zu)\n",
255                                 ret, libusb_error_name(ret), transferred, sizeof(response));
256                         return ret;
257                 }
258
259                 for (j = 0; j < (unsigned int)transferred; j++) {
260                         buffer[i] = response[j];
261                         i += 1;
262                 }
263
264         } while (buffer[i - 1] != ETX && i < len);
265
266         /* Check the buffer is a valid response packet */
267         if (buffer[0] != STX || buffer[i - 1] != ETX)
268                 return -EINVAL;
269
270         return i;
271 }
272
273 /* Candidates for a future public API, if a shared library will ever be made */
274 #define visomat_device libusb_device_handle
275 static int visomat_dump_eeprom(visomat_device *dev, unsigned int user_mask)
276 {
277         /* Assuming an EEPROM of 1 KiB  */
278         unsigned char buffer[1024] = { 0 };
279         int ret;
280
281         ret = send_command(dev, VISOMAT_CMD_DUMP_EEPROM);
282         if (ret < 0)
283                 return ret;
284
285         ret = get_response(dev, buffer, sizeof(buffer));
286         if (ret < 0)
287                 return ret;
288
289         ret = decode_eeprom(buffer, ret, user_mask);
290         if (ret < 0)
291                 return ret;
292
293         return 0;
294 }
295
296 static int visomat_get_datetime(visomat_device *dev)
297 {
298         unsigned char buffer[255] = { 0 };
299         int ret;
300
301         ret = send_command(dev, VISOMAT_CMD_GET_DATETIME);
302         if (ret < 0)
303                 return ret;
304
305         ret = get_response(dev, buffer, sizeof(buffer));
306         if (ret < 0)
307                 return ret;
308
309         ret = decode_datetime(buffer, ret);
310         if (ret < 0)
311                 return ret;
312
313         return 0;
314 }
315
316 int main(void)
317 {
318         int ret;
319         libusb_device_handle *dev;
320         int current_configuration;
321
322         ret = libusb_init(NULL);
323         if (ret < 0) {
324                 fprintf(stderr, "libusb_init failed: %s\n", libusb_error_name(ret));
325                 goto out;
326         }
327
328         libusb_set_debug(NULL, LIBUSB_LOG_LEVEL_INFO);
329
330         dev = libusb_open_device_with_vid_pid(NULL,
331                                               VISOMAT_DEVICE_VID,
332                                               VISOMAT_DEVICE_PID);
333         if (dev == NULL) {
334                 fprintf(stderr, "libusb_open failed: %s\n", strerror(errno));
335                 ret = -errno;
336                 goto out_libusb_exit;
337         }
338
339         current_configuration = -1;
340         ret = libusb_get_configuration(dev, &current_configuration);
341         if (ret < 0) {
342                 fprintf(stderr, "libusb_get_configuration failed: %s\n",
343                         libusb_error_name(ret));
344                 goto out_libusb_close;
345         }
346
347         if (current_configuration != VISOMAT_CONFIGURATION) {
348                 ret = libusb_set_configuration(dev, VISOMAT_CONFIGURATION);
349                 if (ret < 0) {
350                         fprintf(stderr, "libusb_set_configuration failed: %s\n",
351                                 libusb_error_name(ret));
352                         fprintf(stderr, "Cannot set configuration %hhu\n",
353                                 VISOMAT_CONFIGURATION);
354                         goto out_libusb_close;
355                 }
356         }
357
358         libusb_set_auto_detach_kernel_driver(dev, 1);
359
360         ret = libusb_claim_interface(dev, VISOMAT_INTERFACE);
361         if (ret < 0) {
362                 fprintf(stderr, "libusb_claim_interface failed: %s\n",
363                         libusb_error_name(ret));
364                 fprintf(stderr, "Cannot claim interface %hhu\n",
365                         VISOMAT_INTERFACE);
366                 goto out_libusb_close;
367         }
368
369         /* Checking that the configuration has not changed, as suggested in
370          * http://libusb.sourceforge.net/api-1.0/caveats.html
371          */
372         current_configuration = -1;
373         ret = libusb_get_configuration(dev, &current_configuration);
374         if (ret < 0) {
375                 fprintf(stderr, "libusb_get_configuration after claim failed: %s\n",
376                         libusb_error_name(ret));
377                 goto out_libusb_release_interface;
378         }
379
380         if (current_configuration != VISOMAT_CONFIGURATION) {
381                 fprintf(stderr, "libusb configuration changed (expected: %hhu, current: %hhu\n",
382                         VISOMAT_CONFIGURATION, current_configuration);
383                 ret = -EINVAL;
384                 goto out_libusb_release_interface;
385         }
386
387         ret = visomat_get_datetime(dev);
388         if (ret < 0)
389                 goto out_libusb_release_interface;
390
391         ret = visomat_dump_eeprom(dev, 0x01 | 0x02);
392         if (ret < 0)
393                 goto out_libusb_release_interface;
394
395 out_libusb_release_interface:
396         libusb_release_interface(dev, VISOMAT_INTERFACE);
397 out_libusb_close:
398         libusb_close(dev);
399         dev = NULL;
400 out_libusb_exit:
401         libusb_exit(NULL);
402 out:
403         return ret;
404 }