]> sigrok.org Git - libsigrok.git/blob - src/hardware/scpi-dmm/protocol.c
scpi-dmm: Add infinity limit to model-specific config.
[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         double limit;
174
175         scpi = sdi->conn;
176         devc = sdi->priv;
177         info = &devc->run_acq_info;
178         analog = &info->analog[ch];
179
180         /*
181          * Get the meter's current mode, keep the response around.
182          * Skip the measurement if the mode is uncertain.
183          */
184         ret = scpi_dmm_get_mq(sdi, &mq, &mqflag, &mode_response, &item);
185         if (ret != SR_OK) {
186                 g_free(mode_response);
187                 return ret;
188         }
189         if (!mode_response)
190                 return SR_ERR;
191         if (!mq) {
192                 g_free(mode_response);
193                 return +1;
194         }
195
196         /*
197          * Get the last comma separated field of the function query
198          * response, or fallback to the model's default precision for
199          * the current function. This copes with either of these cases:
200          *   VOLT +1.00000E-01,+1.00000E-06
201          *   DIOD
202          *   TEMP THER,5000,+1.00000E+00,+1.00000E-01
203          */
204         p = sr_scpi_unquote_string(mode_response);
205         fields = g_strsplit(p, ",", 0);
206         count = g_strv_length(fields);
207         if (count >= 2) {
208                 snprintf(prec_text, sizeof(prec_text),
209                         "%s", fields[count - 1]);
210                 p = prec_text;
211         } else if (!item) {
212                 p = NULL;
213         } else if (item->default_precision == NO_DFLT_PREC) {
214                 p = NULL;
215         } else {
216                 snprintf(prec_text, sizeof(prec_text),
217                         "1e%d", item->default_precision);
218                 p = prec_text;
219         }
220         g_strfreev(fields);
221
222         /*
223          * Need to extract the exponent value ourselves, since a strtod()
224          * call will "eat" the exponent, too. Strip space, strip sign,
225          * strip float number (without! exponent), check for exponent
226          * and get exponent value. Accept absence of Esnn suffixes.
227          */
228         while (p && *p && g_ascii_isspace(*p))
229                 p++;
230         if (p && *p && (*p == '+' || *p == '-'))
231                 p++;
232         while (p && *p && g_ascii_isdigit(*p))
233                 p++;
234         if (p && *p && *p == '.')
235                 p++;
236         while (p && *p && g_ascii_isdigit(*p))
237                 p++;
238         ret = SR_OK;
239         if (!p || !*p)
240                 prec_exp = 0;
241         else if (*p != 'e' && *p != 'E')
242                 ret = SR_ERR_DATA;
243         else
244                 ret = sr_atoi(++p, &prec_exp);
245         g_free(mode_response);
246         if (ret != SR_OK)
247                 return ret;
248
249         /*
250          * Get the measurement value. Make sure to strip trailing space
251          * or else number conversion may fail in fatal ways. Detect OL
252          * conditions. Determine the measurement's precision: Count the
253          * number of significant digits before the period, and get the
254          * exponent's value.
255          *
256          * The text presentation of values is like this:
257          *   +1.09450000E-01
258          * Skip space/sign, count digits before the period, skip to the
259          * exponent, get exponent value.
260          *
261          * TODO Can sr_parse_rational() return the exponent for us? In
262          * addition to providing a precise rational value instead of a
263          * float that's an approximation of the received value? Can the
264          * 'analog' struct that we fill in carry rationals?
265          *
266          * Use double precision FP here during conversion. Optionally
267          * downgrade to single precision later to reduce the amount of
268          * logged information.
269          */
270         command = sr_scpi_cmd_get(devc->cmdset, DMM_CMD_QUERY_VALUE);
271         if (!command || !*command)
272                 return SR_ERR_NA;
273         scpi_dmm_cmd_delay(scpi);
274         ret = sr_scpi_get_string(scpi, command, &response);
275         if (ret != SR_OK)
276                 return ret;
277         g_strstrip(response);
278         use_double = devc->model->digits > 6;
279         ret = sr_atod_ascii(response, &info->d_value);
280         if (ret != SR_OK) {
281                 g_free(response);
282                 return ret;
283         }
284         if (!response)
285                 return SR_ERR;
286         limit = 9e37;
287         if (info->d_value > +limit) {
288                 info->d_value = +INFINITY;
289         } else if (info->d_value < -limit) {
290                 info->d_value = -INFINITY;
291         } else {
292                 p = response;
293                 while (p && *p && g_ascii_isspace(*p))
294                         p++;
295                 if (p && *p && (*p == '-' || *p == '+'))
296                         p++;
297                 sig_digits = 0;
298                 while (p && *p && g_ascii_isdigit(*p)) {
299                         sig_digits++;
300                         p++;
301                 }
302                 if (p && *p && *p == '.')
303                         p++;
304                 while (p && *p && g_ascii_isdigit(*p))
305                         p++;
306                 ret = SR_OK;
307                 if (!p || !*p)
308                         val_exp = 0;
309                 else if (*p != 'e' && *p != 'E')
310                         ret = SR_ERR_DATA;
311                 else
312                         ret = sr_atoi(++p, &val_exp);
313         }
314         g_free(response);
315         if (ret != SR_OK)
316                 return ret;
317         /*
318          * TODO Come up with the most appropriate 'digits' calculation.
319          * This implementation assumes that either the device provides
320          * the resolution with the query for the meter's function, or
321          * the driver uses a fallback text pretending the device had
322          * provided it. This works with supported Agilent devices.
323          *
324          * An alternative may be to assume a given digits count which
325          * depends on the device, and adjust that count based on the
326          * value's significant digits and exponent. But this approach
327          * fails if devices change their digits count depending on
328          * modes or user requests, and also fails when e.g. devices
329          * with "100000 counts" can provide values between 100000 and
330          * 120000 in either 4 or 5 digits modes, depending on the most
331          * recent trend of the values. This less robust approach should
332          * only be taken if the mode inquiry won't yield the resolution
333          * (as e.g. DIOD does on 34405A, though we happen to know the
334          * fixed resolution for this very mode on this very model).
335          *
336          * For now, let's keep the prepared code path for the second
337          * approach in place, should some Agilent devices need it yet
338          * benefit from re-using most of the remaining acquisition
339          * routine.
340          */
341 #if 1
342         digits = -prec_exp;
343 #else
344         digits = devc->model->digits;
345         digits -= sig_digits;
346         digits -= val_exp;
347 #endif
348
349         /*
350          * Fill in the 'analog' description: value, encoding, meaning.
351          * Callers will fill in the sample count, and channel name,
352          * and will send out the packet.
353          */
354         if (use_double) {
355                 analog->data = &info->d_value;
356                 analog->encoding->unitsize = sizeof(info->d_value);
357         } else {
358                 info->f_value = info->d_value;
359                 analog->data = &info->f_value;
360                 analog->encoding->unitsize = sizeof(info->f_value);
361         }
362         analog->encoding->digits = digits;
363         analog->meaning->mq = mq;
364         analog->meaning->mqflags = mqflag;
365         switch (mq) {
366         case SR_MQ_VOLTAGE:
367                 unit = SR_UNIT_VOLT;
368                 break;
369         case SR_MQ_CURRENT:
370                 unit = SR_UNIT_AMPERE;
371                 break;
372         case SR_MQ_RESISTANCE:
373         case SR_MQ_CONTINUITY:
374                 unit = SR_UNIT_OHM;
375                 break;
376         case SR_MQ_CAPACITANCE:
377                 unit = SR_UNIT_FARAD;
378                 break;
379         case SR_MQ_TEMPERATURE:
380                 unit = SR_UNIT_CELSIUS;
381                 break;
382         case SR_MQ_FREQUENCY:
383                 unit = SR_UNIT_HERTZ;
384                 break;
385         case SR_MQ_TIME:
386                 unit = SR_UNIT_SECOND;
387                 break;
388         default:
389                 return SR_ERR_NA;
390         }
391         analog->meaning->unit = unit;
392         analog->spec->spec_digits = digits;
393
394         return SR_OK;
395 }
396
397 SR_PRIV int scpi_dmm_get_meas_gwinstek(const struct sr_dev_inst *sdi, size_t ch)
398 {
399         struct sr_scpi_dev_inst *scpi;
400         struct dev_context *devc;
401         struct scpi_dmm_acq_info *info;
402         struct sr_datafeed_analog *analog;
403         int ret;
404         enum sr_mq mq;
405         enum sr_mqflag mqflag;
406         char *mode_response;
407         const char *p;
408         const struct mqopt_item *item;
409         const char *command;
410         char *response;
411         gboolean use_double;
412         double limit;
413         int sig_digits, val_exp;
414         int digits;
415         enum sr_unit unit;
416         int mmode;
417
418         scpi = sdi->conn;
419         devc = sdi->priv;
420         info = &devc->run_acq_info;
421         analog = &info->analog[ch];
422
423         /*
424          * Get the meter's current mode, keep the response around.
425          * Skip the measurement if the mode is uncertain.
426          */
427         ret = scpi_dmm_get_mq(sdi, &mq, &mqflag, &mode_response, &item);
428         if (ret != SR_OK) {
429                 g_free(mode_response);
430                 return ret;
431         }
432         if (!mode_response)
433                 return SR_ERR;
434         if (!mq) {
435                 g_free(mode_response);
436                 return +1;
437         }
438         mmode = atoi(mode_response);
439         g_free(mode_response);
440
441         /*
442          * Get the current reading from the meter.
443          */
444         scpi_dmm_cmd_delay(scpi);
445         command = sr_scpi_cmd_get(devc->cmdset, DMM_CMD_QUERY_VALUE);
446         if (!command || !*command)
447                 return SR_ERR_NA;
448         scpi_dmm_cmd_delay(scpi);
449         ret = sr_scpi_get_string(scpi, command, &response);
450         if (ret != SR_OK)
451                 return ret;
452         g_strstrip(response);
453         use_double = devc->model->digits > 6;
454         ret = sr_atod_ascii(response, &info->d_value);
455         if (ret != SR_OK) {
456                 g_free(response);
457                 return ret;
458         }
459         if (!response)
460                 return SR_ERR;
461         limit = 9e37;
462         if (devc->model->infinity_limit != 0.0)
463                 limit = devc->model->infinity_limit;
464         if (info->d_value >= +limit) {
465                 info->d_value = +INFINITY;
466         } else if (info->d_value <= -limit) {
467                 info->d_value = -INFINITY;
468         } else {
469                 p = response;
470                 while (p && *p && g_ascii_isspace(*p))
471                         p++;
472                 if (p && *p && (*p == '-' || *p == '+'))
473                         p++;
474                 sig_digits = 0;
475                 while (p && *p && g_ascii_isdigit(*p)) {
476                         sig_digits++;
477                         p++;
478                 }
479                 if (p && *p && *p == '.')
480                         p++;
481                 while (p && *p && g_ascii_isdigit(*p))
482                         p++;
483                 ret = SR_OK;
484                 if (!p || !*p)
485                         val_exp = 0;
486                 else if (*p != 'e' && *p != 'E')
487                         ret = SR_ERR_DATA;
488                 else
489                         ret = sr_atoi(++p, &val_exp);
490         }
491         g_free(response);
492         if (ret != SR_OK)
493                 return ret;
494
495         /*
496          * Make sure we report "INFINITY" when meter displays "0L".
497          */
498         switch (mmode) {
499         case 7:
500         case 16:
501                 /* In resitance modes 0L reads as 1.20000E8 or 1.99999E8. */
502                 limit = 1.2e8;
503                 if (strcmp(devc->model->model, "GDM8255A") == 0)
504                         limit = 1.99999e8;
505                 if (info->d_value >= limit)
506                         info->d_value = +INFINITY;
507                 break;
508         case 13:
509                 /* In continuity mode 0L reads as 1.20000E3. */
510                 if (info->d_value >= 1.2e3)
511                         info->d_value = +INFINITY;
512                 break;
513         case 17:
514                 /* In diode mode 0L reads as 1.00000E0. */
515                 if (info->d_value == 1.0e0)
516                         info->d_value = +INFINITY;
517                 break;
518         }
519
520         /*
521          * Calculate 'digits' based on the result of the optional
522          * precision reading which was done at acquisition start.
523          * The GW-Instek manual gives the following information
524          * regarding the resolution:
525          *
526          * Type      Digit
527          * --------  ------
528          * Slow      5 1/2
529          * Medium    4 1/2
530          * Fast      3 1/2
531          */
532         digits = devc->model->digits;
533         if (devc->precision && *devc->precision) {
534                 if (g_str_has_prefix(devc->precision, "Slow"))
535                         digits = 6;
536                 else if (g_str_has_prefix(devc->precision, "Mid"))
537                         digits = 5;
538                 else if (g_str_has_prefix(devc->precision, "Fast"))
539                         digits = 4;
540                 else
541                         sr_info("Unknown precision: '%s'", devc->precision);
542         }
543
544         /*
545          * Fill in the 'analog' description: value, encoding, meaning.
546          * Callers will fill in the sample count, and channel name,
547          * and will send out the packet.
548          */
549         if (use_double) {
550                 analog->data = &info->d_value;
551                 analog->encoding->unitsize = sizeof(info->d_value);
552         } else {
553                 info->f_value = info->d_value;
554                 analog->data = &info->f_value;
555                 analog->encoding->unitsize = sizeof(info->f_value);
556         }
557         analog->encoding->digits = digits;
558         analog->meaning->mq = mq;
559         analog->meaning->mqflags = mqflag;
560         switch (mq) {
561         case SR_MQ_VOLTAGE:
562                 unit = SR_UNIT_VOLT;
563                 break;
564         case SR_MQ_CURRENT:
565                 unit = SR_UNIT_AMPERE;
566                 break;
567         case SR_MQ_RESISTANCE:
568         case SR_MQ_CONTINUITY:
569                 unit = SR_UNIT_OHM;
570                 break;
571         case SR_MQ_CAPACITANCE:
572                 unit = SR_UNIT_FARAD;
573                 break;
574         case SR_MQ_TEMPERATURE:
575                 switch (mmode) {
576                 case 15:
577                         unit = SR_UNIT_FAHRENHEIT;
578                         break;
579                 case 9:
580                 default:
581                         unit = SR_UNIT_CELSIUS;
582                 }
583                 break;
584         case SR_MQ_FREQUENCY:
585                 unit = SR_UNIT_HERTZ;
586                 break;
587         case SR_MQ_TIME:
588                 unit = SR_UNIT_SECOND;
589                 break;
590         default:
591                 return SR_ERR_NA;
592         }
593         analog->meaning->unit = unit;
594         analog->spec->spec_digits = digits;
595
596         return SR_OK;
597 }
598
599 /* Strictly speaking this is a timer controlled poll routine. */
600 SR_PRIV int scpi_dmm_receive_data(int fd, int revents, void *cb_data)
601 {
602         struct sr_dev_inst *sdi;
603         struct sr_scpi_dev_inst *scpi;
604         struct dev_context *devc;
605         struct scpi_dmm_acq_info *info;
606         gboolean sent_sample;
607         size_t ch;
608         struct sr_channel *channel;
609         int ret;
610
611         (void)fd;
612         (void)revents;
613
614         sdi = cb_data;
615         if (!sdi)
616                 return TRUE;
617         scpi = sdi->conn;
618         devc = sdi->priv;
619         if (!scpi || !devc)
620                 return TRUE;
621         info = &devc->run_acq_info;
622
623         sent_sample = FALSE;
624         ret = SR_OK;
625         for (ch = 0; ch < devc->num_channels; ch++) {
626                 /* Check the channel's enabled status. */
627                 channel = g_slist_nth_data(sdi->channels, ch);
628                 if (!channel->enabled)
629                         continue;
630
631                 /*
632                  * Prepare an analog measurement value. Note that digits
633                  * will get updated later.
634                  */
635                 info->packet.type = SR_DF_ANALOG;
636                 info->packet.payload = &info->analog[ch];
637                 sr_analog_init(&info->analog[ch], &info->encoding[ch],
638                         &info->meaning[ch], &info->spec[ch], 0);
639
640                 /* Just check OPC before sending another request. */
641                 scpi_dmm_cmd_delay(sdi->conn);
642
643                 /*
644                  * Have the model take and interpret a measurement. Lack
645                  * of support is pointless, failed retrieval/conversion
646                  * is considered fatal. The routine will fill in the
647                  * 'analog' details, except for channel name and sample
648                  * count (assume one value per channel).
649                  *
650                  * Note that non-zero non-negative return codes signal
651                  * that the channel's data shell get skipped in this
652                  * iteration over the channels. This copes with devices
653                  * or modes where channels may provide data at different
654                  * rates.
655                  */
656                 if (!devc->model->get_measurement) {
657                         ret = SR_ERR_NA;
658                         break;
659                 }
660                 ret = devc->model->get_measurement(sdi, ch);
661                 if (ret > 0)
662                         continue;
663                 if (ret != SR_OK)
664                         break;
665
666                 /* Send the packet that was filled in by the model's routine. */
667                 info->analog[ch].num_samples = 1;
668                 info->analog[ch].meaning->channels = g_slist_append(NULL, channel);
669                 sr_session_send(sdi, &info->packet);
670                 g_slist_free(info->analog[ch].meaning->channels);
671                 sent_sample = TRUE;
672         }
673         if (sent_sample)
674                 sr_sw_limits_update_samples_read(&devc->limits, 1);
675         if (ret != SR_OK) {
676                 /* Stop acquisition upon communication or data errors. */
677                 sr_dev_acquisition_stop(sdi);
678                 return TRUE;
679         }
680         if (sr_sw_limits_check(&devc->limits))
681                 sr_dev_acquisition_stop(sdi);
682
683         return TRUE;
684 }