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