]> sigrok.org Git - libsigrok.git/blob - src/hardware/rigol-ds/protocol.c
rigol-ds: Add support for reading segmented data for protocol v4
[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         int buffer_samples;
337
338         if (!(devc = sdi->priv))
339                 return SR_ERR;
340
341         uint64_t limit_frames = devc->limit_frames;
342         if (devc->num_frames_segmented != 0 && devc->num_frames_segmented < limit_frames)
343                 limit_frames = devc->num_frames_segmented;
344         if (limit_frames == 0)
345                 sr_dbg("Starting data capture for frameset %" PRIu64,
346                        devc->num_frames + 1);
347         else
348                 sr_dbg("Starting data capture for frameset %" PRIu64 " of %"
349                        PRIu64, devc->num_frames + 1, limit_frames);
350
351         switch (devc->model->series->protocol) {
352         case PROTOCOL_V1:
353                 rigol_ds_set_wait_event(devc, WAIT_TRIGGER);
354                 break;
355         case PROTOCOL_V2:
356                 if (devc->data_source == DATA_SOURCE_LIVE) {
357                         if (rigol_ds_config_set(sdi, ":WAV:POIN:MODE NORMAL") != SR_OK)
358                                 return SR_ERR;
359                         rigol_ds_set_wait_event(devc, WAIT_TRIGGER);
360                 } else {
361                         if (rigol_ds_config_set(sdi, ":STOP") != SR_OK)
362                                 return SR_ERR;
363                         if (rigol_ds_config_set(sdi, ":WAV:POIN:MODE RAW") != SR_OK)
364                                 return SR_ERR;
365                         if (sr_scpi_get_string(sdi->conn, ":TRIG:MODE?", &trig_mode) != SR_OK)
366                                 return SR_ERR;
367                         if (rigol_ds_config_set(sdi, ":TRIG:%s:SWE SING", trig_mode) != SR_OK)
368                                 return SR_ERR;
369                         if (rigol_ds_config_set(sdi, ":RUN") != SR_OK)
370                                 return SR_ERR;
371                         rigol_ds_set_wait_event(devc, WAIT_STOP);
372                 }
373                 break;
374         case PROTOCOL_V3:
375         case PROTOCOL_V4:
376         case PROTOCOL_V5:
377                 if (rigol_ds_config_set(sdi, ":WAV:FORM BYTE") != SR_OK)
378                         return SR_ERR;
379                 if (devc->data_source == DATA_SOURCE_LIVE) {
380                         if (rigol_ds_config_set(sdi, ":WAV:MODE NORM") != SR_OK)
381                                 return SR_ERR;
382                         devc->analog_frame_size = devc->model->series->live_samples;
383                         devc->digital_frame_size = devc->model->series->live_samples;
384                         rigol_ds_set_wait_event(devc, WAIT_TRIGGER);
385                 } else {
386                         if (devc->model->series->protocol == PROTOCOL_V3) {
387                                 if (rigol_ds_config_set(sdi, ":WAV:MODE RAW") != SR_OK)
388                                         return SR_ERR;
389                         } else if (devc->model->series->protocol >= PROTOCOL_V4) {
390                                 num_channels = 0;
391
392                                 /* Channels 3 and 4 are multiplexed with D0-7 and D8-15 */
393                                 for (i = 0; i < devc->model->analog_channels; i++) {
394                                         if (devc->analog_channels[i]) {
395                                                 num_channels++;
396                                         } else if (i >= 2 && devc->model->has_digital) {
397                                                 for (j = 0; j < 8; j++) {
398                                                         if (devc->digital_channels[8 * (i - 2) + j]) {
399                                                                 num_channels++;
400                                                                 break;
401                                                         }
402                                                 }
403                                         }
404                                 }
405
406                                 buffer_samples = devc->model->series->buffer_samples;
407                                 if (buffer_samples == 0)
408                                 {
409                                         /* The DS4000 series does not have a fixed memory depth, it
410                                          * can be chosen from the menu and also varies with number
411                                          * of active channels. Retrieve the actual number with the
412                                          * ACQ:MDEP command. */
413                                         sr_scpi_get_int(sdi->conn, "ACQ:MDEP?", &buffer_samples);
414                                         devc->analog_frame_size = devc->digital_frame_size =
415                                                         buffer_samples;
416                                 }
417                                 else
418                                 {
419                                         /* The DS1000Z series has a fixed memory depth which we
420                                          * need to divide correctly according to the number of
421                                          * active channels. */
422                                         devc->analog_frame_size = devc->digital_frame_size =
423                                                 num_channels == 1 ?
424                                                         buffer_samples :
425                                                                 num_channels == 2 ?
426                                                                         buffer_samples / 2 :
427                                                                         buffer_samples / 4;
428                                 }
429                         }
430
431                         if (rigol_ds_config_set(sdi, ":SING") != SR_OK)
432                                 return SR_ERR;
433                         rigol_ds_set_wait_event(devc, WAIT_STOP);
434                         if (devc->data_source == DATA_SOURCE_SEGMENTED)
435                                 if (rigol_ds_config_set(sdi, "FUNC:WREP:FCUR %d", devc->num_frames + 1) != SR_OK)
436                                         return SR_ERR;
437                 }
438                 break;
439         }
440
441         return SR_OK;
442 }
443
444 /* Start reading data from the current channel */
445 SR_PRIV int rigol_ds_channel_start(const struct sr_dev_inst *sdi)
446 {
447         struct dev_context *devc;
448         struct sr_channel *ch;
449
450         if (!(devc = sdi->priv))
451                 return SR_ERR;
452
453         ch = devc->channel_entry->data;
454
455         sr_dbg("Starting reading data from channel %d", ch->index + 1);
456
457         switch (devc->model->series->protocol) {
458         case PROTOCOL_V1:
459         case PROTOCOL_V2:
460                 if (ch->type == SR_CHANNEL_LOGIC) {
461                         if (sr_scpi_send(sdi->conn, ":WAV:DATA? DIG") != SR_OK)
462                                 return SR_ERR;
463                 } else {
464                         if (sr_scpi_send(sdi->conn, ":WAV:DATA? CHAN%d",
465                                         ch->index + 1) != SR_OK)
466                                 return SR_ERR;
467                 }
468                 rigol_ds_set_wait_event(devc, WAIT_NONE);
469                 break;
470         case PROTOCOL_V3:
471                 if (ch->type == SR_CHANNEL_LOGIC) {
472                         if (rigol_ds_config_set(sdi, ":WAV:SOUR LA") != SR_OK)
473                                 return SR_ERR;
474                 } else {
475                         if (rigol_ds_config_set(sdi, ":WAV:SOUR CHAN%d",
476                                         ch->index + 1) != SR_OK)
477                                 return SR_ERR;
478                 }
479                 if (devc->data_source != DATA_SOURCE_LIVE) {
480                         if (rigol_ds_config_set(sdi, ":WAV:RES") != SR_OK)
481                                 return SR_ERR;
482                         if (rigol_ds_config_set(sdi, ":WAV:BEG") != SR_OK)
483                                 return SR_ERR;
484                 }
485                 break;
486         case PROTOCOL_V4:
487         case PROTOCOL_V5:
488                 if (ch->type == SR_CHANNEL_ANALOG) {
489                         if (rigol_ds_config_set(sdi, ":WAV:SOUR CHAN%d",
490                                         ch->index + 1) != SR_OK)
491                                 return SR_ERR;
492                 } else {
493                         if (rigol_ds_config_set(sdi, ":WAV:SOUR D%d",
494                                         ch->index) != SR_OK)
495                                 return SR_ERR;
496                 }
497
498                 if (rigol_ds_config_set(sdi,
499                                         devc->data_source == DATA_SOURCE_LIVE ?
500                                                 ":WAV:MODE NORM" :":WAV:MODE RAW") != SR_OK)
501                         return SR_ERR;
502
503                 if (devc->data_source != DATA_SOURCE_LIVE) {
504                         if (rigol_ds_config_set(sdi, ":WAV:RES") != SR_OK)
505                                 return SR_ERR;
506                 }
507                 break;
508         }
509
510         if (devc->model->series->protocol >= PROTOCOL_V3 &&
511                         ch->type == SR_CHANNEL_ANALOG) {
512                 /* Vertical increment. */
513                 if (sr_scpi_get_float(sdi->conn, ":WAV:YINC?",
514                                 &devc->vert_inc[ch->index]) != SR_OK)
515                         return SR_ERR;
516                 /* Vertical origin. */
517                 if (sr_scpi_get_float(sdi->conn, ":WAV:YOR?",
518                         &devc->vert_origin[ch->index]) != SR_OK)
519                         return SR_ERR;
520                 /* Vertical reference. */
521                 if (sr_scpi_get_int(sdi->conn, ":WAV:YREF?",
522                                 &devc->vert_reference[ch->index]) != SR_OK)
523                         return SR_ERR;
524         } else if (ch->type == SR_CHANNEL_ANALOG) {
525                 devc->vert_inc[ch->index] = devc->vdiv[ch->index] / 25.6;
526         }
527
528         rigol_ds_set_wait_event(devc, WAIT_BLOCK);
529
530         devc->num_channel_bytes = 0;
531         devc->num_header_bytes = 0;
532         devc->num_block_bytes = 0;
533
534         return SR_OK;
535 }
536
537 /* Read the header of a data block */
538 static int rigol_ds_read_header(struct sr_dev_inst *sdi)
539 {
540         struct sr_scpi_dev_inst *scpi = sdi->conn;
541         struct dev_context *devc = sdi->priv;
542         char *buf = (char *) devc->buffer;
543         size_t header_length;
544         int ret;
545
546         /* Try to read the hashsign and length digit. */
547         if (devc->num_header_bytes < 2) {
548                 ret = sr_scpi_read_data(scpi, buf + devc->num_header_bytes,
549                                 2 - devc->num_header_bytes);
550                 if (ret < 0) {
551                         sr_err("Read error while reading data header.");
552                         return SR_ERR;
553                 }
554                 devc->num_header_bytes += ret;
555         }
556
557         if (devc->num_header_bytes < 2)
558                 return 0;
559
560         if (buf[0] != '#' || !isdigit(buf[1]) || buf[1] == '0') {
561                 sr_err("Received invalid data block header '%c%c'.", buf[0], buf[1]);
562                 return SR_ERR;
563         }
564
565         header_length = 2 + buf[1] - '0';
566
567         /* Try to read the length. */
568         if (devc->num_header_bytes < header_length) {
569                 ret = sr_scpi_read_data(scpi, buf + devc->num_header_bytes,
570                                 header_length - devc->num_header_bytes);
571                 if (ret < 0) {
572                         sr_err("Read error while reading data header.");
573                         return SR_ERR;
574                 }
575                 devc->num_header_bytes += ret;
576         }
577
578         if (devc->num_header_bytes < header_length)
579                 return 0;
580
581         /* Read the data length. */
582         buf[header_length] = '\0';
583
584         if (parse_int(buf + 2, &ret) != SR_OK) {
585                 sr_err("Received invalid data block length '%s'.", buf + 2);
586                 return -1;
587         }
588
589         sr_dbg("Received data block header: '%s' -> block length %d", buf, ret);
590
591         return ret;
592 }
593
594 SR_PRIV int rigol_ds_receive(int fd, int revents, void *cb_data)
595 {
596         struct sr_dev_inst *sdi;
597         struct sr_scpi_dev_inst *scpi;
598         struct dev_context *devc;
599         struct sr_datafeed_packet packet;
600         struct sr_datafeed_analog analog;
601         struct sr_analog_encoding encoding;
602         struct sr_analog_meaning meaning;
603         struct sr_analog_spec spec;
604         struct sr_datafeed_logic logic;
605         double vdiv, offset, origin;
606         int len, i, vref;
607         struct sr_channel *ch;
608         gsize expected_data_bytes;
609
610         (void)fd;
611
612         if (!(sdi = cb_data))
613                 return TRUE;
614
615         if (!(devc = sdi->priv))
616                 return TRUE;
617
618         scpi = sdi->conn;
619
620         if (!(revents == G_IO_IN || revents == 0))
621                 return TRUE;
622
623         switch (devc->wait_event) {
624         case WAIT_NONE:
625                 break;
626         case WAIT_TRIGGER:
627                 if (rigol_ds_trigger_wait(sdi) != SR_OK)
628                         return TRUE;
629                 if (rigol_ds_channel_start(sdi) != SR_OK)
630                         return TRUE;
631                 return TRUE;
632         case WAIT_BLOCK:
633                 if (rigol_ds_block_wait(sdi) != SR_OK)
634                         return TRUE;
635                 break;
636         case WAIT_STOP:
637                 if (rigol_ds_stop_wait(sdi) != SR_OK)
638                         return TRUE;
639                 if (rigol_ds_check_stop(sdi) != SR_OK)
640                         return TRUE;
641                 if (rigol_ds_channel_start(sdi) != SR_OK)
642                         return TRUE;
643                 return TRUE;
644         default:
645                 sr_err("BUG: Unknown event target encountered");
646                 break;
647         }
648
649         ch = devc->channel_entry->data;
650
651         expected_data_bytes = ch->type == SR_CHANNEL_ANALOG ?
652                         devc->analog_frame_size : devc->digital_frame_size;
653
654         if (devc->num_block_bytes == 0) {
655                 if (devc->model->series->protocol >= PROTOCOL_V4) {
656                         if (rigol_ds_config_set(sdi, ":WAV:START %d",
657                                         devc->num_channel_bytes + 1) != SR_OK)
658                                 return TRUE;
659                         if (rigol_ds_config_set(sdi, ":WAV:STOP %d",
660                                         MIN(devc->num_channel_bytes + ACQ_BLOCK_SIZE,
661                                                 devc->analog_frame_size)) != SR_OK)
662                                 return TRUE;
663                 }
664
665                 if (devc->model->series->protocol >= PROTOCOL_V3) {
666                         if (rigol_ds_config_set(sdi, ":WAV:BEG") != SR_OK)
667                                 return TRUE;
668                         if (sr_scpi_send(sdi->conn, ":WAV:DATA?") != SR_OK)
669                                 return TRUE;
670                 }
671
672                 if (sr_scpi_read_begin(scpi) != SR_OK)
673                         return TRUE;
674
675                 if (devc->format == FORMAT_IEEE488_2) {
676                         sr_dbg("New block header expected");
677                         len = rigol_ds_read_header(sdi);
678                         if (len == 0)
679                                 /* Still reading the header. */
680                                 return TRUE;
681                         if (len == -1) {
682                                 sr_err("Error while reading block header, aborting capture.");
683                                 std_session_send_df_frame_end(sdi);
684                                 sr_dev_acquisition_stop(sdi);
685                                 return TRUE;
686                         }
687                         /* At slow timebases in live capture the DS2072
688                          * sometimes returns "short" data blocks, with
689                          * apparently no way to get the rest of the data.
690                          * Discard these, the complete data block will
691                          * appear eventually.
692                          */
693                         if (devc->data_source == DATA_SOURCE_LIVE
694                                         && (unsigned)len < expected_data_bytes) {
695                                 sr_dbg("Discarding short data block");
696                                 sr_scpi_read_data(scpi, (char *)devc->buffer, len + 1);
697                                 return TRUE;
698                         }
699                         devc->num_block_bytes = len;
700                 } else {
701                         devc->num_block_bytes = expected_data_bytes;
702                 }
703                 devc->num_block_read = 0;
704         }
705
706         len = devc->num_block_bytes - devc->num_block_read;
707         if (len > ACQ_BUFFER_SIZE)
708                 len = ACQ_BUFFER_SIZE;
709         sr_dbg("Requesting read of %d bytes", len);
710
711         len = sr_scpi_read_data(scpi, (char *)devc->buffer, len);
712
713         if (len == -1) {
714                 sr_err("Error while reading block data, aborting capture.");
715                 std_session_send_df_frame_end(sdi);
716                 sr_dev_acquisition_stop(sdi);
717                 return TRUE;
718         }
719
720         sr_dbg("Received %d bytes.", len);
721
722         devc->num_block_read += len;
723
724         if (ch->type == SR_CHANNEL_ANALOG) {
725                 vref = devc->vert_reference[ch->index];
726                 vdiv = devc->vert_inc[ch->index];
727                 origin = devc->vert_origin[ch->index];
728                 offset = devc->vert_offset[ch->index];
729                 if (devc->model->series->protocol >= PROTOCOL_V3)
730                         for (i = 0; i < len; i++)
731                                 devc->data[i] = ((int)devc->buffer[i] - vref - origin) * vdiv;
732                 else
733                         for (i = 0; i < len; i++)
734                                 devc->data[i] = (128 - devc->buffer[i]) * vdiv - offset;
735                 float vdivlog = log10f(vdiv);
736                 int digits = -(int)vdivlog + (vdivlog < 0.0);
737                 sr_analog_init(&analog, &encoding, &meaning, &spec, digits);
738                 analog.meaning->channels = g_slist_append(NULL, ch);
739                 analog.num_samples = len;
740                 analog.data = devc->data;
741                 analog.meaning->mq = SR_MQ_VOLTAGE;
742                 analog.meaning->unit = SR_UNIT_VOLT;
743                 analog.meaning->mqflags = 0;
744                 packet.type = SR_DF_ANALOG;
745                 packet.payload = &analog;
746                 sr_session_send(sdi, &packet);
747                 g_slist_free(analog.meaning->channels);
748         } else {
749                 logic.length = len;
750                 // TODO: For the MSO1000Z series, we need a way to express that
751                 // this data is in fact just for a single channel, with the valid
752                 // data for that channel in the LSB of each byte.
753                 logic.unitsize = devc->model->series->protocol >= PROTOCOL_V4 ? 1 : 2;
754                 logic.data = devc->buffer;
755                 packet.type = SR_DF_LOGIC;
756                 packet.payload = &logic;
757                 sr_session_send(sdi, &packet);
758         }
759
760         if (devc->num_block_read == devc->num_block_bytes) {
761                 sr_dbg("Block has been completed");
762                 if (devc->model->series->protocol >= PROTOCOL_V3) {
763                         /* Discard the terminating linefeed */
764                         sr_scpi_read_data(scpi, (char *)devc->buffer, 1);
765                 }
766                 if (devc->format == FORMAT_IEEE488_2) {
767                         /* Prepare for possible next block */
768                         devc->num_header_bytes = 0;
769                         devc->num_block_bytes = 0;
770                         if (devc->data_source != DATA_SOURCE_LIVE)
771                                 rigol_ds_set_wait_event(devc, WAIT_BLOCK);
772                 }
773                 if (!sr_scpi_read_complete(scpi) && !devc->channel_entry->next) {
774                         sr_err("Read should have been completed");
775                 }
776                 devc->num_block_read = 0;
777         } else {
778                 sr_dbg("%" PRIu64 " of %" PRIu64 " block bytes read",
779                         devc->num_block_read, devc->num_block_bytes);
780         }
781
782         devc->num_channel_bytes += len;
783
784         if (devc->num_channel_bytes < expected_data_bytes)
785                 /* Don't have the full data for this channel yet, re-run. */
786                 return TRUE;
787
788         /* End of data for this channel. */
789         if (devc->model->series->protocol == PROTOCOL_V3) {
790                 /* Signal end of data download to scope */
791                 if (devc->data_source != DATA_SOURCE_LIVE)
792                         /*
793                          * This causes a query error, without it switching
794                          * to the next channel causes an error. Fun with
795                          * firmware...
796                          */
797                         rigol_ds_config_set(sdi, ":WAV:END");
798         }
799
800         if (devc->channel_entry->next) {
801                 /* We got the frame for this channel, now get the next channel. */
802                 devc->channel_entry = devc->channel_entry->next;
803                 rigol_ds_channel_start(sdi);
804         } else {
805                 /* Done with this frame. */
806                 std_session_send_df_frame_end(sdi);
807
808                 if (++devc->num_frames == devc->limit_frames || 
809                                 devc->num_frames == devc->num_frames_segmented ||
810                                 devc->data_source == DATA_SOURCE_MEMORY) {
811                         /* Last frame, stop capture. */
812                         sr_dev_acquisition_stop(sdi);
813                 } else {
814                         /* Get the next frame, starting with the first channel. */
815                         devc->channel_entry = devc->enabled_channels;
816
817                         rigol_ds_capture_start(sdi);
818
819                         /* Start of next frame. */
820                         std_session_send_df_frame_begin(sdi);
821                 }
822         }
823
824         return TRUE;
825 }
826
827 SR_PRIV int rigol_ds_get_dev_cfg(const struct sr_dev_inst *sdi)
828 {
829         struct dev_context *devc;
830         struct sr_channel *ch;
831         char *cmd;
832         unsigned int i;
833         int res;
834
835         devc = sdi->priv;
836
837         /* Analog channel state. */
838         for (i = 0; i < devc->model->analog_channels; i++) {
839                 cmd = g_strdup_printf(":CHAN%d:DISP?", i + 1);
840                 res = sr_scpi_get_bool(sdi->conn, cmd, &devc->analog_channels[i]);
841                 g_free(cmd);
842                 if (res != SR_OK)
843                         return SR_ERR;
844                 ch = g_slist_nth_data(sdi->channels, i);
845                 ch->enabled = devc->analog_channels[i];
846         }
847         sr_dbg("Current analog channel state:");
848         for (i = 0; i < devc->model->analog_channels; i++)
849                 sr_dbg("CH%d %s", i + 1, devc->analog_channels[i] ? "on" : "off");
850
851         /* Digital channel state. */
852         if (devc->model->has_digital) {
853                 if (sr_scpi_get_bool(sdi->conn,
854                                 devc->model->series->protocol >= PROTOCOL_V3 ?
855                                         ":LA:STAT?" : ":LA:DISP?",
856                                 &devc->la_enabled) != SR_OK)
857                         return SR_ERR;
858                 sr_dbg("Logic analyzer %s, current digital channel state:",
859                                 devc->la_enabled ? "enabled" : "disabled");
860                 for (i = 0; i < ARRAY_SIZE(devc->digital_channels); i++) {
861                         if (devc->model->series->protocol >= PROTOCOL_V5)
862                                 cmd = g_strdup_printf(":LA:DISP? D%d", i);
863                         else if (devc->model->series->protocol >= PROTOCOL_V3)
864                                 cmd = g_strdup_printf(":LA:DIG%d:DISP?", i);
865                         else
866                                 cmd = g_strdup_printf(":DIG%d:TURN?", i);
867                         res = sr_scpi_get_bool(sdi->conn, cmd, &devc->digital_channels[i]);
868                         g_free(cmd);
869                         if (res != SR_OK)
870                                 return SR_ERR;
871                         ch = g_slist_nth_data(sdi->channels, i + devc->model->analog_channels);
872                         ch->enabled = devc->digital_channels[i];
873                         sr_dbg("D%d: %s", i, devc->digital_channels[i] ? "on" : "off");
874                 }
875         }
876
877         /* Timebase. */
878         if (sr_scpi_get_float(sdi->conn, ":TIM:SCAL?", &devc->timebase) != SR_OK)
879                 return SR_ERR;
880         sr_dbg("Current timebase %g", devc->timebase);
881
882         /* Probe attenuation. */
883         for (i = 0; i < devc->model->analog_channels; i++) {
884                 cmd = g_strdup_printf(":CHAN%d:PROB?", i + 1);
885                 res = sr_scpi_get_float(sdi->conn, cmd, &devc->attenuation[i]);
886                 g_free(cmd);
887                 if (res != SR_OK)
888                         return SR_ERR;
889         }
890         sr_dbg("Current probe attenuation:");
891         for (i = 0; i < devc->model->analog_channels; i++)
892                 sr_dbg("CH%d %g", i + 1, devc->attenuation[i]);
893
894         /* Vertical gain and offset. */
895         if (rigol_ds_get_dev_cfg_vertical(sdi) != SR_OK)
896                 return SR_ERR;
897
898         /* Coupling. */
899         for (i = 0; i < devc->model->analog_channels; i++) {
900                 cmd = g_strdup_printf(":CHAN%d:COUP?", i + 1);
901                 res = sr_scpi_get_string(sdi->conn, cmd, &devc->coupling[i]);
902                 g_free(cmd);
903                 if (res != SR_OK)
904                         return SR_ERR;
905         }
906         sr_dbg("Current coupling:");
907         for (i = 0; i < devc->model->analog_channels; i++)
908                 sr_dbg("CH%d %s", i + 1, devc->coupling[i]);
909
910         /* Trigger source. */
911         if (sr_scpi_get_string(sdi->conn, ":TRIG:EDGE:SOUR?", &devc->trigger_source) != SR_OK)
912                 return SR_ERR;
913         sr_dbg("Current trigger source %s", devc->trigger_source);
914
915         /* Horizontal trigger position. */
916         if (sr_scpi_get_float(sdi->conn, devc->model->cmds[CMD_GET_HORIZ_TRIGGERPOS].str,
917                         &devc->horiz_triggerpos) != SR_OK)
918                 return SR_ERR;
919         sr_dbg("Current horizontal trigger position %g", devc->horiz_triggerpos);
920
921         /* Trigger slope. */
922         if (sr_scpi_get_string(sdi->conn, ":TRIG:EDGE:SLOP?", &devc->trigger_slope) != SR_OK)
923                 return SR_ERR;
924         sr_dbg("Current trigger slope %s", devc->trigger_slope);
925
926         /* Trigger level. */
927         if (sr_scpi_get_float(sdi->conn, ":TRIG:EDGE:LEV?", &devc->trigger_level) != SR_OK)
928                 return SR_ERR;
929         sr_dbg("Current trigger level %g", devc->trigger_level);
930
931         return SR_OK;
932 }
933
934 SR_PRIV int rigol_ds_get_dev_cfg_vertical(const struct sr_dev_inst *sdi)
935 {
936         struct dev_context *devc;
937         char *cmd;
938         unsigned int i;
939         int res;
940
941         devc = sdi->priv;
942
943         /* Vertical gain. */
944         for (i = 0; i < devc->model->analog_channels; i++) {
945                 cmd = g_strdup_printf(":CHAN%d:SCAL?", i + 1);
946                 res = sr_scpi_get_float(sdi->conn, cmd, &devc->vdiv[i]);
947                 g_free(cmd);
948                 if (res != SR_OK)
949                         return SR_ERR;
950         }
951         sr_dbg("Current vertical gain:");
952         for (i = 0; i < devc->model->analog_channels; i++)
953                 sr_dbg("CH%d %g", i + 1, devc->vdiv[i]);
954
955         /* Vertical offset. */
956         for (i = 0; i < devc->model->analog_channels; i++) {
957                 cmd = g_strdup_printf(":CHAN%d:OFFS?", i + 1);
958                 res = sr_scpi_get_float(sdi->conn, cmd, &devc->vert_offset[i]);
959                 g_free(cmd);
960                 if (res != SR_OK)
961                         return SR_ERR;
962         }
963         sr_dbg("Current vertical offset:");
964         for (i = 0; i < devc->model->analog_channels; i++)
965                 sr_dbg("CH%d %g", i + 1, devc->vert_offset[i]);
966
967         return SR_OK;
968 }