]> sigrok.org Git - libsigrok.git/blob - hardware/common/scpi.c
scpi: make the scpi_dev_inst_new more generic
[libsigrok.git] / hardware / common / scpi.c
1 /*
2  * This file is part of the libsigrok project.
3  *
4  * Copyright (C) 2013 poljar (Damir Jelić) <poljarinho@gmail.com>
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 #include "libsigrok.h"
21 #include "libsigrok-internal.h"
22
23 #include <glib.h>
24 #include <string.h>
25
26 #define LOG_PREFIX "scpi"
27
28 #define SCPI_READ_RETRIES 100
29 #define SCPI_READ_RETRY_TIMEOUT 10000
30
31 /**
32  * Parse a string representation of a boolean-like value into a gboolean.
33  * Similar to sr_parse_boolstring but rejects strings which do not represent
34  * a boolean-like value.
35  *
36  * @param str String to convert.
37  * @param ret Pointer to a gboolean where the result of the conversion will be
38  * stored.
39  *
40  * @return SR_OK on success, SR_ERR on failure.
41  */
42 static int parse_strict_bool(const char *str, gboolean *ret)
43 {
44         if (!str)
45                 return SR_ERR_ARG;
46
47         if (!g_strcmp0(str, "1") ||
48             !g_ascii_strncasecmp(str, "y", 1) ||
49             !g_ascii_strncasecmp(str, "t", 1) ||
50             !g_ascii_strncasecmp(str, "yes", 3) ||
51             !g_ascii_strncasecmp(str, "true", 4) ||
52             !g_ascii_strncasecmp(str, "on", 2)) {
53                 *ret = TRUE;
54                 return SR_OK;
55         } else if (!g_strcmp0(str, "0") ||
56                    !g_ascii_strncasecmp(str, "n", 1) ||
57                    !g_ascii_strncasecmp(str, "f", 1) ||
58                    !g_ascii_strncasecmp(str, "no", 2) ||
59                    !g_ascii_strncasecmp(str, "false", 5) ||
60                    !g_ascii_strncasecmp(str, "off", 3)) {
61                 *ret = FALSE;
62                 return SR_OK;
63         }
64
65         return SR_ERR;
66 }
67
68 SR_PRIV extern const struct sr_scpi_dev_inst scpi_serial_dev;
69 SR_PRIV extern const struct sr_scpi_dev_inst scpi_tcp_dev;
70 SR_PRIV extern const struct sr_scpi_dev_inst scpi_usbtmc_dev;
71 SR_PRIV extern const struct sr_scpi_dev_inst scpi_vxi_dev;
72
73 static const struct sr_scpi_dev_inst *scpi_devs[] = {
74         &scpi_tcp_dev,
75         &scpi_usbtmc_dev,
76 #ifdef HAVE_RPC
77         &scpi_vxi_dev,
78 #endif
79 #ifdef HAVE_LIBSERIALPORT
80         &scpi_serial_dev,  /* must be last as it matches any resource */
81 #endif
82 };
83
84 SR_PRIV struct sr_scpi_dev_inst *scpi_dev_inst_new(const char *resource,
85                 const char *serialcomm)
86 {
87         struct sr_scpi_dev_inst *scpi = NULL;
88         const struct sr_scpi_dev_inst *scpi_dev;
89         gchar **params;
90         unsigned i;
91
92         for (i = 0; i < ARRAY_SIZE(scpi_devs); i++) {
93                 scpi_dev = scpi_devs[i];
94                 if (!strncmp(resource, scpi_dev->prefix, strlen(scpi_dev->prefix))) {
95                         sr_dbg("Opening %s device %s.", scpi_dev->name, resource);
96                         scpi = g_malloc(sizeof(*scpi));
97                         *scpi = *scpi_dev;
98                         scpi->priv = g_malloc0(scpi->priv_size);
99                         params = g_strsplit(resource, "/", 0);
100                         if (scpi->dev_inst_new(scpi->priv, resource,
101                                                params, serialcomm) != SR_OK) {
102                                 sr_scpi_free(scpi);
103                                 scpi = NULL;
104                         }
105                         g_strfreev(params);
106                         break;
107                 }
108         }
109
110         return scpi;
111 }
112
113 /**
114  * Open SCPI device.
115  *
116  * @param scpi Previously initialized SCPI device structure.
117  *
118  * @return SR_OK on success, SR_ERR on failure.
119  */
120 SR_PRIV int sr_scpi_open(struct sr_scpi_dev_inst *scpi)
121 {
122         return scpi->open(scpi->priv);
123 }
124
125 /**
126  * Add an event source for an SCPI device.
127  *
128  * @param scpi Previously initialized SCPI device structure.
129  * @param events Events to check for.
130  * @param timeout Max time to wait before the callback is called, ignored if 0.
131  * @param cb Callback function to add. Must not be NULL.
132  * @param cb_data Data for the callback function. Can be NULL.
133  *
134  * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments, or
135  *         SR_ERR_MALLOC upon memory allocation errors.
136  */
137 SR_PRIV int sr_scpi_source_add(struct sr_scpi_dev_inst *scpi, int events,
138                 int timeout, sr_receive_data_callback_t cb, void *cb_data)
139 {
140         return scpi->source_add(scpi->priv, events, timeout, cb, cb_data);
141 }
142
143 /**
144  * Remove event source for an SCPI device.
145  *
146  * @param scpi Previously initialized SCPI device structure.
147  *
148  * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments, or
149  *         SR_ERR_MALLOC upon memory allocation errors, SR_ERR_BUG upon
150  *         internal errors.
151  */
152 SR_PRIV int sr_scpi_source_remove(struct sr_scpi_dev_inst *scpi)
153 {
154         return scpi->source_remove(scpi->priv);
155 }
156
157 /**
158  * Send a SCPI command.
159  *
160  * @param scpi Previously initialized SCPI device structure.
161  * @param format Format string, to be followed by any necessary arguments.
162  *
163  * @return SR_OK on success, SR_ERR on failure.
164  */
165 SR_PRIV int sr_scpi_send(struct sr_scpi_dev_inst *scpi,
166                          const char *format, ...)
167 {
168         va_list args;
169         int ret;
170
171         va_start(args, format);
172         ret = sr_scpi_send_variadic(scpi, format, args);
173         va_end(args);
174
175         return ret;
176 }
177
178 /**
179  * Send a SCPI command with a variadic argument list.
180  *
181  * @param scpi Previously initialized SCPI device structure.
182  * @param format Format string.
183  * @param args Argument list.
184  *
185  * @return SR_OK on success, SR_ERR on failure.
186  */
187 SR_PRIV int sr_scpi_send_variadic(struct sr_scpi_dev_inst *scpi,
188                          const char *format, va_list args)
189 {
190         va_list args_copy;
191         char *buf;
192         int len, ret;
193
194         /* Get length of buffer required. */
195         va_copy(args_copy, args);
196         len = vsnprintf(NULL, 0, format, args_copy);
197         va_end(args_copy);
198
199         /* Allocate buffer and write out command. */
200         buf = g_malloc(len + 1);
201         vsprintf(buf, format, args);
202
203         /* Send command. */
204         ret = scpi->send(scpi->priv, buf);
205
206         /* Free command buffer. */
207         g_free(buf);
208
209         return ret;
210 }
211
212 /**
213  * Begin receiving an SCPI reply.
214  *
215  * @param scpi Previously initialised SCPI device structure.
216  *
217  * @return SR_OK on success, SR_ERR on failure.
218  */
219 SR_PRIV int sr_scpi_read_begin(struct sr_scpi_dev_inst *scpi)
220 {
221         return scpi->read_begin(scpi->priv);
222 }
223
224 /**
225  * Read part of a response from SCPI device.
226  *
227  * @param scpi Previously initialised SCPI device structure.
228  * @param buf Buffer to store result.
229  * @param maxlen Maximum number of bytes to read.
230  *
231  * @return Number of bytes read, or SR_ERR upon failure.
232  */
233 SR_PRIV int sr_scpi_read_data(struct sr_scpi_dev_inst *scpi,
234                         char *buf, int maxlen)
235 {
236         return scpi->read_data(scpi->priv, buf, maxlen);
237 }
238
239 /**
240  * Check whether a complete SCPI response has been received.
241  *
242  * @param scpi Previously initialised SCPI device structure.
243  *
244  * @return 1 if complete, 0 otherwise.
245  */
246 SR_PRIV int sr_scpi_read_complete(struct sr_scpi_dev_inst *scpi)
247 {
248         return scpi->read_complete(scpi->priv);
249 }
250
251 /**
252  * Close SCPI device.
253  *
254  * @param scpi Previously initialized SCPI device structure.
255  *
256  * @return SR_OK on success, SR_ERR on failure.
257  */
258 SR_PRIV int sr_scpi_close(struct sr_scpi_dev_inst *scpi)
259 {
260         return scpi->close(scpi->priv);
261 }
262
263 /**
264  * Free SCPI device.
265  *
266  * @param scpi Previously initialized SCPI device structure.
267  *
268  * @return SR_OK on success, SR_ERR on failure.
269  */
270 SR_PRIV void sr_scpi_free(struct sr_scpi_dev_inst *scpi)
271 {
272         scpi->free(scpi->priv);
273         g_free(scpi->priv);
274         g_free(scpi);
275 }
276
277 /**
278  * Send a SCPI command, receive the reply and store the reply in scpi_response.
279  *
280  * @param scpi Previously initialised SCPI device structure.
281  * @param command The SCPI command to send to the device (can be NULL).
282  * @param scpi_response Pointer where to store the SCPI response.
283  *
284  * @return SR_OK on success, SR_ERR on failure.
285  */
286 SR_PRIV int sr_scpi_get_string(struct sr_scpi_dev_inst *scpi,
287                                const char *command, char **scpi_response)
288 {
289         char buf[256];
290         int len;
291         GString *response;
292
293         if (command)
294                 if (sr_scpi_send(scpi, command) != SR_OK)
295                         return SR_ERR;
296
297         if (sr_scpi_read_begin(scpi) != SR_OK)
298                 return SR_ERR;
299
300         response = g_string_new("");
301
302         *scpi_response = NULL;
303
304         while (!sr_scpi_read_complete(scpi)) {
305                 len = sr_scpi_read_data(scpi, buf, sizeof(buf));
306                 if (len < 0) {
307                         g_string_free(response, TRUE);
308                         return SR_ERR;
309                 }
310                 g_string_append_len(response, buf, len);
311         }
312
313         *scpi_response = response->str;
314         g_string_free(response, FALSE);
315
316         return SR_OK;
317 }
318
319 /**
320  * Send a SCPI command, read the reply, parse it as a bool value and store the
321  * result in scpi_response.
322  *
323  * @param scpi Previously initialised SCPI device structure.
324  * @param command The SCPI command to send to the device (can be NULL).
325  * @param scpi_response Pointer where to store the parsed result.
326  *
327  * @return SR_OK on success, SR_ERR on failure.
328  */
329 SR_PRIV int sr_scpi_get_bool(struct sr_scpi_dev_inst *scpi,
330                              const char *command, gboolean *scpi_response)
331 {
332         int ret;
333         char *response;
334
335         response = NULL;
336
337         if (sr_scpi_get_string(scpi, command, &response) != SR_OK)
338                 if (!response)
339                         return SR_ERR;
340
341         if (parse_strict_bool(response, scpi_response) == SR_OK)
342                 ret = SR_OK;
343         else
344                 ret = SR_ERR;
345
346         g_free(response);
347
348         return ret;
349 }
350
351 /**
352  * Send a SCPI command, read the reply, parse it as an integer and store the
353  * result in scpi_response.
354  *
355  * @param scpi Previously initialised SCPI device structure.
356  * @param command The SCPI command to send to the device (can be NULL).
357  * @param scpi_response Pointer where to store the parsed result.
358  *
359  * @return SR_OK on success, SR_ERR on failure.
360  */
361 SR_PRIV int sr_scpi_get_int(struct sr_scpi_dev_inst *scpi,
362                             const char *command, int *scpi_response)
363 {
364         int ret;
365         char *response;
366
367         response = NULL;
368
369         if (sr_scpi_get_string(scpi, command, &response) != SR_OK)
370                 if (!response)
371                         return SR_ERR;
372
373         if (sr_atoi(response, scpi_response) == SR_OK)
374                 ret = SR_OK;
375         else
376                 ret = SR_ERR;
377
378         g_free(response);
379
380         return ret;
381 }
382
383 /**
384  * Send a SCPI command, read the reply, parse it as a float and store the
385  * result in scpi_response.
386  *
387  * @param scpi Previously initialised SCPI device structure.
388  * @param command The SCPI command to send to the device (can be NULL).
389  * @param scpi_response Pointer where to store the parsed result.
390  *
391  * @return SR_OK on success, SR_ERR on failure.
392  */
393 SR_PRIV int sr_scpi_get_float(struct sr_scpi_dev_inst *scpi,
394                               const char *command, float *scpi_response)
395 {
396         int ret;
397         char *response;
398
399         response = NULL;
400
401         if (sr_scpi_get_string(scpi, command, &response) != SR_OK)
402                 if (!response)
403                         return SR_ERR;
404
405         if (sr_atof(response, scpi_response) == SR_OK)
406                 ret = SR_OK;
407         else
408                 ret = SR_ERR;
409
410         g_free(response);
411
412         return ret;
413 }
414
415 /**
416  * Send a SCPI command, read the reply, parse it as a double and store the
417  * result in scpi_response.
418  *
419  * @param scpi Previously initialised SCPI device structure.
420  * @param command The SCPI command to send to the device (can be NULL).
421  * @param scpi_response Pointer where to store the parsed result.
422  *
423  * @return SR_OK on success, SR_ERR on failure.
424  */
425 SR_PRIV int sr_scpi_get_double(struct sr_scpi_dev_inst *scpi,
426                                const char *command, double *scpi_response)
427 {
428         int ret;
429         char *response;
430
431         response = NULL;
432
433         if (sr_scpi_get_string(scpi, command, &response) != SR_OK)
434                 if (!response)
435                         return SR_ERR;
436
437         if (sr_atod(response, scpi_response) == SR_OK)
438                 ret = SR_OK;
439         else
440                 ret = SR_ERR;
441
442         g_free(response);
443
444         return ret;
445 }
446
447 /**
448  * Send a SCPI *OPC? command, read the reply and return the result of the
449  * command.
450  *
451  * @param scpi Previously initialised SCPI device structure.
452  *
453  * @return SR_OK on success, SR_ERR on failure.
454  */
455 SR_PRIV int sr_scpi_get_opc(struct sr_scpi_dev_inst *scpi)
456 {
457         unsigned int i;
458         gboolean opc;
459
460         for (i = 0; i < SCPI_READ_RETRIES; ++i) {
461                 sr_scpi_get_bool(scpi, SCPI_CMD_OPC, &opc);
462                 if (opc)
463                         return SR_OK;
464                 g_usleep(SCPI_READ_RETRY_TIMEOUT);
465         }
466
467         return SR_ERR;
468 }
469
470 /**
471  * Send a SCPI command, read the reply, parse it as comma separated list of
472  * floats and store the as an result in scpi_response.
473  *
474  * @param scpi Previously initialised SCPI device structure.
475  * @param command The SCPI command to send to the device (can be NULL).
476  * @param scpi_response Pointer where to store the parsed result.
477  *
478  * @return SR_OK upon successfully parsing all values, SR_ERR upon a parsing
479  *         error or upon no response. The allocated response must be freed by
480  *         the caller in the case of an SR_OK as well as in the case of
481  *         parsing error.
482  */
483 SR_PRIV int sr_scpi_get_floatv(struct sr_scpi_dev_inst *scpi,
484                                const char *command, GArray **scpi_response)
485 {
486         int ret;
487         float tmp;
488         char *response;
489         gchar **ptr, **tokens;
490         GArray *response_array;
491
492         ret = SR_OK;
493         response = NULL;
494         tokens = NULL;
495
496         if (sr_scpi_get_string(scpi, command, &response) != SR_OK)
497                 if (!response)
498                         return SR_ERR;
499
500         tokens = g_strsplit(response, ",", 0);
501         ptr = tokens;
502
503         response_array = g_array_sized_new(TRUE, FALSE, sizeof(float), 256);
504
505         while (*ptr) {
506                 if (sr_atof(*ptr, &tmp) == SR_OK)
507                         response_array = g_array_append_val(response_array,
508                                                             tmp);
509                 else
510                         ret = SR_ERR;
511
512                 ptr++;
513         }
514         g_strfreev(tokens);
515         g_free(response);
516
517         if (ret == SR_ERR && response_array->len == 0) {
518                 g_array_free(response_array, TRUE);
519                 *scpi_response = NULL;
520                 return SR_ERR;
521         }
522
523         *scpi_response = response_array;
524
525         return ret;
526 }
527
528 /**
529  * Send a SCPI command, read the reply, parse it as comma separated list of
530  * unsigned 8 bit integers and store the as an result in scpi_response.
531  *
532  * @param scpi Previously initialised SCPI device structure.
533  * @param command The SCPI command to send to the device (can be NULL).
534  * @param scpi_response Pointer where to store the parsed result.
535  *
536  * @return SR_OK upon successfully parsing all values, SR_ERR upon a parsing
537  *         error or upon no response. The allocated response must be freed by
538  *         the caller in the case of an SR_OK as well as in the case of
539  *         parsing error.
540  */
541 SR_PRIV int sr_scpi_get_uint8v(struct sr_scpi_dev_inst *scpi,
542                                const char *command, GArray **scpi_response)
543 {
544         int tmp, ret;
545         char *response;
546         gchar **ptr, **tokens;
547         GArray *response_array;
548
549         ret = SR_OK;
550         response = NULL;
551         tokens = NULL;
552
553         if (sr_scpi_get_string(scpi, command, &response) != SR_OK)
554                 if (!response)
555                         return SR_ERR;
556
557         tokens = g_strsplit(response, ",", 0);
558         ptr = tokens;
559
560         response_array = g_array_sized_new(TRUE, FALSE, sizeof(uint8_t), 256);
561
562         while (*ptr) {
563                 if (sr_atoi(*ptr, &tmp) == SR_OK)
564                         response_array = g_array_append_val(response_array,
565                                                             tmp);
566                 else
567                         ret = SR_ERR;
568
569                 ptr++;
570         }
571         g_strfreev(tokens);
572         g_free(response);
573
574         if (response_array->len == 0) {
575                 g_array_free(response_array, TRUE);
576                 *scpi_response = NULL;
577                 return SR_ERR;
578         }
579
580         *scpi_response = response_array;
581
582         return ret;
583 }
584
585 /**
586  * Send the *IDN? SCPI command, receive the reply, parse it and store the
587  * reply as a sr_scpi_hw_info structure in the supplied scpi_response pointer.
588  *
589  * The hw_info structure must be freed by the caller via sr_scpi_hw_info_free().
590  *
591  * @param scpi Previously initialised SCPI device structure.
592  * @param scpi_response Pointer where to store the hw_info structure.
593  *
594  * @return SR_OK upon success, SR_ERR on failure.
595  */
596 SR_PRIV int sr_scpi_get_hw_id(struct sr_scpi_dev_inst *scpi,
597                               struct sr_scpi_hw_info **scpi_response)
598 {
599         int num_tokens;
600         char *response;
601         char *newline;
602         gchar **tokens;
603         struct sr_scpi_hw_info *hw_info;
604
605         response = NULL;
606         tokens = NULL;
607
608         if (sr_scpi_get_string(scpi, SCPI_CMD_IDN, &response) != SR_OK)
609                 if (!response)
610                         return SR_ERR;
611
612         sr_info("Got IDN string: '%s'", response);
613
614         /* Remove trailing newline if present. */
615         if ((newline = g_strrstr(response, "\n")))
616                 newline[0] = '\0';
617
618         /*
619          * The response to a '*IDN?' is specified by the SCPI spec. It contains
620          * a comma-separated list containing the manufacturer name, instrument
621          * model, serial number of the instrument and the firmware version.
622          */
623         tokens = g_strsplit(response, ",", 0);
624
625         for (num_tokens = 0; tokens[num_tokens] != NULL; num_tokens++);
626
627         if (num_tokens != 4) {
628                 sr_dbg("IDN response not according to spec: %80.s.", response);
629                 g_strfreev(tokens);
630                 g_free(response);
631                 return SR_ERR;
632         }
633         g_free(response);
634
635         hw_info = g_try_malloc(sizeof(struct sr_scpi_hw_info));
636         if (!hw_info) {
637                 g_strfreev(tokens);
638                 return SR_ERR_MALLOC;
639         }
640
641         hw_info->manufacturer = g_strdup(tokens[0]);
642         hw_info->model = g_strdup(tokens[1]);
643         hw_info->serial_number = g_strdup(tokens[2]);
644         hw_info->firmware_version = g_strdup(tokens[3]);
645
646         g_strfreev(tokens);
647
648         *scpi_response = hw_info;
649
650         return SR_OK;
651 }
652
653 /**
654  * Free a sr_scpi_hw_info struct.
655  *
656  * @param hw_info Pointer to the struct to free.
657  *
658  * This function is safe to call with a NULL pointer.
659  */
660 SR_PRIV void sr_scpi_hw_info_free(struct sr_scpi_hw_info *hw_info)
661 {
662         if (hw_info) {
663                 g_free(hw_info->manufacturer);
664                 g_free(hw_info->model);
665                 g_free(hw_info->serial_number);
666                 g_free(hw_info->firmware_version);
667                 g_free(hw_info);
668         }
669 }