]> sigrok.org Git - libsigrok.git/blob - hardware/common/scpi.c
ff18b6e507fb75287850f70db2b0e3cf2221f24f
[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 /* Message logging helpers with subsystem-specific prefix string. */
27 #define LOG_PREFIX "scpi: "
28 #define sr_log(l, s, args...) sr_log(l, LOG_PREFIX s, ## args)
29 #define sr_spew(s, args...) sr_spew(LOG_PREFIX s, ## args)
30 #define sr_dbg(s, args...) sr_dbg(LOG_PREFIX s, ## args)
31 #define sr_info(s, args...) sr_info(LOG_PREFIX s, ## args)
32 #define sr_warn(s, args...) sr_warn(LOG_PREFIX s, ## args)
33
34 #define SCPI_READ_RETRIES 100
35 #define SCPI_READ_RETRY_TIMEOUT 10000
36
37 /**
38  * Parse a string representation of a boolean-like value into a gboolean.
39  * Similar to sr_parse_boolstring but rejects strings which do not represent
40  * a boolean-like value.
41  *
42  * @param str String to convert.
43  * @param ret Pointer to a gboolean where the result of the conversion will be
44  * stored.
45  *
46  * @return SR_OK on success, SR_ERR on failure.
47  */
48 static int parse_strict_bool(const char *str, gboolean *ret)
49 {
50         if (!str)
51                 return SR_ERR_ARG;
52
53         if (!g_strcmp0(str, "1") ||
54             !g_ascii_strncasecmp(str, "y", 1) ||
55             !g_ascii_strncasecmp(str, "t", 1) ||
56             !g_ascii_strncasecmp(str, "yes", 3) ||
57             !g_ascii_strncasecmp(str, "true", 4) ||
58             !g_ascii_strncasecmp(str, "on", 2)) {
59                 *ret = TRUE;
60                 return SR_OK;
61         } else if (!g_strcmp0(str, "0") ||
62                    !g_ascii_strncasecmp(str, "n", 1) ||
63                    !g_ascii_strncasecmp(str, "f", 1) ||
64                    !g_ascii_strncasecmp(str, "no", 2) ||
65                    !g_ascii_strncasecmp(str, "false", 5) ||
66                    !g_ascii_strncasecmp(str, "off", 3)) {
67                 *ret = FALSE;
68                 return SR_OK;
69         }
70
71         return SR_ERR;
72 }
73
74 /**
75  * Send a SCPI command.
76  *
77  * @param serial Previously initialized serial port structure.
78  * @param command The SCPI command to send to the device.
79  *
80  * @return SR_OK on success, SR_ERR on failure.
81  */
82 SR_PRIV int sr_scpi_send(struct sr_serial_dev_inst *serial,
83                          const char *command)
84 {
85         int len, out;
86         gchar *terminated_command;
87
88         terminated_command = g_strconcat(command, "\n", NULL);
89         len = strlen(terminated_command);
90         out = serial_write(serial, terminated_command, len);
91         g_free(terminated_command);
92
93         if (out != len) {
94                 sr_dbg("Only sent %d/%d bytes of SCPI command: '%s'.", out,
95                        len, command);
96                 return SR_ERR;
97         }
98
99         sr_spew("Successfully sent SCPI command: '%s'.", command);
100
101         return SR_OK;
102 }
103
104 /**
105  * Send a SCPI command, receive the reply and store the reply in scpi_response.
106  *
107  * @param serial Previously initialized serial port structure.
108  * @param command The SCPI command to send to the device (can be NULL).
109  * @param scpi_response Pointer where to store the SCPI response.
110  *
111  * @return SR_OK upon fetching a full SCPI response, SR_ERR upon fetching an
112  *         incomplete or no response. The allocated response must be freed by
113  *         the caller in the case of a full response as well in the case of
114  *         an incomplete.
115  */
116 SR_PRIV int sr_scpi_get_string(struct sr_serial_dev_inst *serial,
117                                const char *command, char **scpi_response)
118 {
119         int len, ret;
120         char buf[256];
121         unsigned int i;
122         GString *response;
123
124         if (command)
125                 if (sr_scpi_send(serial, command) != SR_OK)
126                         return SR_ERR;
127
128         response = g_string_sized_new(1024);
129
130         for (i = 0; i <= SCPI_READ_RETRIES; i++) {
131                 while ((len = serial_read(serial, buf, sizeof(buf))) > 0)
132                         response = g_string_append_len(response, buf, len);
133
134                 if (response->len > 0 &&
135                     response->str[response->len-1] == '\n') {
136                         sr_spew("Fetched full SCPI response.");
137                         break;
138                 }
139
140                 g_usleep(SCPI_READ_RETRY_TIMEOUT);
141         }
142
143         if (response->len == 0) {
144                 sr_dbg("No SCPI response received.");
145                 g_string_free(response, TRUE);
146                 *scpi_response = NULL;
147                 return SR_ERR;
148         } else if (response->str[response->len - 1] == '\n') {
149                 /*
150                  * The SCPI response contains a LF ('\n') at the end and we
151                  * don't need this so replace it with a '\0' and decrement
152                  * the length.
153                  */
154                 response->str[--response->len] = '\0';
155                 ret = SR_OK;
156         } else {
157                 sr_warn("Incomplete SCPI response received!");
158                 ret = SR_ERR;
159         }
160
161         /* Minor optimization: steal the string instead of copying. */
162         *scpi_response = response->str;
163
164         /* A SCPI response can be quite large, print at most 50 characters. */
165         sr_dbg("SCPI response for command %s received (length %d): '%.50s'",
166                command, response->len, response->str);
167
168         g_string_free(response, FALSE);
169
170         return ret;
171 }
172
173 /**
174  * Send a SCPI command, read the reply, parse it as a bool value and store the
175  * result in scpi_response.
176  *
177  * @param serial Previously initialized serial port structure.
178  * @param command The SCPI command to send to the device (can be NULL).
179  * @param scpi_response Pointer where to store the parsed result.
180  *
181  * @return SR_OK on success, SR_ERR on failure.
182  */
183 SR_PRIV int sr_scpi_get_bool(struct sr_serial_dev_inst *serial,
184                              const char *command, gboolean *scpi_response)
185 {
186         int ret;
187         char *response;
188
189         response = NULL;
190
191         if (sr_scpi_get_string(serial, command, &response) != SR_OK)
192                 if (!response)
193                         return SR_ERR;
194
195         if (parse_strict_bool(response, scpi_response) == SR_OK)
196                 ret = SR_OK;
197         else
198                 ret = SR_ERR;
199
200         g_free(response);
201
202         return ret;
203 }
204
205 /**
206  * Send a SCPI command, read the reply, parse it as an integer and store the
207  * result in scpi_response.
208  *
209  * @param serial Previously initialized serial port structure.
210  * @param command The SCPI command to send to the device (can be NULL).
211  * @param scpi_response Pointer where to store the parsed result.
212  *
213  * @return SR_OK on success, SR_ERR on failure.
214  */
215 SR_PRIV int sr_scpi_get_int(struct sr_serial_dev_inst *serial,
216                             const char *command, int *scpi_response)
217 {
218         int ret;
219         char *response;
220
221         response = NULL;
222
223         if (sr_scpi_get_string(serial, command, &response) != SR_OK)
224                 if (!response)
225                         return SR_ERR;
226
227         if (sr_atoi(response, scpi_response) == SR_OK)
228                 ret = SR_OK;
229         else
230                 ret = SR_ERR;
231
232         g_free(response);
233
234         return ret;
235 }
236
237 /**
238  * Send a SCPI command, read the reply, parse it as a float and store the
239  * result in scpi_response.
240  *
241  * @param serial Previously initialized serial port structure.
242  * @param command The SCPI command to send to the device (can be NULL).
243  * @param scpi_response Pointer where to store the parsed result.
244  *
245  * @return SR_OK on success, SR_ERR on failure.
246  */
247 SR_PRIV int sr_scpi_get_float(struct sr_serial_dev_inst *serial,
248                               const char *command, float *scpi_response)
249 {
250         int ret;
251         char *response;
252
253         response = NULL;
254
255         if (sr_scpi_get_string(serial, command, &response) != SR_OK)
256                 if (!response)
257                         return SR_ERR;
258
259         if (sr_atof(response, scpi_response) == SR_OK)
260                 ret = SR_OK;
261         else
262                 ret = SR_ERR;
263
264         g_free(response);
265
266         return ret;
267 }
268
269 /**
270  * Send a SCPI command, read the reply, parse it as a double and store the
271  * result in scpi_response.
272  *
273  * @param serial Previously initialized serial port structure.
274  * @param command The SCPI command to send to the device (can be NULL).
275  * @param scpi_response Pointer where to store the parsed result.
276  *
277  * @return SR_OK on success, SR_ERR on failure.
278  */
279 SR_PRIV int sr_scpi_get_double(struct sr_serial_dev_inst *serial,
280                                const char *command, double *scpi_response)
281 {
282         int ret;
283         char *response;
284
285         response = NULL;
286
287         if (sr_scpi_get_string(serial, command, &response) != SR_OK)
288                 if (!response)
289                         return SR_ERR;
290
291         if (sr_atod(response, scpi_response) == SR_OK)
292                 ret = SR_OK;
293         else
294                 ret = SR_ERR;
295
296         g_free(response);
297
298         return ret;
299 }
300
301 /**
302  * Send a SCPI *OPC? command, read the reply and return the result of the
303  * command.
304  *
305  * @param serial Previously initialized serial port structure.
306  *
307  * @return SR_OK on success, SR_ERR on failure.
308  */
309 SR_PRIV int sr_scpi_get_opc(struct sr_serial_dev_inst *serial)
310 {
311         unsigned int i;
312         gboolean opc;
313
314         for (i = 0; i < SCPI_READ_RETRIES; ++i) {
315                 sr_scpi_get_bool(serial, SCPI_CMD_OPC, &opc);
316                 if (opc)
317                         return SR_OK;
318                 g_usleep(SCPI_READ_RETRY_TIMEOUT);
319         }
320
321         return SR_ERR;
322 }
323
324 /**
325  * Send a SCPI command, read the reply, parse it as comma separated list of
326  * floats and store the as an result in scpi_response.
327  *
328  * @param serial Previously initialized serial port structure.
329  * @param command The SCPI command to send to the device (can be NULL).
330  * @param scpi_response Pointer where to store the parsed result.
331  *
332  * @return SR_OK upon successfully parsing all values, SR_ERR upon a parsing
333  *         error or upon no response. The allocated response must be freed by
334  *         the caller in the case of an SR_OK as well as in the case of
335  *         parsing error.
336  */
337 SR_PRIV int sr_scpi_get_floatv(struct sr_serial_dev_inst *serial,
338                                const char *command, GArray **scpi_response)
339 {
340         int ret;
341         float tmp;
342         char *response;
343         gchar **ptr, **tokens;
344         GArray *response_array;
345
346         ret = SR_OK;
347         response = NULL;
348         tokens = NULL;
349
350         if (sr_scpi_get_string(serial, command, &response) != SR_OK)
351                 if (!response)
352                         return SR_ERR;
353
354         tokens = g_strsplit(response, ",", 0);
355         ptr = tokens;
356
357         response_array = g_array_sized_new(TRUE, FALSE, sizeof(float), 256);
358
359         while (*ptr) {
360                 if (sr_atof(*ptr, &tmp) == SR_OK)
361                         response_array = g_array_append_val(response_array,
362                                                             tmp);
363                 else
364                         ret = SR_ERR;
365
366                 ptr++;
367         }
368         g_strfreev(tokens);
369         g_free(response);
370
371         if (ret == SR_ERR && response_array->len == 0) {
372                 g_array_free(response_array, TRUE);
373                 *scpi_response = NULL;
374                 return SR_ERR;
375         }
376
377         *scpi_response = response_array;
378
379         return ret;
380 }
381
382 /**
383  * Send a SCPI command, read the reply, parse it as comma separated list of
384  * unsigned 8 bit integers and store the as an result in scpi_response.
385  *
386  * @param serial Previously initialized serial port structure.
387  * @param command The SCPI command to send to the device (can be NULL).
388  * @param scpi_response Pointer where to store the parsed result.
389  *
390  * @return SR_OK upon successfully parsing all values, SR_ERR upon a parsing
391  *         error or upon no response. The allocated response must be freed by
392  *         the caller in the case of an SR_OK as well as in the case of
393  *         parsing error.
394  */
395 SR_PRIV int sr_scpi_get_uint8v(struct sr_serial_dev_inst *serial,
396                                const char *command, GArray **scpi_response)
397 {
398         int tmp, ret;
399         char *response;
400         gchar **ptr, **tokens;
401         GArray *response_array;
402
403         ret = SR_OK;
404         response = NULL;
405         tokens = NULL;
406
407         if (sr_scpi_get_string(serial, command, &response) != SR_OK)
408                 if (!response)
409                         return SR_ERR;
410
411         tokens = g_strsplit(response, ",", 0);
412         ptr = tokens;
413
414         response_array = g_array_sized_new(TRUE, FALSE, sizeof(uint8_t), 256);
415
416         while (*ptr) {
417                 if (sr_atoi(*ptr, &tmp) == SR_OK)
418                         response_array = g_array_append_val(response_array,
419                                                             tmp);
420                 else
421                         ret = SR_ERR;
422
423                 ptr++;
424         }
425         g_strfreev(tokens);
426         g_free(response);
427
428         if (response_array->len == 0) {
429                 g_array_free(response_array, TRUE);
430                 *scpi_response = NULL;
431                 return SR_ERR;
432         }
433
434         *scpi_response = response_array;
435
436         return ret;
437 }
438
439 /**
440  * Send the *IDN? SCPI command, receive the reply, parse it and store the
441  * reply as a sr_scpi_hw_info structure in the supplied scpi_response pointer.
442  *
443  * The hw_info structure must be freed by the caller via sr_scpi_hw_info_free().
444  *
445  * @param serial Previously initialized serial port structure.
446  * @param scpi_response Pointer where to store the hw_info structure.
447  *
448  * @return SR_OK upon success, SR_ERR on failure.
449  */
450 SR_PRIV int sr_scpi_get_hw_id(struct sr_serial_dev_inst *serial,
451                               struct sr_scpi_hw_info **scpi_response)
452 {
453         int num_tokens;
454         char *response;
455         gchar **tokens;
456         struct sr_scpi_hw_info *hw_info;
457
458         response = NULL;
459         tokens = NULL;
460
461         if (sr_scpi_get_string(serial, SCPI_CMD_IDN, &response) != SR_OK)
462                 if (!response)
463                         return SR_ERR;
464
465         /*
466          * The response to a '*IDN?' is specified by the SCPI spec. It contains
467          * a comma-separated list containing the manufacturer name, instrument
468          * model, serial number of the instrument and the firmware version.
469          */
470         tokens = g_strsplit(response, ",", 0);
471
472         for (num_tokens = 0; tokens[num_tokens] != NULL; num_tokens++);
473
474         if (num_tokens != 4) {
475                 sr_dbg("IDN response not according to spec: %80.s.", response);
476                 g_strfreev(tokens);
477                 g_free(response);
478                 return SR_ERR;
479         }
480         g_free(response);
481
482         hw_info = g_try_malloc(sizeof(struct sr_scpi_hw_info));
483         if (!hw_info) {
484                 g_strfreev(tokens);
485                 return SR_ERR_MALLOC;
486         }
487
488         hw_info->manufacturer = g_strdup(tokens[0]);
489         hw_info->model = g_strdup(tokens[1]);
490         hw_info->serial_number = g_strdup(tokens[2]);
491         hw_info->firmware_version = g_strdup(tokens[3]);
492
493         g_strfreev(tokens);
494
495         *scpi_response = hw_info;
496
497         return SR_OK;
498 }
499
500 /**
501  * Free a sr_scpi_hw_info struct.
502  *
503  * @param hw_info Pointer to the struct to free.
504  *
505  * This function is safe to call with a NULL pointer.
506  */
507 SR_PRIV void sr_scpi_hw_info_free(struct sr_scpi_hw_info *hw_info)
508 {
509         if (hw_info) {
510                 g_free(hw_info->manufacturer);
511                 g_free(hw_info->model);
512                 g_free(hw_info->serial_number);
513                 g_free(hw_info->firmware_version);
514                 g_free(hw_info);
515         }
516 }