]> sigrok.org Git - libsigrok.git/blob - src/hardware/rigol-ds/protocol.c
rigol-ds: Initial patch for Rigol DS4000 support
[libsigrok.git] / src / hardware / rigol-ds / protocol.c
1 /*
2  * This file is part of the libsigrok project.
3  *
4  * Copyright (C) 2012 Martin Ling <martin-git@earth.li>
5  * Copyright (C) 2013 Bert Vermeulen <bert@biot.com>
6  * Copyright (C) 2013 Mathias Grimmberger <mgri@zaphod.sax.de>
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 <stdlib.h>
24 #include <stdarg.h>
25 #include <unistd.h>
26 #include <errno.h>
27 #include <string.h>
28 #include <math.h>
29 #include <ctype.h>
30 #include <time.h>
31 #include <glib.h>
32 #include <libsigrok/libsigrok.h>
33 #include "libsigrok-internal.h"
34 #include "scpi.h"
35 #include "protocol.h"
36
37 /*
38  * This is a unified protocol driver for the DS1000 and DS2000 series.
39  *
40  * DS1000 support tested with a Rigol DS1102D.
41  *
42  * DS2000 support tested with a Rigol DS2072 using firmware version 01.01.00.02.
43  *
44  * The Rigol DS2000 series scopes try to adhere to the IEEE 488.2 (I think)
45  * standard. If you want to read it - it costs real money...
46  *
47  * Every response from the scope has a linefeed appended because the
48  * standard says so. In principle this could be ignored because sending the
49  * next command clears the output queue of the scope. This driver tries to
50  * avoid doing that because it may cause an error being generated inside the
51  * scope and who knows what bugs the firmware has WRT this.
52  *
53  * Waveform data is transferred in a format called "arbitrary block program
54  * data" specified in IEEE 488.2. See Agilents programming manuals for their
55  * 2000/3000 series scopes for a nice description.
56  *
57  * Each data block from the scope has a header, e.g. "#900000001400".
58  * The '#' marks the start of a block.
59  * Next is one ASCII decimal digit between 1 and 9, this gives the number of
60  * ASCII decimal digits following.
61  * Last are the ASCII decimal digits giving the number of bytes (not
62  * samples!) in the block.
63  *
64  * After this header as many data bytes as indicated follow.
65  *
66  * Each data block has a trailing linefeed too.
67  */
68
69 static int parse_int(const char *str, int *ret)
70 {
71         char *e;
72         long tmp;
73
74         errno = 0;
75         tmp = strtol(str, &e, 10);
76         if (e == str || *e != '\0') {
77                 sr_dbg("Failed to parse integer: '%s'", str);
78                 return SR_ERR;
79         }
80         if (errno) {
81                 sr_dbg("Failed to parse integer: '%s', numerical overflow", str);
82                 return SR_ERR;
83         }
84         if (tmp > INT_MAX || tmp < INT_MIN) {
85                 sr_dbg("Failed to parse integer: '%s', value to large/small", str);
86                 return SR_ERR;
87         }
88
89         *ret = (int)tmp;
90         return SR_OK;
91 }
92
93 /* Set the next event to wait for in rigol_ds_receive */
94 static void rigol_ds_set_wait_event(struct dev_context *devc, enum wait_events event)
95 {
96         if (event == WAIT_STOP)
97                 devc->wait_status = 2;
98         else
99                 devc->wait_status = 1;
100         devc->wait_event = event;
101 }
102
103 /*
104  * Waiting for a event will return a timeout after 2 to 3 seconds in order
105  * to not block the application.
106  */
107 static int rigol_ds_event_wait(const struct sr_dev_inst *sdi, char status1, char status2)
108 {
109         char *buf;
110         struct dev_context *devc;
111         time_t start;
112
113         if (!(devc = sdi->priv))
114                 return SR_ERR;
115
116         start = time(NULL);
117
118         /*
119          * Trigger status may return:
120          * "TD" or "T'D" - triggered
121          * "AUTO"        - autotriggered
122          * "RUN"         - running
123          * "WAIT"        - waiting for trigger
124          * "STOP"        - stopped
125          */
126
127         if (devc->wait_status == 1) {
128                 do {
129                         if (time(NULL) - start >= 3) {
130                                 sr_dbg("Timeout waiting for trigger");
131                                 return SR_ERR_TIMEOUT;
132                         }
133
134                         if (sr_scpi_get_string(sdi->conn, ":TRIG:STAT?", &buf) != SR_OK)
135                                 return SR_ERR;
136                 } while (buf[0] == status1 || buf[0] == status2);
137
138                 devc->wait_status = 2;
139         }
140         if (devc->wait_status == 2) {
141                 do {
142                         if (time(NULL) - start >= 3) {
143                                 sr_dbg("Timeout waiting for trigger");
144                                 return SR_ERR_TIMEOUT;
145                         }
146
147                         if (sr_scpi_get_string(sdi->conn, ":TRIG:STAT?", &buf) != SR_OK)
148                                 return SR_ERR;
149                 } while (buf[0] != status1 && buf[0] != status2);
150
151                 rigol_ds_set_wait_event(devc, WAIT_NONE);
152         }
153
154         return SR_OK;
155 }
156
157 /*
158  * For live capture we need to wait for a new trigger event to ensure that
159  * sample data is not returned twice.
160  *
161  * Unfortunately this will never really work because for sufficiently fast
162  * timebases and trigger rates it just can't catch the status changes.
163  *
164  * What would be needed is a trigger event register with autoreset like the
165  * Agilents have. The Rigols don't seem to have anything like this.
166  *
167  * The workaround is to only wait for the trigger when the timebase is slow
168  * enough. Of course this means that for faster timebases sample data can be
169  * returned multiple times, this effect is mitigated somewhat by sleeping
170  * for about one sweep time in that case.
171  */
172 static int rigol_ds_trigger_wait(const struct sr_dev_inst *sdi)
173 {
174         struct dev_context *devc;
175         long s;
176
177         if (!(devc = sdi->priv))
178                 return SR_ERR;
179
180         /*
181          * If timebase < 50 msecs/DIV just sleep about one sweep time except
182          * for really fast sweeps.
183          */
184         if (devc->timebase < 0.0499) {
185                 if (devc->timebase > 0.99e-6) {
186                         /*
187                          * Timebase * num hor. divs * 85(%) * 1e6(usecs) / 100
188                          * -> 85 percent of sweep time
189                          */
190                         s = (devc->timebase * devc->model->series->num_horizontal_divs
191                              * 85e6) / 100L;
192                         sr_spew("Sleeping for %ld usecs instead of trigger-wait", s);
193                         g_usleep(s);
194                 }
195                 rigol_ds_set_wait_event(devc, WAIT_NONE);
196                 return SR_OK;
197         } else {
198                 return rigol_ds_event_wait(sdi, 'T', 'A');
199         }
200 }
201
202 /* Wait for scope to got to "Stop" in single shot mode */
203 static int rigol_ds_stop_wait(const struct sr_dev_inst *sdi)
204 {
205         return rigol_ds_event_wait(sdi, 'S', 'S');
206 }
207
208 /* Check that a single shot acquisition actually succeeded on the DS2000 */
209 static int rigol_ds_check_stop(const struct sr_dev_inst *sdi)
210 {
211         struct dev_context *devc;
212         struct sr_channel *ch;
213         int tmp;
214
215         if (!(devc = sdi->priv))
216                 return SR_ERR;
217
218         ch = devc->channel_entry->data;
219
220         if (devc->model->series->protocol != PROTOCOL_V3)
221                 return SR_OK;
222
223         if (ch->type == SR_CHANNEL_LOGIC) {
224                 if (rigol_ds_config_set(sdi, ":WAV:SOUR LA") != SR_OK)
225                         return SR_ERR;
226         } else {
227                 if (rigol_ds_config_set(sdi, ":WAV:SOUR CHAN%d",
228                                 ch->index + 1) != SR_OK)
229                         return SR_ERR;
230         }
231         /* Check that the number of samples will be accepted */
232         if (rigol_ds_config_set(sdi, ":WAV:POIN %d",
233                         ch->type == SR_CHANNEL_LOGIC ?
234                                 devc->digital_frame_size :
235                                 devc->analog_frame_size) != SR_OK)
236                 return SR_ERR;
237         if (sr_scpi_get_int(sdi->conn, "*ESR?", &tmp) != SR_OK)
238                 return SR_ERR;
239         /*
240          * If we get an "Execution error" the scope went from "Single" to
241          * "Stop" without actually triggering. There is no waveform
242          * displayed and trying to download one will fail - the scope thinks
243          * it has 1400 samples (like display memory) and the driver thinks
244          * it has a different number of samples.
245          *
246          * In that case just try to capture something again. Might still
247          * fail in interesting ways.
248          *
249          * Ain't firmware fun?
250          */
251         if (tmp & 0x10) {
252                 sr_warn("Single shot acquisition failed, retrying...");
253                 /* Sleep a bit, otherwise the single shot will often fail */
254                 g_usleep(500 * 1000);
255                 rigol_ds_config_set(sdi, ":SING");
256                 rigol_ds_set_wait_event(devc, WAIT_STOP);
257                 return SR_ERR;
258         }
259
260         return SR_OK;
261 }
262
263 /* Wait for enough data becoming available in scope output buffer */
264 static int rigol_ds_block_wait(const struct sr_dev_inst *sdi)
265 {
266         char *buf;
267         struct dev_context *devc;
268         time_t start;
269         int len;
270
271         if (!(devc = sdi->priv))
272                 return SR_ERR;
273
274         if (devc->model->series->protocol == PROTOCOL_V3) {
275
276                 start = time(NULL);
277
278                 do {
279                         if (time(NULL) - start >= 3) {
280                                 sr_dbg("Timeout waiting for data block");
281                                 return SR_ERR_TIMEOUT;
282                         }
283
284                         /*
285                          * The scope copies data really slowly from sample
286                          * memory to its output buffer, so try not to bother
287                          * it too much with SCPI requests but don't wait too
288                          * long for short sample frame sizes.
289                          */
290                         g_usleep(devc->analog_frame_size < (15 * 1000) ? (100 * 1000) : (1000 * 1000));
291
292                         /* "READ,nnnn" (still working) or "IDLE,nnnn" (finished) */
293                         if (sr_scpi_get_string(sdi->conn, ":WAV:STAT?", &buf) != SR_OK)
294                                 return SR_ERR;
295
296                         if (parse_int(buf + 5, &len) != SR_OK)
297                                 return SR_ERR;
298                 } while (buf[0] == 'R' && len < (1000 * 1000));
299         }
300
301         rigol_ds_set_wait_event(devc, WAIT_NONE);
302
303         return SR_OK;
304 }
305
306 /* Send a configuration setting. */
307 SR_PRIV int rigol_ds_config_set(const struct sr_dev_inst *sdi, const char *format, ...)
308 {
309         struct dev_context *devc = sdi->priv;
310         va_list args;
311         int ret;
312
313         va_start(args, format);
314         ret = sr_scpi_send_variadic(sdi->conn, format, args);
315         va_end(args);
316
317         if (ret != SR_OK)
318                 return SR_ERR;
319
320         if (devc->model->series->protocol == PROTOCOL_V2) {
321                 /* The DS1000 series needs this stupid delay, *OPC? doesn't work. */
322                 sr_spew("delay %dms", 100);
323                 g_usleep(100 * 1000);
324                 return SR_OK;
325         } else {
326                 return sr_scpi_get_opc(sdi->conn);
327         }
328 }
329
330 /* Start capturing a new frameset */
331 SR_PRIV int rigol_ds_capture_start(const struct sr_dev_inst *sdi)
332 {
333         struct dev_context *devc;
334         gchar *trig_mode;
335         unsigned int num_channels, i, j;
336
337         if (!(devc = sdi->priv))
338                 return SR_ERR;
339
340         sr_dbg("Starting data capture for frameset %" PRIu64 " of %" PRIu64,
341                devc->num_frames + 1, devc->limit_frames);
342
343         switch (devc->model->series->protocol) {
344         case PROTOCOL_V1:
345                 rigol_ds_set_wait_event(devc, WAIT_TRIGGER);
346                 break;
347         case PROTOCOL_V2:
348                 if (devc->data_source == DATA_SOURCE_LIVE) {
349                         if (rigol_ds_config_set(sdi, ":WAV:POIN:MODE NORMAL") != SR_OK)
350                                 return SR_ERR;
351                         rigol_ds_set_wait_event(devc, WAIT_TRIGGER);
352                 } else {
353                         if (rigol_ds_config_set(sdi, ":STOP") != SR_OK)
354                                 return SR_ERR;
355                         if (rigol_ds_config_set(sdi, ":WAV:POIN:MODE RAW") != SR_OK)
356                                 return SR_ERR;
357                         if (sr_scpi_get_string(sdi->conn, ":TRIG:MODE?", &trig_mode) != SR_OK)
358                                 return SR_ERR;
359                         if (rigol_ds_config_set(sdi, ":TRIG:%s:SWE SING", trig_mode) != SR_OK)
360                                 return SR_ERR;
361                         if (rigol_ds_config_set(sdi, ":RUN") != SR_OK)
362                                 return SR_ERR;
363                         rigol_ds_set_wait_event(devc, WAIT_STOP);
364                 }
365                 break;
366         case PROTOCOL_V3:
367         case PROTOCOL_V4:
368                 if (rigol_ds_config_set(sdi, ":WAV:FORM BYTE") != SR_OK)
369                         return SR_ERR;
370                 if (devc->data_source == DATA_SOURCE_LIVE) {
371                         if (rigol_ds_config_set(sdi, ":WAV:MODE NORM") != SR_OK)
372                                 return SR_ERR;
373                         devc->analog_frame_size = devc->model->series->live_samples;
374                         devc->digital_frame_size = devc->model->series->live_samples;
375                         rigol_ds_set_wait_event(devc, WAIT_TRIGGER);
376                 } else {
377                         if (devc->model->series->protocol == PROTOCOL_V3) {
378                                 if (rigol_ds_config_set(sdi, ":WAV:MODE RAW") != SR_OK)
379                                         return SR_ERR;
380                         } else if (devc->model->series->protocol == PROTOCOL_V4) {
381                                 num_channels = 0;
382
383                                 /* Channels 3 and 4 are multiplexed with D0-7 and D8-15 */
384                                 for (i = 0; i < devc->model->analog_channels; i++) {
385                                         if (devc->analog_channels[i]) {
386                                                 num_channels++;
387                                         } else if (i >= 2 && devc->model->has_digital) {
388                                                 for (j = 0; j < 8; j++) {
389                                                         if (devc->digital_channels[8 * (i - 2) + j]) {
390                                                                 num_channels++;
391                                                                 break;
392                                                         }
393                                                 }
394                                         }
395                                 }
396
397                                 devc->analog_frame_size = devc->digital_frame_size =
398                                         num_channels == 1 ?
399                                                 devc->model->series->buffer_samples :
400                                                         num_channels == 2 ?
401                                                                 devc->model->series->buffer_samples / 2 :
402                                                                 devc->model->series->buffer_samples / 4;
403                         }
404
405                         if (rigol_ds_config_set(sdi, ":SING") != SR_OK)
406                                 return SR_ERR;
407                         rigol_ds_set_wait_event(devc, WAIT_STOP);
408                 }
409                 break;
410         }
411
412         return SR_OK;
413 }
414
415 /* Start reading data from the current channel */
416 SR_PRIV int rigol_ds_channel_start(const struct sr_dev_inst *sdi)
417 {
418         struct dev_context *devc;
419         struct sr_channel *ch;
420
421         if (!(devc = sdi->priv))
422                 return SR_ERR;
423
424         ch = devc->channel_entry->data;
425
426         sr_dbg("Starting reading data from channel %d", ch->index + 1);
427
428         switch (devc->model->series->protocol) {
429         case PROTOCOL_V1:
430         case PROTOCOL_V2:
431                 if (ch->type == SR_CHANNEL_LOGIC) {
432                         if (sr_scpi_send(sdi->conn, ":WAV:DATA? DIG") != SR_OK)
433                                 return SR_ERR;
434                 } else {
435                         if (sr_scpi_send(sdi->conn, ":WAV:DATA? CHAN%d",
436                                         ch->index + 1) != SR_OK)
437                                 return SR_ERR;
438                 }
439                 rigol_ds_set_wait_event(devc, WAIT_NONE);
440                 break;
441         case PROTOCOL_V3:
442                 if (ch->type == SR_CHANNEL_LOGIC) {
443                         if (rigol_ds_config_set(sdi, ":WAV:SOUR LA") != SR_OK)
444                                 return SR_ERR;
445                 } else {
446                         if (rigol_ds_config_set(sdi, ":WAV:SOUR CHAN%d",
447                                         ch->index + 1) != SR_OK)
448                                 return SR_ERR;
449                 }
450                 if (devc->data_source != DATA_SOURCE_LIVE) {
451                         if (rigol_ds_config_set(sdi, ":WAV:RES") != SR_OK)
452                                 return SR_ERR;
453                         if (rigol_ds_config_set(sdi, ":WAV:BEG") != SR_OK)
454                                 return SR_ERR;
455                 }
456                 break;
457         case PROTOCOL_V4:
458                 if (ch->type == SR_CHANNEL_ANALOG) {
459                         if (rigol_ds_config_set(sdi, ":WAV:SOUR CHAN%d",
460                                         ch->index + 1) != SR_OK)
461                                 return SR_ERR;
462                 } else {
463                         if (rigol_ds_config_set(sdi, ":WAV:SOUR D%d",
464                                         ch->index) != SR_OK)
465                                 return SR_ERR;
466                 }
467
468                 if (rigol_ds_config_set(sdi,
469                                         devc->data_source == DATA_SOURCE_LIVE ?
470                                                 ":WAV:MODE NORM" :":WAV:MODE RAW") != SR_OK)
471                         return SR_ERR;
472                 break;
473         }
474
475         if (devc->model->series->protocol >= PROTOCOL_V3 &&
476                         ch->type == SR_CHANNEL_ANALOG) {
477                 /* Vertical increment. */
478                 if (sr_scpi_get_float(sdi->conn, ":WAV:YINC?",
479                                 &devc->vert_inc[ch->index]) != SR_OK)
480                         /* Vertical origin. */
481                         if (sr_scpi_get_float(sdi->conn, ":WAV:YOR?",
482                                 &devc->vert_origin[ch->index]) != SR_OK)
483                                 return SR_ERR;
484                 /* Vertical reference. */
485                 if (sr_scpi_get_int(sdi->conn, ":WAV:YREF?",
486                                 &devc->vert_reference[ch->index]) != SR_OK)
487                         return SR_ERR;
488         } else if (ch->type == SR_CHANNEL_ANALOG) {
489                 devc->vert_inc[ch->index] = devc->vdiv[ch->index] / 25.6;
490         }
491
492         rigol_ds_set_wait_event(devc, WAIT_BLOCK);
493
494         devc->num_channel_bytes = 0;
495         devc->num_header_bytes = 0;
496         devc->num_block_bytes = 0;
497
498         return SR_OK;
499 }
500
501 /* Read the header of a data block */
502 static int rigol_ds_read_header(struct sr_dev_inst *sdi)
503 {
504         struct sr_scpi_dev_inst *scpi = sdi->conn;
505         struct dev_context *devc = sdi->priv;
506         char *buf = (char *) devc->buffer;
507         size_t header_length;
508         int ret;
509
510         /* Try to read the hashsign and length digit. */
511         if (devc->num_header_bytes < 2) {
512                 ret = sr_scpi_read_data(scpi, buf + devc->num_header_bytes,
513                                 2 - devc->num_header_bytes);
514                 if (ret < 0) {
515                         sr_err("Read error while reading data header.");
516                         return SR_ERR;
517                 }
518                 devc->num_header_bytes += ret;
519         }
520
521         if (devc->num_header_bytes < 2)
522                 return 0;
523
524         if (buf[0] != '#' || !isdigit(buf[1]) || buf[1] == '0') {
525                 sr_err("Received invalid data block header '%c%c'.", buf[0], buf[1]);
526                 return SR_ERR;
527         }
528
529         header_length = 2 + buf[1] - '0';
530
531         /* Try to read the length. */
532         if (devc->num_header_bytes < header_length) {
533                 ret = sr_scpi_read_data(scpi, buf + devc->num_header_bytes,
534                                 header_length - devc->num_header_bytes);
535                 if (ret < 0) {
536                         sr_err("Read error while reading data header.");
537                         return SR_ERR;
538                 }
539                 devc->num_header_bytes += ret;
540         }
541
542         if (devc->num_header_bytes < header_length)
543                 return 0;
544
545         /* Read the data length. */
546         buf[header_length] = '\0';
547
548         if (parse_int(buf + 2, &ret) != SR_OK) {
549                 sr_err("Received invalid data block length '%s'.", buf + 2);
550                 return -1;
551         }
552
553         sr_dbg("Received data block header: '%s' -> block length %d", buf, ret);
554
555         return ret;
556 }
557
558 SR_PRIV int rigol_ds_receive(int fd, int revents, void *cb_data)
559 {
560         struct sr_dev_inst *sdi;
561         struct sr_scpi_dev_inst *scpi;
562         struct dev_context *devc;
563         struct sr_datafeed_packet packet;
564         struct sr_datafeed_analog analog;
565         struct sr_analog_encoding encoding;
566         struct sr_analog_meaning meaning;
567         struct sr_analog_spec spec;
568         struct sr_datafeed_logic logic;
569         double vdiv, offset, origin;
570         int len, i, vref;
571         struct sr_channel *ch;
572         gsize expected_data_bytes;
573
574         (void)fd;
575
576         if (!(sdi = cb_data))
577                 return TRUE;
578
579         if (!(devc = sdi->priv))
580                 return TRUE;
581
582         scpi = sdi->conn;
583
584         if (!(revents == G_IO_IN || revents == 0))
585                 return TRUE;
586
587         switch (devc->wait_event) {
588         case WAIT_NONE:
589                 break;
590         case WAIT_TRIGGER:
591                 if (rigol_ds_trigger_wait(sdi) != SR_OK)
592                         return TRUE;
593                 if (rigol_ds_channel_start(sdi) != SR_OK)
594                         return TRUE;
595                 return TRUE;
596         case WAIT_BLOCK:
597                 if (rigol_ds_block_wait(sdi) != SR_OK)
598                         return TRUE;
599                 break;
600         case WAIT_STOP:
601                 if (rigol_ds_stop_wait(sdi) != SR_OK)
602                         return TRUE;
603                 if (rigol_ds_check_stop(sdi) != SR_OK)
604                         return TRUE;
605                 if (rigol_ds_channel_start(sdi) != SR_OK)
606                         return TRUE;
607                 return TRUE;
608         default:
609                 sr_err("BUG: Unknown event target encountered");
610                 break;
611         }
612
613         ch = devc->channel_entry->data;
614
615         expected_data_bytes = ch->type == SR_CHANNEL_ANALOG ?
616                         devc->analog_frame_size : devc->digital_frame_size;
617
618         if (devc->num_block_bytes == 0) {
619                 if (devc->model->series->protocol >= PROTOCOL_V4) {
620                         if (rigol_ds_config_set(sdi, ":WAV:START %d",
621                                         devc->num_channel_bytes + 1) != SR_OK)
622                                 return TRUE;
623                         if (rigol_ds_config_set(sdi, ":WAV:STOP %d",
624                                         MIN(devc->num_channel_bytes + ACQ_BLOCK_SIZE,
625                                                 devc->analog_frame_size)) != SR_OK)
626                                 return TRUE;
627                 }
628
629                 if (devc->model->series->protocol >= PROTOCOL_V3)
630                         if (sr_scpi_send(sdi->conn, ":WAV:DATA?") != SR_OK)
631                                 return TRUE;
632
633                 if (sr_scpi_read_begin(scpi) != SR_OK)
634                         return TRUE;
635
636                 if (devc->format == FORMAT_IEEE488_2) {
637                         sr_dbg("New block header expected");
638                         len = rigol_ds_read_header(sdi);
639                         if (len == 0)
640                                 /* Still reading the header. */
641                                 return TRUE;
642                         if (len == -1) {
643                                 sr_err("Error while reading block header, aborting capture.");
644                                 packet.type = SR_DF_FRAME_END;
645                                 sr_session_send(sdi, &packet);
646                                 sr_dev_acquisition_stop(sdi);
647                                 return TRUE;
648                         }
649                         /* At slow timebases in live capture the DS2072
650                          * sometimes returns "short" data blocks, with
651                          * apparently no way to get the rest of the data.
652                          * Discard these, the complete data block will
653                          * appear eventually.
654                          */
655                         if (devc->data_source == DATA_SOURCE_LIVE
656                                         && (unsigned)len < expected_data_bytes) {
657                                 sr_dbg("Discarding short data block");
658                                 sr_scpi_read_data(scpi, (char *)devc->buffer, len + 1);
659                                 return TRUE;
660                         }
661                         devc->num_block_bytes = len;
662                 } else {
663                         devc->num_block_bytes = expected_data_bytes;
664                 }
665                 devc->num_block_read = 0;
666         }
667
668         len = devc->num_block_bytes - devc->num_block_read;
669         if (len > ACQ_BUFFER_SIZE)
670                 len = ACQ_BUFFER_SIZE;
671         sr_dbg("Requesting read of %d bytes", len);
672
673         len = sr_scpi_read_data(scpi, (char *)devc->buffer, len);
674
675         if (len == -1) {
676                 sr_err("Error while reading block data, aborting capture.");
677                 packet.type = SR_DF_FRAME_END;
678                 sr_session_send(sdi, &packet);
679                 sr_dev_acquisition_stop(sdi);
680                 return TRUE;
681         }
682
683         sr_dbg("Received %d bytes.", len);
684
685         devc->num_block_read += len;
686
687         if (ch->type == SR_CHANNEL_ANALOG) {
688                 vref = devc->vert_reference[ch->index];
689                 vdiv = devc->vert_inc[ch->index];
690                 origin = devc->vert_origin[ch->index];
691                 offset = devc->vert_offset[ch->index];
692                 if (devc->model->series->protocol >= PROTOCOL_V3)
693                         for (i = 0; i < len; i++)
694                                 devc->data[i] = ((int)devc->buffer[i] - vref - origin) * vdiv;
695                 else
696                         for (i = 0; i < len; i++)
697                                 devc->data[i] = (128 - devc->buffer[i]) * vdiv - offset;
698                 float vdivlog = log10f(vdiv);
699                 int digits = -(int)vdivlog + (vdivlog < 0.0);
700                 sr_analog_init(&analog, &encoding, &meaning, &spec, digits);
701                 analog.meaning->channels = g_slist_append(NULL, ch);
702                 analog.num_samples = len;
703                 analog.data = devc->data;
704                 analog.meaning->mq = SR_MQ_VOLTAGE;
705                 analog.meaning->unit = SR_UNIT_VOLT;
706                 analog.meaning->mqflags = 0;
707                 packet.type = SR_DF_ANALOG;
708                 packet.payload = &analog;
709                 sr_session_send(sdi, &packet);
710                 g_slist_free(analog.meaning->channels);
711         } else {
712                 logic.length = len;
713                 // TODO: For the MSO1000Z series, we need a way to express that
714                 // this data is in fact just for a single channel, with the valid
715                 // data for that channel in the LSB of each byte.
716                 logic.unitsize = devc->model->series->protocol == PROTOCOL_V4 ? 1 : 2;
717                 logic.data = devc->buffer;
718                 packet.type = SR_DF_LOGIC;
719                 packet.payload = &logic;
720                 sr_session_send(sdi, &packet);
721         }
722
723         if (devc->num_block_read == devc->num_block_bytes) {
724                 sr_dbg("Block has been completed");
725                 if (devc->model->series->protocol >= PROTOCOL_V3) {
726                         /* Discard the terminating linefeed */
727                         sr_scpi_read_data(scpi, (char *)devc->buffer, 1);
728                 }
729                 if (devc->format == FORMAT_IEEE488_2) {
730                         /* Prepare for possible next block */
731                         devc->num_header_bytes = 0;
732                         devc->num_block_bytes = 0;
733                         if (devc->data_source != DATA_SOURCE_LIVE)
734                                 rigol_ds_set_wait_event(devc, WAIT_BLOCK);
735                 }
736                 /* End acquisition when data for all channels is acquired. */
737                 if (!sr_scpi_read_complete(scpi) && !devc->channel_entry->next) {
738                         sr_err("Read should have been completed");
739                         packet.type = SR_DF_FRAME_END;
740                         sr_session_send(sdi, &packet);
741                         sr_dev_acquisition_stop(sdi);
742                         return TRUE;
743                 }
744                 devc->num_block_read = 0;
745         } else {
746                 sr_dbg("%" PRIu64 " of %" PRIu64 " block bytes read",
747                         devc->num_block_read, devc->num_block_bytes);
748         }
749
750         devc->num_channel_bytes += len;
751
752         if (devc->num_channel_bytes < expected_data_bytes)
753                 /* Don't have the full data for this channel yet, re-run. */
754                 return TRUE;
755
756         /* End of data for this channel. */
757         if (devc->model->series->protocol == PROTOCOL_V3) {
758                 /* Signal end of data download to scope */
759                 if (devc->data_source != DATA_SOURCE_LIVE)
760                         /*
761                          * This causes a query error, without it switching
762                          * to the next channel causes an error. Fun with
763                          * firmware...
764                          */
765                         rigol_ds_config_set(sdi, ":WAV:END");
766         }
767
768         if (devc->channel_entry->next) {
769                 /* We got the frame for this channel, now get the next channel. */
770                 devc->channel_entry = devc->channel_entry->next;
771                 rigol_ds_channel_start(sdi);
772         } else {
773                 /* Done with this frame. */
774                 packet.type = SR_DF_FRAME_END;
775                 sr_session_send(sdi, &packet);
776
777                 if (++devc->num_frames == devc->limit_frames) {
778                         /* Last frame, stop capture. */
779                         sr_dev_acquisition_stop(sdi);
780                 } else {
781                         /* Get the next frame, starting with the first channel. */
782                         devc->channel_entry = devc->enabled_channels;
783
784                         rigol_ds_capture_start(sdi);
785
786                         /* Start of next frame. */
787                         packet.type = SR_DF_FRAME_BEGIN;
788                         sr_session_send(sdi, &packet);
789                 }
790         }
791
792         return TRUE;
793 }
794
795 SR_PRIV int rigol_ds_get_dev_cfg(const struct sr_dev_inst *sdi)
796 {
797         struct dev_context *devc;
798         struct sr_channel *ch;
799         char *cmd;
800         unsigned int i;
801         int res;
802
803         devc = sdi->priv;
804
805         /* Analog channel state. */
806         for (i = 0; i < devc->model->analog_channels; i++) {
807                 cmd = g_strdup_printf(":CHAN%d:DISP?", i + 1);
808                 res = sr_scpi_get_bool(sdi->conn, cmd, &devc->analog_channels[i]);
809                 g_free(cmd);
810                 if (res != SR_OK)
811                         return SR_ERR;
812                 ch = g_slist_nth_data(sdi->channels, i);
813                 ch->enabled = devc->analog_channels[i];
814         }
815         sr_dbg("Current analog channel state:");
816         for (i = 0; i < devc->model->analog_channels; i++)
817                 sr_dbg("CH%d %s", i + 1, devc->analog_channels[i] ? "on" : "off");
818
819         /* Digital channel state. */
820         if (devc->model->has_digital) {
821                 if (sr_scpi_get_bool(sdi->conn,
822                                 devc->model->series->protocol >= PROTOCOL_V3 ?
823                                         ":LA:STAT?" : ":LA:DISP?",
824                                 &devc->la_enabled) != SR_OK)
825                         return SR_ERR;
826                 sr_dbg("Logic analyzer %s, current digital channel state:",
827                                 devc->la_enabled ? "enabled" : "disabled");
828                 for (i = 0; i < ARRAY_SIZE(devc->digital_channels); i++) {
829                         cmd = g_strdup_printf(
830                                 devc->model->series->protocol >= PROTOCOL_V3 ?
831                                         ":LA:DIG%d:DISP?" : ":DIG%d:TURN?", i);
832                         res = sr_scpi_get_bool(sdi->conn, cmd, &devc->digital_channels[i]);
833                         g_free(cmd);
834                         if (res != SR_OK)
835                                 return SR_ERR;
836                         ch = g_slist_nth_data(sdi->channels, i + devc->model->analog_channels);
837                         ch->enabled = devc->digital_channels[i];
838                         sr_dbg("D%d: %s", i, devc->digital_channels[i] ? "on" : "off");
839                 }
840         }
841
842         /* Timebase. */
843         if (sr_scpi_get_float(sdi->conn, ":TIM:SCAL?", &devc->timebase) != SR_OK)
844                 return SR_ERR;
845         sr_dbg("Current timebase %g", devc->timebase);
846
847         /* Probe attenuation. */
848         for (i = 0; i < devc->model->analog_channels; i++) {
849                 cmd = g_strdup_printf(":CHAN%d:PROB?", i + 1);
850                 res = sr_scpi_get_float(sdi->conn, cmd, &devc->attenuation[i]);
851                 g_free(cmd);
852                 if (res != SR_OK)
853                         return SR_ERR;
854         }
855         sr_dbg("Current probe attenuation:");
856         for (i = 0; i < devc->model->analog_channels; i++)
857                 sr_dbg("CH%d %g", i + 1, devc->attenuation[i]);
858
859         /* Vertical gain and offset. */
860         if (rigol_ds_get_dev_cfg_vertical(sdi) != SR_OK)
861                 return SR_ERR;
862
863         /* Coupling. */
864         for (i = 0; i < devc->model->analog_channels; i++) {
865                 cmd = g_strdup_printf(":CHAN%d:COUP?", i + 1);
866                 res = sr_scpi_get_string(sdi->conn, cmd, &devc->coupling[i]);
867                 g_free(cmd);
868                 if (res != SR_OK)
869                         return SR_ERR;
870         }
871         sr_dbg("Current coupling:");
872         for (i = 0; i < devc->model->analog_channels; i++)
873                 sr_dbg("CH%d %s", i + 1, devc->coupling[i]);
874
875         /* Trigger source. */
876         if (sr_scpi_get_string(sdi->conn, ":TRIG:EDGE:SOUR?", &devc->trigger_source) != SR_OK)
877                 return SR_ERR;
878         sr_dbg("Current trigger source %s", devc->trigger_source);
879
880         /* Horizontal trigger position. */
881         if (sr_scpi_get_float(sdi->conn, ":TIM:OFFS?", &devc->horiz_triggerpos) != SR_OK)
882                 return SR_ERR;
883         sr_dbg("Current horizontal trigger position %g", devc->horiz_triggerpos);
884
885         /* Trigger slope. */
886         if (sr_scpi_get_string(sdi->conn, ":TRIG:EDGE:SLOP?", &devc->trigger_slope) != SR_OK)
887                 return SR_ERR;
888         sr_dbg("Current trigger slope %s", devc->trigger_slope);
889
890         /* Trigger level. */
891         if (sr_scpi_get_float(sdi->conn, ":TRIG:EDGE:LEV?", &devc->trigger_level) != SR_OK)
892                 return SR_ERR;
893         sr_dbg("Current trigger level %g", devc->trigger_level);
894
895         return SR_OK;
896 }
897
898 SR_PRIV int rigol_ds_get_dev_cfg_vertical(const struct sr_dev_inst *sdi)
899 {
900         struct dev_context *devc;
901         char *cmd;
902         unsigned int i;
903         int res;
904
905         devc = sdi->priv;
906
907         /* Vertical gain. */
908         for (i = 0; i < devc->model->analog_channels; i++) {
909                 cmd = g_strdup_printf(":CHAN%d:SCAL?", i + 1);
910                 res = sr_scpi_get_float(sdi->conn, cmd, &devc->vdiv[i]);
911                 g_free(cmd);
912                 if (res != SR_OK)
913                         return SR_ERR;
914         }
915         sr_dbg("Current vertical gain:");
916         for (i = 0; i < devc->model->analog_channels; i++)
917                 sr_dbg("CH%d %g", i + 1, devc->vdiv[i]);
918
919         /* Vertical offset. */
920         for (i = 0; i < devc->model->analog_channels; i++) {
921                 cmd = g_strdup_printf(":CHAN%d:OFFS?", i + 1);
922                 res = sr_scpi_get_float(sdi->conn, cmd, &devc->vert_offset[i]);
923                 g_free(cmd);
924                 if (res != SR_OK)
925                         return SR_ERR;
926         }
927         sr_dbg("Current vertical offset:");
928         for (i = 0; i < devc->model->analog_channels; i++)
929                 sr_dbg("CH%d %g", i + 1, devc->vert_offset[i]);
930
931         return SR_OK;
932 }