]> sigrok.org Git - libsigrok.git/blob - src/hardware/scpi-dmm/protocol.c
scpi-dmm: run OPC queries immediately before essential commands
[libsigrok.git] / src / hardware / scpi-dmm / protocol.c
1 /*
2  * This file is part of the libsigrok project.
3  *
4  * Copyright (C) 2018 Gerhard Sittig <gerhard.sittig@gmx.net>
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 <config.h>
21 #include <math.h>
22 #include <string.h>
23 #include "protocol.h"
24
25 #define WITH_CMD_DELAY 0        /* TODO See which devices need delays. */
26
27 SR_PRIV void scpi_dmm_cmd_delay(struct sr_scpi_dev_inst *scpi)
28 {
29         if (WITH_CMD_DELAY)
30                 g_usleep(WITH_CMD_DELAY * 1000);
31         sr_scpi_get_opc(scpi);
32 }
33
34 SR_PRIV const struct mqopt_item *scpi_dmm_lookup_mq_number(
35         const struct sr_dev_inst *sdi, enum sr_mq mq, enum sr_mqflag flag)
36 {
37         struct dev_context *devc;
38         size_t i;
39         const struct mqopt_item *item;
40
41         devc = sdi->priv;
42         for (i = 0; i < devc->model->mqopt_size; i++) {
43                 item = &devc->model->mqopts[i];
44                 if (item->mq != mq || item->mqflag != flag)
45                         continue;
46                 return item;
47         }
48
49         return NULL;
50 }
51
52 SR_PRIV const struct mqopt_item *scpi_dmm_lookup_mq_text(
53         const struct sr_dev_inst *sdi, const char *text)
54 {
55         struct dev_context *devc;
56         size_t i;
57         const struct mqopt_item *item;
58
59         devc = sdi->priv;
60         for (i = 0; i < devc->model->mqopt_size; i++) {
61                 item = &devc->model->mqopts[i];
62                 if (!item->scpi_func_query || !item->scpi_func_query[0])
63                         continue;
64                 if (!g_str_has_prefix(text, item->scpi_func_query))
65                         continue;
66                 return item;
67         }
68
69         return NULL;
70 }
71
72 SR_PRIV int scpi_dmm_get_mq(const struct sr_dev_inst *sdi,
73         enum sr_mq *mq, enum sr_mqflag *flag, char **rsp,
74         const struct mqopt_item **mqitem)
75 {
76         struct dev_context *devc;
77         const char *command;
78         char *response;
79         const char *have;
80         int ret;
81         const struct mqopt_item *item;
82
83         devc = sdi->priv;
84         if (mq)
85                 *mq = 0;
86         if (flag)
87                 *flag = 0;
88         if (rsp)
89                 *rsp = NULL;
90         if (mqitem)
91                 *mqitem = NULL;
92
93         scpi_dmm_cmd_delay(sdi->conn);
94         command = sr_scpi_cmd_get(devc->cmdset, DMM_CMD_QUERY_FUNC);
95         if (!command || !*command)
96                 return SR_ERR_NA;
97         response = NULL;
98         ret = sr_scpi_get_string(sdi->conn, command, &response);
99         if (ret != SR_OK)
100                 return ret;
101         if (!response || !*response)
102                 return SR_ERR_NA;
103         have = response;
104         if (*have == '"')
105                 have++;
106
107         ret = SR_ERR_NA;
108         item = scpi_dmm_lookup_mq_text(sdi, have);
109         if (item) {
110                 if (mq)
111                         *mq = item->mq;
112                 if (flag)
113                         *flag = item->mqflag;
114                 if (mqitem)
115                         *mqitem = item;
116                 ret = SR_OK;
117         }
118
119         if (rsp) {
120                 *rsp = response;
121                 response = NULL;
122         }
123         g_free(response);
124
125         return ret;
126 }
127
128 SR_PRIV int scpi_dmm_set_mq(const struct sr_dev_inst *sdi,
129         enum sr_mq mq, enum sr_mqflag flag)
130 {
131         struct dev_context *devc;
132         const struct mqopt_item *item;
133         const char *mode, *command;
134         int ret;
135
136         devc = sdi->priv;
137         item = scpi_dmm_lookup_mq_number(sdi, mq, flag);
138         if (!item)
139                 return SR_ERR_NA;
140
141         mode = item->scpi_func_setup;
142         command = sr_scpi_cmd_get(devc->cmdset, DMM_CMD_SETUP_FUNC);
143         scpi_dmm_cmd_delay(sdi->conn);
144         ret = sr_scpi_send(sdi->conn, command, mode);
145         if (ret != SR_OK)
146                 return ret;
147
148         return SR_OK;
149 }
150
151 SR_PRIV int scpi_dmm_get_meas_agilent(const struct sr_dev_inst *sdi, size_t ch)
152 {
153         struct sr_scpi_dev_inst *scpi;
154         struct dev_context *devc;
155         struct scpi_dmm_acq_info *info;
156         struct sr_datafeed_analog *analog;
157         int ret;
158         enum sr_mq mq;
159         enum sr_mqflag mqflag;
160         char *mode_response;
161         const char *p;
162         char **fields;
163         size_t count;
164         char prec_text[20];
165         const struct mqopt_item *item;
166         int prec_exp;
167         const char *command;
168         char *response;
169         gboolean use_double;
170         int sig_digits, val_exp;
171         int digits;
172         enum sr_unit unit;
173
174         scpi = sdi->conn;
175         devc = sdi->priv;
176         info = &devc->run_acq_info;
177         analog = &info->analog[ch];
178
179         /*
180          * Get the meter's current mode, keep the response around.
181          * Skip the measurement if the mode is uncertain.
182          */
183         ret = scpi_dmm_get_mq(sdi, &mq, &mqflag, &mode_response, &item);
184         if (ret != SR_OK) {
185                 g_free(mode_response);
186                 return ret;
187         }
188         if (!mode_response)
189                 return SR_ERR;
190         if (!mq) {
191                 g_free(mode_response);
192                 return +1;
193         }
194
195         /*
196          * Get the last comma separated field of the function query
197          * response, or fallback to the model's default precision for
198          * the current function. This copes with either of these cases:
199          *   VOLT +1.00000E-01,+1.00000E-06
200          *   DIOD
201          *   TEMP THER,5000,+1.00000E+00,+1.00000E-01
202          */
203         p = sr_scpi_unquote_string(mode_response);
204         fields = g_strsplit(p, ",", 0);
205         count = g_strv_length(fields);
206         if (count >= 2) {
207                 snprintf(prec_text, sizeof(prec_text),
208                         "%s", fields[count - 1]);
209                 p = prec_text;
210         } else if (!item) {
211                 p = NULL;
212         } else if (item->default_precision == NO_DFLT_PREC) {
213                 p = NULL;
214         } else {
215                 snprintf(prec_text, sizeof(prec_text),
216                         "1e%d", item->default_precision);
217                 p = prec_text;
218         }
219         g_strfreev(fields);
220
221         /*
222          * Need to extract the exponent value ourselves, since a strtod()
223          * call will "eat" the exponent, too. Strip space, strip sign,
224          * strip float number (without! exponent), check for exponent
225          * and get exponent value. Accept absence of Esnn suffixes.
226          */
227         while (p && *p && g_ascii_isspace(*p))
228                 p++;
229         if (p && *p && (*p == '+' || *p == '-'))
230                 p++;
231         while (p && *p && g_ascii_isdigit(*p))
232                 p++;
233         if (p && *p && *p == '.')
234                 p++;
235         while (p && *p && g_ascii_isdigit(*p))
236                 p++;
237         ret = SR_OK;
238         if (!p || !*p)
239                 prec_exp = 0;
240         else if (*p != 'e' && *p != 'E')
241                 ret = SR_ERR_DATA;
242         else
243                 ret = sr_atoi(++p, &prec_exp);
244         g_free(mode_response);
245         if (ret != SR_OK)
246                 return ret;
247
248         /*
249          * Get the measurement value. Make sure to strip trailing space
250          * or else number conversion may fail in fatal ways. Detect OL
251          * conditions. Determine the measurement's precision: Count the
252          * number of significant digits before the period, and get the
253          * exponent's value.
254          *
255          * The text presentation of values is like this:
256          *   +1.09450000E-01
257          * Skip space/sign, count digits before the period, skip to the
258          * exponent, get exponent value.
259          *
260          * TODO Can sr_parse_rational() return the exponent for us? In
261          * addition to providing a precise rational value instead of a
262          * float that's an approximation of the received value? Can the
263          * 'analog' struct that we fill in carry rationals?
264          *
265          * Use double precision FP here during conversion. Optionally
266          * downgrade to single precision later to reduce the amount of
267          * logged information.
268          */
269         command = sr_scpi_cmd_get(devc->cmdset, DMM_CMD_QUERY_VALUE);
270         if (!command || !*command)
271                 return SR_ERR_NA;
272         scpi_dmm_cmd_delay(scpi);
273         ret = sr_scpi_get_string(scpi, command, &response);
274         if (ret != SR_OK)
275                 return ret;
276         g_strstrip(response);
277         use_double = devc->model->digits > 6;
278         ret = sr_atod_ascii(response, &info->d_value);
279         if (ret != SR_OK) {
280                 g_free(response);
281                 return ret;
282         }
283         if (!response)
284                 return SR_ERR;
285         if (info->d_value > +9e37) {
286                 info->d_value = +INFINITY;
287         } else if (info->d_value < -9e37) {
288                 info->d_value = -INFINITY;
289         } else {
290                 p = response;
291                 while (p && *p && g_ascii_isspace(*p))
292                         p++;
293                 if (p && *p && (*p == '-' || *p == '+'))
294                         p++;
295                 sig_digits = 0;
296                 while (p && *p && g_ascii_isdigit(*p)) {
297                         sig_digits++;
298                         p++;
299                 }
300                 if (p && *p && *p == '.')
301                         p++;
302                 while (p && *p && g_ascii_isdigit(*p))
303                         p++;
304                 ret = SR_OK;
305                 if (!p || !*p)
306                         val_exp = 0;
307                 else if (*p != 'e' && *p != 'E')
308                         ret = SR_ERR_DATA;
309                 else
310                         ret = sr_atoi(++p, &val_exp);
311         }
312         g_free(response);
313         if (ret != SR_OK)
314                 return ret;
315         /*
316          * TODO Come up with the most appropriate 'digits' calculation.
317          * This implementation assumes that either the device provides
318          * the resolution with the query for the meter's function, or
319          * the driver uses a fallback text pretending the device had
320          * provided it. This works with supported Agilent devices.
321          *
322          * An alternative may be to assume a given digits count which
323          * depends on the device, and adjust that count based on the
324          * value's significant digits and exponent. But this approach
325          * fails if devices change their digits count depending on
326          * modes or user requests, and also fails when e.g. devices
327          * with "100000 counts" can provide values between 100000 and
328          * 120000 in either 4 or 5 digits modes, depending on the most
329          * recent trend of the values. This less robust approach should
330          * only be taken if the mode inquiry won't yield the resolution
331          * (as e.g. DIOD does on 34405A, though we happen to know the
332          * fixed resolution for this very mode on this very model).
333          *
334          * For now, let's keep the prepared code path for the second
335          * approach in place, should some Agilent devices need it yet
336          * benefit from re-using most of the remaining acquisition
337          * routine.
338          */
339 #if 1
340         digits = -prec_exp;
341 #else
342         digits = devc->model->digits;
343         digits -= sig_digits;
344         digits -= val_exp;
345 #endif
346
347         /*
348          * Fill in the 'analog' description: value, encoding, meaning.
349          * Callers will fill in the sample count, and channel name,
350          * and will send out the packet.
351          */
352         if (use_double) {
353                 analog->data = &info->d_value;
354                 analog->encoding->unitsize = sizeof(info->d_value);
355         } else {
356                 info->f_value = info->d_value;
357                 analog->data = &info->f_value;
358                 analog->encoding->unitsize = sizeof(info->f_value);
359         }
360         analog->encoding->is_float = TRUE;
361 #ifdef WORDS_BIGENDIAN
362         analog->encoding->is_bigendian = TRUE;
363 #else
364         analog->encoding->is_bigendian = FALSE;
365 #endif
366         analog->encoding->digits = digits;
367         analog->meaning->mq = mq;
368         analog->meaning->mqflags = mqflag;
369         switch (mq) {
370         case SR_MQ_VOLTAGE:
371                 unit = SR_UNIT_VOLT;
372                 break;
373         case SR_MQ_CURRENT:
374                 unit = SR_UNIT_AMPERE;
375                 break;
376         case SR_MQ_RESISTANCE:
377         case SR_MQ_CONTINUITY:
378                 unit = SR_UNIT_OHM;
379                 break;
380         case SR_MQ_CAPACITANCE:
381                 unit = SR_UNIT_FARAD;
382                 break;
383         case SR_MQ_TEMPERATURE:
384                 unit = SR_UNIT_CELSIUS;
385                 break;
386         case SR_MQ_FREQUENCY:
387                 unit = SR_UNIT_HERTZ;
388                 break;
389         default:
390                 return SR_ERR_NA;
391         }
392         analog->meaning->unit = unit;
393         analog->spec->spec_digits = digits;
394
395         return SR_OK;
396 }
397
398 /* Strictly speaking this is a timer controlled poll routine. */
399 SR_PRIV int scpi_dmm_receive_data(int fd, int revents, void *cb_data)
400 {
401         struct sr_dev_inst *sdi;
402         struct sr_scpi_dev_inst *scpi;
403         struct dev_context *devc;
404         struct scpi_dmm_acq_info *info;
405         gboolean sent_sample;
406         size_t ch;
407         struct sr_channel *channel;
408         int ret;
409
410         (void)fd;
411         (void)revents;
412
413         sdi = cb_data;
414         if (!sdi)
415                 return TRUE;
416         scpi = sdi->conn;
417         devc = sdi->priv;
418         if (!scpi || !devc)
419                 return TRUE;
420         info = &devc->run_acq_info;
421
422         sent_sample = FALSE;
423         ret = SR_OK;
424         for (ch = 0; ch < devc->num_channels; ch++) {
425                 /* Check the channel's enabled status. */
426                 channel = g_slist_nth_data(sdi->channels, ch);
427                 if (!channel->enabled)
428                         continue;
429
430                 /*
431                  * Prepare an analog measurement value. Note that digits
432                  * will get updated later.
433                  */
434                 info->packet.type = SR_DF_ANALOG;
435                 info->packet.payload = &info->analog[ch];
436                 sr_analog_init(&info->analog[ch], &info->encoding[ch],
437                         &info->meaning[ch], &info->spec[ch], 0);
438
439                 /* Just check OPC before sending another request. */
440                 scpi_dmm_cmd_delay(sdi->conn);
441
442                 /*
443                  * Have the model take and interpret a measurement. Lack
444                  * of support is pointless, failed retrieval/conversion
445                  * is considered fatal. The routine will fill in the
446                  * 'analog' details, except for channel name and sample
447                  * count (assume one value per channel).
448                  *
449                  * Note that non-zero non-negative return codes signal
450                  * that the channel's data shell get skipped in this
451                  * iteration over the channels. This copes with devices
452                  * or modes where channels may provide data at different
453                  * rates.
454                  */
455                 if (!devc->model->get_measurement) {
456                         ret = SR_ERR_NA;
457                         break;
458                 }
459                 ret = devc->model->get_measurement(sdi, ch);
460                 if (ret > 0)
461                         continue;
462                 if (ret != SR_OK)
463                         break;
464
465                 /* Send the packet that was filled in by the model's routine. */
466                 info->analog[ch].num_samples = 1;
467                 info->analog[ch].meaning->channels = g_slist_append(NULL, channel);
468                 sr_session_send(sdi, &info->packet);
469                 g_slist_free(info->analog[ch].meaning->channels);
470                 sent_sample = TRUE;
471         }
472         if (sent_sample)
473                 sr_sw_limits_update_samples_read(&devc->limits, 1);
474         if (ret != SR_OK) {
475                 /* Stop acquisition upon communication or data errors. */
476                 sr_dev_acquisition_stop(sdi);
477                 return TRUE;
478         }
479         if (sr_sw_limits_check(&devc->limits))
480                 sr_dev_acquisition_stop(sdi);
481
482         return TRUE;
483 }