]> sigrok.org Git - libsigrok.git/blob - hardware/rigol-ds/protocol.c
e8bfb93fc66ba895266154a1ff346d6ec5adf1ed
[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         sr_dbg("Starting acquisition on channel %d",
173                    devc->channel_frame->index + 1);
174
175         if (rigol_ds_send(sdi, ":WAV:FORM BYTE") != SR_OK)
176                 return SR_ERR;
177         if (rigol_ds_send(sdi, ":WAV:SOUR CHAN%d",
178                                   devc->channel_frame->index + 1) != SR_OK)
179                 return SR_ERR;
180         if (rigol_ds_send(sdi, ":WAV:MODE NORM") != SR_OK)
181                 return SR_ERR;
182
183         devc->num_frame_bytes = 0;
184         devc->num_block_bytes = 0;
185
186         /* only wait for trigger if timbase 50 msecs/DIV or slower */
187         if (wait_for_trigger && devc->timebase > 0.0499)
188         {
189                 devc->trigger_wait_status = 1;
190         } else {
191                 devc->trigger_wait_status = 0;
192         }
193
194         return SR_OK;
195 }
196
197 static int rigol_ds2xx2_read_header(struct sr_serial_dev_inst *serial)
198 {
199         char start[3], length[10];
200         int len, tmp;
201
202         /* Read the hashsign and length digit. */
203         tmp = serial_read(serial, start, 2);
204         start[2] = '\0';
205         if (tmp != 2)
206         {
207                 sr_err("Failed to read first two bytes of data block header.");
208                 return -1;
209         }
210         if (start[0] != '#' || !isdigit(start[1]) || start[1] == '0')
211         {
212                 sr_err("Received invalid data block header start '%s'.", start);
213                 return -1;
214         }
215         len = atoi(start + 1);
216
217         /* Read the data length. */
218         tmp = serial_read(serial, length, len);
219         length[len] = '\0';
220         if (tmp != len)
221         {
222                 sr_err("Failed to read %d bytes of data block length.", len);
223                 return -1;
224         }
225         if (parse_int(length, &len) != SR_OK)
226         {
227                 sr_err("Received invalid data block length '%s'.", length);
228                 return -1;
229         }
230
231         sr_dbg("Received data block header: %s%s -> block length %d", start, length, len);
232
233         return len;
234 }
235
236 SR_PRIV int rigol_ds_receive(int fd, int revents, void *cb_data)
237 {
238         struct sr_dev_inst *sdi;
239         struct sr_serial_dev_inst *serial;
240         struct dev_context *devc;
241         struct sr_datafeed_packet packet;
242         struct sr_datafeed_analog analog;
243         struct sr_datafeed_logic logic;
244         unsigned char buf[DS2000_ANALOG_WAVEFORM_SIZE];
245         double vdiv, offset;
246         float data[DS2000_ANALOG_WAVEFORM_SIZE];
247         int len, i, waveform_size, vref;
248         struct sr_probe *probe;
249
250         (void)fd;
251
252         if (!(sdi = cb_data))
253                 return TRUE;
254
255         if (!(devc = sdi->priv))
256                 return TRUE;
257
258         serial = sdi->conn;
259
260         if (revents == G_IO_IN) {
261                 if (devc->trigger_wait_status > 0) {
262                         if (rigol_ds2xx2_trigger_wait(sdi) != SR_OK)
263                                 return TRUE;
264                 }
265
266                 if (devc->model->series == 2 && devc->num_block_bytes == 0) {
267                         sr_dbg("New block header expected");
268                         if (rigol_ds_send(sdi, ":WAV:DATA?") != SR_OK)
269                                 return TRUE;
270                         len = rigol_ds2xx2_read_header(serial);
271                         if (len == -1)
272                                 return TRUE;
273                         /* At slow timebases the scope sometimes returns
274                          * "short" data blocks, with apparently no way to
275                          * get the rest of the data. Discard these, the
276                          * complete data block will appear eventually.
277                          */
278                         if (len < DS2000_ANALOG_WAVEFORM_SIZE) {
279                                 sr_dbg("Discarding short data block");
280                                 serial_read(serial, buf, len + 1);
281                                 return TRUE;
282                         }
283                         devc->num_block_bytes = len;
284                         devc->num_block_read = 0;
285                 }
286
287                 probe = devc->channel_frame;
288                 if (devc->model->series == 2) {
289                         len = devc->num_block_bytes - devc->num_block_read;
290                         len = serial_read(serial, buf,
291                                         len < DS2000_ANALOG_WAVEFORM_SIZE ? len : DS2000_ANALOG_WAVEFORM_SIZE);
292                 } else {
293                         waveform_size = probe->type == SR_PROBE_ANALOG ?
294                                         DS1000_ANALOG_WAVEFORM_SIZE : DIGITAL_WAVEFORM_SIZE;
295                         len = serial_read(serial, buf, waveform_size - devc->num_frame_bytes);
296                 }
297                 sr_dbg("Received %d bytes.", len);
298                 if (len == -1)
299                         return TRUE;
300
301                 if (devc->num_frame_bytes == 0) {
302                         /* Start of a new frame. */
303                         packet.type = SR_DF_FRAME_BEGIN;
304                         sr_session_send(sdi, &packet);
305                 }
306
307                 if (probe->type == SR_PROBE_ANALOG) {
308                         if (devc->model->series == 2)
309                                 devc->num_block_read += len;
310                         vref = devc->vert_reference[probe->index];
311                         vdiv = devc->vdiv[probe->index] / 25.6;
312                         offset = devc->vert_offset[probe->index];
313                         if (devc->model->series == 2)
314                                 for (i = 0; i < len; i++)
315                                         data[i] = ((int)buf[i] - vref) * vdiv - offset;
316                         else
317                                 for (i = 0; i < len; i++)
318                                         data[i] = (128 - buf[i]) * vdiv - offset;
319                         analog.probes = g_slist_append(NULL, probe);
320                         analog.num_samples = len;
321                         analog.data = data;
322                         analog.mq = SR_MQ_VOLTAGE;
323                         analog.unit = SR_UNIT_VOLT;
324                         analog.mqflags = 0;
325                         packet.type = SR_DF_ANALOG;
326                         packet.payload = &analog;
327                         sr_session_send(cb_data, &packet);
328                         g_slist_free(analog.probes);
329
330                         if (devc->model->series == 2) {
331                                 devc->num_frame_bytes += len;
332
333                                 if (devc->num_frame_bytes < DS2000_ANALOG_WAVEFORM_SIZE)
334                                         /* Don't have the whole frame yet. */
335                                         return TRUE;
336
337                                 sr_dbg("Frame completed, %d samples", devc->num_frame_bytes);
338                         } else {
339                                 if (len != DS1000_ANALOG_WAVEFORM_SIZE)
340                                         /* Don't have the whole frame yet. */
341                                         return TRUE;
342                         }
343                 } else {
344                         logic.length = len - 10;
345                         logic.unitsize = 2;
346                         logic.data = buf + 10;
347                         packet.type = SR_DF_LOGIC;
348                         packet.payload = &logic;
349                         sr_session_send(cb_data, &packet);
350
351                         if (len != DIGITAL_WAVEFORM_SIZE)
352                                 /* Don't have the whole frame yet. */
353                                 return TRUE;
354                 }
355
356                 /* End of the frame. */
357                 packet.type = SR_DF_FRAME_END;
358                 sr_session_send(sdi, &packet);
359                 if (devc->model->series == 1)
360                         devc->num_frame_bytes = 0;
361
362                 if (devc->enabled_analog_probes
363                                 && devc->channel_frame == devc->enabled_analog_probes->data
364                                 && devc->enabled_analog_probes->next != NULL) {
365                         /* We got the frame for the first analog channel, but
366                          * there's a second analog channel. */
367                         devc->channel_frame = devc->enabled_analog_probes->next->data;
368                         if (devc->model->series == 2) {
369                                 /* Do not wait for trigger to try and keep channel data related. */
370                                 rigol_ds2xx2_acquisition_start(sdi, FALSE);
371                         } else {
372                                 rigol_ds_send(sdi, ":WAV:DATA? CHAN%c",
373                                                 devc->channel_frame->name[2]);
374                         }
375                 } else {
376                         /* Done with both analog channels in this frame. */
377                         if (devc->enabled_digital_probes
378                                         && devc->channel_frame != devc->enabled_digital_probes->data) {
379                                 /* Now we need to get the digital data. */
380                                 devc->channel_frame = devc->enabled_digital_probes->data;
381                                 rigol_ds_send(sdi, ":WAV:DATA? DIG");
382                         } else if (++devc->num_frames == devc->limit_frames) {
383                                 /* End of last frame. */
384                                 packet.type = SR_DF_END;
385                                 sr_session_send(sdi, &packet);
386                                 sdi->driver->dev_acquisition_stop(sdi, cb_data);
387                         } else {
388                                 /* Get the next frame, starting with the first analog channel. */
389                                 if (devc->model->series == 2) {
390                                         if (devc->enabled_analog_probes) {
391                                                 devc->channel_frame = devc->enabled_analog_probes->data;
392                                                 /* Must wait for trigger because at
393                                                  * slow timebases the scope will
394                                                  * return old data otherwise. */
395                                                 rigol_ds2xx2_acquisition_start(sdi, TRUE);
396                                         }
397                                 } else {
398                                         if (devc->enabled_analog_probes) {
399                                                 devc->channel_frame = devc->enabled_analog_probes->data;
400                                                 rigol_ds_send(sdi, ":WAV:DATA? CHAN%c",
401                                                                 devc->channel_frame->name[2]);
402                                         } else {
403                                                 devc->channel_frame = devc->enabled_digital_probes->data;
404                                                 rigol_ds_send(sdi, ":WAV:DATA? DIG");
405                                         }
406                                 }
407                         }
408                 }
409         }
410
411         return TRUE;
412 }
413
414 SR_PRIV int rigol_ds_send(const struct sr_dev_inst *sdi, const char *format, ...)
415 {
416         va_list args;
417         char buf[256];
418         int len, out, ret;
419
420         va_start(args, format);
421         len = vsnprintf(buf, 255, format, args);
422         va_end(args);
423         strcat(buf, "\n");
424         len++;
425         out = serial_write(sdi->conn, buf, len);
426         buf[len - 1] = '\0';
427         if (out != len) {
428                 sr_dbg("Only sent %d/%d bytes of '%s'.", out, len, buf);
429                 ret = SR_ERR;
430         } else {
431                 sr_spew("Sent '%s'.", buf);
432                 ret = SR_OK;
433         }
434
435         return ret;
436 }
437
438 static int get_cfg(const struct sr_dev_inst *sdi, char *cmd, char *reply, size_t maxlen)
439 {
440         int len;
441         struct dev_context *devc = sdi->priv;
442
443         if (rigol_ds_send(sdi, cmd) != SR_OK)
444                 return SR_ERR;
445
446         if ((len = serial_read(sdi->conn, reply, maxlen - 1)) < 0)
447                 return SR_ERR;
448         reply[len] = '\0';
449
450         if (devc->model->series == 2) {
451                 /* get rid of trailing linefeed */
452                 if (len >= 1 && reply[len-1] == '\n')
453                         reply[len-1] = '\0';
454         }
455
456         sr_spew("Received '%s'.", reply);
457
458         return SR_OK;
459 }
460
461 static int get_cfg_int(const struct sr_dev_inst *sdi, char *cmd, int *i)
462 {
463         char buf[32];
464
465         if (get_cfg(sdi, cmd, buf, sizeof(buf)) != SR_OK)
466                 return SR_ERR;
467
468         if (parse_int(buf, i) != SR_OK)
469                 return SR_ERR;
470
471         return SR_OK;
472 }
473
474 static int get_cfg_float(const struct sr_dev_inst *sdi, char *cmd, float *f)
475 {
476         char buf[32], *e;
477
478         if (get_cfg(sdi, cmd, buf, sizeof(buf)) != SR_OK)
479                 return SR_ERR;
480         *f = strtof(buf, &e);
481         if (e == buf || (fpclassify(*f) & (FP_ZERO | FP_NORMAL)) == 0) {
482                 sr_dbg("failed to parse response to '%s': '%s'", cmd, buf);
483                 return SR_ERR;
484         }
485
486         return SR_OK;
487 }
488
489 static int get_cfg_string(const struct sr_dev_inst *sdi, char *cmd, char **buf)
490 {
491         if (!(*buf = g_try_malloc0(256)))
492                 return SR_ERR_MALLOC;
493
494         if (get_cfg(sdi, cmd, *buf, 256) != SR_OK)
495                 return SR_ERR;
496
497         return SR_OK;
498 }
499
500 SR_PRIV int rigol_ds_get_dev_cfg(const struct sr_dev_inst *sdi)
501 {
502         struct dev_context *devc;
503         char *t_s, *cmd;
504         int i, res;
505
506         devc = sdi->priv;
507
508         /* Analog channel state. */
509         if (get_cfg_string(sdi, ":CHAN1:DISP?", &t_s) != SR_OK)
510                 return SR_ERR;
511         devc->analog_channels[0] = !strcmp(t_s, "ON") || !strcmp(t_s, "1");
512         g_free(t_s);
513         if (get_cfg_string(sdi, ":CHAN2:DISP?", &t_s) != SR_OK)
514                 return SR_ERR;
515         devc->analog_channels[1] = !strcmp(t_s, "ON") || !strcmp(t_s, "1");
516         g_free(t_s);
517         sr_dbg("Current analog channel state CH1 %s CH2 %s",
518                         devc->analog_channels[0] ? "on" : "off",
519                         devc->analog_channels[1] ? "on" : "off");
520
521         /* Digital channel state. */
522         if (devc->model->has_digital) {
523                 sr_dbg("Current digital channel state:");
524                 for (i = 0; i < 16; i++) {
525                         cmd = g_strdup_printf(":DIG%d:TURN?", i);
526                         res = get_cfg_string(sdi, cmd, &t_s);
527                         g_free(cmd);
528                         if (res != SR_OK)
529                                 return SR_ERR;
530                         devc->digital_channels[i] = !strcmp(t_s, "ON") ? TRUE : FALSE;
531                         g_free(t_s);
532                         sr_dbg("D%d: %s", i, devc->digital_channels[i] ? "on" : "off");
533                 }
534         }
535
536         /* Timebase. */
537         if (get_cfg_float(sdi, ":TIM:SCAL?", &devc->timebase) != SR_OK)
538                 return SR_ERR;
539         sr_dbg("Current timebase %g", devc->timebase);
540
541         /* Vertical gain. */
542         if (get_cfg_float(sdi, ":CHAN1:SCAL?", &devc->vdiv[0]) != SR_OK)
543                 return SR_ERR;
544         if (get_cfg_float(sdi, ":CHAN2:SCAL?", &devc->vdiv[1]) != SR_OK)
545                 return SR_ERR;
546         sr_dbg("Current vertical gain CH1 %g CH2 %g", devc->vdiv[0], devc->vdiv[1]);
547
548         if (devc->model->series == 2) {
549                 /* Vertical reference - not certain if this is the place to read it. */
550                 if (rigol_ds_send(sdi, ":WAV:SOUR CHAN1") != SR_OK)
551                         return SR_ERR;
552                 if (get_cfg_int(sdi, ":WAV:YREF?", &devc->vert_reference[0]) != SR_OK)
553                         return SR_ERR;
554                 if (rigol_ds_send(sdi, ":WAV:SOUR CHAN2") != SR_OK)
555                         return SR_ERR;
556                 if (get_cfg_int(sdi, ":WAV:YREF?", &devc->vert_reference[1]) != SR_OK)
557                         return SR_ERR;
558                 sr_dbg("Current vertical reference CH1 %d CH2 %d",
559                                 devc->vert_reference[0], devc->vert_reference[1]);
560         }
561
562         /* Vertical offset. */
563         if (get_cfg_float(sdi, ":CHAN1:OFFS?", &devc->vert_offset[0]) != SR_OK)
564                 return SR_ERR;
565         if (get_cfg_float(sdi, ":CHAN2:OFFS?", &devc->vert_offset[1]) != SR_OK)
566                 return SR_ERR;
567         sr_dbg("Current vertical offset CH1 %g CH2 %g", devc->vert_offset[0],
568                         devc->vert_offset[1]);
569
570         /* Coupling. */
571         if (get_cfg_string(sdi, ":CHAN1:COUP?", &devc->coupling[0]) != SR_OK)
572                 return SR_ERR;
573         if (get_cfg_string(sdi, ":CHAN2:COUP?", &devc->coupling[1]) != SR_OK)
574                 return SR_ERR;
575         sr_dbg("Current coupling CH1 %s CH2 %s", devc->coupling[0],
576                         devc->coupling[1]);
577
578         /* Trigger source. */
579         if (get_cfg_string(sdi, ":TRIG:EDGE:SOUR?", &devc->trigger_source) != SR_OK)
580                 return SR_ERR;
581         sr_dbg("Current trigger source %s", devc->trigger_source);
582
583         /* Horizontal trigger position. */
584         if (get_cfg_float(sdi, ":TIM:OFFS?", &devc->horiz_triggerpos) != SR_OK)
585                 return SR_ERR;
586         sr_dbg("Current horizontal trigger position %g", devc->horiz_triggerpos);
587
588         /* Trigger slope. */
589         if (get_cfg_string(sdi, ":TRIG:EDGE:SLOP?", &devc->trigger_slope) != SR_OK)
590                 return SR_ERR;
591         sr_dbg("Current trigger slope %s", devc->trigger_slope);
592
593         return SR_OK;
594 }