2 * This file is part of the libsigrok project.
4 * Copyright (C) 2013 poljar (Damir Jelić) <poljarinho@gmail.com>
5 * Copyright (C) 2015 Bert Vermeulen <bert@biot.com>
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.
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.
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/>.
24 #include <libsigrok/libsigrok.h>
25 #include "libsigrok-internal.h"
28 #define LOG_PREFIX "scpi"
30 #define SCPI_READ_RETRIES 100
31 #define SCPI_READ_RETRY_TIMEOUT_US (10 * 1000)
33 static const char *scpi_vendors[][2] = {
34 { "Agilent Technologies", "Agilent" },
35 { "CHROMA", "Chroma" },
36 { "Chroma ATE", "Chroma" },
37 { "HEWLETT-PACKARD", "HP" },
38 { "Keysight Technologies", "Keysight" },
39 { "PHILIPS", "Philips" },
40 { "RIGOL TECHNOLOGIES", "Rigol" },
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.
48 * @param str String to convert.
49 * @param ret Pointer to a gboolean where the result of the conversion will be
52 * @return SR_OK on success, SR_ERR on failure.
54 static int parse_strict_bool(const char *str, gboolean *ret)
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)) {
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)) {
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;
88 static const struct sr_scpi_dev_inst *scpi_devs[] = {
91 #ifdef HAVE_LIBUSB_1_0
92 &scpi_usbtmc_libusb_dev,
103 #ifdef HAVE_SERIAL_COMM
104 &scpi_serial_dev, /* Must be last as it matches any resource. */
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))
112 struct sr_scpi_dev_inst *scpi;
113 struct sr_dev_inst *sdi;
115 if (!(scpi = scpi_dev_inst_new(drvc, resource, serialcomm)))
118 if (sr_scpi_open(scpi) != SR_OK) {
119 sr_info("Couldn't open SCPI device.");
124 sdi = probe_device(scpi);
129 sdi->status = SR_ST_INACTIVE;
137 * Send a SCPI command with a variadic argument list without mutex.
139 * @param scpi Previously initialized SCPI device structure.
140 * @param format Format string.
141 * @param args Argument list.
143 * @return SR_OK on success, SR_ERR on failure.
145 static int scpi_send_variadic(struct sr_scpi_dev_inst *scpi,
146 const char *format, va_list args)
152 /* Get length of buffer required. */
153 va_copy(args_copy, args);
154 len = sr_vsnprintf_ascii(NULL, 0, format, args_copy);
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')
164 ret = scpi->send(scpi->priv, buf);
166 /* Free command buffer. */
173 * Send a SCPI command without mutex.
175 * @param scpi Previously initialized SCPI device structure.
176 * @param format Format string, to be followed by any necessary arguments.
178 * @return SR_OK on success, SR_ERR on failure.
180 static int scpi_send(struct sr_scpi_dev_inst *scpi, const char *format, ...)
185 va_start(args, format);
186 ret = scpi_send_variadic(scpi, format, args);
193 * Send data to SCPI device without mutex.
195 * TODO: This is only implemented in TcpRaw, but never used.
196 * TODO: Use Mutex at all?
198 * @param scpi Previously initialised SCPI device structure.
199 * @param buf Buffer with data to send.
200 * @param len Number of bytes to send.
202 * @return Number of bytes read, or SR_ERR upon failure.
204 static int scpi_write_data(struct sr_scpi_dev_inst *scpi, char *buf, int maxlen)
206 return scpi->write_data(scpi->priv, buf, maxlen);
210 * Read part of a response from SCPI device without mutex.
212 * @param scpi Previously initialised SCPI device structure.
213 * @param buf Buffer to store result.
214 * @param maxlen Maximum number of bytes to read.
216 * @return Number of bytes read, or SR_ERR upon failure.
218 static int scpi_read_data(struct sr_scpi_dev_inst *scpi, char *buf, int maxlen)
220 return scpi->read_data(scpi->priv, buf, maxlen);
224 * Do a non-blocking read of up to the allocated length, and
225 * check if a timeout has occured, without mutex.
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
231 * @return read length on success, SR_ERR* on failure.
233 static int scpi_read_response(struct sr_scpi_dev_inst *scpi,
234 GString *response, gint64 abs_timeout_us)
238 space = response->allocated_len - response->len;
239 len = scpi->read_data(scpi->priv, &response->str[response->len], space);
242 sr_err("Incompletely read SCPI response.");
247 g_string_set_size(response, response->len + len);
251 if (g_get_monotonic_time() > abs_timeout_us) {
252 sr_err("Timed out waiting for SCPI response.");
253 return SR_ERR_TIMEOUT;
260 * Send a SCPI command, receive the reply and store the reply in
261 * scpi_response, without mutex.
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.
267 * @return SR_OK on success, SR_ERR on failure.
269 static int scpi_get_data(struct sr_scpi_dev_inst *scpi,
270 const char *command, GString **scpi_response)
277 /* Optionally send caller provided command. */
279 if (scpi_send(scpi, command) != SR_OK)
283 /* Initiate SCPI read operation. */
284 if (sr_scpi_read_begin(scpi) != SR_OK)
287 /* Keep reading until completion or until timeout. */
288 timeout = g_get_monotonic_time() + scpi->read_timeout_us;
290 response = *scpi_response;
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;
296 int oldlen = response->len;
297 g_string_set_size(response, oldlen + 1024);
298 g_string_set_size(response, oldlen);
301 /* Read another chunk of the response. */
302 ret = scpi_read_response(scpi, response, timeout);
307 timeout = g_get_monotonic_time() + scpi->read_timeout_us;
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))
316 GSList *resources, *l, *devices;
317 struct sr_dev_inst *sdi;
318 const char *resource, *conn;
319 const char *serialcomm, *comm;
325 (void)sr_serial_extract_options(options, &resource, &serialcomm);
328 for (i = 0; i < ARRAY_SIZE(scpi_devs); i++) {
329 if (resource && strcmp(resource, scpi_devs[i]->prefix) != 0)
331 if (!scpi_devs[i]->scan)
333 resources = scpi_devs[i]->scan(drvc);
334 for (l = resources; l; l = l->next) {
335 res = g_strsplit(l->data, ":", 2);
341 comm = serialcomm ? : res[1];
342 sdi = sr_scpi_scan_resource(drvc, conn, comm, probe_device);
344 devices = g_slist_append(devices, sdi);
345 sdi->connection_id = g_strdup(l->data);
349 g_slist_free_full(resources, g_free);
352 if (!devices && resource) {
353 sdi = sr_scpi_scan_resource(drvc, resource, serialcomm, probe_device);
355 devices = g_slist_append(NULL, sdi);
358 /* Tack a copy of the newly found devices onto the driver list. */
360 drvc->instances = g_slist_concat(drvc->instances, g_slist_copy(devices));
365 SR_PRIV struct sr_scpi_dev_inst *scpi_dev_inst_new(struct drv_context *drvc,
366 const char *resource, const char *serialcomm)
368 struct sr_scpi_dev_inst *scpi = NULL;
369 const struct sr_scpi_dev_inst *scpi_dev;
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));
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) {
398 * @param scpi Previously initialized SCPI device structure.
400 * @return SR_OK on success, SR_ERR on failure.
402 SR_PRIV int sr_scpi_open(struct sr_scpi_dev_inst *scpi)
404 g_mutex_init(&scpi->scpi_mutex);
406 return scpi->open(scpi);
410 * Get the connection ID of the SCPI device.
412 * Callers must free the allocated memory regardless of the routine's
413 * return code. See @ref g_free().
415 * @param[in] scpi Previously initialized SCPI device structure.
416 * @param[out] connection_id Pointer where to store the connection ID.
418 * @return SR_OK on success, SR_ERR on failure.
420 SR_PRIV int sr_scpi_connection_id(struct sr_scpi_dev_inst *scpi,
421 char **connection_id)
423 return scpi->connection_id(scpi, connection_id);
427 * Add an event source for an SCPI device.
429 * @param session The session to add the event source to.
430 * @param scpi Previously initialized SCPI device structure.
431 * @param events Events to check for.
432 * @param timeout Max time to wait before the callback is called, ignored if 0.
433 * @param cb Callback function to add. Must not be NULL.
434 * @param cb_data Data for the callback function. Can be NULL.
436 * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments, or
437 * SR_ERR_MALLOC upon memory allocation errors.
439 SR_PRIV int sr_scpi_source_add(struct sr_session *session,
440 struct sr_scpi_dev_inst *scpi, int events, int timeout,
441 sr_receive_data_callback cb, void *cb_data)
443 return scpi->source_add(session, scpi->priv, events, timeout, cb, cb_data);
447 * Remove event source for an SCPI device.
449 * @param session The session to remove the event source from.
450 * @param scpi Previously initialized SCPI device structure.
452 * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments, or
453 * SR_ERR_MALLOC upon memory allocation errors, SR_ERR_BUG upon
456 SR_PRIV int sr_scpi_source_remove(struct sr_session *session,
457 struct sr_scpi_dev_inst *scpi)
459 return scpi->source_remove(session, scpi->priv);
463 * Send a SCPI command.
465 * @param scpi Previously initialized SCPI device structure.
466 * @param format Format string, to be followed by any necessary arguments.
468 * @return SR_OK on success, SR_ERR on failure.
470 SR_PRIV int sr_scpi_send(struct sr_scpi_dev_inst *scpi,
471 const char *format, ...)
476 va_start(args, format);
477 g_mutex_lock(&scpi->scpi_mutex);
478 ret = scpi_send_variadic(scpi, format, args);
479 g_mutex_unlock(&scpi->scpi_mutex);
486 * Send a SCPI command with a variadic argument list.
488 * @param scpi Previously initialized SCPI device structure.
489 * @param format Format string.
490 * @param args Argument list.
492 * @return SR_OK on success, SR_ERR on failure.
494 SR_PRIV int sr_scpi_send_variadic(struct sr_scpi_dev_inst *scpi,
495 const char *format, va_list args)
499 g_mutex_lock(&scpi->scpi_mutex);
500 ret = scpi_send_variadic(scpi, format, args);
501 g_mutex_unlock(&scpi->scpi_mutex);
507 * Begin receiving an SCPI reply.
509 * @param scpi Previously initialised SCPI device structure.
511 * @return SR_OK on success, SR_ERR on failure.
513 SR_PRIV int sr_scpi_read_begin(struct sr_scpi_dev_inst *scpi)
515 return scpi->read_begin(scpi->priv);
519 * Read part of a response from SCPI device.
521 * @param scpi Previously initialised SCPI device structure.
522 * @param buf Buffer to store result.
523 * @param maxlen Maximum number of bytes to read.
525 * @return Number of bytes read, or SR_ERR upon failure.
527 SR_PRIV int sr_scpi_read_data(struct sr_scpi_dev_inst *scpi,
528 char *buf, int maxlen)
532 g_mutex_lock(&scpi->scpi_mutex);
533 ret = scpi_read_data(scpi, buf, maxlen);
534 g_mutex_unlock(&scpi->scpi_mutex);
540 * Send data to SCPI device.
542 * TODO: This is only implemented in TcpRaw, but never used.
543 * TODO: Use Mutex at all?
545 * @param scpi Previously initialised SCPI device structure.
546 * @param buf Buffer with data to send.
547 * @param len Number of bytes to send.
549 * @return Number of bytes read, or SR_ERR upon failure.
551 SR_PRIV int sr_scpi_write_data(struct sr_scpi_dev_inst *scpi,
552 char *buf, int maxlen)
556 g_mutex_lock(&scpi->scpi_mutex);
557 ret = scpi_write_data(scpi, buf, maxlen);
558 g_mutex_unlock(&scpi->scpi_mutex);
564 * Check whether a complete SCPI response has been received.
566 * @param scpi Previously initialised SCPI device structure.
568 * @return 1 if complete, 0 otherwise.
570 SR_PRIV int sr_scpi_read_complete(struct sr_scpi_dev_inst *scpi)
572 return scpi->read_complete(scpi->priv);
578 * @param scpi Previously initialized SCPI device structure.
580 * @return SR_OK on success, SR_ERR on failure.
582 SR_PRIV int sr_scpi_close(struct sr_scpi_dev_inst *scpi)
586 g_mutex_lock(&scpi->scpi_mutex);
587 ret = scpi->close(scpi);
588 g_mutex_unlock(&scpi->scpi_mutex);
589 g_mutex_clear(&scpi->scpi_mutex);
597 * @param scpi Previously initialized SCPI device structure. If NULL,
598 * this function does nothing.
600 SR_PRIV void sr_scpi_free(struct sr_scpi_dev_inst *scpi)
605 scpi->free(scpi->priv);
607 g_free(scpi->actual_channel_name);
612 * Send a SCPI command, receive the reply and store the reply in scpi_response.
614 * Callers must free the allocated memory regardless of the routine's
615 * return code. See @ref g_free().
617 * @param[in] scpi Previously initialised SCPI device structure.
618 * @param[in] command The SCPI command to send to the device (can be NULL).
619 * @param[out] scpi_response Pointer where to store the SCPI response.
621 * @return SR_OK on success, SR_ERR* on failure.
623 SR_PRIV int sr_scpi_get_string(struct sr_scpi_dev_inst *scpi,
624 const char *command, char **scpi_response)
628 *scpi_response = NULL;
630 response = g_string_sized_new(1024);
631 if (sr_scpi_get_data(scpi, command, &response) != SR_OK) {
633 g_string_free(response, TRUE);
637 /* Get rid of trailing linefeed if present */
638 if (response->len >= 1 && response->str[response->len - 1] == '\n')
639 g_string_truncate(response, response->len - 1);
641 /* Get rid of trailing carriage return if present */
642 if (response->len >= 1 && response->str[response->len - 1] == '\r')
643 g_string_truncate(response, response->len - 1);
645 sr_spew("Got response: '%.70s', length %" G_GSIZE_FORMAT ".",
646 response->str, response->len);
648 *scpi_response = g_string_free(response, FALSE);
654 * Do a non-blocking read of up to the allocated length, and
655 * check if a timeout has occured.
657 * @param scpi Previously initialised SCPI device structure.
658 * @param response Buffer to which the response is appended.
659 * @param abs_timeout_us Absolute timeout in microseconds
661 * @return read length on success, SR_ERR* on failure.
663 SR_PRIV int sr_scpi_read_response(struct sr_scpi_dev_inst *scpi,
664 GString *response, gint64 abs_timeout_us)
668 g_mutex_lock(&scpi->scpi_mutex);
669 ret = scpi_read_response(scpi, response, abs_timeout_us);
670 g_mutex_unlock(&scpi->scpi_mutex);
675 SR_PRIV int sr_scpi_get_data(struct sr_scpi_dev_inst *scpi,
676 const char *command, GString **scpi_response)
680 g_mutex_lock(&scpi->scpi_mutex);
681 ret = scpi_get_data(scpi, command, scpi_response);
682 g_mutex_unlock(&scpi->scpi_mutex);
688 * Send a SCPI command, read the reply, parse it as a bool value and store the
689 * result in scpi_response.
691 * @param scpi Previously initialised SCPI device structure.
692 * @param command The SCPI command to send to the device (can be NULL).
693 * @param scpi_response Pointer where to store the parsed result.
695 * @return SR_OK on success, SR_ERR* on failure.
697 SR_PRIV int sr_scpi_get_bool(struct sr_scpi_dev_inst *scpi,
698 const char *command, gboolean *scpi_response)
705 ret = sr_scpi_get_string(scpi, command, &response);
706 if (ret != SR_OK && !response)
709 if (parse_strict_bool(response, scpi_response) == SR_OK)
720 * Send a SCPI command, read the reply, parse it as an integer and store the
721 * result in scpi_response.
723 * @param scpi Previously initialised SCPI device structure.
724 * @param command The SCPI command to send to the device (can be NULL).
725 * @param scpi_response Pointer where to store the parsed result.
727 * @return SR_OK on success, SR_ERR* on failure.
729 SR_PRIV int sr_scpi_get_int(struct sr_scpi_dev_inst *scpi,
730 const char *command, int *scpi_response)
733 struct sr_rational ret_rational;
738 ret = sr_scpi_get_string(scpi, command, &response);
739 if (ret != SR_OK && !response)
742 ret = sr_parse_rational(response, &ret_rational);
743 if (ret == SR_OK && (ret_rational.p % ret_rational.q) == 0) {
744 *scpi_response = ret_rational.p / ret_rational.q;
746 sr_dbg("get_int: non-integer rational=%" PRId64 "/%" PRIu64,
747 ret_rational.p, ret_rational.q);
757 * Send a SCPI command, read the reply, parse it as a float and store the
758 * result in scpi_response.
760 * @param scpi Previously initialised SCPI device structure.
761 * @param command The SCPI command to send to the device (can be NULL).
762 * @param scpi_response Pointer where to store the parsed result.
764 * @return SR_OK on success, SR_ERR* on failure.
766 SR_PRIV int sr_scpi_get_float(struct sr_scpi_dev_inst *scpi,
767 const char *command, float *scpi_response)
774 ret = sr_scpi_get_string(scpi, command, &response);
775 if (ret != SR_OK && !response)
778 if (sr_atof_ascii(response, scpi_response) == SR_OK)
789 * Send a SCPI command, read the reply, parse it as a double and store the
790 * result in scpi_response.
792 * @param scpi Previously initialised SCPI device structure.
793 * @param command The SCPI command to send to the device (can be NULL).
794 * @param scpi_response Pointer where to store the parsed result.
796 * @return SR_OK on success, SR_ERR* on failure.
798 SR_PRIV int sr_scpi_get_double(struct sr_scpi_dev_inst *scpi,
799 const char *command, double *scpi_response)
806 ret = sr_scpi_get_string(scpi, command, &response);
807 if (ret != SR_OK && !response)
810 if (sr_atod_ascii(response, scpi_response) == SR_OK)
821 * Send a SCPI *OPC? command, read the reply and return the result of the
824 * @param scpi Previously initialised SCPI device structure.
826 * @return SR_OK on success, SR_ERR* on failure.
828 SR_PRIV int sr_scpi_get_opc(struct sr_scpi_dev_inst *scpi)
833 for (i = 0; i < SCPI_READ_RETRIES; i++) {
835 sr_scpi_get_bool(scpi, SCPI_CMD_OPC, &opc);
838 g_usleep(SCPI_READ_RETRY_TIMEOUT_US);
845 * Send a SCPI command, read the reply, parse it as comma separated list of
846 * floats and store the as an result in scpi_response.
848 * Callers must free the allocated memory (unless it's NULL) regardless of
849 * the routine's return code. See @ref g_array_free().
851 * @param[in] scpi Previously initialised SCPI device structure.
852 * @param[in] command The SCPI command to send to the device (can be NULL).
853 * @param[out] scpi_response Pointer where to store the parsed result.
855 * @return SR_OK upon successfully parsing all values, SR_ERR* upon a parsing
856 * error or upon no response.
858 SR_PRIV int sr_scpi_get_floatv(struct sr_scpi_dev_inst *scpi,
859 const char *command, GArray **scpi_response)
864 gchar **ptr, **tokens;
866 GArray *response_array;
868 *scpi_response = NULL;
871 ret = sr_scpi_get_string(scpi, command, &response);
872 if (ret != SR_OK && !response)
875 tokens = g_strsplit(response, ",", 0);
876 token_count = g_strv_length(tokens);
878 response_array = g_array_sized_new(TRUE, FALSE,
879 sizeof(float), token_count + 1);
883 ret = sr_atof_ascii(*ptr, &tmp);
888 response_array = g_array_append_val(response_array, tmp);
894 if (ret != SR_OK && response_array->len == 0) {
895 g_array_free(response_array, TRUE);
899 *scpi_response = response_array;
905 * Send a SCPI command, read the reply, parse it as comma separated list of
906 * unsigned 8 bit integers and store the as an result in scpi_response.
908 * Callers must free the allocated memory (unless it's NULL) regardless of
909 * the routine's return code. See @ref g_array_free().
911 * @param[in] scpi Previously initialised SCPI device structure.
912 * @param[in] command The SCPI command to send to the device (can be NULL).
913 * @param[out] scpi_response Pointer where to store the parsed result.
915 * @return SR_OK upon successfully parsing all values, SR_ERR* upon a parsing
916 * error or upon no response.
918 SR_PRIV int sr_scpi_get_uint8v(struct sr_scpi_dev_inst *scpi,
919 const char *command, GArray **scpi_response)
923 gchar **ptr, **tokens;
925 GArray *response_array;
927 *scpi_response = NULL;
930 ret = sr_scpi_get_string(scpi, command, &response);
931 if (ret != SR_OK && !response)
934 tokens = g_strsplit(response, ",", 0);
935 token_count = g_strv_length(tokens);
937 response_array = g_array_sized_new(TRUE, FALSE,
938 sizeof(uint8_t), token_count + 1);
942 ret = sr_atoi(*ptr, &tmp);
947 response_array = g_array_append_val(response_array, tmp);
953 if (response_array->len == 0) {
954 g_array_free(response_array, TRUE);
958 *scpi_response = response_array;
964 * Send a SCPI command, read the reply, parse it as binary data with a
965 * "definite length block" header and store the as an result in scpi_response.
967 * Callers must free the allocated memory (unless it's NULL) regardless of
968 * the routine's return code. See @ref g_byte_array_free().
970 * @param[in] scpi Previously initialised SCPI device structure.
971 * @param[in] command The SCPI command to send to the device (can be NULL).
972 * @param[out] scpi_response Pointer where to store the parsed result.
974 * @return SR_OK upon successfully parsing all values, SR_ERR* upon a parsing
975 * error or upon no response.
977 SR_PRIV int sr_scpi_get_block(struct sr_scpi_dev_inst *scpi,
978 const char *command, GByteArray **scpi_response)
988 *scpi_response = NULL;
990 g_mutex_lock(&scpi->scpi_mutex);
993 if (scpi_send(scpi, command) != SR_OK) {
994 g_mutex_unlock(&scpi->scpi_mutex);
998 if (sr_scpi_read_begin(scpi) != SR_OK) {
999 g_mutex_unlock(&scpi->scpi_mutex);
1004 * Assume an initial maximum length, optionally gets adjusted below.
1005 * Prepare a NULL return value for when error paths will be taken.
1007 response = g_string_sized_new(1024);
1009 timeout = g_get_monotonic_time() + scpi->read_timeout_us;
1011 /* Get (the first chunk of) the response. */
1013 ret = scpi_read_response(scpi, response, timeout);
1015 g_mutex_unlock(&scpi->scpi_mutex);
1016 g_string_free(response, TRUE);
1019 } while (response->len < 2);
1022 * SCPI protocol data blocks are preceeded with a length spec.
1023 * The length spec consists of a '#' marker, one digit which
1024 * specifies the character count of the length spec, and the
1025 * respective number of characters which specify the data block's
1026 * length. Raw data bytes follow (thus one must no longer assume
1027 * that the received input stream would be an ASCIIZ string).
1029 * Get the data block length, and strip off the length spec from
1030 * the input buffer, leaving just the data bytes.
1032 if (response->str[0] != '#') {
1033 g_mutex_unlock(&scpi->scpi_mutex);
1034 g_string_free(response, TRUE);
1037 buf[0] = response->str[1];
1039 ret = sr_atol(buf, &llen);
1041 * The form "#0..." is legal, and does not mean "empty response",
1042 * but means that the number of data bytes is not known (or was
1043 * not communicated) at this time. Instead the block ends at an
1044 * "END MESSAGE" termination sequence. Which translates to active
1045 * EOI while a text line termination is sent (CR or LF, and this
1046 * text line termination is not part of the block's data value).
1047 * Since this kind of #0... response is considered rare, and
1048 * depends on specific support in physical transports underneath
1049 * the SCPI layer, let's flag the condition and bail out with an
1050 * error here, until it's found to be a genuine issue in the field.
1052 * The SCPI 1999.0 specification (see page 220 and following in
1053 * the "HCOPy" description) references IEEE 488.2, especially
1054 * section 8.7.9 for DEFINITE LENGTH and section 8.7.10 for
1055 * INDEFINITE LENGTH ARBITRARY BLOCK RESPONSE DATA. The latter
1056 * with a leading "#0" length and a trailing "NL^END" marker.
1058 if (ret == SR_OK && !llen) {
1059 sr_err("unsupported INDEFINITE LENGTH ARBITRARY BLOCK RESPONSE");
1063 g_mutex_unlock(&scpi->scpi_mutex);
1064 g_string_free(response, TRUE);
1068 while (response->len < (unsigned long)(2 + llen)) {
1069 ret = scpi_read_response(scpi, response, timeout);
1071 g_mutex_unlock(&scpi->scpi_mutex);
1072 g_string_free(response, TRUE);
1077 memcpy(buf, &response->str[2], llen);
1079 ret = sr_atol(buf, &datalen);
1080 if ((ret != SR_OK) || (datalen == 0)) {
1081 g_mutex_unlock(&scpi->scpi_mutex);
1082 g_string_free(response, TRUE);
1085 g_string_erase(response, 0, 2 + llen);
1088 * Re-allocate the buffer size to the now known length
1089 * and keep reading more chunks of response data.
1091 oldlen = response->len;
1092 g_string_set_size(response, datalen);
1093 g_string_set_size(response, oldlen);
1095 if (oldlen < (unsigned long)(datalen)) {
1097 oldlen = response->len;
1098 ret = scpi_read_response(scpi, response, timeout);
1100 /* On timeout truncate the buffer and send the partial response
1101 * instead of getting stuck on timeouts...
1103 if (ret == SR_ERR_TIMEOUT) {
1108 g_mutex_unlock(&scpi->scpi_mutex);
1109 g_string_free(response, TRUE);
1113 timeout = g_get_monotonic_time() + scpi->read_timeout_us;
1114 } while (response->len < (unsigned long)(datalen));
1117 g_mutex_unlock(&scpi->scpi_mutex);
1119 /* Convert received data to byte array. */
1120 *scpi_response = g_byte_array_new_take(
1121 (guint8*)g_string_free(response, FALSE), datalen);
1127 * Send the *IDN? SCPI command, receive the reply, parse it and store the
1128 * reply as a sr_scpi_hw_info structure in the supplied scpi_response pointer.
1130 * Callers must free the allocated memory regardless of the routine's
1131 * return code. See @ref sr_scpi_hw_info_free().
1133 * @param[in] scpi Previously initialised SCPI device structure.
1134 * @param[out] scpi_response Pointer where to store the hw_info structure.
1136 * @return SR_OK upon success, SR_ERR* on failure.
1138 SR_PRIV int sr_scpi_get_hw_id(struct sr_scpi_dev_inst *scpi,
1139 struct sr_scpi_hw_info **scpi_response)
1141 int num_tokens, ret;
1144 struct sr_scpi_hw_info *hw_info;
1147 *scpi_response = NULL;
1151 ret = sr_scpi_get_string(scpi, SCPI_CMD_IDN, &response);
1152 if (ret != SR_OK && !response)
1156 * The response to a '*IDN?' is specified by the SCPI spec. It contains
1157 * a comma-separated list containing the manufacturer name, instrument
1158 * model, serial number of the instrument and the firmware version.
1160 * BEWARE! Although strictly speaking a smaller field count is invalid,
1161 * this implementation also accepts IDN responses with one field less,
1162 * and assumes that the serial number is missing. Some GWInstek DMMs
1163 * were found to do this. Keep warning about this condition, which may
1164 * need more consideration later.
1166 tokens = g_strsplit(response, ",", 0);
1167 num_tokens = g_strv_length(tokens);
1168 if (num_tokens < 3) {
1169 sr_dbg("IDN response not according to spec: '%s'", response);
1174 if (num_tokens < 4) {
1175 sr_warn("Short IDN response, assume missing serial number.");
1179 hw_info = g_malloc0(sizeof(*hw_info));
1181 idn_substr = g_strstr_len(tokens[0], -1, "IDN ");
1182 if (idn_substr == NULL)
1183 hw_info->manufacturer = g_strstrip(g_strdup(tokens[0]));
1185 hw_info->manufacturer = g_strstrip(g_strdup(idn_substr + 4));
1187 hw_info->model = g_strstrip(g_strdup(tokens[1]));
1188 if (num_tokens < 4) {
1189 hw_info->serial_number = g_strdup("Unknown");
1190 hw_info->firmware_version = g_strstrip(g_strdup(tokens[2]));
1192 hw_info->serial_number = g_strstrip(g_strdup(tokens[2]));
1193 hw_info->firmware_version = g_strstrip(g_strdup(tokens[3]));
1198 *scpi_response = hw_info;
1204 * Free a sr_scpi_hw_info struct.
1206 * @param hw_info Pointer to the struct to free. If NULL, this
1207 * function does nothing.
1209 SR_PRIV void sr_scpi_hw_info_free(struct sr_scpi_hw_info *hw_info)
1214 g_free(hw_info->manufacturer);
1215 g_free(hw_info->model);
1216 g_free(hw_info->serial_number);
1217 g_free(hw_info->firmware_version);
1222 * Remove potentially enclosing pairs of quotes, un-escape content.
1223 * This implementation modifies the caller's buffer when quotes are found
1224 * and doubled quote characters need to get removed from the content.
1226 * @param[in, out] s The SCPI string to check and un-quote.
1228 * @return The start of the un-quoted string.
1230 SR_PRIV const char *sr_scpi_unquote_string(char *s)
1236 /* Immediately bail out on invalid or short input. */
1243 /* Check for matching quote characters front and back. */
1244 if (s[0] != '\'' && s[0] != '"')
1246 if (s[0] != s[s_len - 1])
1249 /* Need to strip quotes, and un-double quote chars inside. */
1250 quotes[0] = quotes[1] = *s;
1252 s[s_len - 1] = '\0';
1255 while ((rdptr = strstr(rdptr, quotes)) != NULL) {
1256 memmove(rdptr, rdptr + 1, strlen(rdptr));
1263 SR_PRIV const char *sr_vendor_alias(const char *raw_vendor)
1267 for (i = 0; i < ARRAY_SIZE(scpi_vendors); i++) {
1268 if (!g_ascii_strcasecmp(raw_vendor, scpi_vendors[i][0]))
1269 return scpi_vendors[i][1];
1275 SR_PRIV const char *sr_scpi_cmd_get(const struct scpi_command *cmdtable,
1285 for (i = 0; cmdtable[i].string; i++) {
1286 if (cmdtable[i].command == command) {
1287 cmd = cmdtable[i].string;
1295 SR_PRIV int sr_scpi_cmd(const struct sr_dev_inst *sdi,
1296 const struct scpi_command *cmdtable,
1297 int channel_command, const char *channel_name,
1300 struct sr_scpi_dev_inst *scpi;
1303 const char *channel_cmd;
1308 if (!(cmd = sr_scpi_cmd_get(cmdtable, command))) {
1309 /* Device does not implement this command, that's OK. */
1313 g_mutex_lock(&scpi->scpi_mutex);
1315 /* Select channel. */
1316 channel_cmd = sr_scpi_cmd_get(cmdtable, channel_command);
1317 if (channel_cmd && channel_name &&
1318 g_strcmp0(channel_name, scpi->actual_channel_name)) {
1319 sr_spew("sr_scpi_cmd(): new channel = %s", channel_name);
1320 g_free(scpi->actual_channel_name);
1321 scpi->actual_channel_name = g_strdup(channel_name);
1322 ret = scpi_send(scpi, channel_cmd, channel_name);
1327 va_start(args, command);
1328 ret = scpi_send_variadic(scpi, cmd, args);
1331 g_mutex_unlock(&scpi->scpi_mutex);
1336 SR_PRIV int sr_scpi_cmd_resp(const struct sr_dev_inst *sdi,
1337 const struct scpi_command *cmdtable,
1338 int channel_command, const char *channel_name,
1339 GVariant **gvar, const GVariantType *gvtype, int command, ...)
1341 struct sr_scpi_dev_inst *scpi;
1343 const char *channel_cmd;
1353 if (!(cmd = sr_scpi_cmd_get(cmdtable, command))) {
1354 /* Device does not implement this command. */
1358 g_mutex_lock(&scpi->scpi_mutex);
1360 /* Select channel. */
1361 channel_cmd = sr_scpi_cmd_get(cmdtable, channel_command);
1362 if (channel_cmd && channel_name &&
1363 g_strcmp0(channel_name, scpi->actual_channel_name)) {
1364 sr_spew("sr_scpi_cmd_get(): new channel = %s", channel_name);
1365 g_free(scpi->actual_channel_name);
1366 scpi->actual_channel_name = g_strdup(channel_name);
1367 ret = scpi_send(scpi, channel_cmd, channel_name);
1372 va_start(args, command);
1373 ret = scpi_send_variadic(scpi, cmd, args);
1376 g_mutex_unlock(&scpi->scpi_mutex);
1380 response = g_string_sized_new(1024);
1381 ret = scpi_get_data(scpi, NULL, &response);
1383 g_mutex_unlock(&scpi->scpi_mutex);
1385 g_string_free(response, TRUE);
1389 g_mutex_unlock(&scpi->scpi_mutex);
1391 /* Get rid of trailing linefeed if present */
1392 if (response->len >= 1 && response->str[response->len - 1] == '\n')
1393 g_string_truncate(response, response->len - 1);
1395 /* Get rid of trailing carriage return if present */
1396 if (response->len >= 1 && response->str[response->len - 1] == '\r')
1397 g_string_truncate(response, response->len - 1);
1399 s = g_string_free(response, FALSE);
1402 if (g_variant_type_equal(gvtype, G_VARIANT_TYPE_BOOLEAN)) {
1403 if ((ret = parse_strict_bool(s, &b)) == SR_OK)
1404 *gvar = g_variant_new_boolean(b);
1405 } else if (g_variant_type_equal(gvtype, G_VARIANT_TYPE_DOUBLE)) {
1406 if ((ret = sr_atod_ascii(s, &d)) == SR_OK)
1407 *gvar = g_variant_new_double(d);
1408 } else if (g_variant_type_equal(gvtype, G_VARIANT_TYPE_STRING)) {
1409 *gvar = g_variant_new_string(s);
1411 sr_err("Unable to convert to desired GVariant type.");