]> sigrok.org Git - libsigrok.git/blob - hardware/testo/api.c
testo: Detach kernel driver as needed, and code optimization.
[libsigrok.git] / hardware / testo / api.c
1 /*
2  * This file is part of the libsigrok project.
3  *
4  * Copyright (C) 2014 Bert Vermeulen <bert@biot.com>
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 #include <string.h>
21 #include <libserialport.h>
22 #include "protocol.h"
23
24 #define SERIALCOMM "115200/8n1"
25
26 SR_PRIV struct sr_dev_driver testo_driver_info;
27 static struct sr_dev_driver *di = &testo_driver_info;
28 static int dev_acquisition_stop(struct sr_dev_inst *sdi, void *cb_data);
29
30 static const int32_t scanopts[] = {
31         SR_CONF_CONN,
32 };
33
34 static const int32_t devopts[] = {
35         SR_CONF_MULTIMETER,
36         SR_CONF_LIMIT_MSEC,
37         SR_CONF_LIMIT_SAMPLES,
38         SR_CONF_CONTINUOUS,
39 };
40
41 unsigned char TESTO_x35_REQUEST[] = { 0x12, 0, 0, 0, 1, 1, 0x55, 0xd1, 0xb7 };
42 struct testo_model models[] = {
43         { "435", 9, TESTO_x35_REQUEST },
44 };
45
46 static int init(struct sr_context *sr_ctx)
47 {
48         return std_init(sr_ctx, di, LOG_PREFIX);
49 }
50
51 static GSList *scan(GSList *options)
52 {
53         struct drv_context *drvc;
54         struct dev_context *devc;
55         struct sr_config *src;
56         struct sr_dev_inst *sdi;
57         struct sr_usb_dev_inst *usb;
58         struct libusb_device_descriptor des;
59         libusb_device **devlist;
60         struct libusb_device_handle *hdl;
61         GSList *conn_devices, *devices, *l;
62         int devcnt, ret, i;
63         const char *str;
64         char manufacturer[64], product[64];
65
66         devices = NULL;
67         drvc = di->priv;
68         drvc->instances = NULL;
69
70         conn_devices = NULL;
71         for (l = options; l; l = l->next) {
72                 src = l->data;
73                 if (src->key != SR_CONF_CONN)
74                         continue;
75                 str = g_variant_get_string(src->data, NULL);
76                 conn_devices = sr_usb_find(drvc->sr_ctx->libusb_ctx, str);
77         }
78
79         libusb_get_device_list(drvc->sr_ctx->libusb_ctx, &devlist);
80         for (i = 0; devlist[i]; i++) {
81                 if (conn_devices) {
82                         usb = NULL;
83                         for (l = conn_devices; l; l = l->next) {
84                                 usb = l->data;
85                                 if (usb->bus == libusb_get_bus_number(devlist[i])
86                                         && usb->address == libusb_get_device_address(devlist[i]))
87                                         break;
88                         }
89                         if (!l)
90                                 /* This device matched none of the ones that
91                                  * matched the conn specification. */
92                                 continue;
93                 }
94
95                 if ((ret = libusb_get_device_descriptor( devlist[i], &des)) != 0) {
96                         sr_warn("Failed to get device descriptor: %s.",
97                                 libusb_error_name(ret));
98                         continue;
99                 }
100
101                 if ((ret = libusb_open(devlist[i], &hdl)) < 0)
102                         continue;
103
104                 manufacturer[0] = product[0] = '\0';
105                 if (des.iManufacturer && (ret = libusb_get_string_descriptor_ascii(
106                                 hdl, des.iManufacturer, (unsigned char *) manufacturer,
107                                 sizeof(manufacturer))) < 0) {
108                         sr_warn("Failed to get manufacturer string descriptor: %s.",
109                                 libusb_error_name(ret));
110                 }
111                 if (des.iProduct && (ret = libusb_get_string_descriptor_ascii(
112                                 hdl, des.iProduct, (unsigned char *) product,
113                                 sizeof(product))) < 0) {
114                         sr_warn("Failed to get product string descriptor: %s.",
115                                 libusb_error_name(ret));
116                 }
117                 libusb_close(hdl);
118
119                 if (strncmp(manufacturer, "testo", 5))
120                         continue;
121
122                 /* Hardcode the 435 for now.*/
123                 if (strcmp(product, "testo 435/635/735"))
124                         continue;
125
126                 devcnt = g_slist_length(drvc->instances);
127                 sdi = sr_dev_inst_new(devcnt, SR_ST_INACTIVE, "Testo",
128                                 "435/635/735", NULL);
129                 sdi->driver = di;
130                 sdi->inst_type = SR_INST_USB;
131                 sdi->conn = sr_usb_dev_inst_new(libusb_get_bus_number(devlist[i]),
132                                 libusb_get_device_address(devlist[i]), NULL);
133                 devc = g_malloc(sizeof(struct dev_context));
134                 devc->model = &models[0];
135                 devc->limit_msec = 0;
136                 devc->limit_samples = 0;
137                 sdi->priv = devc;
138                 if (testo_probe_channels(sdi) != SR_OK)
139                         continue;
140                 drvc->instances = g_slist_append(drvc->instances, sdi);
141                 devices = g_slist_append(devices, sdi);
142         }
143         libusb_free_device_list(devlist, 1);
144         g_slist_free_full(conn_devices, (GDestroyNotify)sr_usb_dev_inst_free);
145
146         return devices;
147 }
148
149 static GSList *dev_list(void)
150 {
151         return ((struct drv_context *)(di->priv))->instances;
152 }
153
154 static int dev_clear(void)
155 {
156         return std_dev_clear(di, NULL);
157 }
158
159 static int dev_open(struct sr_dev_inst *sdi)
160 {
161         struct drv_context *drvc = di->priv;
162         struct sr_usb_dev_inst *usb;
163         libusb_device **devlist;
164         int ret, i;
165
166         if (!di->priv) {
167                 sr_err("Driver was not initialized.");
168                 return SR_ERR;
169         }
170
171         usb = sdi->conn;
172         libusb_get_device_list(drvc->sr_ctx->libusb_ctx, &devlist);
173         for (i = 0; devlist[i]; i++) {
174                 if (libusb_get_bus_number(devlist[i]) != usb->bus
175                                 || libusb_get_device_address(devlist[i]) != usb->address)
176                         continue;
177                 if ((ret = libusb_open(devlist[i], &usb->devhdl))) {
178                         sr_err("Failed to open device: %s.", libusb_error_name(ret));
179                         return SR_ERR;
180                 }
181                 break;
182         }
183         libusb_free_device_list(devlist, 1);
184         if (!devlist[i]) {
185                 sr_err("Device not found.");
186                 return SR_ERR;
187         }
188
189         if (libusb_has_capability(LIBUSB_CAP_SUPPORTS_DETACH_KERNEL_DRIVER)) {
190                 if (libusb_kernel_driver_active(usb->devhdl, 0) == 1) {
191                         if ((ret = libusb_detach_kernel_driver(usb->devhdl, 0)) < 0) {
192                                 sr_err("Failed to detach kernel driver: %s.",
193                                            libusb_error_name(ret));
194                                 return SR_ERR;
195                         }
196                 }
197         }
198
199         if ((ret = libusb_claim_interface(usb->devhdl, 0))) {
200                 sr_err("Failed to claim interface: %s.", libusb_error_name(ret));
201                 return SR_ERR;
202         }
203         sdi->status = SR_ST_ACTIVE;
204
205         return SR_OK;
206 }
207
208 static int dev_close(struct sr_dev_inst *sdi)
209 {
210         struct sr_usb_dev_inst *usb;
211
212         if (!di->priv) {
213                 sr_err("Driver was not initialized.");
214                 return SR_ERR;
215         }
216
217         usb = sdi->conn;
218         if (!usb->devhdl)
219                 /*  Nothing to do. */
220                 return SR_OK;
221
222         libusb_release_interface(usb->devhdl, 0);
223         libusb_close(usb->devhdl);
224         usb->devhdl = NULL;
225         sdi->status = SR_ST_INACTIVE;
226
227         return SR_OK;
228 }
229
230 static int cleanup(void)
231 {
232         int ret;
233         struct drv_context *drvc;
234
235         if (!(drvc = di->priv))
236                 return SR_OK;
237
238         ret = dev_clear();
239         g_free(drvc);
240         di->priv = NULL;
241
242         return ret;
243 }
244
245 static int config_get(int key, GVariant **data, const struct sr_dev_inst *sdi,
246                 const struct sr_channel_group *cg)
247 {
248         struct sr_usb_dev_inst *usb;
249         char str[128];
250
251         (void)cg;
252
253         switch (key) {
254         case SR_CONF_CONN:
255                 if (!sdi || !sdi->conn)
256                         return SR_ERR_ARG;
257                 usb = sdi->conn;
258                 snprintf(str, 128, "%d.%d", usb->bus, usb->address);
259                 *data = g_variant_new_string(str);
260                 break;
261         default:
262                 return SR_ERR_NA;
263         }
264
265         return SR_OK;
266 }
267
268 static int config_set(int key, GVariant *data, const struct sr_dev_inst *sdi,
269                 const struct sr_channel_group *cg)
270 {
271         struct dev_context *devc;
272         gint64 now;
273         int ret;
274
275         (void)cg;
276
277         if (sdi->status != SR_ST_ACTIVE)
278                 return SR_ERR_DEV_CLOSED;
279
280         if (!di->priv) {
281                 sr_err("Driver was not initialized.");
282                 return SR_ERR;
283         }
284
285         devc = sdi->priv;
286         ret = SR_OK;
287         switch (key) {
288         case SR_CONF_LIMIT_MSEC:
289                 devc->limit_msec = g_variant_get_uint64(data);
290                 now = g_get_monotonic_time() / 1000;
291                 devc->end_time = now + devc->limit_msec;
292                 sr_dbg("Setting time limit to %" PRIu64 "ms.",
293                        devc->limit_msec);
294                 break;
295         case SR_CONF_LIMIT_SAMPLES:
296                 devc->limit_samples = g_variant_get_uint64(data);
297                 sr_dbg("Setting sample limit to %" PRIu64 ".",
298                        devc->limit_samples);
299                 break;
300         default:
301                 ret = SR_ERR_NA;
302         }
303
304         return ret;
305 }
306
307 static int config_list(int key, GVariant **data, const struct sr_dev_inst *sdi,
308                 const struct sr_channel_group *cg)
309 {
310         (void)sdi;
311         (void)cg;
312
313         switch (key) {
314         case SR_CONF_SCAN_OPTIONS:
315                 *data = g_variant_new_fixed_array(G_VARIANT_TYPE_INT32,
316                                 scanopts, ARRAY_SIZE(scanopts), sizeof(int32_t));
317                 break;
318         case SR_CONF_DEVICE_OPTIONS:
319                 *data = g_variant_new_fixed_array(G_VARIANT_TYPE_INT32,
320                                 devopts, ARRAY_SIZE(devopts), sizeof(int32_t));
321                 break;
322         default:
323                 return SR_ERR_NA;
324         }
325
326         return SR_OK;
327 }
328
329 static void receive_data(struct sr_dev_inst *sdi, unsigned char *data, int len)
330 {
331         struct dev_context *devc;
332         int packet_size;
333         uint16_t crc;
334
335         devc = sdi->priv;
336
337         if (devc->reply_size + len > MAX_REPLY_SIZE) {
338                 /* Something went very wrong. */
339                 sr_dbg("Receive buffer overrun.");
340                 devc->reply_size = 0;
341                 return;
342         }
343
344         memcpy(devc->reply + devc->reply_size, data, len);
345         devc->reply_size += len;
346         /* Sixth byte contains the length of the packet. */
347         if (devc->reply_size < 7)
348                 return;
349
350         packet_size = 7 + devc->reply[6] * 7 + 2;
351         if (devc->reply_size < packet_size)
352                 return;
353
354         if (!testo_check_packet_prefix(devc->reply, devc->reply_size))
355                 return;
356
357         crc = crc16_mcrf4xx(0xffff, devc->reply, devc->reply_size - 2);
358         if (crc == RL16(&devc->reply[devc->reply_size - 2])) {
359                 testo_receive_packet(sdi);
360                 devc->num_samples++;
361         } else {
362                 sr_dbg("Packet has invalid CRC.");
363         }
364
365         devc->reply_size = 0;
366         if (devc->limit_samples && devc->num_samples >= devc->limit_samples)
367                 dev_acquisition_stop(sdi, devc->cb_data);
368         else
369                 testo_request_packet(sdi);
370
371 }
372
373 SR_PRIV void receive_transfer(struct libusb_transfer *transfer)
374 {
375         struct dev_context *devc;
376         struct sr_dev_inst *sdi;
377         int ret;
378
379         sdi = transfer->user_data;
380         devc = sdi->priv;
381         if (transfer == devc->out_transfer)
382                 /* Just the command acknowledgement. */
383                 return;
384
385         if (transfer->status == LIBUSB_TRANSFER_NO_DEVICE) {
386                 /* USB device was unplugged. */
387                 dev_acquisition_stop(sdi, devc->cb_data);
388         } else if (transfer->status == LIBUSB_TRANSFER_COMPLETED) {
389                 /* First two bytes in any transfer are FTDI status bytes. */
390                 if (transfer->actual_length > 2)
391                         receive_data(sdi, transfer->buffer + 2, transfer->actual_length - 2);
392         }
393         /* Anything else is either an error or a timeout, which is fine:
394          * we were just going to send another transfer request anyway. */
395
396         if (sdi->status == SR_ST_ACTIVE) {
397                 if ((ret = libusb_submit_transfer(transfer) != 0)) {
398                         sr_err("Unable to resubmit transfer: %s.",
399                                libusb_error_name(ret));
400                         g_free(transfer->buffer);
401                         libusb_free_transfer(transfer);
402                         dev_acquisition_stop(sdi, devc->cb_data);
403                 }
404         } else {
405                 /* This was the last transfer we're going to receive, so
406                  * clean up now. */
407                 g_free(transfer->buffer);
408                 libusb_free_transfer(transfer);
409         }
410 }
411
412 static int handle_events(int fd, int revents, void *cb_data)
413 {
414         struct dev_context *devc;
415         struct drv_context *drvc = di->priv;
416         struct sr_datafeed_packet packet;
417         struct sr_dev_inst *sdi;
418         struct timeval tv;
419         gint64 now;
420
421         (void)fd;
422         (void)revents;
423
424         sdi = cb_data;
425         devc = sdi->priv;
426
427         if (devc->limit_msec) {
428                 now = g_get_monotonic_time() / 1000;
429                 if (now > devc->end_time)
430                         dev_acquisition_stop(sdi, devc->cb_data);
431         }
432
433         if (sdi->status == SR_ST_STOPPING) {
434                 usb_source_remove(drvc->sr_ctx);
435
436                 dev_close(sdi);
437
438                 packet.type = SR_DF_END;
439                 sr_session_send(sdi, &packet);
440         }
441
442         memset(&tv, 0, sizeof(struct timeval));
443         libusb_handle_events_timeout_completed(drvc->sr_ctx->libusb_ctx, &tv,
444                         NULL);
445
446         return TRUE;
447 }
448
449 static int dev_acquisition_start(const struct sr_dev_inst *sdi, void *cb_data)
450 {
451         struct drv_context *drvc;
452         struct dev_context *devc;
453         struct sr_usb_dev_inst *usb;
454         struct libusb_transfer *transfer;
455         int ret;
456         unsigned char *buf;
457
458         drvc = di->priv;
459         if (sdi->status != SR_ST_ACTIVE)
460                 return SR_ERR_DEV_CLOSED;
461
462         if (!di->priv) {
463                 sr_err("Driver was not initialized.");
464                 return SR_ERR;
465         }
466
467         devc = sdi->priv;
468         usb = sdi->conn;
469         devc->cb_data = cb_data;
470         devc->end_time = 0;
471         devc->num_samples = 0;
472         devc->reply_size = 0;
473
474         /* Send header packet to the session bus. */
475         std_session_send_df_header(cb_data, LOG_PREFIX);
476
477         usb_source_add(drvc->sr_ctx, 100, handle_events, (void *)sdi);
478
479         if (testo_set_serial_params(usb) != SR_OK)
480                 return SR_ERR;
481
482         devc->out_transfer = libusb_alloc_transfer(0);
483         if (testo_request_packet(sdi) != SR_OK)
484                 return SR_ERR;
485
486         buf = g_try_malloc(MAX_REPLY_SIZE);
487         transfer = libusb_alloc_transfer(0);
488         libusb_fill_bulk_transfer(transfer, usb->devhdl, EP_IN, buf,
489                         MAX_REPLY_SIZE, receive_transfer, (void *)sdi, 100);
490         if ((ret = libusb_submit_transfer(transfer) != 0)) {
491                 sr_err("Unable to submit transfer: %s.", libusb_error_name(ret));
492                 libusb_free_transfer(transfer);
493                 g_free(buf);
494                 return SR_ERR;
495         }
496         devc->reply_size = 0;
497
498         return SR_OK;
499 }
500
501 static int dev_acquisition_stop(struct sr_dev_inst *sdi, void *cb_data)
502 {
503         (void)cb_data;
504
505         if (!di->priv) {
506                 sr_err("Driver was not initialized.");
507                 return SR_ERR;
508         }
509
510         if (sdi->status != SR_ST_ACTIVE)
511                 return SR_ERR_DEV_CLOSED;
512
513         sdi->status = SR_ST_STOPPING;
514
515         return SR_OK;
516 }
517
518 SR_PRIV struct sr_dev_driver testo_driver_info = {
519         .name = "testo",
520         .longname = "Testo",
521         .api_version = 1,
522         .init = init,
523         .cleanup = cleanup,
524         .scan = scan,
525         .dev_list = dev_list,
526         .dev_clear = dev_clear,
527         .config_get = config_get,
528         .config_set = config_set,
529         .config_list = config_list,
530         .dev_open = dev_open,
531         .dev_close = dev_close,
532         .dev_acquisition_start = dev_acquisition_start,
533         .dev_acquisition_stop = dev_acquisition_stop,
534         .priv = NULL,
535 };