]> sigrok.org Git - libsigrok.git/blob - hardware/rigol-ds/protocol.c
rigol-ds: Add support for DS2xx2 series.
[libsigrok.git] / 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 <stdlib.h>
23 #include <stdarg.h>
24 #include <unistd.h>
25 #include <errno.h>
26 #include <string.h>
27 #include <math.h>
28 #include <ctype.h>
29 #include <time.h>
30 #include <glib.h>
31 #include "libsigrok.h"
32 #include "libsigrok-internal.h"
33 #include "protocol.h"
34
35 /*
36  * This is a unified protocol driver for the DS1000 and DS2000 series.
37  *
38  * DS1000 support tested with a Rigol DS1102D.
39  *
40  * DS2000 support tested with a Rigol DS2072 using firmware version 01.01.00.02.
41  *
42  * The Rigol DS2000 series scopes try to adhere to the IEEE 488.2 (I think)
43  * standard. If you want to read it - it costs real money...
44  *
45  * Every response from the scope has a linefeed appended because the
46  * standard says so. In principle this could be ignored because sending the
47  * next command clears the output queue of the scope. This driver tries to
48  * avoid doing that because it may cause an error being generated inside the
49  * scope and who knows what bugs the firmware has WRT this.
50  *
51  * Waveform data is transferred in a format called "arbitrary block program
52  * data" specified in IEEE 488.2. See Agilents programming manuals for their
53  * 2000/3000 series scopes for a nice description.
54  *
55  * Each data block from the scope has a header, e.g. "#900000001400".
56  * The '#' marks the start of a block.
57  * Next is one ASCII decimal digit between 1 and 9, this gives the number of
58  * ASCII decimal digits following.
59  * Last are the ASCII decimal digits giving the number of bytes (not
60  * samples!) in the block.
61  *
62  * After this header as many data bytes as indicated follow.
63  *
64  * Each data block has a trailing linefeed too.
65  */
66
67 static int get_cfg(const struct sr_dev_inst *sdi, char *cmd, char *reply, size_t maxlen);
68 static int get_cfg_int(const struct sr_dev_inst *sdi, char *cmd, int *i);
69
70 static int parse_int(const char *str, int *ret)
71 {
72         char *e;
73         long tmp;
74
75         errno = 0;
76         tmp = strtol(str, &e, 10);
77         if (e == str || *e != '\0') {
78                 sr_dbg("Failed to parse integer: '%s'", str);
79                 return SR_ERR;
80         }
81         if (errno) {
82                 sr_dbg("Failed to parse integer: '%s', numerical overflow", str);
83                 return SR_ERR;
84         }
85         if (tmp > INT_MAX || tmp < INT_MIN) {
86                 sr_dbg("Failed to parse integer: '%s', value to large/small", str);
87                 return SR_ERR;
88         }
89
90         *ret = (int)tmp;
91         return SR_OK;
92 }
93
94 /*
95  * Waiting for a trigger event will return a timeout after 2, 3 seconds in
96  * order to not block the application.
97  */
98
99 static int rigol_ds2xx2_trigger_wait(const struct sr_dev_inst *sdi)
100 {
101         char buf[20];
102         struct dev_context *devc;
103         time_t start;
104
105         if (!(devc = sdi->priv))
106                 return SR_ERR;
107
108         start = time(NULL);
109
110         /*
111          * Trigger status may return:
112          * "TD"   - triggered
113          * "AUTO" - autotriggered
114          * "RUN"  - running
115          * "WAIT" - waiting for trigger
116          * "STOP" - stopped
117          */
118
119         if (devc->trigger_wait_status == 1) {
120                 do {
121                         if (time(NULL) - start >= 3) {
122                                 sr_dbg("Timeout waiting for trigger");
123                                 return SR_ERR_TIMEOUT;
124                         }
125
126                         if (get_cfg(sdi, ":TRIG:STAT?", buf, sizeof(buf)) != SR_OK)
127                                 return SR_ERR;
128                 } while (buf[0] == 'T' || buf[0] == 'A');
129
130                 devc->trigger_wait_status = 2;
131         }
132         if (devc->trigger_wait_status == 2) {
133                 do {
134                         if (time(NULL) - start >= 3) {
135                                 sr_dbg("Timeout waiting for trigger");
136                                 return SR_ERR_TIMEOUT;
137                         }
138
139                         if (get_cfg(sdi, ":TRIG:STAT?", buf, sizeof(buf)) != SR_OK)
140                                 return SR_ERR;
141                 } while (buf[0] != 'T' && buf[0] != 'A');
142
143                 devc->trigger_wait_status = 0;
144         }
145
146         return SR_OK;
147 }
148
149 /*
150  * This needs to wait for a new trigger event to ensure that sample data is
151  * not returned twice.
152  *
153  * Unfortunately this will never really work because for sufficiently fast
154  * timebases it just can't catch the status changes.
155  *
156  * What would be needed is a trigger event register with autoreset like the
157  * Agilents have. The Rigols don't seem to have anything like this.
158  *
159  * The workaround is to only wait for the trigger when the timebase is slow
160  * enough. Of course this means that for faster timebases sample data can be
161  * returned multiple times.
162  */
163
164 SR_PRIV int rigol_ds2xx2_acquisition_start(const struct sr_dev_inst *sdi,
165                                            gboolean wait_for_trigger)
166 {
167         struct dev_context *devc;
168
169         if (!(devc = sdi->priv))
170                 return SR_ERR;
171
172         devc->channel_frame = devc->enabled_analog_probes->data;
173
174         sr_dbg("Starting acquisition on channel %d",
175                    devc->channel_frame->index + 1);
176
177         if (rigol_ds_send(sdi, ":WAV:FORM BYTE") != SR_OK)
178                 return SR_ERR;
179         if (rigol_ds_send(sdi, ":WAV:SOUR CHAN%d",
180                                   devc->channel_frame->index + 1) != SR_OK)
181                 return SR_ERR;
182         if (rigol_ds_send(sdi, ":WAV:MODE NORM") != SR_OK)
183                 return SR_ERR;
184
185         devc->num_frame_bytes = 0;
186         devc->num_block_bytes = 0;
187
188         /* only wait for trigger if timbase 50 msecs/DIV or slower */
189         if (wait_for_trigger && devc->timebase > 0.0499)
190         {
191                 devc->trigger_wait_status = 1;
192         } else {
193                 devc->trigger_wait_status = 0;
194         }
195
196         return SR_OK;
197 }
198
199 static int rigol_ds2xx2_read_header(struct sr_serial_dev_inst *serial)
200 {
201         char start[3], length[10];
202         int len, tmp;
203
204         /* Read the hashsign and length digit. */
205         tmp = serial_read(serial, start, 2);
206         start[2] = '\0';
207         if (tmp != 2)
208         {
209                 sr_err("Failed to read first two bytes of data block header.");
210                 return -1;
211         }
212         if (start[0] != '#' || !isdigit(start[1]) || start[1] == '0')
213         {
214                 sr_err("Received invalid data block header start '%s'.", start);
215                 return -1;
216         }
217         len = atoi(start + 1);
218
219         /* Read the data length. */
220         tmp = serial_read(serial, length, len);
221         length[len] = '\0';
222         if (tmp != len)
223         {
224                 sr_err("Failed to read %d bytes of data block length.", len);
225                 return -1;
226         }
227         if (parse_int(length, &len) != SR_OK)
228         {
229                 sr_err("Received invalid data block length '%s'.", length);
230                 return -1;
231         }
232
233         sr_dbg("Received data block header: %s%s -> block length %d", start, length, len);
234
235         return len;
236 }
237
238 SR_PRIV int rigol_ds_receive(int fd, int revents, void *cb_data)
239 {
240         struct sr_dev_inst *sdi;
241         struct sr_serial_dev_inst *serial;
242         struct dev_context *devc;
243         struct sr_datafeed_packet packet;
244         struct sr_datafeed_analog analog;
245         struct sr_datafeed_logic logic;
246         unsigned char buf[DS2000_ANALOG_WAVEFORM_SIZE];
247         double vdiv, offset;
248         float data[DS2000_ANALOG_WAVEFORM_SIZE];
249         int len, i, waveform_size, vref;
250         struct sr_probe *probe;
251
252         (void)fd;
253
254         if (!(sdi = cb_data))
255                 return TRUE;
256
257         if (!(devc = sdi->priv))
258                 return TRUE;
259
260         serial = sdi->conn;
261
262         if (revents == G_IO_IN) {
263                 if (devc->trigger_wait_status > 0) {
264                         if (rigol_ds2xx2_trigger_wait(sdi) != SR_OK)
265                                 return TRUE;
266                 }
267
268                 if (devc->model->series == 2 && devc->num_block_bytes == 0) {
269                         sr_dbg("New block header expected");
270                         if (rigol_ds_send(sdi, ":WAV:DATA?") != SR_OK)
271                                 return TRUE;
272                         len = rigol_ds2xx2_read_header(serial);
273                         if (len == -1)
274                                 return TRUE;
275                         /* At slow timebases the scope sometimes returns
276                          * "short" data blocks, with apparently no way to
277                          * get the rest of the data. Discard these, the
278                          * complete data block will appear eventually.
279                          */
280                         if (len < DS2000_ANALOG_WAVEFORM_SIZE) {
281                                 sr_dbg("Discarding short data block");
282                                 serial_read(serial, buf, len + 1);
283                                 return TRUE;
284                         }
285                         devc->num_block_bytes = len;
286                         devc->num_block_read = 0;
287                 }
288
289                 probe = devc->channel_frame;
290                 if (devc->model->series == 2) {
291                         len = devc->num_block_bytes - devc->num_block_read;
292                         len = serial_read(serial, buf,
293                                         len < DS2000_ANALOG_WAVEFORM_SIZE ? len : DS2000_ANALOG_WAVEFORM_SIZE);
294                 } else {
295                         waveform_size = probe->type == SR_PROBE_ANALOG ?
296                                         DS1000_ANALOG_WAVEFORM_SIZE : DIGITAL_WAVEFORM_SIZE;
297                         len = serial_read(serial, buf, waveform_size - devc->num_frame_bytes);
298                 }
299                 sr_dbg("Received %d bytes.", len);
300                 if (len == -1)
301                         return TRUE;
302
303                 if (devc->num_frame_bytes == 0) {
304                         /* Start of a new frame. */
305                         packet.type = SR_DF_FRAME_BEGIN;
306                         sr_session_send(sdi, &packet);
307                 }
308
309                 if (probe->type == SR_PROBE_ANALOG) {
310                         if (devc->model->series == 2)
311                                 devc->num_block_read += len;
312                         vref = devc->vert_reference[probe->index];
313                         vdiv = devc->vdiv[probe->index] / 25.6;
314                         offset = devc->vert_offset[probe->index];
315                         if (devc->model->series == 2)
316                                 for (i = 0; i < len; i++)
317                                         data[i] = ((int)buf[i] - vref) * vdiv - offset;
318                         else
319                                 for (i = 0; i < len; i++)
320                                         data[i] = (128 - buf[i]) * vdiv - offset;
321                         analog.probes = g_slist_append(NULL, probe);
322                         analog.num_samples = len;
323                         analog.data = data;
324                         analog.mq = SR_MQ_VOLTAGE;
325                         analog.unit = SR_UNIT_VOLT;
326                         analog.mqflags = 0;
327                         packet.type = SR_DF_ANALOG;
328                         packet.payload = &analog;
329                         sr_session_send(cb_data, &packet);
330                         g_slist_free(analog.probes);
331
332                         if (devc->model->series == 2) {
333                                 devc->num_frame_bytes += len;
334
335                                 if (devc->num_frame_bytes < DS2000_ANALOG_WAVEFORM_SIZE)
336                                         /* Don't have the whole frame yet. */
337                                         return TRUE;
338
339                                 sr_dbg("Frame completed, %d samples", devc->num_frame_bytes);
340                         } else {
341                                 if (len != DS1000_ANALOG_WAVEFORM_SIZE)
342                                         /* Don't have the whole frame yet. */
343                                         return TRUE;
344                         }
345                 } else {
346                         logic.length = len - 10;
347                         logic.unitsize = 2;
348                         logic.data = buf + 10;
349                         packet.type = SR_DF_LOGIC;
350                         packet.payload = &logic;
351                         sr_session_send(cb_data, &packet);
352
353                         if (len != DIGITAL_WAVEFORM_SIZE)
354                                 /* Don't have the whole frame yet. */
355                                 return TRUE;
356                 }
357
358                 /* End of the frame. */
359                 packet.type = SR_DF_FRAME_END;
360                 sr_session_send(sdi, &packet);
361                 if (devc->model->series == 1)
362                         devc->num_frame_bytes = 0;
363
364                 if (devc->enabled_analog_probes
365                                 && devc->channel_frame == devc->enabled_analog_probes->data
366                                 && devc->enabled_analog_probes->next != NULL) {
367                         /* We got the frame for the first analog channel, but
368                          * there's a second analog channel. */
369                         if (devc->model->series == 2) {
370                                 /* Do not wait for trigger to try and keep channel data related. */
371                                 rigol_ds2xx2_acquisition_start(sdi, FALSE);
372                         } else {
373                                 devc->channel_frame = devc->enabled_analog_probes->next->data;
374                                 rigol_ds_send(sdi, ":WAV:DATA? CHAN%c",
375                                                 devc->channel_frame->name[2]);
376                         }
377                 } else {
378                         /* Done with both analog channels in this frame. */
379                         if (devc->enabled_digital_probes
380                                         && devc->channel_frame != devc->enabled_digital_probes->data) {
381                                 /* Now we need to get the digital data. */
382                                 devc->channel_frame = devc->enabled_digital_probes->data;
383                                 rigol_ds_send(sdi, ":WAV:DATA? DIG");
384                         } else if (++devc->num_frames == devc->limit_frames) {
385                                 /* End of last frame. */
386                                 packet.type = SR_DF_END;
387                                 sr_session_send(sdi, &packet);
388                                 sdi->driver->dev_acquisition_stop(sdi, cb_data);
389                         } else {
390                                 /* Get the next frame, starting with the first analog channel. */
391                                 if (devc->model->series == 2) {
392                                         if (devc->enabled_analog_probes) {
393                                                 /* Must wait for trigger because at
394                                                  * slow timebases the scope will
395                                                  * return old data otherwise. */
396                                                 rigol_ds2xx2_acquisition_start(sdi, TRUE);
397                                         }
398                                 } else {
399                                         if (devc->enabled_analog_probes) {
400                                                 devc->channel_frame = devc->enabled_analog_probes->data;
401                                                 rigol_ds_send(sdi, ":WAV:DATA? CHAN%c",
402                                                                 devc->channel_frame->name[2]);
403                                         } else {
404                                                 devc->channel_frame = devc->enabled_digital_probes->data;
405                                                 rigol_ds_send(sdi, ":WAV:DATA? DIG");
406                                         }
407                                 }
408                         }
409                 }
410         }
411
412         return TRUE;
413 }
414
415 SR_PRIV int rigol_ds_send(const struct sr_dev_inst *sdi, const char *format, ...)
416 {
417         va_list args;
418         char buf[256];
419         int len, out, ret;
420
421         va_start(args, format);
422         len = vsnprintf(buf, 255, format, args);
423         va_end(args);
424         strcat(buf, "\n");
425         len++;
426         out = serial_write(sdi->conn, buf, len);
427         buf[len - 1] = '\0';
428         if (out != len) {
429                 sr_dbg("Only sent %d/%d bytes of '%s'.", out, len, buf);
430                 ret = SR_ERR;
431         } else {
432                 sr_spew("Sent '%s'.", buf);
433                 ret = SR_OK;
434         }
435
436         return ret;
437 }
438
439 static int get_cfg(const struct sr_dev_inst *sdi, char *cmd, char *reply, size_t maxlen)
440 {
441         int len;
442         struct dev_context *devc = sdi->priv;
443
444         if (rigol_ds_send(sdi, cmd) != SR_OK)
445                 return SR_ERR;
446
447         if ((len = serial_read(sdi->conn, reply, maxlen - 1)) < 0)
448                 return SR_ERR;
449         reply[len] = '\0';
450
451         if (devc->model->series == 2) {
452                 /* get rid of trailing linefeed */
453                 if (len >= 1 && reply[len-1] == '\n')
454                         reply[len-1] = '\0';
455         }
456
457         sr_spew("Received '%s'.", reply);
458
459         return SR_OK;
460 }
461
462 static int get_cfg_int(const struct sr_dev_inst *sdi, char *cmd, int *i)
463 {
464         char buf[32];
465
466         if (get_cfg(sdi, cmd, buf, sizeof(buf)) != SR_OK)
467                 return SR_ERR;
468
469         if (parse_int(buf, i) != SR_OK)
470                 return SR_ERR;
471
472         return SR_OK;
473 }
474
475 static int get_cfg_float(const struct sr_dev_inst *sdi, char *cmd, float *f)
476 {
477         char buf[32], *e;
478
479         if (get_cfg(sdi, cmd, buf, sizeof(buf)) != SR_OK)
480                 return SR_ERR;
481         *f = strtof(buf, &e);
482         if (e == buf || (fpclassify(*f) & (FP_ZERO | FP_NORMAL)) == 0) {
483                 sr_dbg("failed to parse response to '%s': '%s'", cmd, buf);
484                 return SR_ERR;
485         }
486
487         return SR_OK;
488 }
489
490 static int get_cfg_string(const struct sr_dev_inst *sdi, char *cmd, char **buf)
491 {
492         if (!(*buf = g_try_malloc0(256)))
493                 return SR_ERR_MALLOC;
494
495         if (get_cfg(sdi, cmd, *buf, 256) != SR_OK)
496                 return SR_ERR;
497
498         return SR_OK;
499 }
500
501 SR_PRIV int rigol_ds_get_dev_cfg(const struct sr_dev_inst *sdi)
502 {
503         struct dev_context *devc;
504         char *t_s, *cmd;
505         int i, res;
506
507         devc = sdi->priv;
508
509         /* Analog channel state. */
510         if (get_cfg_string(sdi, ":CHAN1:DISP?", &t_s) != SR_OK)
511                 return SR_ERR;
512         devc->analog_channels[0] = !strcmp(t_s, "ON") || !strcmp(t_s, "1");
513         g_free(t_s);
514         if (get_cfg_string(sdi, ":CHAN2:DISP?", &t_s) != SR_OK)
515                 return SR_ERR;
516         devc->analog_channels[1] = !strcmp(t_s, "ON") || !strcmp(t_s, "1");
517         g_free(t_s);
518         sr_dbg("Current analog channel state CH1 %s CH2 %s",
519                         devc->analog_channels[0] ? "on" : "off",
520                         devc->analog_channels[1] ? "on" : "off");
521
522         /* Digital channel state. */
523         if (devc->model->has_digital) {
524                 sr_dbg("Current digital channel state:");
525                 for (i = 0; i < 16; i++) {
526                         cmd = g_strdup_printf(":DIG%d:TURN?", i);
527                         res = get_cfg_string(sdi, cmd, &t_s);
528                         g_free(cmd);
529                         if (res != SR_OK)
530                                 return SR_ERR;
531                         devc->digital_channels[i] = !strcmp(t_s, "ON") ? TRUE : FALSE;
532                         g_free(t_s);
533                         sr_dbg("D%d: %s", i, devc->digital_channels[i] ? "on" : "off");
534                 }
535         }
536
537         /* Timebase. */
538         if (get_cfg_float(sdi, ":TIM:SCAL?", &devc->timebase) != SR_OK)
539                 return SR_ERR;
540         sr_dbg("Current timebase %g", devc->timebase);
541
542         /* Vertical gain. */
543         if (get_cfg_float(sdi, ":CHAN1:SCAL?", &devc->vdiv[0]) != SR_OK)
544                 return SR_ERR;
545         if (get_cfg_float(sdi, ":CHAN2:SCAL?", &devc->vdiv[1]) != SR_OK)
546                 return SR_ERR;
547         sr_dbg("Current vertical gain CH1 %g CH2 %g", devc->vdiv[0], devc->vdiv[1]);
548
549         if (devc->model->series == 2) {
550                 /* Vertical reference - not certain if this is the place to read it. */
551                 if (rigol_ds_send(sdi, ":WAV:SOUR CHAN1") != SR_OK)
552                         return SR_ERR;
553                 if (get_cfg_int(sdi, ":WAV:YREF?", &devc->vert_reference[0]) != SR_OK)
554                         return SR_ERR;
555                 if (rigol_ds_send(sdi, ":WAV:SOUR CHAN2") != SR_OK)
556                         return SR_ERR;
557                 if (get_cfg_int(sdi, ":WAV:YREF?", &devc->vert_reference[1]) != SR_OK)
558                         return SR_ERR;
559                 sr_dbg("Current vertical reference CH1 %d CH2 %d",
560                                 devc->vert_reference[0], devc->vert_reference[1]);
561         }
562
563         /* Vertical offset. */
564         if (get_cfg_float(sdi, ":CHAN1:OFFS?", &devc->vert_offset[0]) != SR_OK)
565                 return SR_ERR;
566         if (get_cfg_float(sdi, ":CHAN2:OFFS?", &devc->vert_offset[1]) != SR_OK)
567                 return SR_ERR;
568         sr_dbg("Current vertical offset CH1 %g CH2 %g", devc->vert_offset[0],
569                         devc->vert_offset[1]);
570
571         /* Coupling. */
572         if (get_cfg_string(sdi, ":CHAN1:COUP?", &devc->coupling[0]) != SR_OK)
573                 return SR_ERR;
574         if (get_cfg_string(sdi, ":CHAN2:COUP?", &devc->coupling[1]) != SR_OK)
575                 return SR_ERR;
576         sr_dbg("Current coupling CH1 %s CH2 %s", devc->coupling[0],
577                         devc->coupling[1]);
578
579         /* Trigger source. */
580         if (get_cfg_string(sdi, ":TRIG:EDGE:SOUR?", &devc->trigger_source) != SR_OK)
581                 return SR_ERR;
582         sr_dbg("Current trigger source %s", devc->trigger_source);
583
584         /* Horizontal trigger position. */
585         if (get_cfg_float(sdi, ":TIM:OFFS?", &devc->horiz_triggerpos) != SR_OK)
586                 return SR_ERR;
587         sr_dbg("Current horizontal trigger position %g", devc->horiz_triggerpos);
588
589         /* Trigger slope. */
590         if (get_cfg_string(sdi, ":TRIG:EDGE:SLOP?", &devc->trigger_slope) != SR_OK)
591                 return SR_ERR;
592         sr_dbg("Current trigger slope %s", devc->trigger_slope);
593
594         return SR_OK;
595 }