]> sigrok.org Git - libsigrok.git/blob - hardware/hantek-dso/api.c
hantek-dso: proper protocol implementation of trigger/samplerate setting
[libsigrok.git] / hardware / hantek-dso / api.c
1 /*
2  * This file is part of the sigrok project.
3  *
4  * Copyright (C) 2012 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 <stdio.h>
21 #include <stdint.h>
22 #include <stdlib.h>
23 #include <sys/types.h>
24 #include <sys/stat.h>
25 #include <fcntl.h>
26 #include <unistd.h>
27 #include <string.h>
28 #include <sys/time.h>
29 #include <inttypes.h>
30 #include <arpa/inet.h>
31 #include <glib.h>
32 #include <libusb.h>
33 #include "sigrok.h"
34 #include "sigrok-internal.h"
35 #include "config.h"
36 #include "dso.h"
37
38
39 /* Max time in ms before we want to check on events */
40 #define TICK    1
41
42 static int capabilities[] = {
43         SR_HWCAP_OSCILLOSCOPE,
44         SR_HWCAP_LIMIT_SAMPLES,
45         SR_HWCAP_CONTINUOUS,
46         0,
47 };
48
49 static const char *probe_names[] = {
50         "CH1",
51         "CH2",
52         NULL,
53 };
54
55 static struct dso_profile dev_profiles[] = {
56         {       0x04b4, 0x2090,
57                 0x04b5, 0x2090,
58                 "Hantek", "DSO-2090",
59                 NULL, 2,
60                 FIRMWARE_DIR "/hantek-dso-2090.fw" },
61         { 0, 0, 0, 0, 0, 0, 0, 0, 0 }
62 };
63
64
65 SR_PRIV libusb_context *usb_context = NULL;
66 SR_PRIV GSList *dev_insts = NULL;
67
68
69 static struct sr_dev_inst *dso_dev_new(int index, struct dso_profile *prof)
70 {
71         struct sr_dev_inst *sdi;
72         struct context *ctx;
73
74         sdi = sr_dev_inst_new(index, SR_ST_INITIALIZING,
75                 prof->vendor, prof->model, prof->model_version);
76         if (!sdi)
77                 return NULL;
78
79         if (!(ctx = g_try_malloc0(sizeof(struct context)))) {
80                 sr_err("hantek-dso: ctx malloc failed");
81                 return NULL;
82         }
83         ctx->profile = prof;
84         ctx->dev_state = IDLE;
85         ctx->timebase = DEFAULT_TIMEBASE;
86         ctx->ch1_enabled = TRUE;
87         ctx->ch2_enabled = TRUE;
88         ctx->voltage_ch1 = DEFAULT_VOLTAGE;
89         ctx->voltage_ch2 = DEFAULT_VOLTAGE;
90         ctx->coupling_ch1 = DEFAULT_COUPLING;
91         ctx->coupling_ch2 = DEFAULT_COUPLING;
92         ctx->voffset_ch1 = DEFAULT_VERT_OFFSET;
93         ctx->voffset_ch2 = DEFAULT_VERT_OFFSET;
94         ctx->voffset_trigger = DEFAULT_VERT_TRIGGERPOS;
95         ctx->framesize = DEFAULT_FRAMESIZE;
96         ctx->triggerslope = SLOPE_POSITIVE;
97         ctx->triggersource = DEFAULT_TRIGGER_SOURCE;
98         ctx->triggerposition = DEFAULT_HORIZ_TRIGGERPOS;
99         sdi->priv = ctx;
100         dev_insts = g_slist_append(dev_insts, sdi);
101
102         return sdi;
103 }
104
105 static int configure_probes(struct context *ctx, GSList *probes)
106 {
107         struct sr_probe *probe;
108         GSList *l;
109
110         ctx->ch1_enabled = ctx->ch2_enabled = FALSE;
111         for (l = probes; l; l = l->next) {
112                 probe = (struct sr_probe *)l->data;
113                 if (probe->index == 1)
114                         ctx->ch1_enabled = probe->enabled;
115                 else if (probe->index == 2)
116                         ctx->ch2_enabled = probe->enabled;
117         }
118
119         return SR_OK;
120 }
121
122 static int hw_init(const char *devinfo)
123 {
124         struct sr_dev_inst *sdi;
125         struct libusb_device_descriptor des;
126         struct dso_profile *prof;
127         struct context *ctx;
128         libusb_device **devlist;
129         int err, devcnt, i, j;
130
131         /* Avoid compiler warnings. */
132         (void)devinfo;
133
134         if (libusb_init(&usb_context) != 0) {
135                 sr_err("hantek-dso: Failed to initialize USB.");
136                 return 0;
137         }
138
139         /* Find all Hantek DSO devices and upload firmware to all of them. */
140         devcnt = 0;
141         libusb_get_device_list(usb_context, &devlist);
142         for (i = 0; devlist[i]; i++) {
143                 if ((err = libusb_get_device_descriptor(devlist[i], &des))) {
144                         sr_err("hantek-dso: failed to get device descriptor: %d", err);
145                         continue;
146                 }
147
148                 prof = NULL;
149                 for (j = 0; dev_profiles[j].orig_vid; j++) {
150                         if (des.idVendor == dev_profiles[j].orig_vid
151                                 && des.idProduct == dev_profiles[j].orig_pid) {
152                                 /* Device matches the pre-firmware profile. */
153                                 prof = &dev_profiles[j];
154                                 sr_dbg("hantek-dso: Found a %s %s.", prof->vendor, prof->model);
155                                 sdi = dso_dev_new(devcnt, prof);
156                                 ctx = sdi->priv;
157                                 if (ezusb_upload_firmware(devlist[i], USB_CONFIGURATION,
158                                                 prof->firmware) == SR_OK)
159                                         /* Remember when the firmware on this device was updated */
160                                         g_get_current_time(&ctx->fw_updated);
161                                 else
162                                         sr_err("hantek-dso: firmware upload failed for "
163                                                "device %d", devcnt);
164                                 /* Dummy USB address of 0xff will get overwritten later. */
165                                 ctx->usb = sr_usb_dev_inst_new(
166                                                 libusb_get_bus_number(devlist[i]), 0xff, NULL);
167                                 devcnt++;
168                                 break;
169                         } else if (des.idVendor == dev_profiles[j].fw_vid
170                                 && des.idProduct == dev_profiles[j].fw_pid) {
171                                 /* Device matches the post-firmware profile. */
172                                 prof = &dev_profiles[j];
173                                 sr_dbg("hantek-dso: Found a %s %s.", prof->vendor, prof->model);
174                                 sdi = dso_dev_new(devcnt, prof);
175                                 sdi->status = SR_ST_INACTIVE;
176                                 ctx = sdi->priv;
177                                 ctx->usb = sr_usb_dev_inst_new(
178                                                 libusb_get_bus_number(devlist[i]),
179                                                 libusb_get_device_address(devlist[i]), NULL);
180                                 devcnt++;
181                                 break;
182                         }
183                 }
184                 if (!prof)
185                         /* not a supported VID/PID */
186                         continue;
187         }
188         libusb_free_device_list(devlist, 1);
189
190         return devcnt;
191 }
192
193 static int hw_dev_open(int dev_index)
194 {
195         GTimeVal cur_time;
196         struct sr_dev_inst *sdi;
197         struct context *ctx;
198         int timediff, err;
199
200         if (!(sdi = sr_dev_inst_get(dev_insts, dev_index)))
201                 return SR_ERR_ARG;
202         ctx = sdi->priv;
203
204         /*
205          * if the firmware was recently uploaded, wait up to MAX_RENUM_DELAY ms
206          * for the FX2 to renumerate
207          */
208         err = 0;
209         if (GTV_TO_MSEC(ctx->fw_updated) > 0) {
210                 sr_info("hantek-dso: waiting for device to reset");
211                 /* takes at least 300ms for the FX2 to be gone from the USB bus */
212                 g_usleep(300 * 1000);
213                 timediff = 0;
214                 while (timediff < MAX_RENUM_DELAY) {
215                         if ((err = dso_open(dev_index)) == SR_OK)
216                                 break;
217                         g_usleep(100 * 1000);
218                         g_get_current_time(&cur_time);
219                         timediff = GTV_TO_MSEC(cur_time) - GTV_TO_MSEC(ctx->fw_updated);
220                 }
221                 sr_info("hantek-dso: device came back after %d ms", timediff);
222         } else {
223                 err = dso_open(dev_index);
224         }
225
226         if (err != SR_OK) {
227                 sr_err("hantek-dso: unable to open device");
228                 return SR_ERR;
229         }
230
231         err = libusb_claim_interface(ctx->usb->devhdl, USB_INTERFACE);
232         if (err != 0) {
233                 sr_err("hantek-dso: Unable to claim interface: %d", err);
234                 return SR_ERR;
235         }
236
237         return SR_OK;
238 }
239
240 static int hw_dev_close(int dev_index)
241 {
242         struct sr_dev_inst *sdi;
243
244         if (!(sdi = sr_dev_inst_get(dev_insts, dev_index)))
245                 return SR_ERR_ARG;
246
247         dso_close(sdi);
248
249         return SR_OK;
250 }
251
252 static int hw_cleanup(void)
253 {
254         GSList *l;
255         struct sr_dev_inst *sdi;
256         struct context *ctx;
257
258         /* Properly close and free all devices. */
259         for (l = dev_insts; l; l = l->next) {
260                 if (!(sdi = l->data)) {
261                         /* Log error, but continue cleaning up the rest. */
262                         sr_err("hantek-dso: %s: sdi was NULL, continuing", __func__);
263                         continue;
264                 }
265                 if (!(ctx = sdi->priv)) {
266                         /* Log error, but continue cleaning up the rest. */
267                         sr_err("hantek-dso: %s: sdi->priv was NULL, continuing", __func__);
268                         continue;
269                 }
270                 dso_close(sdi);
271                 sr_usb_dev_inst_free(ctx->usb);
272                 sr_dev_inst_free(sdi);
273         }
274
275         g_slist_free(dev_insts);
276         dev_insts = NULL;
277
278         if (usb_context)
279                 libusb_exit(usb_context);
280         usb_context = NULL;
281
282         return SR_OK;
283 }
284
285 static void *hw_get_device_info(int dev_index, int dev_info_id)
286 {
287         struct sr_dev_inst *sdi;
288         struct context *ctx;
289         void *info;
290         uint64_t tmp;
291
292         if (!(sdi = sr_dev_inst_get(dev_insts, dev_index)))
293                 return NULL;
294         ctx = sdi->priv;
295
296         info = NULL;
297         switch (dev_info_id) {
298         case SR_DI_INST:
299                 info = sdi;
300                 break;
301         case SR_DI_NUM_PROBES:
302                 info = GINT_TO_POINTER(ctx->profile->num_probes);
303                 break;
304         case SR_DI_PROBE_NAMES:
305                 info = probe_names;
306                 break;
307         /* TODO remove this */
308         case SR_DI_CUR_SAMPLERATE:
309                 info = &tmp;
310                 break;
311         }
312
313         return info;
314 }
315
316 static int hw_get_status(int device_index)
317 {
318         struct sr_dev_inst *sdi;
319
320         if (!(sdi = sr_dev_inst_get(dev_insts, device_index)))
321                 return SR_ST_NOT_FOUND;
322
323         return sdi->status;
324 }
325
326 static int *hwcap_get_all(void)
327 {
328
329         return capabilities;
330 }
331
332 static int hw_dev_config_set(int dev_index, int hwcap, void *value)
333 {
334         struct sr_dev_inst *sdi;
335         struct context *ctx;
336         int tmp, ret;
337
338         if (!(sdi = sr_dev_inst_get(dev_insts, dev_index)))
339                 return SR_ERR;
340
341         if (sdi->status != SR_ST_ACTIVE)
342                 return SR_ERR;
343
344         ctx = sdi->priv;
345         switch (hwcap) {
346         case SR_HWCAP_LIMIT_FRAMES:
347                 ctx->limit_frames = *(uint64_t *)value;
348                 break;
349         case SR_HWCAP_PROBECONFIG:
350                 ret = configure_probes(ctx, (GSList *) value);
351                 break;
352         case SR_HWCAP_TRIGGERSLOPE:
353                 tmp = *(int *)value;
354                 if (tmp != SLOPE_NEGATIVE && tmp != SLOPE_POSITIVE)
355                         ret = SR_ERR_ARG;
356                 ctx->triggerslope = tmp;
357         default:
358                 ret = SR_ERR_ARG;
359         }
360
361         return ret;
362 }
363
364 /* Called by libusb (as triggered by handle_event()) when a transfer comes in.
365  * Only channel data comes in asynchronously, and all transfers for this are
366  * queued up beforehand, so this just needs so chuck the incoming data onto
367  * the libsigrok session bus.
368  */
369 static void receive_transfer(struct libusb_transfer *transfer)
370 {
371         struct sr_datafeed_packet packet;
372         struct sr_datafeed_analog analog;
373         struct context *ctx;
374         float ch1, ch2;
375         int num_probes, data_offset, i;
376
377         ctx = transfer->user_data;
378         sr_dbg("hantek-dso: receive_transfer(): status %d received %d bytes",
379                         transfer->status, transfer->actual_length);
380
381         if (transfer->actual_length == 0)
382                 /* Nothing to send to the bus. */
383                 return;
384
385         ctx->current_transfer += transfer->actual_length;
386         sr_dbg("hantek-dso: got %d of %d in frame", ctx->current_transfer, ctx->framesize * 2);
387
388         num_probes = (ctx->ch1_enabled && ctx->ch2_enabled) ? 2 : 1;
389         packet.type = SR_DF_ANALOG;
390         packet.payload = &analog;
391         /* TODO: support for 5xxx series 9-bit samples */
392         analog.num_samples = transfer->actual_length / 2;
393         analog.data = g_try_malloc(analog.num_samples * sizeof(float) * num_probes);
394         data_offset = 0;
395         for (i = 0; i < analog.num_samples; i++) {
396                 /* The device always sends data for both channels. If a channel
397                  * is disabled, it contains a copy of the enabled channel's
398                  * data. However, we only send the requested channels to the bus.
399                  */
400                 /* TODO: support for 5xxx series 9-bit samples */
401                 if (ctx->ch1_enabled) {
402                         ch1 = (*(transfer->buffer + i * 2 + 1) / 255.0);
403                         analog.data[data_offset++] = ch1;
404                 }
405                 if (ctx->ch2_enabled) {
406                         ch2 = (*(transfer->buffer + i * 2) / 255.0);
407                         analog.data[data_offset++] = ch2;
408                 }
409         }
410         g_free(transfer->buffer);
411         libusb_free_transfer(transfer);
412         sr_session_send(ctx->cb_data, &packet);
413
414         if (ctx->current_transfer >= ctx->framesize * 2) {
415                 /* That's the last chunk in this frame. */
416                 packet.type = SR_DF_FRAME_END;
417                 sr_session_send(ctx->cb_data, &packet);
418
419                 if (ctx->limit_frames && ++ctx->num_frames == ctx->limit_frames) {
420                         /* Terminate session */
421                         /* TODO: don't leave pending USB transfers hanging */
422                         packet.type = SR_DF_END;
423                         sr_session_send(ctx->cb_data, &packet);
424                 } else {
425                         ctx->current_transfer = 0;
426                         ctx->dev_state = NEW_CAPTURE;
427                 }
428         }
429
430 }
431
432 static int handle_event(int fd, int revents, void *cb_data)
433 {
434         struct sr_datafeed_packet packet;
435         struct timeval tv;
436         struct context *ctx;
437         int capturestate;
438
439         /* Avoid compiler warnings. */
440         (void)fd;
441         (void)revents;
442
443         /* Always handle pending libusb events. */
444         tv.tv_sec = tv.tv_usec = 0;
445         libusb_handle_events_timeout(usb_context, &tv);
446
447         ctx = cb_data;
448         /* TODO: ugh */
449         if (ctx->dev_state == NEW_CAPTURE) {
450                 if (dso_capture_start(ctx) != SR_OK)
451                         return TRUE;
452                 if (dso_enable_trigger(ctx) != SR_OK)
453                         return TRUE;
454                 if (dso_force_trigger(ctx) != SR_OK)
455                         return TRUE;
456                 sr_dbg("hantek-dso: successfully requested next chunk");
457                 ctx->dev_state = CAPTURE;
458                 return TRUE;
459         }
460         if (ctx->dev_state != CAPTURE)
461                 return TRUE;
462
463         if ((capturestate = dso_get_capturestate(ctx)) == CAPTURE_UNKNOWN) {
464                 /* Generated by the function, not the hardware. */
465                 return TRUE;
466         }
467
468         sr_dbg("hantek-dso: capturestate %d", capturestate);
469         switch (capturestate) {
470         case CAPTURE_EMPTY:
471                 if (++ctx->capture_empty_count >= MAX_CAPTURE_EMPTY) {
472                         ctx->capture_empty_count = 0;
473                         if (dso_capture_start(ctx) != SR_OK)
474                                 break;
475                         if (dso_enable_trigger(ctx) != SR_OK)
476                                 break;
477                         if (dso_force_trigger(ctx) != SR_OK)
478                                 break;
479                         sr_dbg("hantek-dso: successfully requested next chunk");
480                 }
481                 break;
482         case CAPTURE_FILLING:
483                 /* no data yet */
484                 break;
485         case CAPTURE_READY_8BIT:
486                 /* Tell the scope to send us the first frame. */
487                 if (dso_get_channeldata(ctx, receive_transfer) != SR_OK)
488                         break;
489
490                 /* Don't hit the state machine again until we're done fetching
491                  * the data we just told the scope to send.
492                  */
493                 ctx->dev_state = FETCH_DATA;
494
495                 /* Tell the frontend a new frame is on the way. */
496                 packet.type = SR_DF_FRAME_BEGIN;
497                 sr_session_send(cb_data, &packet);
498                 break;
499         case CAPTURE_READY_9BIT:
500                 /* TODO */
501                 sr_err("not yet supported");
502                 break;
503         case CAPTURE_TIMEOUT:
504                 /* Doesn't matter, we'll try again next time. */
505                 break;
506         default:
507                 sr_dbg("unknown capture state");
508         }
509
510         return TRUE;
511 }
512
513 static int hw_start_acquisition(int device_index, void *cb_data)
514 {
515         const struct libusb_pollfd **lupfd;
516         struct sr_datafeed_packet packet;
517         struct sr_datafeed_header header;
518         struct sr_datafeed_meta_analog meta;
519         struct sr_dev_inst *sdi;
520         struct context *ctx;
521         int i;
522
523         if (!(sdi = sr_dev_inst_get(dev_insts, device_index)))
524                 return SR_ERR;
525
526         if (sdi->status != SR_ST_ACTIVE)
527                 return SR_ERR;
528
529         ctx = sdi->priv;
530         ctx->cb_data = cb_data;
531
532         if (dso_init(ctx) != SR_OK)
533                 return SR_ERR;
534
535         if (dso_capture_start(ctx) != SR_OK)
536                 return SR_ERR;
537
538         ctx->dev_state = CAPTURE;
539         lupfd = libusb_get_pollfds(usb_context);
540         for (i = 0; lupfd[i]; i++)
541                 sr_source_add(lupfd[i]->fd, lupfd[i]->events, TICK, handle_event,
542                               ctx);
543         free(lupfd);
544
545         /* Send header packet to the session bus. */
546         packet.type = SR_DF_HEADER;
547         packet.payload = (unsigned char *)&header;
548         header.feed_version = 1;
549         gettimeofday(&header.starttime, NULL);
550         sr_session_send(cb_data, &packet);
551
552         /* Send metadata about the SR_DF_ANALOG packets to come. */
553         packet.type = SR_DF_META_ANALOG;
554         packet.payload = &meta;
555         meta.num_probes = ctx->profile->num_probes;
556         sr_session_send(cb_data, &packet);
557
558         return SR_OK;
559 }
560
561 /* TODO: doesn't really cancel pending transfers so they might come in after
562  * SR_DF_END is sent.
563  */
564 static int hw_stop_acquisition(int device_index, gpointer session_device_id)
565 {
566         struct sr_datafeed_packet packet;
567         struct sr_dev_inst *sdi;
568         struct context *ctx;
569
570         if (!(sdi = sr_dev_inst_get(dev_insts, device_index)))
571                 return SR_ERR;
572
573         if (sdi->status != SR_ST_ACTIVE)
574                 return SR_ERR;
575
576         ctx = sdi->priv;
577         ctx->dev_state = IDLE;
578
579         packet.type = SR_DF_END;
580         sr_session_send(session_device_id, &packet);
581
582         return SR_OK;
583 }
584
585 SR_PRIV struct sr_dev_driver hantek_dso_plugin_info = {
586         .name = "hantek-dso",
587         .longname = "Hantek DSO",
588         .api_version = 1,
589         .init = hw_init,
590         .cleanup = hw_cleanup,
591         .dev_open = hw_dev_open,
592         .dev_close = hw_dev_close,
593         .dev_info_get = hw_get_device_info,
594         .dev_status_get = hw_get_status,
595         .hwcap_get_all = hwcap_get_all,
596         .dev_config_set = hw_dev_config_set,
597         .dev_acquisition_start = hw_start_acquisition,
598         .dev_acquisition_stop = hw_stop_acquisition,
599 };