c74187ada435f2441e7aa3b88ed926194c9d530b
[libsigrok.git] / src / hardware / hantek-dso / protocol.c
1 /*
2  * This file is part of the libsigrok project.
3  *
4  * Copyright (C) 2012 Bert Vermeulen <bert@biot.com>
5  * With protocol information from the hantekdso project,
6  * Copyright (C) 2008 Oleg Khudyakov <prcoder@gmail.com>
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 <config.h>
23 #include <string.h>
24 #include <glib.h>
25 #include <libusb.h>
26 #include <libsigrok/libsigrok.h>
27 #include "libsigrok-internal.h"
28 #include "protocol.h"
29
30 static int send_begin(const struct sr_dev_inst *sdi)
31 {
32         struct sr_usb_dev_inst *usb;
33         int ret;
34         unsigned char buffer[] = {0x0f, 0x03, 0x03, 0x03, 0x68, 0xac, 0xfe,
35         0x00, 0x01, 0x00};
36
37         sr_dbg("Sending CTRL_BEGINCOMMAND.");
38
39         usb = sdi->conn;
40         if ((ret = libusb_control_transfer(usb->devhdl,
41                         LIBUSB_REQUEST_TYPE_VENDOR, CTRL_BEGINCOMMAND,
42                         0, 0, buffer, sizeof(buffer), 200)) != sizeof(buffer)) {
43                 sr_err("Failed to send begincommand: %s.",
44                        libusb_error_name(ret));
45                 return SR_ERR;
46         }
47
48         return SR_OK;
49 }
50
51 static int send_bulkcmd(const struct sr_dev_inst *sdi, uint8_t *cmdstring, int cmdlen)
52 {
53         struct sr_usb_dev_inst *usb;
54         int ret, tmp;
55
56         usb = sdi->conn;
57
58         if (send_begin(sdi) != SR_OK)
59                 return SR_ERR;
60
61         if ((ret = libusb_bulk_transfer(usb->devhdl, DSO_EP_OUT, cmdstring,
62                         cmdlen, &tmp, 200)) != 0)
63                 return SR_ERR;
64
65         return SR_OK;
66 }
67
68 static int dso_getmps(libusb_device *dev)
69 {
70         struct libusb_device_descriptor des;
71         struct libusb_config_descriptor *conf_dsc;
72         const struct libusb_interface_descriptor *intf_dsc;
73         int mps;
74
75         libusb_get_device_descriptor(dev, &des);
76
77         if (des.bNumConfigurations != 1)
78                 return 0;
79
80         if (libusb_get_config_descriptor(dev, 0, &conf_dsc) != 0)
81                 return 0;
82
83         mps = 0;
84         intf_dsc = &(conf_dsc->interface[0].altsetting[0]);
85         if (intf_dsc->bNumEndpoints != 2)
86                 goto err;
87
88         if ((intf_dsc->endpoint[0].bEndpointAddress & 0x8f) !=
89             (2 | LIBUSB_ENDPOINT_OUT))
90                 /* The first endpoint should be 2 (outbound). */
91                 goto err;
92
93         if ((intf_dsc->endpoint[1].bEndpointAddress & 0x8f) !=
94             (6 | LIBUSB_ENDPOINT_IN))
95                 /* The second endpoint should be 6 (inbound). */
96                 goto err;
97
98         mps = intf_dsc->endpoint[1].wMaxPacketSize;
99
100 err:
101         if (conf_dsc)
102                 libusb_free_config_descriptor(conf_dsc);
103
104         return mps;
105 }
106
107 SR_PRIV int dso_open(struct sr_dev_inst *sdi)
108 {
109         struct dev_context *devc;
110         struct drv_context *drvc = sdi->driver->context;
111         struct sr_usb_dev_inst *usb;
112         struct libusb_device_descriptor des;
113         libusb_device **devlist;
114         int err, i;
115         char connection_id[64];
116
117         devc = sdi->priv;
118         usb = sdi->conn;
119
120         libusb_get_device_list(drvc->sr_ctx->libusb_ctx, &devlist);
121         for (i = 0; devlist[i]; i++) {
122                 libusb_get_device_descriptor(devlist[i], &des);
123
124                 if (des.idVendor != devc->profile->fw_vid
125                     || des.idProduct != devc->profile->fw_pid)
126                         continue;
127
128                 if ((sdi->status == SR_ST_INITIALIZING) ||
129                                 (sdi->status == SR_ST_INACTIVE)) {
130                         /*
131                          * Check device by its physical USB bus/port address.
132                          */
133                         if (usb_get_port_path(devlist[i], connection_id, sizeof(connection_id)) < 0)
134                                 continue;
135
136                         if (strcmp(sdi->connection_id, connection_id))
137                                 /* This is not the one. */
138                                 continue;
139                 }
140
141                 if (!(err = libusb_open(devlist[i], &usb->devhdl))) {
142                         if (usb->address == 0xff)
143                                 /*
144                                  * first time we touch this device after firmware upload,
145                                  * so we don't know the address yet.
146                                  */
147                                 usb->address = libusb_get_device_address(devlist[i]);
148
149                         if (!(devc->epin_maxpacketsize = dso_getmps(devlist[i])))
150                                 sr_err("Wrong endpoint profile.");
151                         else {
152                                 sdi->status = SR_ST_ACTIVE;
153                                 sr_info("Opened device on %d.%d (logical) / "
154                                                 "%s (physical) interface %d.",
155                                         usb->bus, usb->address,
156                                         sdi->connection_id, USB_INTERFACE);
157                         }
158                 } else {
159                         sr_err("Failed to open device: %s.",
160                                libusb_error_name(err));
161                 }
162
163                 /* If we made it here, we handled the device (somehow). */
164                 break;
165         }
166         libusb_free_device_list(devlist, 1);
167
168         if (sdi->status != SR_ST_ACTIVE)
169                 return SR_ERR;
170
171         return SR_OK;
172 }
173
174 SR_PRIV void dso_close(struct sr_dev_inst *sdi)
175 {
176         struct sr_usb_dev_inst *usb;
177
178         usb = sdi->conn;
179
180         if (!usb->devhdl)
181                 return;
182
183         sr_info("Closing device on %d.%d (logical) / %s (physical) interface %d.",
184                         usb->bus, usb->address, sdi->connection_id, USB_INTERFACE);
185         libusb_release_interface(usb->devhdl, USB_INTERFACE);
186         libusb_close(usb->devhdl);
187         usb->devhdl = NULL;
188         sdi->status = SR_ST_INACTIVE;
189 }
190
191 static int get_channel_offsets(const struct sr_dev_inst *sdi)
192 {
193         struct dev_context *devc;
194         struct sr_usb_dev_inst *usb;
195         GString *gs;
196         int chan, v, ret;
197
198         sr_dbg("Getting channel offsets.");
199
200         devc = sdi->priv;
201         usb = sdi->conn;
202
203         ret = libusb_control_transfer(usb->devhdl,
204                         LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_VENDOR,
205                         CTRL_READ_EEPROM, EEPROM_CHANNEL_OFFSETS, 0,
206                         (unsigned char *)&devc->channel_levels,
207                         sizeof(devc->channel_levels), 200);
208         if (ret != sizeof(devc->channel_levels)) {
209                 sr_err("Failed to get channel offsets: %s.",
210                        libusb_error_name(ret));
211                 return SR_ERR;
212         }
213
214         /* Comes in as 16-bit numbers with the second byte always 0 on
215          * the DSO-2090. Guessing this is supposed to be big-endian,
216          * since that's how voltage offsets are submitted back to the DSO.
217          * Convert to host order now, so we can use them natively.
218          */
219         for (chan = 0; chan < NUM_CHANNELS; chan++) {
220                 for (v = 0; v < 9; v++) {
221                         devc->channel_levels[chan][v][0] =
222                                 g_ntohs(devc->channel_levels[chan][v][0]);
223                         devc->channel_levels[chan][v][1] =
224                                 g_ntohs(devc->channel_levels[chan][v][1]);
225                 }
226         }
227
228         if (sr_log_loglevel_get() >= SR_LOG_DBG) {
229                 gs = g_string_sized_new(128);
230                 for (chan = 0; chan < NUM_CHANNELS; chan++) {
231                         g_string_printf(gs, "CH%d:", chan + 1);
232                         for (v = 0; v < 9; v++) {
233                                 g_string_append_printf(gs, " %.4x-%.4x",
234                                         devc->channel_levels[chan][v][0],
235                                         devc->channel_levels[chan][v][1]);
236                         }
237                         sr_dbg("%s", gs->str);
238                 }
239                 g_string_free(gs, TRUE);
240         }
241
242         return SR_OK;
243 }
244
245 static void dso2250_set_triggerpos(int value, int long_buffer, uint8_t dest[], int offset)
246 {
247         uint32_t min, max;
248         uint32_t tmp, diff;
249
250         min = long_buffer ? 0 : 0x7d7ff;
251         max = 0x7ffff;
252
253         diff = max - min;
254         tmp = min + diff * value / 100;
255         sr_dbg("2250 trigger pos: %3d%% * [0x%x,0x%x] == 0x%x", value, min, max, tmp);
256
257         dest[offset + 0] = tmp & 0xff;
258         dest[offset + 1] = (tmp >> 8) & 0xff;
259         dest[offset + 2] = (tmp >> 16) & 0x7;
260 }
261
262 /* See http://openhantek.sourceforge.net/doc/namespaceHantek.html#ac1cd181814cf3da74771c29800b39028 */
263 static int dso2250_set_trigger_samplerate(const struct sr_dev_inst *sdi)
264 {
265         struct dev_context *devc;
266         struct sr_usb_dev_inst *usb;
267         int ret, tmp;
268         uint64_t base;
269         uint8_t cmdstring[12];
270         int trig;
271
272         devc = sdi->priv;
273         usb = sdi->conn;
274
275         memset(cmdstring, 0, sizeof(cmdstring));
276         /* Command */
277         cmdstring[0] = CMD_2250_SET_TRIGGERSOURCE;
278         sr_dbg("Trigger source %s.", devc->triggersource);
279         if (!strcmp("CH2", devc->triggersource))
280                 tmp = 3;
281         else if (!strcmp("CH1", devc->triggersource))
282                 tmp = 2;
283         else if (!strcmp("EXT", devc->triggersource))
284                 tmp = 0;
285         else {
286                 sr_err("Invalid trigger source: '%s'.", devc->triggersource);
287                 return SR_ERR_ARG;
288         }
289         cmdstring[2] = tmp;
290
291         sr_dbg("Trigger slope: %d.", devc->triggerslope);
292         cmdstring[2] |= (devc->triggerslope == SLOPE_NEGATIVE ? 1 : 0) << 3;
293
294         if (send_begin(sdi) != SR_OK)
295                 return SR_ERR;
296
297         if ((ret = libusb_bulk_transfer(usb->devhdl, DSO_EP_OUT,
298                         cmdstring, 8, &tmp, 100)) != 0) {
299                 sr_err("Failed to set trigger/samplerate: %s.",
300                        libusb_error_name(ret));
301                 return SR_ERR;
302         }
303
304         /* Frame size */
305         sr_dbg("Frame size: %d.", devc->framesize);
306         cmdstring[0] = CMD_2250_SET_RECORD_LENGTH;
307         cmdstring[2] = (devc->framesize == FRAMESIZE_SMALL) ? 0x01 : 0x02;
308
309         if (send_begin(sdi) != SR_OK)
310                 return SR_ERR;
311
312         if ((ret = libusb_bulk_transfer(usb->devhdl, DSO_EP_OUT,
313                         cmdstring, 4, &tmp, 100)) != 0) {
314                 sr_err("Failed to set record length: %s.",
315                        libusb_error_name(ret));
316                 return SR_ERR;
317         }
318
319         memset(cmdstring, 0, sizeof(cmdstring));
320         cmdstring[0] = CMD_2250_SET_SAMPLERATE;
321         base = 100e6;
322         if (devc->samplerate > base) {
323                 /* Timebase fast */
324                 sr_err("Sample rate > 100MHz not yet supported.");
325                 return SR_ERR_ARG;
326         }
327
328         tmp = base / devc->samplerate;
329         if (tmp) {
330                 /* Downsampling on */
331                 cmdstring[2] |= 2;
332                 /* Downsampler = 1comp((Base / Samplerate) - 2)
333                  *  Base == 100Msa resp. 200MSa
334                  *
335                  * Example for 500kSa/s:
336                  *  100e6 / 500e3 => 200
337                  *  200 - 2 => 198
338                  *  1comp(198) => ff39 */
339                 tmp -= 2;
340                 tmp = ~tmp;
341                 sr_dbg("Down sampler value: 0x%x.", tmp & 0xffff);
342                 cmdstring[4] = (tmp >> 0) & 0xff;
343                 cmdstring[5] = (tmp >> 8) & 0xff;
344         }
345
346         if (send_begin(sdi) != SR_OK)
347                 return SR_ERR;
348
349         if ((ret = libusb_bulk_transfer(usb->devhdl, DSO_EP_OUT,
350                         cmdstring, 8, &tmp, 100)) != 0) {
351                 sr_err("Failed to set sample rate: %s.",
352                        libusb_error_name(ret));
353                 return SR_ERR;
354         }
355         sr_dbg("Sent CMD_2250_SET_SAMPLERATE.");
356
357         /* Enabled channels: 00=CH1, 01=CH2, 10=both. */
358         memset(cmdstring, 0, sizeof(cmdstring));
359         cmdstring[0] = CMD_2250_SET_CHANNELS;
360         sr_dbg("Channels: CH1=%d, CH2=%d.", devc->ch_enabled[0], devc->ch_enabled[1]);
361         cmdstring[2] = (devc->ch_enabled[0] ? 0 : 1) + (devc->ch_enabled[1] ? 2 : 0);
362
363         if (send_begin(sdi) != SR_OK)
364                 return SR_ERR;
365
366         if ((ret = libusb_bulk_transfer(usb->devhdl, DSO_EP_OUT,
367                         cmdstring, 4, &tmp, 100)) != 0) {
368                 sr_err("Failed to set channels: %s.",
369                        libusb_error_name(ret));
370                 return SR_ERR;
371         }
372         sr_dbg("Sent CMD_2250_SET_CHANNELS.");
373
374         /* Trigger slope: 0=positive, 1=negative. */
375         memset(cmdstring, 0, sizeof(cmdstring));
376         cmdstring[0] = CMD_2250_SET_TRIGGERPOS_AND_BUFFER;
377
378         sr_dbg("Capture ratio: %" PRIu64 ".", devc->capture_ratio);
379         trig = devc->capture_ratio;
380         dso2250_set_triggerpos(trig,
381                         devc->framesize != FRAMESIZE_SMALL, cmdstring, 2);
382         dso2250_set_triggerpos(100 - trig,
383                         devc->framesize != FRAMESIZE_SMALL, cmdstring, 6);
384
385         if (send_begin(sdi) != SR_OK)
386                 return SR_ERR;
387
388         /* TODO: 12 bytes according to documentation? */
389         if ((ret = libusb_bulk_transfer(usb->devhdl, DSO_EP_OUT,
390                         cmdstring, 10, &tmp, 100)) != 0) {
391                 sr_err("Failed to set trigger position: %s.",
392                        libusb_error_name(ret));
393                 return SR_ERR;
394         }
395
396         return SR_OK;
397 }
398
399 SR_PRIV int dso_set_trigger_samplerate(const struct sr_dev_inst *sdi)
400 {
401         struct dev_context *devc;
402         struct sr_usb_dev_inst *usb;
403         int ret, tmp;
404         uint8_t cmdstring[12];
405         uint16_t timebase_small[] = { 0xffff, 0xfffc, 0xfff7, 0xffe8, 0xffce,
406                 0xff9c, 0xff07, 0xfe0d, 0xfc19, 0xf63d, 0xec79, 0xd8f1 };
407         uint16_t timebase_large[] = { 0xffff, 0x0000, 0xfffc, 0xfff7, 0xffe8,
408                 0xffce, 0xff9d, 0xff07, 0xfe0d, 0xfc19, 0xf63d, 0xec79 };
409
410         devc = sdi->priv;
411         if (devc->profile->fw_pid == 0x2250)
412                 return dso2250_set_trigger_samplerate(sdi);
413
414         sr_dbg("Preparing CMD_SET_TRIGGER_SAMPLERATE.");
415
416         usb = sdi->conn;
417
418         memset(cmdstring, 0, sizeof(cmdstring));
419         /* Command */
420         cmdstring[0] = CMD_SET_TRIGGER_SAMPLERATE;
421
422         /* Trigger source */
423         sr_dbg("Trigger source %s.", devc->triggersource);
424         if (!strcmp("CH2", devc->triggersource))
425                 tmp = 0;
426         else if (!strcmp("CH1", devc->triggersource))
427                 tmp = 1;
428         else if (!strcmp("EXT", devc->triggersource))
429                 tmp = 2;
430         else {
431                 sr_err("Invalid trigger source: '%s'.", devc->triggersource);
432                 return SR_ERR_ARG;
433         }
434         cmdstring[2] = tmp;
435
436         /* Frame size */
437         sr_dbg("Frame size: %d.", devc->framesize);
438         cmdstring[2] |= (devc->framesize == FRAMESIZE_SMALL ? 0x01 : 0x02) << 2;
439
440         /* Timebase fast */
441         sr_dbg("Time base index: %d.", devc->timebase);
442         if (devc->framesize == FRAMESIZE_SMALL) {
443                 if (devc->timebase < TIME_20us)
444                         tmp = 0;
445                 else if (devc->timebase == TIME_20us)
446                         tmp = 1;
447                 else if (devc->timebase == TIME_40us)
448                         tmp = 2;
449                 else if (devc->timebase == TIME_100us)
450                         tmp = 3;
451                 else if (devc->timebase >= TIME_200us)
452                         tmp = 4;
453         } else {
454                 if (devc->timebase < TIME_40us) {
455                         sr_err("Timebase < 40us only supported with 10K buffer.");
456                         return SR_ERR_ARG;
457                 }
458                 else if (devc->timebase == TIME_40us)
459                         tmp = 0;
460                 else if (devc->timebase == TIME_100us)
461                         tmp = 2;
462                 else if (devc->timebase == TIME_200us)
463                         tmp = 3;
464                 else if (devc->timebase >= TIME_400us)
465                         tmp = 4;
466         }
467         cmdstring[2] |= (tmp & 0x07) << 5;
468
469         /* Enabled channels: 00=CH1 01=CH2 10=both */
470         sr_dbg("Channels CH1=%d CH2=%d", devc->ch_enabled[0], devc->ch_enabled[1]);
471         tmp = (((devc->ch_enabled[1] ? 1 : 0) << 1) + (devc->ch_enabled[0] ? 1 : 0)) - 1;
472         cmdstring[3] = tmp;
473
474         /* Fast rates channel */
475         /* TODO: Is this right? */
476         tmp = devc->timebase < TIME_10us ? 1 : 0;
477         cmdstring[3] |= tmp << 2;
478
479         /* Trigger slope: 0=positive 1=negative */
480         /* TODO: Does this work? */
481         sr_dbg("Trigger slope: %d.", devc->triggerslope);
482         cmdstring[3] |= (devc->triggerslope == SLOPE_NEGATIVE ? 1 : 0) << 3;
483
484         /* Timebase slow */
485         if (devc->timebase < TIME_100us)
486                 tmp = 0;
487         else if (devc->timebase > TIME_400ms)
488                 tmp = 0xffed;
489         else {
490                 if (devc->framesize == FRAMESIZE_SMALL)
491                         tmp = timebase_small[devc->timebase - 3];
492                 else
493                         tmp = timebase_large[devc->timebase - 3];
494         }
495         cmdstring[4] = tmp & 0xff;
496         cmdstring[5] = (tmp >> 8) & 0xff;
497
498         /* Horizontal trigger position */
499         sr_dbg("Capture ratio: %" PRIu64 ".", devc->capture_ratio);
500         tmp = 0x77fff + 0x8000 * devc->capture_ratio / 100;
501         cmdstring[6] = tmp & 0xff;
502         cmdstring[7] = (tmp >> 8) & 0xff;
503         cmdstring[10] = (tmp >> 16) & 0xff;
504
505         if (send_begin(sdi) != SR_OK)
506                 return SR_ERR;
507
508         if ((ret = libusb_bulk_transfer(usb->devhdl, DSO_EP_OUT,
509                         cmdstring, sizeof(cmdstring), &tmp, 100)) != 0) {
510                 sr_err("Failed to set trigger/samplerate: %s.",
511                        libusb_error_name(ret));
512                 return SR_ERR;
513         }
514         sr_dbg("Sent CMD_SET_TRIGGER_SAMPLERATE.");
515
516         return SR_OK;
517 }
518
519 static int dso_set_filters(const struct sr_dev_inst *sdi)
520 {
521         struct dev_context *devc;
522         struct sr_usb_dev_inst *usb;
523         int ret, tmp;
524         uint8_t cmdstring[8];
525
526         sr_dbg("Preparing CMD_SET_FILTERS.");
527
528         devc = sdi->priv;
529         usb = sdi->conn;
530
531         memset(cmdstring, 0, sizeof(cmdstring));
532         cmdstring[0] = CMD_SET_FILTERS;
533         cmdstring[1] = 0x0f;
534         if (devc->filter[0]) {
535                 sr_dbg("Turning on CH1 filter.");
536                 cmdstring[2] |= 0x80;
537         }
538         if (devc->filter[1]) {
539                 sr_dbg("Turning on CH2 filter.");
540                 cmdstring[2] |= 0x40;
541         }
542         /*
543          * Not supported: filtering on the trigger
544          * cmdstring[2] |= 0x20;
545          */
546
547         if (send_begin(sdi) != SR_OK)
548                 return SR_ERR;
549
550         if ((ret = libusb_bulk_transfer(usb->devhdl, DSO_EP_OUT,
551                         cmdstring, sizeof(cmdstring), &tmp, 100)) != 0) {
552                 sr_err("Failed to set filters: %s.", libusb_error_name(ret));
553                 return SR_ERR;
554         }
555         sr_dbg("Sent CMD_SET_FILTERS.");
556
557         return SR_OK;
558 }
559
560 static int dso_set_voltage(const struct sr_dev_inst *sdi)
561 {
562         struct dev_context *devc;
563         struct sr_usb_dev_inst *usb;
564         int ret, tmp;
565         uint8_t cmdstring[8];
566
567         sr_dbg("Preparing CMD_SET_VOLTAGE.");
568
569         devc = sdi->priv;
570         usb = sdi->conn;
571
572         memset(cmdstring, 0, sizeof(cmdstring));
573         cmdstring[0] = CMD_SET_VOLTAGE;
574
575         if (devc->profile->fw_pid == 0x2250) {
576                 cmdstring[1] = 0x00;
577                 cmdstring[2] = 0x08;
578         } else {
579                 cmdstring[1] = 0x0f;
580                 cmdstring[2] = 0x30;
581         }
582
583         /* CH1 volts/div is encoded in bits 0-1. */
584         sr_dbg("CH1 vdiv index: %d.", devc->voltage[0]);
585         switch (devc->voltage[0]) {
586         case VDIV_1V:
587         case VDIV_100MV:
588         case VDIV_10MV:
589                 cmdstring[2] |= 0x00;
590                 break;
591         case VDIV_2V:
592         case VDIV_200MV:
593         case VDIV_20MV:
594                 cmdstring[2] |= 0x01;
595                 break;
596         case VDIV_5V:
597         case VDIV_500MV:
598         case VDIV_50MV:
599                 cmdstring[2] |= 0x02;
600                 break;
601         }
602
603         /* CH2 volts/div is encoded in bits 2-3. */
604         sr_dbg("CH2 vdiv index: %d.", devc->voltage[1]);
605         switch (devc->voltage[1]) {
606         case VDIV_1V:
607         case VDIV_100MV:
608         case VDIV_10MV:
609                 cmdstring[2] |= 0x00;
610                 break;
611         case VDIV_2V:
612         case VDIV_200MV:
613         case VDIV_20MV:
614                 cmdstring[2] |= 0x04;
615                 break;
616         case VDIV_5V:
617         case VDIV_500MV:
618         case VDIV_50MV:
619                 cmdstring[2] |= 0x08;
620                 break;
621         }
622
623         if (send_begin(sdi) != SR_OK)
624                 return SR_ERR;
625
626         if ((ret = libusb_bulk_transfer(usb->devhdl, DSO_EP_OUT,
627                         cmdstring, sizeof(cmdstring), &tmp, 100)) != 0) {
628                 sr_err("Failed to set voltage: %s.", libusb_error_name(ret));
629                 return SR_ERR;
630         }
631         sr_dbg("Sent CMD_SET_VOLTAGE.");
632
633         return SR_OK;
634 }
635
636 static int dso_set_relays(const struct sr_dev_inst *sdi)
637 {
638         struct dev_context *devc;
639         struct sr_usb_dev_inst *usb;
640         GString *gs;
641         int ret, i;
642         uint8_t relays[17] = { 0x00, 0x04, 0x08, 0x02, 0x20, 0x40, 0x10, 0x01,
643                         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
644
645         sr_dbg("Preparing CTRL_SETRELAYS.");
646
647         devc = sdi->priv;
648         usb = sdi->conn;
649
650         if (devc->voltage[0] < VDIV_1V)
651                 relays[1] = ~relays[1];
652
653         if (devc->voltage[0] < VDIV_100MV)
654                 relays[2] = ~relays[2];
655
656         sr_dbg("CH1 coupling: %d.", devc->coupling[0]);
657         if (devc->coupling[0] != COUPLING_AC)
658                 relays[3] = ~relays[3];
659
660         if (devc->voltage[1] < VDIV_1V)
661                 relays[4] = ~relays[4];
662
663         if (devc->voltage[1] < VDIV_100MV)
664                 relays[5] = ~relays[5];
665
666         sr_dbg("CH2 coupling: %d.", devc->coupling[1]);
667         if (devc->coupling[1] != COUPLING_AC)
668                 relays[6] = ~relays[6];
669
670         if (!strcmp(devc->triggersource, "EXT"))
671                 relays[7] = ~relays[7];
672
673         if (sr_log_loglevel_get() >= SR_LOG_DBG) {
674                 gs = g_string_sized_new(128);
675                 g_string_printf(gs, "Relays:");
676                 for (i = 0; i < 17; i++)
677                         g_string_append_printf(gs, " %.2x", relays[i]);
678                 sr_dbg("%s", gs->str);
679                 g_string_free(gs, TRUE);
680         }
681
682         if ((ret = libusb_control_transfer(usb->devhdl,
683                         LIBUSB_REQUEST_TYPE_VENDOR, CTRL_SETRELAYS,
684                         0, 0, relays, 17, 100)) != sizeof(relays)) {
685                 sr_err("Failed to set relays: %s.", libusb_error_name(ret));
686                 return SR_ERR;
687         }
688         sr_dbg("Sent CTRL_SETRELAYS.");
689
690         return SR_OK;
691 }
692
693 SR_PRIV int dso_set_voffsets(const struct sr_dev_inst *sdi)
694 {
695         struct dev_context *devc;
696         struct sr_usb_dev_inst *usb;
697         int offset, ret;
698         uint16_t *ch_levels;
699         uint8_t offsets[17];
700
701         sr_dbg("Preparing CTRL_SETOFFSET.");
702
703         devc = sdi->priv;
704         usb = sdi->conn;
705
706         memset(offsets, 0, sizeof(offsets));
707         /* Channel 1 */
708         ch_levels = devc->channel_levels[0][devc->voltage[0]];
709         offset = (ch_levels[1] - ch_levels[0]) * devc->voffset_ch1 + ch_levels[0];
710         offsets[0] = (offset >> 8) | 0x20;
711         offsets[1] = offset & 0xff;
712         sr_dbg("CH1 offset: %3.2f (%.2x%.2x).", devc->voffset_ch1,
713                offsets[0], offsets[1]);
714
715         /* Channel 2 */
716         ch_levels = devc->channel_levels[1][devc->voltage[1]];
717         offset = (ch_levels[1] - ch_levels[0]) * devc->voffset_ch2 + ch_levels[0];
718         offsets[2] = (offset >> 8) | 0x20;
719         offsets[3] = offset & 0xff;
720         sr_dbg("CH2 offset: %3.2f (%.2x%.2x).", devc->voffset_ch2,
721                offsets[2], offsets[3]);
722
723         /* Trigger */
724         offset = MAX_VERT_TRIGGER * devc->voffset_trigger;
725         offsets[4] = (offset >> 8) | 0x20;
726         offsets[5] = offset & 0xff;
727         sr_dbg("Trigger offset: %3.2f (%.2x%.2x).", devc->voffset_trigger,
728                         offsets[4], offsets[5]);
729
730         if ((ret = libusb_control_transfer(usb->devhdl,
731                         LIBUSB_REQUEST_TYPE_VENDOR, CTRL_SETOFFSET,
732                         0, 0, offsets, sizeof(offsets), 100)) != sizeof(offsets)) {
733                 sr_err("Failed to set offsets: %s.", libusb_error_name(ret));
734                 return SR_ERR;
735         }
736         sr_dbg("Sent CTRL_SETOFFSET.");
737
738         return SR_OK;
739 }
740
741 SR_PRIV int dso_enable_trigger(const struct sr_dev_inst *sdi)
742 {
743         struct sr_usb_dev_inst *usb;
744         int ret, tmp;
745         uint8_t cmdstring[2];
746
747         sr_dbg("Sending CMD_ENABLE_TRIGGER.");
748
749         usb = sdi->conn;
750
751         memset(cmdstring, 0, sizeof(cmdstring));
752         cmdstring[0] = CMD_ENABLE_TRIGGER;
753         cmdstring[1] = 0x00;
754
755         if (send_begin(sdi) != SR_OK)
756                 return SR_ERR;
757
758         if ((ret = libusb_bulk_transfer(usb->devhdl, DSO_EP_OUT,
759                         cmdstring, sizeof(cmdstring), &tmp, 100)) != 0) {
760                 sr_err("Failed to enable trigger: %s.", libusb_error_name(ret));
761                 return SR_ERR;
762         }
763
764         return SR_OK;
765 }
766
767 SR_PRIV int dso_force_trigger(const struct sr_dev_inst *sdi)
768 {
769         struct sr_usb_dev_inst *usb;
770         int ret, tmp;
771         uint8_t cmdstring[2];
772
773         sr_dbg("Sending CMD_FORCE_TRIGGER.");
774
775         usb = sdi->conn;
776
777         memset(cmdstring, 0, sizeof(cmdstring));
778         cmdstring[0] = CMD_FORCE_TRIGGER;
779         cmdstring[1] = 0x00;
780
781         if (send_begin(sdi) != SR_OK)
782                 return SR_ERR;
783
784         if ((ret = libusb_bulk_transfer(usb->devhdl, DSO_EP_OUT,
785                         cmdstring, sizeof(cmdstring), &tmp, 100)) != 0) {
786                 sr_err("Failed to force trigger: %s.", libusb_error_name(ret));
787                 return SR_ERR;
788         }
789
790         return SR_OK;
791 }
792
793 SR_PRIV int dso_init(const struct sr_dev_inst *sdi)
794 {
795         sr_dbg("Initializing DSO.");
796
797         if (get_channel_offsets(sdi) != SR_OK)
798                 return SR_ERR;
799
800         if (dso_set_trigger_samplerate(sdi) != SR_OK)
801                 return SR_ERR;
802
803         if (dso_set_filters(sdi) != SR_OK)
804                 return SR_ERR;
805
806         if (dso_set_voltage(sdi) != SR_OK)
807                 return SR_ERR;
808
809         if (dso_set_relays(sdi) != SR_OK)
810                 return SR_ERR;
811
812         if (dso_set_voffsets(sdi) != SR_OK)
813                 return SR_ERR;
814
815         if (dso_enable_trigger(sdi) != SR_OK)
816                 return SR_ERR;
817
818         return SR_OK;
819 }
820
821 SR_PRIV int dso_get_capturestate(const struct sr_dev_inst *sdi,
822                 uint8_t *capturestate, uint32_t *trigger_offset)
823 {
824         struct sr_usb_dev_inst *usb;
825         int ret, tmp, i;
826         unsigned int bitvalue, toff;
827         uint8_t cmdstring[2], inbuf[512];
828
829         sr_dbg("Sending CMD_GET_CAPTURESTATE.");
830
831         usb = sdi->conn;
832
833         cmdstring[0] = CMD_GET_CAPTURESTATE;
834         cmdstring[1] = 0;
835
836         if ((ret = send_bulkcmd(sdi, cmdstring, sizeof(cmdstring))) != SR_OK) {
837                 sr_dbg("Failed to send get_capturestate command: %s.",
838                        libusb_error_name(ret));
839                 return SR_ERR;
840         }
841
842         if ((ret = libusb_bulk_transfer(usb->devhdl, DSO_EP_IN,
843                         inbuf, 512, &tmp, 100)) != 0) {
844                 sr_dbg("Failed to get capturestate: %s.",
845                        libusb_error_name(ret));
846                 return SR_ERR;
847         }
848         *capturestate = inbuf[0];
849         toff = (inbuf[1] << 16) | (inbuf[3] << 8) | inbuf[2];
850
851         /*
852          * This conversion comes from the openhantek project.
853          * Each set bit in the 24-bit value inverts all bits with a lower
854          * value. No idea why the device reports the trigger point this way.
855          */
856         bitvalue = 1;
857         for (i = 0; i < 24; i++) {
858                 /* Each set bit inverts all bits with a lower value. */
859                 if (toff & bitvalue)
860                         toff ^= bitvalue - 1;
861                 bitvalue <<= 1;
862         }
863         *trigger_offset = toff;
864
865         return SR_OK;
866 }
867
868 SR_PRIV int dso_capture_start(const struct sr_dev_inst *sdi)
869 {
870         int ret;
871         uint8_t cmdstring[2];
872
873         sr_dbg("Sending CMD_CAPTURE_START.");
874
875         cmdstring[0] = CMD_CAPTURE_START;
876         cmdstring[1] = 0;
877
878         if ((ret = send_bulkcmd(sdi, cmdstring, sizeof(cmdstring))) != SR_OK) {
879                 sr_err("Failed to send capture_start command: %s.",
880                        libusb_error_name(ret));
881                 return SR_ERR;
882         }
883
884         return SR_OK;
885 }
886
887 SR_PRIV int dso_get_channeldata(const struct sr_dev_inst *sdi,
888                 libusb_transfer_cb_fn cb)
889 {
890         struct dev_context *devc;
891         struct sr_usb_dev_inst *usb;
892         struct libusb_transfer *transfer;
893         int num_transfers, ret, i;
894         uint8_t cmdstring[2];
895         unsigned char *buf;
896
897         sr_dbg("Sending CMD_GET_CHANNELDATA.");
898
899         devc = sdi->priv;
900         usb = sdi->conn;
901
902         cmdstring[0] = CMD_GET_CHANNELDATA;
903         cmdstring[1] = 0;
904
905         if ((ret = send_bulkcmd(sdi, cmdstring, sizeof(cmdstring))) != SR_OK) {
906                 sr_err("Failed to get channel data: %s.",
907                        libusb_error_name(ret));
908                 return SR_ERR;
909         }
910
911         /* TODO: DSO-2xxx only. */
912         num_transfers = devc->framesize *
913                         sizeof(unsigned short) / devc->epin_maxpacketsize;
914         sr_dbg("Queueing up %d transfers.", num_transfers);
915         for (i = 0; i < num_transfers; i++) {
916                 if (!(buf = g_try_malloc(devc->epin_maxpacketsize))) {
917                         sr_err("Failed to malloc USB endpoint buffer.");
918                         return SR_ERR_MALLOC;
919                 }
920                 transfer = libusb_alloc_transfer(0);
921                 libusb_fill_bulk_transfer(transfer, usb->devhdl, DSO_EP_IN, buf,
922                                 devc->epin_maxpacketsize, cb, (void *)sdi, 40);
923                 if ((ret = libusb_submit_transfer(transfer)) != 0) {
924                         sr_err("Failed to submit transfer: %s.",
925                                libusb_error_name(ret));
926                         /* TODO: Free them all. */
927                         libusb_free_transfer(transfer);
928                         g_free(buf);
929                         return SR_ERR;
930                 }
931         }
932
933         return SR_OK;
934 }