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