]> sigrok.org Git - libsigrok.git/blob - src/scpi/scpi.c
9fa4ac03605392245ca0077f468cd006bb99f235
[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         { "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" },
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_SERIAL_COMM
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  * Get the connection ID of the SCPI device.
412  *
413  * @param scpi Previously initialized SCPI device structure.
414  * @param connection_id Pointer where to store the connection ID. The caller
415  *        is responsible for g_free()ing the string when it is no longer needed.
416  *
417  * @return SR_OK on success, SR_ERR on failure.
418  */
419 SR_PRIV int sr_scpi_connection_id(struct sr_scpi_dev_inst *scpi,
420                 char **connection_id)
421 {
422         return scpi->connection_id(scpi, connection_id);
423 }
424
425 /**
426  * Add an event source for an SCPI device.
427  *
428  * @param session The session to add the event source to.
429  * @param scpi Previously initialized SCPI device structure.
430  * @param events Events to check for.
431  * @param timeout Max time to wait before the callback is called, ignored if 0.
432  * @param cb Callback function to add. Must not be NULL.
433  * @param cb_data Data for the callback function. Can be NULL.
434  *
435  * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments, or
436  *         SR_ERR_MALLOC upon memory allocation errors.
437  */
438 SR_PRIV int sr_scpi_source_add(struct sr_session *session,
439                 struct sr_scpi_dev_inst *scpi, int events, int timeout,
440                 sr_receive_data_callback cb, void *cb_data)
441 {
442         return scpi->source_add(session, scpi->priv, events, timeout, cb, cb_data);
443 }
444
445 /**
446  * Remove event source for an SCPI device.
447  *
448  * @param session The session to remove the event source from.
449  * @param scpi Previously initialized SCPI device structure.
450  *
451  * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments, or
452  *         SR_ERR_MALLOC upon memory allocation errors, SR_ERR_BUG upon
453  *         internal errors.
454  */
455 SR_PRIV int sr_scpi_source_remove(struct sr_session *session,
456                 struct sr_scpi_dev_inst *scpi)
457 {
458         return scpi->source_remove(session, scpi->priv);
459 }
460
461 /**
462  * Send a SCPI command.
463  *
464  * @param scpi Previously initialized SCPI device structure.
465  * @param format Format string, to be followed by any necessary arguments.
466  *
467  * @return SR_OK on success, SR_ERR on failure.
468  */
469 SR_PRIV int sr_scpi_send(struct sr_scpi_dev_inst *scpi,
470                          const char *format, ...)
471 {
472         va_list args;
473         int ret;
474
475         va_start(args, format);
476         g_mutex_lock(&scpi->scpi_mutex);
477         ret = scpi_send_variadic(scpi, format, args);
478         g_mutex_unlock(&scpi->scpi_mutex);
479         va_end(args);
480
481         return ret;
482 }
483
484 /**
485  * Send a SCPI command with a variadic argument list.
486  *
487  * @param scpi Previously initialized SCPI device structure.
488  * @param format Format string.
489  * @param args Argument list.
490  *
491  * @return SR_OK on success, SR_ERR on failure.
492  */
493 SR_PRIV int sr_scpi_send_variadic(struct sr_scpi_dev_inst *scpi,
494                          const char *format, va_list args)
495 {
496         int ret;
497
498         g_mutex_lock(&scpi->scpi_mutex);
499         ret = scpi_send_variadic(scpi, format, args);
500         g_mutex_unlock(&scpi->scpi_mutex);
501
502         return ret;
503 }
504
505 /**
506  * Begin receiving an SCPI reply.
507  *
508  * @param scpi Previously initialised SCPI device structure.
509  *
510  * @return SR_OK on success, SR_ERR on failure.
511  */
512 SR_PRIV int sr_scpi_read_begin(struct sr_scpi_dev_inst *scpi)
513 {
514         return scpi->read_begin(scpi->priv);
515 }
516
517 /**
518  * Read part of a response from SCPI device.
519  *
520  * @param scpi Previously initialised SCPI device structure.
521  * @param buf Buffer to store result.
522  * @param maxlen Maximum number of bytes to read.
523  *
524  * @return Number of bytes read, or SR_ERR upon failure.
525  */
526 SR_PRIV int sr_scpi_read_data(struct sr_scpi_dev_inst *scpi,
527                         char *buf, int maxlen)
528 {
529         int ret;
530
531         g_mutex_lock(&scpi->scpi_mutex);
532         ret = scpi_read_data(scpi, buf, maxlen);
533         g_mutex_unlock(&scpi->scpi_mutex);
534
535         return ret;
536 }
537
538 /**
539  * Send data to SCPI device.
540  *
541  * TODO: This is only implemented in TcpRaw, but never used.
542  * TODO: Use Mutex at all?
543  *
544  * @param scpi Previously initialised SCPI device structure.
545  * @param buf Buffer with data to send.
546  * @param len Number of bytes to send.
547  *
548  * @return Number of bytes read, or SR_ERR upon failure.
549  */
550 SR_PRIV int sr_scpi_write_data(struct sr_scpi_dev_inst *scpi,
551                         char *buf, int maxlen)
552 {
553         int ret;
554
555         g_mutex_lock(&scpi->scpi_mutex);
556         ret = scpi_write_data(scpi, buf, maxlen);
557         g_mutex_unlock(&scpi->scpi_mutex);
558
559         return ret;
560 }
561
562 /**
563  * Check whether a complete SCPI response has been received.
564  *
565  * @param scpi Previously initialised SCPI device structure.
566  *
567  * @return 1 if complete, 0 otherwise.
568  */
569 SR_PRIV int sr_scpi_read_complete(struct sr_scpi_dev_inst *scpi)
570 {
571         return scpi->read_complete(scpi->priv);
572 }
573
574 /**
575  * Close SCPI device.
576  *
577  * @param scpi Previously initialized SCPI device structure.
578  *
579  * @return SR_OK on success, SR_ERR on failure.
580  */
581 SR_PRIV int sr_scpi_close(struct sr_scpi_dev_inst *scpi)
582 {
583         int ret;
584
585         g_mutex_lock(&scpi->scpi_mutex);
586         ret = scpi->close(scpi);
587         g_mutex_unlock(&scpi->scpi_mutex);
588         g_mutex_clear(&scpi->scpi_mutex);
589
590         return ret;
591 }
592
593 /**
594  * Free SCPI device.
595  *
596  * @param scpi Previously initialized SCPI device structure. If NULL,
597  *             this function does nothing.
598  */
599 SR_PRIV void sr_scpi_free(struct sr_scpi_dev_inst *scpi)
600 {
601         if (!scpi)
602                 return;
603
604         scpi->free(scpi->priv);
605         g_free(scpi->priv);
606         g_free(scpi->actual_channel_name);
607         g_free(scpi);
608 }
609
610 /**
611  * Send a SCPI command, receive the reply and store the reply in scpi_response.
612  *
613  * @param scpi Previously initialised SCPI device structure.
614  * @param command The SCPI command to send to the device (can be NULL).
615  * @param scpi_response Pointer where to store the SCPI response.
616  *
617  * @return SR_OK on success, SR_ERR* on failure.
618  */
619 SR_PRIV int sr_scpi_get_string(struct sr_scpi_dev_inst *scpi,
620                                const char *command, char **scpi_response)
621 {
622         GString *response;
623         response = g_string_sized_new(1024);
624
625         if (sr_scpi_get_data(scpi, command, &response) != SR_OK) {
626                 if (response)
627                         g_string_free(response, TRUE);
628                 return SR_ERR;
629         }
630
631         /* Get rid of trailing linefeed if present */
632         if (response->len >= 1 && response->str[response->len - 1] == '\n')
633                 g_string_truncate(response, response->len - 1);
634
635         /* Get rid of trailing carriage return if present */
636         if (response->len >= 1 && response->str[response->len - 1] == '\r')
637                 g_string_truncate(response, response->len - 1);
638
639         sr_spew("Got response: '%.70s', length %" G_GSIZE_FORMAT ".",
640                 response->str, response->len);
641
642         *scpi_response = g_string_free(response, FALSE);
643
644         return SR_OK;
645 }
646
647 /**
648  * Do a non-blocking read of up to the allocated length, and
649  * check if a timeout has occured.
650  *
651  * @param scpi Previously initialised SCPI device structure.
652  * @param response Buffer to which the response is appended.
653  * @param abs_timeout_us Absolute timeout in microseconds
654  *
655  * @return read length on success, SR_ERR* on failure.
656  */
657 SR_PRIV int sr_scpi_read_response(struct sr_scpi_dev_inst *scpi,
658                                   GString *response, gint64 abs_timeout_us)
659 {
660         int ret;
661
662         g_mutex_lock(&scpi->scpi_mutex);
663         ret = scpi_read_response(scpi, response, abs_timeout_us);
664         g_mutex_unlock(&scpi->scpi_mutex);
665
666         return ret;
667 }
668
669 SR_PRIV int sr_scpi_get_data(struct sr_scpi_dev_inst *scpi,
670                              const char *command, GString **scpi_response)
671 {
672         int ret;
673
674         g_mutex_lock(&scpi->scpi_mutex);
675         ret = scpi_get_data(scpi, command, scpi_response);
676         g_mutex_unlock(&scpi->scpi_mutex);
677
678         return ret;
679 }
680
681 /**
682  * Send a SCPI command, read the reply, parse it as a bool value and store the
683  * result in scpi_response.
684  *
685  * @param scpi Previously initialised SCPI device structure.
686  * @param command The SCPI command to send to the device (can be NULL).
687  * @param scpi_response Pointer where to store the parsed result.
688  *
689  * @return SR_OK on success, SR_ERR* on failure.
690  */
691 SR_PRIV int sr_scpi_get_bool(struct sr_scpi_dev_inst *scpi,
692                              const char *command, gboolean *scpi_response)
693 {
694         int ret;
695         char *response;
696
697         response = NULL;
698
699         ret = sr_scpi_get_string(scpi, command, &response);
700         if (ret != SR_OK && !response)
701                 return ret;
702
703         if (parse_strict_bool(response, scpi_response) == SR_OK)
704                 ret = SR_OK;
705         else
706                 ret = SR_ERR_DATA;
707
708         g_free(response);
709
710         return ret;
711 }
712
713 /**
714  * Send a SCPI command, read the reply, parse it as an integer and store the
715  * result in scpi_response.
716  *
717  * @param scpi Previously initialised SCPI device structure.
718  * @param command The SCPI command to send to the device (can be NULL).
719  * @param scpi_response Pointer where to store the parsed result.
720  *
721  * @return SR_OK on success, SR_ERR* on failure.
722  */
723 SR_PRIV int sr_scpi_get_int(struct sr_scpi_dev_inst *scpi,
724                             const char *command, int *scpi_response)
725 {
726         int ret;
727         struct sr_rational ret_rational;
728         char *response;
729
730         response = NULL;
731
732         ret = sr_scpi_get_string(scpi, command, &response);
733         if (ret != SR_OK && !response)
734                 return ret;
735
736         ret = sr_parse_rational(response, &ret_rational);
737         if (ret == SR_OK && (ret_rational.p % ret_rational.q) == 0) {
738                 *scpi_response = ret_rational.p / ret_rational.q;
739         } else {
740                 sr_dbg("get_int: non-integer rational=%" PRId64 "/%" PRIu64,
741                         ret_rational.p, ret_rational.q);
742                 ret = SR_ERR_DATA;
743         }
744
745         g_free(response);
746
747         return ret;
748 }
749
750 /**
751  * Send a SCPI command, read the reply, parse it as a float and store the
752  * result in scpi_response.
753  *
754  * @param scpi Previously initialised SCPI device structure.
755  * @param command The SCPI command to send to the device (can be NULL).
756  * @param scpi_response Pointer where to store the parsed result.
757  *
758  * @return SR_OK on success, SR_ERR* on failure.
759  */
760 SR_PRIV int sr_scpi_get_float(struct sr_scpi_dev_inst *scpi,
761                               const char *command, float *scpi_response)
762 {
763         int ret;
764         char *response;
765
766         response = NULL;
767
768         ret = sr_scpi_get_string(scpi, command, &response);
769         if (ret != SR_OK && !response)
770                 return ret;
771
772         if (sr_atof_ascii(response, scpi_response) == SR_OK)
773                 ret = SR_OK;
774         else
775                 ret = SR_ERR_DATA;
776
777         g_free(response);
778
779         return ret;
780 }
781
782 /**
783  * Send a SCPI command, read the reply, parse it as a double and store the
784  * result in scpi_response.
785  *
786  * @param scpi Previously initialised SCPI device structure.
787  * @param command The SCPI command to send to the device (can be NULL).
788  * @param scpi_response Pointer where to store the parsed result.
789  *
790  * @return SR_OK on success, SR_ERR* on failure.
791  */
792 SR_PRIV int sr_scpi_get_double(struct sr_scpi_dev_inst *scpi,
793                                const char *command, double *scpi_response)
794 {
795         int ret;
796         char *response;
797
798         response = NULL;
799
800         ret = sr_scpi_get_string(scpi, command, &response);
801         if (ret != SR_OK && !response)
802                 return ret;
803
804         if (sr_atod_ascii(response, scpi_response) == SR_OK)
805                 ret = SR_OK;
806         else
807                 ret = SR_ERR_DATA;
808
809         g_free(response);
810
811         return ret;
812 }
813
814 /**
815  * Send a SCPI *OPC? command, read the reply and return the result of the
816  * command.
817  *
818  * @param scpi Previously initialised SCPI device structure.
819  *
820  * @return SR_OK on success, SR_ERR* on failure.
821  */
822 SR_PRIV int sr_scpi_get_opc(struct sr_scpi_dev_inst *scpi)
823 {
824         unsigned int i;
825         gboolean opc;
826
827         for (i = 0; i < SCPI_READ_RETRIES; i++) {
828                 opc = FALSE;
829                 sr_scpi_get_bool(scpi, SCPI_CMD_OPC, &opc);
830                 if (opc)
831                         return SR_OK;
832                 g_usleep(SCPI_READ_RETRY_TIMEOUT_US);
833         }
834
835         return SR_ERR;
836 }
837
838 /**
839  * Send a SCPI command, read the reply, parse it as comma separated list of
840  * floats and store the as an result in scpi_response.
841  *
842  * @param scpi Previously initialised SCPI device structure.
843  * @param command The SCPI command to send to the device (can be NULL).
844  * @param scpi_response Pointer where to store the parsed result.
845  *
846  * @return SR_OK upon successfully parsing all values, SR_ERR* upon a parsing
847  *         error or upon no response. The allocated response must be freed by
848  *         the caller in the case of an SR_OK as well as in the case of
849  *         parsing error.
850  */
851 SR_PRIV int sr_scpi_get_floatv(struct sr_scpi_dev_inst *scpi,
852                                const char *command, GArray **scpi_response)
853 {
854         int ret;
855         float tmp;
856         char *response;
857         gchar **ptr, **tokens;
858         GArray *response_array;
859
860         response = NULL;
861         tokens = NULL;
862
863         ret = sr_scpi_get_string(scpi, command, &response);
864         if (ret != SR_OK && !response)
865                 return ret;
866
867         tokens = g_strsplit(response, ",", 0);
868         ptr = tokens;
869
870         response_array = g_array_sized_new(TRUE, FALSE, sizeof(float), 256);
871
872         while (*ptr) {
873                 if (sr_atof_ascii(*ptr, &tmp) == SR_OK)
874                         response_array = g_array_append_val(response_array,
875                                                             tmp);
876                 else
877                         ret = SR_ERR_DATA;
878
879                 ptr++;
880         }
881         g_strfreev(tokens);
882         g_free(response);
883
884         if (ret != SR_OK && response_array->len == 0) {
885                 g_array_free(response_array, TRUE);
886                 *scpi_response = NULL;
887                 return SR_ERR_DATA;
888         }
889
890         *scpi_response = response_array;
891
892         return ret;
893 }
894
895 /**
896  * Send a SCPI command, read the reply, parse it as comma separated list of
897  * unsigned 8 bit integers and store the as an result in scpi_response.
898  *
899  * @param scpi Previously initialised SCPI device structure.
900  * @param command The SCPI command to send to the device (can be NULL).
901  * @param scpi_response Pointer where to store the parsed result.
902  *
903  * @return SR_OK upon successfully parsing all values, SR_ERR* upon a parsing
904  *         error or upon no response. The allocated response must be freed by
905  *         the caller in the case of an SR_OK as well as in the case of
906  *         parsing error.
907  */
908 SR_PRIV int sr_scpi_get_uint8v(struct sr_scpi_dev_inst *scpi,
909                                const char *command, GArray **scpi_response)
910 {
911         int tmp, ret;
912         char *response;
913         gchar **ptr, **tokens;
914         GArray *response_array;
915
916         response = NULL;
917         tokens = NULL;
918
919         ret = sr_scpi_get_string(scpi, command, &response);
920         if (ret != SR_OK && !response)
921                 return ret;
922
923         tokens = g_strsplit(response, ",", 0);
924         ptr = tokens;
925
926         response_array = g_array_sized_new(TRUE, FALSE, sizeof(uint8_t), 256);
927
928         while (*ptr) {
929                 if (sr_atoi(*ptr, &tmp) == SR_OK)
930                         response_array = g_array_append_val(response_array,
931                                                             tmp);
932                 else
933                         ret = SR_ERR_DATA;
934
935                 ptr++;
936         }
937         g_strfreev(tokens);
938         g_free(response);
939
940         if (response_array->len == 0) {
941                 g_array_free(response_array, TRUE);
942                 *scpi_response = NULL;
943                 return SR_ERR_DATA;
944         }
945
946         *scpi_response = response_array;
947
948         return ret;
949 }
950
951 /**
952  * Send a SCPI command, read the reply, parse it as binary data with a
953  * "definite length block" header and store the as an result in scpi_response.
954  *
955  * @param scpi Previously initialised SCPI device structure.
956  * @param command The SCPI command to send to the device (can be NULL).
957  * @param scpi_response Pointer where to store the parsed result.
958  *
959  * @return SR_OK upon successfully parsing all values, SR_ERR* upon a parsing
960  *         error or upon no response. The allocated response must be freed by
961  *         the caller in the case of an SR_OK as well as in the case of
962  *         parsing error.
963  */
964 SR_PRIV int sr_scpi_get_block(struct sr_scpi_dev_inst *scpi,
965                                const char *command, GByteArray **scpi_response)
966 {
967         int ret;
968         GString* response;
969         gsize oldlen;
970         char buf[10];
971         long llen;
972         long datalen;
973         gint64 timeout;
974
975         g_mutex_lock(&scpi->scpi_mutex);
976
977         if (command)
978                 if (scpi_send(scpi, command) != SR_OK) {
979                         g_mutex_unlock(&scpi->scpi_mutex);
980                         return SR_ERR;
981                 }
982
983         if (sr_scpi_read_begin(scpi) != SR_OK) {
984                 g_mutex_unlock(&scpi->scpi_mutex);
985                 return SR_ERR;
986         }
987
988         /*
989          * Assume an initial maximum length, optionally gets adjusted below.
990          * Prepare a NULL return value for when error paths will be taken.
991          */
992         response = g_string_sized_new(1024);
993
994         timeout = g_get_monotonic_time() + scpi->read_timeout_us;
995
996         *scpi_response = NULL;
997
998         /* Get (the first chunk of) the response. */
999         do {
1000                 ret = scpi_read_response(scpi, response, timeout);
1001                 if (ret < 0) {
1002                         g_mutex_unlock(&scpi->scpi_mutex);
1003                         g_string_free(response, TRUE);
1004                         return ret;
1005                 }
1006         } while (response->len < 2);
1007
1008         /*
1009          * SCPI protocol data blocks are preceeded with a length spec.
1010          * The length spec consists of a '#' marker, one digit which
1011          * specifies the character count of the length spec, and the
1012          * respective number of characters which specify the data block's
1013          * length. Raw data bytes follow (thus one must no longer assume
1014          * that the received input stream would be an ASCIIZ string).
1015          *
1016          * Get the data block length, and strip off the length spec from
1017          * the input buffer, leaving just the data bytes.
1018          */
1019         if (response->str[0] != '#') {
1020                 g_mutex_unlock(&scpi->scpi_mutex);
1021                 g_string_free(response, TRUE);
1022                 return SR_ERR_DATA;
1023         }
1024         buf[0] = response->str[1];
1025         buf[1] = '\0';
1026         ret = sr_atol(buf, &llen);
1027         if ((ret != SR_OK) || (llen == 0)) {
1028                 g_mutex_unlock(&scpi->scpi_mutex);
1029                 g_string_free(response, TRUE);
1030                 return ret;
1031         }
1032
1033         while (response->len < (unsigned long)(2 + llen)) {
1034                 ret = scpi_read_response(scpi, response, timeout);
1035                 if (ret < 0) {
1036                         g_mutex_unlock(&scpi->scpi_mutex);
1037                         g_string_free(response, TRUE);
1038                         return ret;
1039                 }
1040         }
1041
1042         memcpy(buf, &response->str[2], llen);
1043         buf[llen] = '\0';
1044         ret = sr_atol(buf, &datalen);
1045         if ((ret != SR_OK) || (datalen == 0)) {
1046                 g_mutex_unlock(&scpi->scpi_mutex);
1047                 g_string_free(response, TRUE);
1048                 return ret;
1049         }
1050         g_string_erase(response, 0, 2 + llen);
1051
1052         /*
1053          * Re-allocate the buffer size to the now known length
1054          * and keep reading more chunks of response data.
1055          */
1056         oldlen = response->len;
1057         g_string_set_size(response, datalen);
1058         g_string_set_size(response, oldlen);
1059
1060         if (oldlen < (unsigned long)(datalen)) {
1061                 do {
1062                         oldlen = response->len;
1063                         ret = scpi_read_response(scpi, response, timeout);
1064
1065                         /* On timeout truncate the buffer and send the partial response
1066                          * instead of getting stuck on timeouts...
1067                          */
1068                         if (ret == SR_ERR_TIMEOUT) {
1069                                 datalen = oldlen;
1070                                 break;
1071                         }
1072                         if (ret < 0) {
1073                                 g_mutex_unlock(&scpi->scpi_mutex);
1074                                 g_string_free(response, TRUE);
1075                                 return ret;
1076                         }
1077                         if (ret > 0)
1078                                 timeout = g_get_monotonic_time() + scpi->read_timeout_us;
1079                 } while (response->len < (unsigned long)(datalen));
1080         }
1081
1082         g_mutex_unlock(&scpi->scpi_mutex);
1083
1084         /* Convert received data to byte array. */
1085         *scpi_response = g_byte_array_new_take(
1086                 (guint8*)g_string_free(response, FALSE), datalen);
1087
1088         return SR_OK;
1089 }
1090
1091 /**
1092  * Send the *IDN? SCPI command, receive the reply, parse it and store the
1093  * reply as a sr_scpi_hw_info structure in the supplied scpi_response pointer.
1094  *
1095  * The hw_info structure must be freed by the caller via sr_scpi_hw_info_free().
1096  *
1097  * @param scpi Previously initialised SCPI device structure.
1098  * @param scpi_response Pointer where to store the hw_info structure.
1099  *
1100  * @return SR_OK upon success, SR_ERR* on failure.
1101  */
1102 SR_PRIV int sr_scpi_get_hw_id(struct sr_scpi_dev_inst *scpi,
1103                               struct sr_scpi_hw_info **scpi_response)
1104 {
1105         int num_tokens, ret;
1106         char *response;
1107         gchar **tokens;
1108         struct sr_scpi_hw_info *hw_info;
1109         gchar *idn_substr;
1110
1111         response = NULL;
1112         tokens = NULL;
1113
1114         ret = sr_scpi_get_string(scpi, SCPI_CMD_IDN, &response);
1115         if (ret != SR_OK && !response)
1116                 return ret;
1117
1118         /*
1119          * The response to a '*IDN?' is specified by the SCPI spec. It contains
1120          * a comma-separated list containing the manufacturer name, instrument
1121          * model, serial number of the instrument and the firmware version.
1122          *
1123          * BEWARE! Although strictly speaking a smaller field count is invalid,
1124          * this implementation also accepts IDN responses with one field less,
1125          * and assumes that the serial number is missing. Some GWInstek DMMs
1126          * were found to do this. Keep warning about this condition, which may
1127          * need more consideration later.
1128          */
1129         tokens = g_strsplit(response, ",", 0);
1130         num_tokens = g_strv_length(tokens);
1131         if (num_tokens < 3) {
1132                 sr_dbg("IDN response not according to spec: '%s'", response);
1133                 g_strfreev(tokens);
1134                 g_free(response);
1135                 return SR_ERR_DATA;
1136         }
1137         if (num_tokens < 4) {
1138                 sr_warn("Short IDN response, assume missing serial number.");
1139         }
1140         g_free(response);
1141
1142         hw_info = g_malloc0(sizeof(struct sr_scpi_hw_info));
1143
1144         idn_substr = g_strstr_len(tokens[0], -1, "IDN ");
1145         if (idn_substr == NULL)
1146                 hw_info->manufacturer = g_strstrip(g_strdup(tokens[0]));
1147         else
1148                 hw_info->manufacturer = g_strstrip(g_strdup(idn_substr + 4));
1149
1150         hw_info->model = g_strstrip(g_strdup(tokens[1]));
1151         if (num_tokens < 4) {
1152                 hw_info->serial_number = g_strdup("Unknown");
1153                 hw_info->firmware_version = g_strstrip(g_strdup(tokens[2]));
1154         } else {
1155                 hw_info->serial_number = g_strstrip(g_strdup(tokens[2]));
1156                 hw_info->firmware_version = g_strstrip(g_strdup(tokens[3]));
1157         }
1158
1159         g_strfreev(tokens);
1160
1161         *scpi_response = hw_info;
1162
1163         return SR_OK;
1164 }
1165
1166 /**
1167  * Free a sr_scpi_hw_info struct.
1168  *
1169  * @param hw_info Pointer to the struct to free. If NULL, this
1170  *                function does nothing.
1171  */
1172 SR_PRIV void sr_scpi_hw_info_free(struct sr_scpi_hw_info *hw_info)
1173 {
1174         if (!hw_info)
1175                 return;
1176
1177         g_free(hw_info->manufacturer);
1178         g_free(hw_info->model);
1179         g_free(hw_info->serial_number);
1180         g_free(hw_info->firmware_version);
1181         g_free(hw_info);
1182 }
1183
1184 /**
1185  * Remove potentially enclosing pairs of quotes, un-escape content.
1186  * This implementation modifies the caller's buffer when quotes are found
1187  * and doubled quote characters need to get removed from the content.
1188  *
1189  * @param[in, out] s    The SCPI string to check and un-quote.
1190  *
1191  * @return The start of the un-quoted string.
1192  */
1193 SR_PRIV const char *sr_scpi_unquote_string(char *s)
1194 {
1195         size_t s_len;
1196         char quotes[3];
1197         char *rdptr;
1198
1199         /* Immediately bail out on invalid or short input. */
1200         if (!s || !*s)
1201                 return s;
1202         s_len = strlen(s);
1203         if (s_len < 2)
1204                 return s;
1205
1206         /* Check for matching quote characters front and back. */
1207         if (s[0] != '\'' && s[0] != '"')
1208                 return s;
1209         if (s[0] != s[s_len - 1])
1210                 return s;
1211
1212         /* Need to strip quotes, and un-double quote chars inside. */
1213         quotes[0] = quotes[1] = *s;
1214         quotes[2] = '\0';
1215         s[s_len - 1] = '\0';
1216         s++;
1217         rdptr = s;
1218         while ((rdptr = strstr(rdptr, quotes)) != NULL) {
1219                 memmove(rdptr, rdptr + 1, strlen(rdptr));
1220                 rdptr++;
1221         }
1222
1223         return s;
1224 }
1225
1226 SR_PRIV const char *sr_vendor_alias(const char *raw_vendor)
1227 {
1228         unsigned int i;
1229
1230         for (i = 0; i < ARRAY_SIZE(scpi_vendors); i++) {
1231                 if (!g_ascii_strcasecmp(raw_vendor, scpi_vendors[i][0]))
1232                         return scpi_vendors[i][1];
1233         }
1234
1235         return raw_vendor;
1236 }
1237
1238 SR_PRIV const char *sr_scpi_cmd_get(const struct scpi_command *cmdtable,
1239                 int command)
1240 {
1241         unsigned int i;
1242         const char *cmd;
1243
1244         if (!cmdtable)
1245                 return NULL;
1246
1247         cmd = NULL;
1248         for (i = 0; cmdtable[i].string; i++) {
1249                 if (cmdtable[i].command == command) {
1250                         cmd = cmdtable[i].string;
1251                         break;
1252                 }
1253         }
1254
1255         return cmd;
1256 }
1257
1258 SR_PRIV int sr_scpi_cmd(const struct sr_dev_inst *sdi,
1259                 const struct scpi_command *cmdtable,
1260                 int channel_command, const char *channel_name,
1261                 int command, ...)
1262 {
1263         struct sr_scpi_dev_inst *scpi;
1264         va_list args;
1265         int ret;
1266         const char *channel_cmd;
1267         const char *cmd;
1268
1269         scpi = sdi->conn;
1270
1271         if (!(cmd = sr_scpi_cmd_get(cmdtable, command))) {
1272                 /* Device does not implement this command, that's OK. */
1273                 return SR_OK;
1274         }
1275
1276         g_mutex_lock(&scpi->scpi_mutex);
1277
1278         /* Select channel. */
1279         channel_cmd = sr_scpi_cmd_get(cmdtable, channel_command);
1280         if (channel_cmd && channel_name &&
1281                         g_strcmp0(channel_name, scpi->actual_channel_name)) {
1282                 sr_spew("sr_scpi_cmd(): new channel = %s", channel_name);
1283                 g_free(scpi->actual_channel_name);
1284                 scpi->actual_channel_name = g_strdup(channel_name);
1285                 ret = scpi_send(scpi, channel_cmd, channel_name);
1286                 if (ret != SR_OK)
1287                         return ret;
1288         }
1289
1290         va_start(args, command);
1291         ret = scpi_send_variadic(scpi, cmd, args);
1292         va_end(args);
1293
1294         g_mutex_unlock(&scpi->scpi_mutex);
1295
1296         return ret;
1297 }
1298
1299 SR_PRIV int sr_scpi_cmd_resp(const struct sr_dev_inst *sdi,
1300                 const struct scpi_command *cmdtable,
1301                 int channel_command, const char *channel_name,
1302                 GVariant **gvar, const GVariantType *gvtype, int command, ...)
1303 {
1304         struct sr_scpi_dev_inst *scpi;
1305         va_list args;
1306         const char *channel_cmd;
1307         const char *cmd;
1308         GString *response;
1309         char *s;
1310         gboolean b;
1311         double d;
1312         int ret;
1313
1314         scpi = sdi->conn;
1315
1316         if (!(cmd = sr_scpi_cmd_get(cmdtable, command))) {
1317                 /* Device does not implement this command. */
1318                 return SR_ERR_NA;
1319         }
1320
1321         g_mutex_lock(&scpi->scpi_mutex);
1322
1323         /* Select channel. */
1324         channel_cmd = sr_scpi_cmd_get(cmdtable, channel_command);
1325         if (channel_cmd && channel_name &&
1326                         g_strcmp0(channel_name, scpi->actual_channel_name)) {
1327                 sr_spew("sr_scpi_cmd_get(): new channel = %s", channel_name);
1328                 g_free(scpi->actual_channel_name);
1329                 scpi->actual_channel_name = g_strdup(channel_name);
1330                 ret = scpi_send(scpi, channel_cmd, channel_name);
1331                 if (ret != SR_OK)
1332                         return ret;
1333         }
1334
1335         va_start(args, command);
1336         ret = scpi_send_variadic(scpi, cmd, args);
1337         va_end(args);
1338         if (ret != SR_OK) {
1339                 g_mutex_unlock(&scpi->scpi_mutex);
1340                 return ret;
1341         }
1342
1343         response = g_string_sized_new(1024);
1344         ret = scpi_get_data(scpi, NULL, &response);
1345         if (ret != SR_OK) {
1346                 g_mutex_unlock(&scpi->scpi_mutex);
1347                 if (response)
1348                         g_string_free(response, TRUE);
1349                 return ret;
1350         }
1351
1352         g_mutex_unlock(&scpi->scpi_mutex);
1353
1354         /* Get rid of trailing linefeed if present */
1355         if (response->len >= 1 && response->str[response->len - 1] == '\n')
1356                 g_string_truncate(response, response->len - 1);
1357
1358         /* Get rid of trailing carriage return if present */
1359         if (response->len >= 1 && response->str[response->len - 1] == '\r')
1360                 g_string_truncate(response, response->len - 1);
1361
1362         s = g_string_free(response, FALSE);
1363
1364         ret = SR_OK;
1365         if (g_variant_type_equal(gvtype, G_VARIANT_TYPE_BOOLEAN)) {
1366                 if ((ret = parse_strict_bool(s, &b)) == SR_OK)
1367                         *gvar = g_variant_new_boolean(b);
1368         } else if (g_variant_type_equal(gvtype, G_VARIANT_TYPE_DOUBLE)) {
1369                 if ((ret = sr_atod_ascii(s, &d)) == SR_OK)
1370                         *gvar = g_variant_new_double(d);
1371         } else if (g_variant_type_equal(gvtype, G_VARIANT_TYPE_STRING)) {
1372                 *gvar = g_variant_new_string(s);
1373         } else {
1374                 sr_err("Unable to convert to desired GVariant type.");
1375                 ret = SR_ERR_NA;
1376         }
1377
1378         g_free(s);
1379
1380         return ret;
1381 }