]> sigrok.org Git - libsigrok.git/blob - src/scpi/scpi.c
scpi-pps: Reimplemention of switching channel groups (PSU channels)
[libsigrok.git] / src / scpi / scpi.c
1 /*
2  * This file is part of the libsigrok project.
3  *
4  * Copyright (C) 2013 poljar (Damir Jelić) <poljarinho@gmail.com>
5  * Copyright (C) 2015 Bert Vermeulen <bert@biot.com>
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation, either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
19  */
20
21 #include <config.h>
22 #include <glib.h>
23 #include <string.h>
24 #include <libsigrok/libsigrok.h>
25 #include "libsigrok-internal.h"
26 #include "scpi.h"
27
28 #define LOG_PREFIX "scpi"
29
30 #define SCPI_READ_RETRIES 100
31 #define SCPI_READ_RETRY_TIMEOUT_US (10 * 1000)
32
33 static const char *scpi_vendors[][2] = {
34         { "HEWLETT-PACKARD", "HP" },
35         { "Agilent Technologies", "Agilent" },
36         { "RIGOL TECHNOLOGIES", "Rigol" },
37         { "PHILIPS", "Philips" },
38         { "CHROMA", "Chroma" },
39         { "Chroma ATE", "Chroma" },
40 };
41
42 /**
43  * Parse a string representation of a boolean-like value into a gboolean.
44  * Similar to sr_parse_boolstring but rejects strings which do not represent
45  * a boolean-like value.
46  *
47  * @param str String to convert.
48  * @param ret Pointer to a gboolean where the result of the conversion will be
49  * stored.
50  *
51  * @return SR_OK on success, SR_ERR on failure.
52  */
53 static int parse_strict_bool(const char *str, gboolean *ret)
54 {
55         if (!str)
56                 return SR_ERR_ARG;
57
58         if (!g_strcmp0(str, "1") ||
59             !g_ascii_strncasecmp(str, "y", 1) ||
60             !g_ascii_strncasecmp(str, "t", 1) ||
61             !g_ascii_strncasecmp(str, "yes", 3) ||
62             !g_ascii_strncasecmp(str, "true", 4) ||
63             !g_ascii_strncasecmp(str, "on", 2)) {
64                 *ret = TRUE;
65                 return SR_OK;
66         } else if (!g_strcmp0(str, "0") ||
67                    !g_ascii_strncasecmp(str, "n", 1) ||
68                    !g_ascii_strncasecmp(str, "f", 1) ||
69                    !g_ascii_strncasecmp(str, "no", 2) ||
70                    !g_ascii_strncasecmp(str, "false", 5) ||
71                    !g_ascii_strncasecmp(str, "off", 3)) {
72                 *ret = FALSE;
73                 return SR_OK;
74         }
75
76         return SR_ERR;
77 }
78
79 SR_PRIV extern const struct sr_scpi_dev_inst scpi_serial_dev;
80 SR_PRIV extern const struct sr_scpi_dev_inst scpi_tcp_raw_dev;
81 SR_PRIV extern const struct sr_scpi_dev_inst scpi_tcp_rigol_dev;
82 SR_PRIV extern const struct sr_scpi_dev_inst scpi_usbtmc_libusb_dev;
83 SR_PRIV extern const struct sr_scpi_dev_inst scpi_vxi_dev;
84 SR_PRIV extern const struct sr_scpi_dev_inst scpi_visa_dev;
85 SR_PRIV extern const struct sr_scpi_dev_inst scpi_libgpib_dev;
86
87 static const struct sr_scpi_dev_inst *scpi_devs[] = {
88         &scpi_tcp_raw_dev,
89         &scpi_tcp_rigol_dev,
90 #ifdef HAVE_LIBUSB_1_0
91         &scpi_usbtmc_libusb_dev,
92 #endif
93 #if HAVE_RPC
94         &scpi_vxi_dev,
95 #endif
96 #ifdef HAVE_LIBREVISA
97         &scpi_visa_dev,
98 #endif
99 #ifdef HAVE_LIBGPIB
100         &scpi_libgpib_dev,
101 #endif
102 #ifdef HAVE_LIBSERIALPORT
103         &scpi_serial_dev, /* Must be last as it matches any resource. */
104 #endif
105 };
106
107 static struct sr_dev_inst *sr_scpi_scan_resource(struct drv_context *drvc,
108                 const char *resource, const char *serialcomm,
109                 struct sr_dev_inst *(*probe_device)(struct sr_scpi_dev_inst *scpi))
110 {
111         struct sr_scpi_dev_inst *scpi;
112         struct sr_dev_inst *sdi;
113
114         if (!(scpi = scpi_dev_inst_new(drvc, resource, serialcomm)))
115                 return NULL;
116
117         if (sr_scpi_open(scpi) != SR_OK) {
118                 sr_info("Couldn't open SCPI device.");
119                 sr_scpi_free(scpi);
120                 return NULL;
121         };
122
123         sdi = probe_device(scpi);
124
125         sr_scpi_close(scpi);
126
127         if (sdi)
128                 sdi->status = SR_ST_INACTIVE;
129         else
130                 sr_scpi_free(scpi);
131
132         return sdi;
133 }
134
135 /**
136  * Send a SCPI command with a variadic argument list without mutex.
137  *
138  * @param scpi Previously initialized SCPI device structure.
139  * @param format Format string.
140  * @param args Argument list.
141  *
142  * @return SR_OK on success, SR_ERR on failure.
143  */
144 static int scpi_send_variadic(struct sr_scpi_dev_inst *scpi,
145                          const char *format, va_list args)
146 {
147         va_list args_copy;
148         char *buf;
149         int len, ret;
150
151         /* Get length of buffer required. */
152         va_copy(args_copy, args);
153         len = vsnprintf(NULL, 0, format, args_copy);
154         va_end(args_copy);
155
156         /* Allocate buffer and write out command. */
157         buf = g_malloc0(len + 2);
158         vsprintf(buf, format, args);
159         if (buf[len - 1] != '\n')
160                 buf[len] = '\n';
161
162         /* Send command. */
163         ret = scpi->send(scpi->priv, buf);
164
165         /* Free command buffer. */
166         g_free(buf);
167
168         return ret;
169 }
170
171 /**
172  * Send a SCPI command without mutex.
173  *
174  * @param scpi Previously initialized SCPI device structure.
175  * @param format Format string, to be followed by any necessary arguments.
176  *
177  * @return SR_OK on success, SR_ERR on failure.
178  */
179 static int scpi_send(struct sr_scpi_dev_inst *scpi, const char *format, ...)
180 {
181         va_list args;
182         int ret;
183
184         va_start(args, format);
185         ret = scpi_send_variadic(scpi, format, args);
186         va_end(args);
187
188         return ret;
189 }
190
191 /**
192  * Send data to SCPI device without mutex.
193  *
194  * TODO: This is only implemented in TcpRaw, but never used.
195  * TODO: Use Mutex at all?
196  *
197  * @param scpi Previously initialised SCPI device structure.
198  * @param buf Buffer with data to send.
199  * @param len Number of bytes to send.
200  *
201  * @return Number of bytes read, or SR_ERR upon failure.
202  */
203 static int scpi_write_data(struct sr_scpi_dev_inst *scpi, char *buf, int maxlen)
204 {
205         return scpi->write_data(scpi->priv, buf, maxlen);
206 }
207
208 /**
209  * Read part of a response from SCPI device without mutex.
210  *
211  * @param scpi Previously initialised SCPI device structure.
212  * @param buf Buffer to store result.
213  * @param maxlen Maximum number of bytes to read.
214  *
215  * @return Number of bytes read, or SR_ERR upon failure.
216  */
217 static int scpi_read_data(struct sr_scpi_dev_inst *scpi, char *buf, int maxlen)
218 {
219         return scpi->read_data(scpi->priv, buf, maxlen);
220 }
221
222 /**
223  * Do a non-blocking read of up to the allocated length, and
224  * check if a timeout has occured, without mutex.
225  *
226  * @param scpi Previously initialised SCPI device structure.
227  * @param response Buffer to which the response is appended.
228  * @param abs_timeout_us Absolute timeout in microseconds
229  *
230  * @return read length on success, SR_ERR* on failure.
231  */
232 static int scpi_read_response(struct sr_scpi_dev_inst *scpi,
233                                 GString *response, gint64 abs_timeout_us)
234 {
235         int len, space;
236
237         space = response->allocated_len - response->len;
238         len = scpi->read_data(scpi->priv, &response->str[response->len], space);
239
240         if (len < 0) {
241                 sr_err("Incompletely read SCPI response.");
242                 return SR_ERR;
243         }
244
245         if (len > 0) {
246                 g_string_set_size(response, response->len + len);
247                 return len;
248         }
249
250         if (g_get_monotonic_time() > abs_timeout_us) {
251                 sr_err("Timed out waiting for SCPI response.");
252                 return SR_ERR_TIMEOUT;
253         }
254
255         return 0;
256 }
257
258 /**
259  * Send a SCPI command, receive the reply and store the reply in
260  * scpi_response, without mutex.
261  *
262  * @param scpi Previously initialised SCPI device structure.
263  * @param command The SCPI command to send to the device.
264  * @param scpi_response Pointer where to store the SCPI response.
265  *
266  * @return SR_OK on success, SR_ERR on failure.
267  */
268 static int scpi_get_data(struct sr_scpi_dev_inst *scpi,
269                                 const char *command, GString **scpi_response)
270 {
271         int ret;
272         GString *response;
273         int space;
274         gint64 timeout;
275
276         /* Optionally send caller provided command. */
277         if (command) {
278                 if (scpi_send(scpi, command) != SR_OK)
279                         return SR_ERR;
280         }
281
282         /* Initiate SCPI read operation. */
283         if (sr_scpi_read_begin(scpi) != SR_OK)
284                 return SR_ERR;
285
286         /* Keep reading until completion or until timeout. */
287         timeout = g_get_monotonic_time() + scpi->read_timeout_us;
288
289         response = *scpi_response;
290
291         while (!sr_scpi_read_complete(scpi)) {
292                 /* Resize the buffer when free space drops below a threshold. */
293                 space = response->allocated_len - response->len;
294                 if (space < 128) {
295                         int oldlen = response->len;
296                         g_string_set_size(response, oldlen + 1024);
297                         g_string_set_size(response, oldlen);
298                 }
299
300                 /* Read another chunk of the response. */
301                 ret = scpi_read_response(scpi, response, timeout);
302
303                 if (ret < 0)
304                         return ret;
305                 if (ret > 0)
306                         timeout = g_get_monotonic_time() + scpi->read_timeout_us;
307         }
308
309         return SR_OK;
310 }
311
312 SR_PRIV GSList *sr_scpi_scan(struct drv_context *drvc, GSList *options,
313                 struct sr_dev_inst *(*probe_device)(struct sr_scpi_dev_inst *scpi))
314 {
315         GSList *resources, *l, *devices;
316         struct sr_dev_inst *sdi;
317         const char *resource = NULL;
318         const char *serialcomm = NULL;
319         gchar **res;
320         unsigned i;
321
322         for (l = options; l; l = l->next) {
323                 struct sr_config *src = l->data;
324                 switch (src->key) {
325                 case SR_CONF_CONN:
326                         resource = g_variant_get_string(src->data, NULL);
327                         break;
328                 case SR_CONF_SERIALCOMM:
329                         serialcomm = g_variant_get_string(src->data, NULL);
330                         break;
331                 }
332         }
333
334         devices = NULL;
335         for (i = 0; i < ARRAY_SIZE(scpi_devs); i++) {
336                 if ((resource && strcmp(resource, scpi_devs[i]->prefix))
337                     || !scpi_devs[i]->scan)
338                         continue;
339                 resources = scpi_devs[i]->scan(drvc);
340                 for (l = resources; l; l = l->next) {
341                         res = g_strsplit(l->data, ":", 2);
342                         if (res[0] && (sdi = sr_scpi_scan_resource(drvc, res[0],
343                                        serialcomm ? serialcomm : res[1], probe_device))) {
344                                 devices = g_slist_append(devices, sdi);
345                                 sdi->connection_id = g_strdup(l->data);
346                         }
347                         g_strfreev(res);
348                 }
349                 g_slist_free_full(resources, g_free);
350         }
351
352         if (!devices && resource) {
353                 sdi = sr_scpi_scan_resource(drvc, resource, serialcomm, probe_device);
354                 if (sdi)
355                         devices = g_slist_append(NULL, sdi);
356         }
357
358         /* Tack a copy of the newly found devices onto the driver list. */
359         if (devices)
360                 drvc->instances = g_slist_concat(drvc->instances, g_slist_copy(devices));
361
362         return devices;
363 }
364
365 SR_PRIV struct sr_scpi_dev_inst *scpi_dev_inst_new(struct drv_context *drvc,
366                 const char *resource, const char *serialcomm)
367 {
368         struct sr_scpi_dev_inst *scpi = NULL;
369         const struct sr_scpi_dev_inst *scpi_dev;
370         gchar **params;
371         unsigned i;
372
373         for (i = 0; i < ARRAY_SIZE(scpi_devs); i++) {
374                 scpi_dev = scpi_devs[i];
375                 if (!strncmp(resource, scpi_dev->prefix, strlen(scpi_dev->prefix))) {
376                         sr_dbg("Opening %s device %s.", scpi_dev->name, resource);
377                         scpi = g_malloc(sizeof(*scpi));
378                         *scpi = *scpi_dev;
379                         scpi->priv = g_malloc0(scpi->priv_size);
380                         scpi->read_timeout_us = 1000 * 1000;
381                         params = g_strsplit(resource, "/", 0);
382                         if (scpi->dev_inst_new(scpi->priv, drvc, resource,
383                                                params, serialcomm) != SR_OK) {
384                                 sr_scpi_free(scpi);
385                                 scpi = NULL;
386                         }
387                         g_strfreev(params);
388                         break;
389                 }
390         }
391
392         return scpi;
393 }
394
395 /**
396  * Open SCPI device.
397  *
398  * @param scpi Previously initialized SCPI device structure.
399  *
400  * @return SR_OK on success, SR_ERR on failure.
401  */
402 SR_PRIV int sr_scpi_open(struct sr_scpi_dev_inst *scpi)
403 {
404         g_mutex_init(&scpi->scpi_mutex);
405
406         return scpi->open(scpi);
407 }
408
409 /**
410  * Add an event source for an SCPI device.
411  *
412  * @param session The session to add the event source to.
413  * @param scpi Previously initialized SCPI device structure.
414  * @param events Events to check for.
415  * @param timeout Max time to wait before the callback is called, ignored if 0.
416  * @param cb Callback function to add. Must not be NULL.
417  * @param cb_data Data for the callback function. Can be NULL.
418  *
419  * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments, or
420  *         SR_ERR_MALLOC upon memory allocation errors.
421  */
422 SR_PRIV int sr_scpi_source_add(struct sr_session *session,
423                 struct sr_scpi_dev_inst *scpi, int events, int timeout,
424                 sr_receive_data_callback cb, void *cb_data)
425 {
426         return scpi->source_add(session, scpi->priv, events, timeout, cb, cb_data);
427 }
428
429 /**
430  * Remove event source for an SCPI device.
431  *
432  * @param session The session to remove the event source from.
433  * @param scpi Previously initialized SCPI device structure.
434  *
435  * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments, or
436  *         SR_ERR_MALLOC upon memory allocation errors, SR_ERR_BUG upon
437  *         internal errors.
438  */
439 SR_PRIV int sr_scpi_source_remove(struct sr_session *session,
440                 struct sr_scpi_dev_inst *scpi)
441 {
442         return scpi->source_remove(session, scpi->priv);
443 }
444
445 /**
446  * Send a SCPI command.
447  *
448  * @param scpi Previously initialized SCPI device structure.
449  * @param format Format string, to be followed by any necessary arguments.
450  *
451  * @return SR_OK on success, SR_ERR on failure.
452  */
453 SR_PRIV int sr_scpi_send(struct sr_scpi_dev_inst *scpi,
454                          const char *format, ...)
455 {
456         va_list args;
457         int ret;
458
459         va_start(args, format);
460         g_mutex_lock(&scpi->scpi_mutex);
461         ret = scpi_send_variadic(scpi, format, args);
462         g_mutex_unlock(&scpi->scpi_mutex);
463         va_end(args);
464
465         return ret;
466 }
467
468 /**
469  * Send a SCPI command with a variadic argument list.
470  *
471  * @param scpi Previously initialized SCPI device structure.
472  * @param format Format string.
473  * @param args Argument list.
474  *
475  * @return SR_OK on success, SR_ERR on failure.
476  */
477 SR_PRIV int sr_scpi_send_variadic(struct sr_scpi_dev_inst *scpi,
478                          const char *format, va_list args)
479 {
480         int ret;
481
482         g_mutex_lock(&scpi->scpi_mutex);
483         ret = scpi_send_variadic(scpi, format, args);
484         g_mutex_unlock(&scpi->scpi_mutex);
485
486         return ret;
487 }
488
489 /**
490  * Begin receiving an SCPI reply.
491  *
492  * @param scpi Previously initialised SCPI device structure.
493  *
494  * @return SR_OK on success, SR_ERR on failure.
495  */
496 SR_PRIV int sr_scpi_read_begin(struct sr_scpi_dev_inst *scpi)
497 {
498         return scpi->read_begin(scpi->priv);
499 }
500
501 /**
502  * Read part of a response from SCPI device.
503  *
504  * @param scpi Previously initialised SCPI device structure.
505  * @param buf Buffer to store result.
506  * @param maxlen Maximum number of bytes to read.
507  *
508  * @return Number of bytes read, or SR_ERR upon failure.
509  */
510 SR_PRIV int sr_scpi_read_data(struct sr_scpi_dev_inst *scpi,
511                         char *buf, int maxlen)
512 {
513         int ret;
514
515         g_mutex_lock(&scpi->scpi_mutex);
516         ret = scpi_read_data(scpi, buf, maxlen);
517         g_mutex_unlock(&scpi->scpi_mutex);
518
519         return ret;
520 }
521
522 /**
523  * Send data to SCPI device.
524  *
525  * TODO: This is only implemented in TcpRaw, but never used.
526  * TODO: Use Mutex at all?
527  *
528  * @param scpi Previously initialised SCPI device structure.
529  * @param buf Buffer with data to send.
530  * @param len Number of bytes to send.
531  *
532  * @return Number of bytes read, or SR_ERR upon failure.
533  */
534 SR_PRIV int sr_scpi_write_data(struct sr_scpi_dev_inst *scpi,
535                         char *buf, int maxlen)
536 {
537         int ret;
538
539         g_mutex_lock(&scpi->scpi_mutex);
540         ret = scpi_write_data(scpi, buf, maxlen);
541         g_mutex_unlock(&scpi->scpi_mutex);
542
543         return ret;
544 }
545
546 /**
547  * Check whether a complete SCPI response has been received.
548  *
549  * @param scpi Previously initialised SCPI device structure.
550  *
551  * @return 1 if complete, 0 otherwise.
552  */
553 SR_PRIV int sr_scpi_read_complete(struct sr_scpi_dev_inst *scpi)
554 {
555         return scpi->read_complete(scpi->priv);
556 }
557
558 /**
559  * Close SCPI device.
560  *
561  * @param scpi Previously initialized SCPI device structure.
562  *
563  * @return SR_OK on success, SR_ERR on failure.
564  */
565 SR_PRIV int sr_scpi_close(struct sr_scpi_dev_inst *scpi)
566 {
567         int ret;
568
569         g_mutex_lock(&scpi->scpi_mutex);
570         ret = scpi->close(scpi);
571         g_mutex_unlock(&scpi->scpi_mutex);
572         g_mutex_clear(&scpi->scpi_mutex);
573
574         return ret;
575 }
576
577 /**
578  * Free SCPI device.
579  *
580  * @param scpi Previously initialized SCPI device structure. If NULL,
581  *             this function does nothing.
582  */
583 SR_PRIV void sr_scpi_free(struct sr_scpi_dev_inst *scpi)
584 {
585         if (!scpi)
586                 return;
587
588         scpi->free(scpi->priv);
589         g_free(scpi->priv);
590         g_free(scpi);
591 }
592
593 /**
594  * Send a SCPI command, receive the reply and store the reply in scpi_response.
595  *
596  * @param scpi Previously initialised SCPI device structure.
597  * @param command The SCPI command to send to the device (can be NULL).
598  * @param scpi_response Pointer where to store the SCPI response.
599  *
600  * @return SR_OK on success, SR_ERR* on failure.
601  */
602 SR_PRIV int sr_scpi_get_string(struct sr_scpi_dev_inst *scpi,
603                                const char *command, char **scpi_response)
604 {
605         GString *response;
606         response = g_string_sized_new(1024);
607
608         if (sr_scpi_get_data(scpi, command, &response) != SR_OK) {
609                 if (response)
610                         g_string_free(response, TRUE);
611                 return SR_ERR;
612         }
613
614         /* Get rid of trailing linefeed if present */
615         if (response->len >= 1 && response->str[response->len - 1] == '\n')
616                 g_string_truncate(response, response->len - 1);
617
618         /* Get rid of trailing carriage return if present */
619         if (response->len >= 1 && response->str[response->len - 1] == '\r')
620                 g_string_truncate(response, response->len - 1);
621
622         sr_spew("Got response: '%.70s', length %" G_GSIZE_FORMAT ".",
623                 response->str, response->len);
624
625         *scpi_response = g_string_free(response, FALSE);
626
627         return SR_OK;
628 }
629
630 /**
631  * Do a non-blocking read of up to the allocated length, and
632  * check if a timeout has occured.
633  *
634  * @param scpi Previously initialised SCPI device structure.
635  * @param response Buffer to which the response is appended.
636  * @param abs_timeout_us Absolute timeout in microseconds
637  *
638  * @return read length on success, SR_ERR* on failure.
639  */
640 SR_PRIV int sr_scpi_read_response(struct sr_scpi_dev_inst *scpi,
641                                   GString *response, gint64 abs_timeout_us)
642 {
643         int ret;
644
645         g_mutex_lock(&scpi->scpi_mutex);
646         ret = scpi_read_response(scpi, response, abs_timeout_us);
647         g_mutex_unlock(&scpi->scpi_mutex);
648
649         return ret;
650 }
651
652 SR_PRIV int sr_scpi_get_data(struct sr_scpi_dev_inst *scpi,
653                              const char *command, GString **scpi_response)
654 {
655         int ret;
656
657         g_mutex_lock(&scpi->scpi_mutex);
658         ret = scpi_get_data(scpi, command, scpi_response);
659         g_mutex_unlock(&scpi->scpi_mutex);
660
661         return ret;
662 }
663
664 /**
665  * Send a SCPI command, read the reply, parse it as a bool value and store the
666  * result in scpi_response.
667  *
668  * @param scpi Previously initialised SCPI device structure.
669  * @param command The SCPI command to send to the device (can be NULL).
670  * @param scpi_response Pointer where to store the parsed result.
671  *
672  * @return SR_OK on success, SR_ERR* on failure.
673  */
674 SR_PRIV int sr_scpi_get_bool(struct sr_scpi_dev_inst *scpi,
675                              const char *command, gboolean *scpi_response)
676 {
677         int ret;
678         char *response;
679
680         response = NULL;
681
682         ret = sr_scpi_get_string(scpi, command, &response);
683         if (ret != SR_OK && !response)
684                 return ret;
685
686         if (parse_strict_bool(response, scpi_response) == SR_OK)
687                 ret = SR_OK;
688         else
689                 ret = SR_ERR_DATA;
690
691         g_free(response);
692
693         return ret;
694 }
695
696 /**
697  * Send a SCPI command, read the reply, parse it as an integer and store the
698  * result in scpi_response.
699  *
700  * @param scpi Previously initialised SCPI device structure.
701  * @param command The SCPI command to send to the device (can be NULL).
702  * @param scpi_response Pointer where to store the parsed result.
703  *
704  * @return SR_OK on success, SR_ERR* on failure.
705  */
706 SR_PRIV int sr_scpi_get_int(struct sr_scpi_dev_inst *scpi,
707                             const char *command, int *scpi_response)
708 {
709         int ret;
710         char *response;
711
712         response = NULL;
713
714         ret = sr_scpi_get_string(scpi, command, &response);
715         if (ret != SR_OK && !response)
716                 return ret;
717
718         if (sr_atoi(response, scpi_response) == SR_OK)
719                 ret = SR_OK;
720         else
721                 ret = SR_ERR_DATA;
722
723         g_free(response);
724
725         return ret;
726 }
727
728 /**
729  * Send a SCPI command, read the reply, parse it as a float and store the
730  * result in scpi_response.
731  *
732  * @param scpi Previously initialised SCPI device structure.
733  * @param command The SCPI command to send to the device (can be NULL).
734  * @param scpi_response Pointer where to store the parsed result.
735  *
736  * @return SR_OK on success, SR_ERR* on failure.
737  */
738 SR_PRIV int sr_scpi_get_float(struct sr_scpi_dev_inst *scpi,
739                               const char *command, float *scpi_response)
740 {
741         int ret;
742         char *response;
743
744         response = NULL;
745
746         ret = sr_scpi_get_string(scpi, command, &response);
747         if (ret != SR_OK && !response)
748                 return ret;
749
750         if (sr_atof_ascii(response, scpi_response) == SR_OK)
751                 ret = SR_OK;
752         else
753                 ret = SR_ERR_DATA;
754
755         g_free(response);
756
757         return ret;
758 }
759
760 /**
761  * Send a SCPI command, read the reply, parse it as a double and store the
762  * result in scpi_response.
763  *
764  * @param scpi Previously initialised SCPI device structure.
765  * @param command The SCPI command to send to the device (can be NULL).
766  * @param scpi_response Pointer where to store the parsed result.
767  *
768  * @return SR_OK on success, SR_ERR* on failure.
769  */
770 SR_PRIV int sr_scpi_get_double(struct sr_scpi_dev_inst *scpi,
771                                const char *command, double *scpi_response)
772 {
773         int ret;
774         char *response;
775
776         response = NULL;
777
778         ret = sr_scpi_get_string(scpi, command, &response);
779         if (ret != SR_OK && !response)
780                 return ret;
781
782         if (sr_atod_ascii(response, scpi_response) == SR_OK)
783                 ret = SR_OK;
784         else
785                 ret = SR_ERR_DATA;
786
787         g_free(response);
788
789         return ret;
790 }
791
792 /**
793  * Send a SCPI *OPC? command, read the reply and return the result of the
794  * command.
795  *
796  * @param scpi Previously initialised SCPI device structure.
797  *
798  * @return SR_OK on success, SR_ERR* on failure.
799  */
800 SR_PRIV int sr_scpi_get_opc(struct sr_scpi_dev_inst *scpi)
801 {
802         unsigned int i;
803         gboolean opc;
804
805         for (i = 0; i < SCPI_READ_RETRIES; i++) {
806                 opc = FALSE;
807                 sr_scpi_get_bool(scpi, SCPI_CMD_OPC, &opc);
808                 if (opc)
809                         return SR_OK;
810                 g_usleep(SCPI_READ_RETRY_TIMEOUT_US);
811         }
812
813         return SR_ERR;
814 }
815
816 /**
817  * Send a SCPI command, read the reply, parse it as comma separated list of
818  * floats and store the as an result in scpi_response.
819  *
820  * @param scpi Previously initialised SCPI device structure.
821  * @param command The SCPI command to send to the device (can be NULL).
822  * @param scpi_response Pointer where to store the parsed result.
823  *
824  * @return SR_OK upon successfully parsing all values, SR_ERR* upon a parsing
825  *         error or upon no response. The allocated response must be freed by
826  *         the caller in the case of an SR_OK as well as in the case of
827  *         parsing error.
828  */
829 SR_PRIV int sr_scpi_get_floatv(struct sr_scpi_dev_inst *scpi,
830                                const char *command, GArray **scpi_response)
831 {
832         int ret;
833         float tmp;
834         char *response;
835         gchar **ptr, **tokens;
836         GArray *response_array;
837
838         response = NULL;
839         tokens = NULL;
840
841         ret = sr_scpi_get_string(scpi, command, &response);
842         if (ret != SR_OK && !response)
843                 return ret;
844
845         tokens = g_strsplit(response, ",", 0);
846         ptr = tokens;
847
848         response_array = g_array_sized_new(TRUE, FALSE, sizeof(float), 256);
849
850         while (*ptr) {
851                 if (sr_atof_ascii(*ptr, &tmp) == SR_OK)
852                         response_array = g_array_append_val(response_array,
853                                                             tmp);
854                 else
855                         ret = SR_ERR_DATA;
856
857                 ptr++;
858         }
859         g_strfreev(tokens);
860         g_free(response);
861
862         if (ret != SR_OK && response_array->len == 0) {
863                 g_array_free(response_array, TRUE);
864                 *scpi_response = NULL;
865                 return SR_ERR_DATA;
866         }
867
868         *scpi_response = response_array;
869
870         return ret;
871 }
872
873 /**
874  * Send a SCPI command, read the reply, parse it as comma separated list of
875  * unsigned 8 bit integers and store the as an result in scpi_response.
876  *
877  * @param scpi Previously initialised SCPI device structure.
878  * @param command The SCPI command to send to the device (can be NULL).
879  * @param scpi_response Pointer where to store the parsed result.
880  *
881  * @return SR_OK upon successfully parsing all values, SR_ERR* upon a parsing
882  *         error or upon no response. The allocated response must be freed by
883  *         the caller in the case of an SR_OK as well as in the case of
884  *         parsing error.
885  */
886 SR_PRIV int sr_scpi_get_uint8v(struct sr_scpi_dev_inst *scpi,
887                                const char *command, GArray **scpi_response)
888 {
889         int tmp, ret;
890         char *response;
891         gchar **ptr, **tokens;
892         GArray *response_array;
893
894         response = NULL;
895         tokens = NULL;
896
897         ret = sr_scpi_get_string(scpi, command, &response);
898         if (ret != SR_OK && !response)
899                 return ret;
900
901         tokens = g_strsplit(response, ",", 0);
902         ptr = tokens;
903
904         response_array = g_array_sized_new(TRUE, FALSE, sizeof(uint8_t), 256);
905
906         while (*ptr) {
907                 if (sr_atoi(*ptr, &tmp) == SR_OK)
908                         response_array = g_array_append_val(response_array,
909                                                             tmp);
910                 else
911                         ret = SR_ERR_DATA;
912
913                 ptr++;
914         }
915         g_strfreev(tokens);
916         g_free(response);
917
918         if (response_array->len == 0) {
919                 g_array_free(response_array, TRUE);
920                 *scpi_response = NULL;
921                 return SR_ERR_DATA;
922         }
923
924         *scpi_response = response_array;
925
926         return ret;
927 }
928
929 /**
930  * Send a SCPI command, read the reply, parse it as binary data with a
931  * "definite length block" header and store the as an result in scpi_response.
932  *
933  * @param scpi Previously initialised SCPI device structure.
934  * @param command The SCPI command to send to the device (can be NULL).
935  * @param scpi_response Pointer where to store the parsed result.
936  *
937  * @return SR_OK upon successfully parsing all values, SR_ERR* upon a parsing
938  *         error or upon no response. The allocated response must be freed by
939  *         the caller in the case of an SR_OK as well as in the case of
940  *         parsing error.
941  */
942 SR_PRIV int sr_scpi_get_block(struct sr_scpi_dev_inst *scpi,
943                                const char *command, GByteArray **scpi_response)
944 {
945         int ret;
946         GString* response;
947         char buf[10];
948         long llen;
949         long datalen;
950         gint64 timeout;
951
952         g_mutex_lock(&scpi->scpi_mutex);
953
954         if (command)
955                 if (scpi_send(scpi, command) != SR_OK) {
956                         g_mutex_unlock(&scpi->scpi_mutex);
957                         return SR_ERR;
958                 }
959
960         if (sr_scpi_read_begin(scpi) != SR_OK) {
961                 g_mutex_unlock(&scpi->scpi_mutex);
962                 return SR_ERR;
963         }
964
965         /*
966          * Assume an initial maximum length, optionally gets adjusted below.
967          * Prepare a NULL return value for when error paths will be taken.
968          */
969         response = g_string_sized_new(1024);
970
971         timeout = g_get_monotonic_time() + scpi->read_timeout_us;
972
973         *scpi_response = NULL;
974
975         /* Get (the first chunk of) the response. */
976         while (response->len < 2) {
977                 ret = scpi_read_response(scpi, response, timeout);
978                 if (ret < 0) {
979                         g_mutex_unlock(&scpi->scpi_mutex);
980                         g_string_free(response, TRUE);
981                         return ret;
982                 }
983         }
984
985         /*
986          * SCPI protocol data blocks are preceeded with a length spec.
987          * The length spec consists of a '#' marker, one digit which
988          * specifies the character count of the length spec, and the
989          * respective number of characters which specify the data block's
990          * length. Raw data bytes follow (thus one must no longer assume
991          * that the received input stream would be an ASCIIZ string).
992          *
993          * Get the data block length, and strip off the length spec from
994          * the input buffer, leaving just the data bytes.
995          */
996         if (response->str[0] != '#') {
997                 g_mutex_unlock(&scpi->scpi_mutex);
998                 g_string_free(response, TRUE);
999                 return SR_ERR_DATA;
1000         }
1001         buf[0] = response->str[1];
1002         buf[1] = '\0';
1003         ret = sr_atol(buf, &llen);
1004         if ((ret != SR_OK) || (llen == 0)) {
1005                 g_mutex_unlock(&scpi->scpi_mutex);
1006                 g_string_free(response, TRUE);
1007                 return ret;
1008         }
1009
1010         while (response->len < (unsigned long)(2 + llen)) {
1011                 ret = scpi_read_response(scpi, response, timeout);
1012                 if (ret < 0) {
1013                         g_mutex_unlock(&scpi->scpi_mutex);
1014                         g_string_free(response, TRUE);
1015                         return ret;
1016                 }
1017         }
1018
1019         memcpy(buf, &response->str[2], llen);
1020         buf[llen] = '\0';
1021         ret = sr_atol(buf, &datalen);
1022         if ((ret != SR_OK) || (datalen == 0)) {
1023                 g_mutex_unlock(&scpi->scpi_mutex);
1024                 g_string_free(response, TRUE);
1025                 return ret;
1026         }
1027         g_string_erase(response, 0, 2 + llen);
1028
1029         /*
1030          * If the initially assumed length does not cover the data block
1031          * length, then re-allocate the buffer size to the now known
1032          * length, and keep reading more chunks of response data.
1033          */
1034         if (response->len < (unsigned long)(datalen)) {
1035                 int oldlen = response->len;
1036                 g_string_set_size(response, datalen);
1037                 g_string_set_size(response, oldlen);
1038         }
1039
1040         while (response->len < (unsigned long)(datalen)) {
1041                 ret = scpi_read_response(scpi, response, timeout);
1042                 if (ret < 0) {
1043                         g_mutex_unlock(&scpi->scpi_mutex);
1044                         g_string_free(response, TRUE);
1045                         return ret;
1046                 }
1047                 if (ret > 0)
1048                         timeout = g_get_monotonic_time() + scpi->read_timeout_us;
1049         }
1050
1051         g_mutex_unlock(&scpi->scpi_mutex);
1052
1053         /* Convert received data to byte array. */
1054         *scpi_response = g_byte_array_new_take(
1055                 (guint8*)g_string_free(response, FALSE), datalen);
1056
1057         return SR_OK;
1058 }
1059
1060 /**
1061  * Send the *IDN? SCPI command, receive the reply, parse it and store the
1062  * reply as a sr_scpi_hw_info structure in the supplied scpi_response pointer.
1063  *
1064  * The hw_info structure must be freed by the caller via sr_scpi_hw_info_free().
1065  *
1066  * @param scpi Previously initialised SCPI device structure.
1067  * @param scpi_response Pointer where to store the hw_info structure.
1068  *
1069  * @return SR_OK upon success, SR_ERR* on failure.
1070  */
1071 SR_PRIV int sr_scpi_get_hw_id(struct sr_scpi_dev_inst *scpi,
1072                               struct sr_scpi_hw_info **scpi_response)
1073 {
1074         int num_tokens, ret;
1075         char *response;
1076         gchar **tokens;
1077         struct sr_scpi_hw_info *hw_info;
1078         gchar *idn_substr;
1079
1080         response = NULL;
1081         tokens = NULL;
1082
1083         ret = sr_scpi_get_string(scpi, SCPI_CMD_IDN, &response);
1084         if (ret != SR_OK && !response)
1085                 return ret;
1086
1087         /*
1088          * The response to a '*IDN?' is specified by the SCPI spec. It contains
1089          * a comma-separated list containing the manufacturer name, instrument
1090          * model, serial number of the instrument and the firmware version.
1091          */
1092         tokens = g_strsplit(response, ",", 0);
1093
1094         for (num_tokens = 0; tokens[num_tokens] != NULL; num_tokens++);
1095
1096         if (num_tokens < 4) {
1097                 sr_dbg("IDN response not according to spec: %80.s.", response);
1098                 g_strfreev(tokens);
1099                 g_free(response);
1100                 return SR_ERR_DATA;
1101         }
1102         g_free(response);
1103
1104         hw_info = g_malloc0(sizeof(struct sr_scpi_hw_info));
1105
1106         idn_substr = g_strstr_len(tokens[0], -1, "IDN ");
1107         if (idn_substr == NULL)
1108                 hw_info->manufacturer = g_strstrip(g_strdup(tokens[0]));
1109         else
1110                 hw_info->manufacturer = g_strstrip(g_strdup(idn_substr + 4));
1111
1112         hw_info->model = g_strstrip(g_strdup(tokens[1]));
1113         hw_info->serial_number = g_strstrip(g_strdup(tokens[2]));
1114         hw_info->firmware_version = g_strstrip(g_strdup(tokens[3]));
1115
1116         g_strfreev(tokens);
1117
1118         *scpi_response = hw_info;
1119
1120         return SR_OK;
1121 }
1122
1123 /**
1124  * Free a sr_scpi_hw_info struct.
1125  *
1126  * @param hw_info Pointer to the struct to free. If NULL, this
1127  *                function does nothing.
1128  */
1129 SR_PRIV void sr_scpi_hw_info_free(struct sr_scpi_hw_info *hw_info)
1130 {
1131         if (!hw_info)
1132                 return;
1133
1134         g_free(hw_info->manufacturer);
1135         g_free(hw_info->model);
1136         g_free(hw_info->serial_number);
1137         g_free(hw_info->firmware_version);
1138         g_free(hw_info);
1139 }
1140
1141 SR_PRIV const char *sr_vendor_alias(const char *raw_vendor)
1142 {
1143         unsigned int i;
1144
1145         for (i = 0; i < ARRAY_SIZE(scpi_vendors); i++) {
1146                 if (!g_ascii_strcasecmp(raw_vendor, scpi_vendors[i][0]))
1147                         return scpi_vendors[i][1];
1148         }
1149
1150         return raw_vendor;
1151 }
1152
1153 SR_PRIV const char *sr_scpi_cmd_get(const struct scpi_command *cmdtable,
1154                 int command)
1155 {
1156         unsigned int i;
1157         const char *cmd;
1158
1159         if (!cmdtable)
1160                 return NULL;
1161
1162         cmd = NULL;
1163         for (i = 0; cmdtable[i].string; i++) {
1164                 if (cmdtable[i].command == command) {
1165                         cmd = cmdtable[i].string;
1166                         break;
1167                 }
1168         }
1169
1170         return cmd;
1171 }
1172
1173 SR_PRIV int sr_scpi_cmd(const struct sr_dev_inst *sdi,
1174                 const struct scpi_command *cmdtable,
1175                 int channel_command, const char *channel_name,
1176                 int command, ...)
1177 {
1178         struct sr_scpi_dev_inst *scpi;
1179         va_list args;
1180         int ret;
1181         const char *channel_cmd;
1182         const char *cmd;
1183
1184         scpi = sdi->conn;
1185
1186         if (!(cmd = sr_scpi_cmd_get(cmdtable, command))) {
1187                 /* Device does not implement this command, that's OK. */
1188                 return SR_OK;
1189         }
1190
1191         g_mutex_lock(&scpi->scpi_mutex);
1192
1193         /* Select channel. */
1194         channel_cmd = sr_scpi_cmd_get(cmdtable, channel_command);
1195         if (channel_cmd && channel_name &&
1196                         g_strcmp0(channel_name, scpi->actual_channel_name)) {
1197                 sr_spew("sr_scpi_cmd(): new channel = %s", channel_name);
1198                 scpi->actual_channel_name = channel_name;
1199                 ret = scpi_send(scpi, channel_cmd, channel_name);
1200                 if (ret != SR_OK)
1201                         return ret;
1202         }
1203
1204         va_start(args, command);
1205         ret = scpi_send_variadic(scpi, cmd, args);
1206         va_end(args);
1207
1208         g_mutex_unlock(&scpi->scpi_mutex);
1209
1210         return ret;
1211 }
1212
1213 SR_PRIV int sr_scpi_cmd_resp(const struct sr_dev_inst *sdi,
1214                 const struct scpi_command *cmdtable,
1215                 int channel_command, const char *channel_name,
1216                 GVariant **gvar, const GVariantType *gvtype, int command, ...)
1217 {
1218         struct sr_scpi_dev_inst *scpi;
1219         va_list args;
1220         const char *channel_cmd;
1221         const char *cmd;
1222         GString *response;
1223         char *s;
1224         gboolean b;
1225         double d;
1226         int ret;
1227
1228         scpi = sdi->conn;
1229
1230         if (!(cmd = sr_scpi_cmd_get(cmdtable, command))) {
1231                 /* Device does not implement this command. */
1232                 return SR_ERR_NA;
1233         }
1234
1235         g_mutex_lock(&scpi->scpi_mutex);
1236
1237         /* Select channel. */
1238         channel_cmd = sr_scpi_cmd_get(cmdtable, channel_command);
1239         if (channel_cmd && channel_name &&
1240                         g_strcmp0(channel_name, scpi->actual_channel_name)) {
1241                 sr_spew("sr_scpi_cmd_get(): new channel = %s", channel_name);
1242                 scpi->actual_channel_name = channel_name;
1243                 ret = scpi_send(scpi, channel_cmd, channel_name);
1244                 if (ret != SR_OK)
1245                         return ret;
1246         }
1247
1248         va_start(args, command);
1249         ret = scpi_send_variadic(scpi, cmd, args);
1250         va_end(args);
1251         if (ret != SR_OK) {
1252                 g_mutex_unlock(&scpi->scpi_mutex);
1253                 return ret;
1254         }
1255
1256         response = g_string_sized_new(1024);
1257         ret = scpi_get_data(scpi, NULL, &response);
1258         if (ret != SR_OK) {
1259                 g_mutex_unlock(&scpi->scpi_mutex);
1260                 if (response)
1261                         g_string_free(response, TRUE);
1262                 return ret;
1263         }
1264
1265         g_mutex_unlock(&scpi->scpi_mutex);
1266
1267         /* Get rid of trailing linefeed if present */
1268         if (response->len >= 1 && response->str[response->len - 1] == '\n')
1269                 g_string_truncate(response, response->len - 1);
1270
1271         /* Get rid of trailing carriage return if present */
1272         if (response->len >= 1 && response->str[response->len - 1] == '\r')
1273                 g_string_truncate(response, response->len - 1);
1274
1275         s = g_string_free(response, FALSE);
1276
1277         ret = SR_OK;
1278         if (g_variant_type_equal(gvtype, G_VARIANT_TYPE_BOOLEAN)) {
1279                 if ((ret = parse_strict_bool(s, &b)) == SR_OK)
1280                         *gvar = g_variant_new_boolean(b);
1281         } else if (g_variant_type_equal(gvtype, G_VARIANT_TYPE_DOUBLE)) {
1282                 if ((ret = sr_atod_ascii(s, &d)) == SR_OK)
1283                         *gvar = g_variant_new_double(d);
1284         } else if (g_variant_type_equal(gvtype, G_VARIANT_TYPE_STRING)) {
1285                 *gvar = g_variant_new_string(s);
1286         } else {
1287                 sr_err("Unable to convert to desired GVariant type.");
1288                 ret = SR_ERR_NA;
1289         }
1290
1291         g_free(s);
1292
1293         return ret;
1294 }