]> sigrok.org Git - libsigrok.git/blob - src/analog.c
analog: improve output readability by using SI prefix
[libsigrok.git] / src / analog.c
1 /*
2  * This file is part of the libsigrok project.
3  *
4  * Copyright (C) 2014 Bert Vermeulen <bert@biot.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 <config.h>
21 #include <stdio.h>
22 #include <stdint.h>
23 #include <string.h>
24 #include <ctype.h>
25 #include <math.h>
26 #include <libsigrok/libsigrok.h>
27 #include "libsigrok-internal.h"
28
29 /** @cond PRIVATE */
30 #define LOG_PREFIX "analog"
31 /** @endcond */
32
33 /**
34  * @file
35  *
36  * Handling and converting analog data.
37  */
38
39 /**
40  * @defgroup grp_analog Analog data handling
41  *
42  * Handling and converting analog data.
43  *
44  * @{
45  */
46
47 struct unit_mq_string {
48         uint64_t value;
49         const char *str;
50 };
51
52 /* Please use the same order as in enum sr_unit (libsigrok.h). */
53 static struct unit_mq_string unit_strings[] = {
54         { SR_UNIT_VOLT, "V" },
55         { SR_UNIT_AMPERE, "A" },
56         { SR_UNIT_OHM, "\xe2\x84\xa6" },
57         { SR_UNIT_FARAD, "F" },
58         { SR_UNIT_KELVIN, "K" },
59         { SR_UNIT_CELSIUS, "\xc2\xb0""C" },
60         { SR_UNIT_FAHRENHEIT, "\xc2\xb0""F" },
61         { SR_UNIT_HERTZ, "Hz" },
62         { SR_UNIT_PERCENTAGE, "%" },
63         { SR_UNIT_BOOLEAN, "" },
64         { SR_UNIT_SECOND, "s" },
65         { SR_UNIT_SIEMENS, "S" },
66         { SR_UNIT_DECIBEL_MW, "dBu" },
67         { SR_UNIT_DECIBEL_VOLT, "dBv" },
68         { SR_UNIT_UNITLESS, "" },
69         { SR_UNIT_DECIBEL_SPL, "dB" },
70         { SR_UNIT_CONCENTRATION, "ppm" },
71         { SR_UNIT_REVOLUTIONS_PER_MINUTE, "RPM" },
72         { SR_UNIT_VOLT_AMPERE, "VA" },
73         { SR_UNIT_WATT, "W" },
74         { SR_UNIT_WATT_HOUR, "Wh" },
75         { SR_UNIT_METER_SECOND, "m/s" },
76         { SR_UNIT_HECTOPASCAL, "hPa" },
77         { SR_UNIT_HUMIDITY_293K, "%rF" },
78         { SR_UNIT_DEGREE, "\xc2\xb0" },
79         { SR_UNIT_HENRY, "H" },
80         { SR_UNIT_GRAM, "g" },
81         { SR_UNIT_CARAT, "ct" },
82         { SR_UNIT_OUNCE, "oz" },
83         { SR_UNIT_TROY_OUNCE, "oz t" },
84         { SR_UNIT_POUND, "lb" },
85         { SR_UNIT_PENNYWEIGHT, "dwt" },
86         { SR_UNIT_GRAIN, "gr" },
87         { SR_UNIT_TAEL, "tael" },
88         { SR_UNIT_MOMME, "momme" },
89         { SR_UNIT_TOLA, "tola" },
90         { SR_UNIT_PIECE, "pcs" },
91         ALL_ZERO
92 };
93
94 /* Please use the same order as in enum sr_mqflag (libsigrok.h). */
95 static struct unit_mq_string mq_strings[] = {
96         { SR_MQFLAG_AC, " AC" },
97         { SR_MQFLAG_DC, " DC" },
98         { SR_MQFLAG_RMS, " RMS" },
99         { SR_MQFLAG_DIODE, " DIODE" },
100         { SR_MQFLAG_HOLD, " HOLD" },
101         { SR_MQFLAG_MAX, " MAX" },
102         { SR_MQFLAG_MIN, " MIN" },
103         { SR_MQFLAG_AUTORANGE, " AUTO" },
104         { SR_MQFLAG_RELATIVE, " REL" },
105         { SR_MQFLAG_SPL_FREQ_WEIGHT_A, "(A)" },
106         { SR_MQFLAG_SPL_FREQ_WEIGHT_C, "(C)" },
107         { SR_MQFLAG_SPL_FREQ_WEIGHT_Z, "(Z)" },
108         { SR_MQFLAG_SPL_FREQ_WEIGHT_FLAT, "(SPL)" },
109         { SR_MQFLAG_SPL_TIME_WEIGHT_S, " S" },
110         { SR_MQFLAG_SPL_TIME_WEIGHT_F, " F" },
111         { SR_MQFLAG_SPL_LAT, " LAT" },
112         /* Not a standard function for SLMs, so this is a made-up notation. */
113         { SR_MQFLAG_SPL_PCT_OVER_ALARM, "%oA" },
114         { SR_MQFLAG_DURATION, " DURATION" },
115         { SR_MQFLAG_AVG, " AVG" },
116         { SR_MQFLAG_REFERENCE, " REF" },
117         { SR_MQFLAG_UNSTABLE, " UNSTABLE" },
118         { SR_MQFLAG_FOUR_WIRE, " 4-WIRE" },
119         ALL_ZERO
120 };
121
122 SR_PRIV int sr_analog_init(struct sr_datafeed_analog *analog,
123                 struct sr_analog_encoding *encoding,
124                 struct sr_analog_meaning *meaning,
125                 struct sr_analog_spec *spec,
126                 int digits)
127 {
128         memset(analog, 0, sizeof(*analog));
129         memset(encoding, 0, sizeof(*encoding));
130         memset(meaning, 0, sizeof(*meaning));
131         memset(spec, 0, sizeof(*spec));
132
133         analog->encoding = encoding;
134         analog->meaning = meaning;
135         analog->spec = spec;
136
137         encoding->unitsize = sizeof(float);
138         encoding->is_float = TRUE;
139 #ifdef WORDS_BIGENDIAN
140         encoding->is_bigendian = TRUE;
141 #else
142         encoding->is_bigendian = FALSE;
143 #endif
144         encoding->digits = digits;
145         encoding->is_digits_decimal = TRUE;
146         encoding->scale.p = 1;
147         encoding->scale.q = 1;
148         encoding->offset.p = 0;
149         encoding->offset.q = 1;
150
151         spec->spec_digits = digits;
152
153         return SR_OK;
154 }
155
156 /**
157  * Convert an analog datafeed payload to an array of floats.
158  *
159  * @param[in] analog The analog payload to convert. Must not be NULL.
160  *                   analog->data, analog->meaning, and analog->encoding
161  *                   must not be NULL.
162  * @param[out] outbuf Memory where to store the result. Must not be NULL.
163  *
164  * Sufficient memory for outbuf must have been pre-allocated by the caller,
165  * who is also responsible for freeing it when no longer needed.
166  *
167  * @retval SR_OK Success.
168  * @retval SR_ERR Unsupported encoding.
169  * @retval SR_ERR_ARG Invalid argument.
170  *
171  * @since 0.4.0
172  */
173 SR_API int sr_analog_to_float(const struct sr_datafeed_analog *analog,
174                 float *outbuf)
175 {
176         float offset;
177         unsigned int b, i, count;
178         gboolean bigendian;
179
180         if (!analog || !(analog->data) || !(analog->meaning)
181                         || !(analog->encoding) || !outbuf)
182                 return SR_ERR_ARG;
183
184         count = analog->num_samples * g_slist_length(analog->meaning->channels);
185
186 #ifdef WORDS_BIGENDIAN
187         bigendian = TRUE;
188 #else
189         bigendian = FALSE;
190 #endif
191         if (!analog->encoding->is_float) {
192                 float offset = analog->encoding->offset.p / (float)analog->encoding->offset.q;
193                 float scale = analog->encoding->scale.p / (float)analog->encoding->scale.q;
194                 gboolean is_signed = analog->encoding->is_signed;
195                 gboolean is_bigendian = analog->encoding->is_bigendian;
196                 int8_t *data8 = (int8_t *)(analog->data);
197                 int16_t *data16 = (int16_t *)(analog->data);
198                 int32_t *data32 = (int32_t *)(analog->data);
199
200                 switch (analog->encoding->unitsize) {
201                 case 1:
202                         if (is_signed) {
203                                 for (unsigned int i = 0; i < count; i++) {
204                                         outbuf[i] = scale * data8[i];
205                                         outbuf[i] += offset;
206                                 }
207                         } else {
208                                 for (unsigned int i = 0; i < count; i++) {
209                                         outbuf[i] = scale * R8(data8 + i);
210                                         outbuf[i] += offset;
211                                 }
212                         }
213                         break;
214                 case 2:
215                         if (is_signed && is_bigendian) {
216                                 for (unsigned int i = 0; i < count; i++) {
217                                         outbuf[i] = scale * RB16S(&data16[i]);
218                                         outbuf[i] += offset;
219                                 }
220                         } else if (is_bigendian) {
221                                 for (unsigned int i = 0; i < count; i++) {
222                                         outbuf[i] = scale * RB16(&data16[i]);
223                                         outbuf[i] += offset;
224                                 }
225                         } else if (is_signed) {
226                                 for (unsigned int i = 0; i < count; i++) {
227                                         outbuf[i] = scale * RL16S(&data16[i]);
228                                         outbuf[i] += offset;
229                                 }
230                         } else {
231                                 for (unsigned int i = 0; i < count; i++) {
232                                         outbuf[i] = scale * RL16(&data16[i]);
233                                         outbuf[i] += offset;
234                                 }
235                         }
236                         break;
237                 case 4:
238                         if (is_signed && is_bigendian) {
239                                 for (unsigned int i = 0; i < count; i++) {
240                                         outbuf[i] = scale * RB32S(&data32[i]);
241                                         outbuf[i] += offset;
242                                 }
243                         } else if (is_bigendian) {
244                                 for (unsigned int i = 0; i < count; i++) {
245                                         outbuf[i] = scale * RB32(&data32[i]);
246                                         outbuf[i] += offset;
247                                 }
248                         } else if (is_signed) {
249                                 for (unsigned int i = 0; i < count; i++) {
250                                         outbuf[i] = scale * RL32S(&data32[i]);
251                                         outbuf[i] += offset;
252                                 }
253                         } else {
254                                 for (unsigned int i = 0; i < count; i++) {
255                                         outbuf[i] = scale * RL32(&data32[i]);
256                                         outbuf[i] += offset;
257                                 }
258                         }
259                         break;
260                 default:
261                         sr_err("Unsupported unit size '%d' for analog-to-float conversion.",
262                                 analog->encoding->unitsize);
263                         return SR_ERR;
264                 }
265                 return SR_OK;
266         }
267
268         if (analog->encoding->unitsize == sizeof(float)
269                         && analog->encoding->is_bigendian == bigendian
270                         && analog->encoding->scale.p == 1
271                         && analog->encoding->scale.q == 1
272                         && analog->encoding->offset.p / (float)analog->encoding->offset.q == 0) {
273                 /* The data is already in the right format. */
274                 memcpy(outbuf, analog->data, count * sizeof(float));
275         } else {
276                 for (i = 0; i < count; i += analog->encoding->unitsize) {
277                         for (b = 0; b < analog->encoding->unitsize; b++) {
278                                 if (analog->encoding->is_bigendian == bigendian)
279                                         ((uint8_t *)outbuf)[i + b] =
280                                                 ((uint8_t *)analog->data)[i * analog->encoding->unitsize + b];
281                                 else
282                                         ((uint8_t *)outbuf)[i + (analog->encoding->unitsize - b)] =
283                                                 ((uint8_t *)analog->data)[i * analog->encoding->unitsize + b];
284                         }
285                         if (analog->encoding->scale.p != 1
286                                         || analog->encoding->scale.q != 1)
287                                 outbuf[i] = (outbuf[i] * analog->encoding->scale.p) / analog->encoding->scale.q;
288                         offset = ((float)analog->encoding->offset.p / (float)analog->encoding->offset.q);
289                         outbuf[i] += offset;
290                 }
291         }
292
293         return SR_OK;
294 }
295
296 /**
297  * Scale a float value to the appropriate SI prefix.
298  *
299  * @param[in,out] value The float value to convert to appropriate SI prefix.
300  * @param[in,out] digits The number of significant decimal digits in value.
301  *
302  * @return The SI prefix to which value was scaled, as a printable string.
303  *
304  * @since 0.5.0
305  */
306 SR_API const char *sr_analog_si_prefix(float *value, int *digits)
307 {
308 #define NEG_PREFIX_COUNT 5  /* number of prefixes below unity */
309 #define POS_PREFIX_COUNT (int)(ARRAY_SIZE(prefixes) - NEG_PREFIX_COUNT - 1)
310         static const char *prefixes[] = { "f","p","n","ยต","m","","k","M","G","T" };
311
312         if (value == NULL || digits == NULL || isnan(*value))
313                 return prefixes[NEG_PREFIX_COUNT];
314
315         float logval = log10f(fabsf(*value));
316         int prefix = (logval / 3) - (logval < 1);
317
318         if (prefix < -NEG_PREFIX_COUNT) prefix = -NEG_PREFIX_COUNT;
319         if (3 * prefix < -*digits)      prefix = (-*digits + 2 * (*digits < 0)) / 3;
320         if (prefix > POS_PREFIX_COUNT)  prefix = POS_PREFIX_COUNT;
321
322         *value *= powf(10, -3 * prefix);
323         *digits += 3 * prefix;
324         return prefixes[prefix + NEG_PREFIX_COUNT];
325 }
326
327 /**
328  * Convert the unit/MQ/MQ flags in the analog struct to a string.
329  *
330  * @param[in] analog Struct containing the unit, MQ and MQ flags.
331  *                   Must not be NULL. analog->meaning must not be NULL.
332  * @param[out] result Pointer to store result. Must not be NULL.
333  *
334  * The string is allocated by the function and must be freed by the caller
335  * after use by calling g_free().
336  *
337  * @retval SR_OK Success.
338  * @retval SR_ERR_ARG Invalid argument.
339  *
340  * @since 0.4.0
341  */
342 SR_API int sr_analog_unit_to_string(const struct sr_datafeed_analog *analog,
343                 char **result)
344 {
345         int i;
346         GString *buf;
347
348         if (!analog || !(analog->meaning) || !result)
349                 return SR_ERR_ARG;
350
351         buf = g_string_new(NULL);
352
353         for (i = 0; unit_strings[i].value; i++) {
354                 if (analog->meaning->unit == unit_strings[i].value) {
355                         g_string_assign(buf, unit_strings[i].str);
356                         break;
357                 }
358         }
359
360         /* More than one MQ flag may apply. */
361         for (i = 0; mq_strings[i].value; i++)
362                 if (analog->meaning->mqflags & mq_strings[i].value)
363                         g_string_append(buf, mq_strings[i].str);
364
365         *result = buf->str;
366         g_string_free(buf, FALSE);
367
368         return SR_OK;
369 }
370
371 /**
372  * Set sr_rational r to the given value.
373  *
374  * @param[out] r Rational number struct to set. Must not be NULL.
375  * @param[in] p Numerator.
376  * @param[in] q Denominator.
377  *
378  * @since 0.4.0
379  */
380 SR_API void sr_rational_set(struct sr_rational *r, int64_t p, uint64_t q)
381 {
382         if (!r)
383                 return;
384
385         r->p = p;
386         r->q = q;
387 }
388
389 #ifndef HAVE___INT128_T
390 struct sr_int128_t {
391         int64_t high;
392         uint64_t low;
393 };
394
395 struct sr_uint128_t {
396         uint64_t high;
397         uint64_t low;
398 };
399
400 static void mult_int64(struct sr_int128_t *res, const int64_t a,
401         const int64_t b)
402 {
403         uint64_t t1, t2, t3, t4;
404
405         t1 = (UINT32_MAX & a) * (UINT32_MAX & b);
406         t2 = (UINT32_MAX & a) * (b >> 32);
407         t3 = (a >> 32) * (UINT32_MAX & b);
408         t4 = (a >> 32) * (b >> 32);
409
410         res->low = t1 + (t2 << 32) + (t3 << 32);
411         res->high = (t1 >> 32) + (uint64_t)((uint32_t)(t2)) + (uint64_t)((uint32_t)(t3));
412         res->high >>= 32;
413         res->high += ((int64_t)t2 >> 32) + ((int64_t)t3 >> 32) + t4;
414 }
415
416 static void mult_uint64(struct sr_uint128_t *res, const uint64_t a,
417         const uint64_t b)
418 {
419         uint64_t t1, t2, t3, t4;
420
421         // (x1 + x2) * (y1 + y2) = x1*y1 + x1*y2 + x2*y1 + x2*y2
422         t1 = (UINT32_MAX & a) * (UINT32_MAX & b);
423         t2 = (UINT32_MAX & a) * (b >> 32);
424         t3 = (a >> 32) * (UINT32_MAX & b);
425         t4 = (a >> 32) * (b >> 32);
426
427         res->low = t1 + (t2 << 32) + (t3 << 32);
428         res->high = (t1 >> 32) + (uint64_t)((uint32_t)(t2)) + (uint64_t)((uint32_t)(t3));
429         res->high >>= 32;
430         res->high += ((int64_t)t2 >> 32) + ((int64_t)t3 >> 32) + t4;
431 }
432 #endif
433
434 /**
435  * Compare two sr_rational for equality
436  *
437  * @param[in] a First value
438  * @param[in] b Second value
439  *
440  * The values are compared for numerical equality, i.e. 2/10 == 1/5
441  *
442  * @retval 1 if both values are equal
443  * @retval 0 otherwise
444  *
445  * @since 0.5.0
446  */
447 SR_API int sr_rational_eq(const struct sr_rational *a, const struct sr_rational *b)
448 {
449 #ifdef HAVE___INT128_T
450         __int128_t m1, m2;
451
452         /* p1/q1 = p2/q2  <=>  p1*q2 = p2*q1 */
453         m1 = ((__int128_t)(b->p)) * ((__uint128_t)a->q);
454         m2 = ((__int128_t)(a->p)) * ((__uint128_t)b->q);
455
456         return (m1 == m2);
457
458 #else
459         struct sr_int128_t m1, m2;
460
461         mult_int64(&m1, a->q, b->p);
462         mult_int64(&m2, a->p, b->q);
463
464         return (m1.high == m2.high) && (m1.low == m2.low);
465 #endif
466 }
467
468 /**
469  * Multiply two sr_rational
470  *
471  * @param[in] a First value
472  * @param[in] b Second value
473  * @param[out] res Result
474  *
475  * The resulting nominator/denominator are reduced if the result would not fit
476  * otherwise. If the resulting nominator/denominator are relatively prime,
477  * this may not be possible.
478  *
479  * It is save to use the same variable for result and input values
480  *
481  * @retval SR_OK Success.
482  * @retval SR_ERR_ARG Resulting value to large
483  *
484  * @since 0.5.0
485  */
486 SR_API int sr_rational_mult(struct sr_rational *res, const struct sr_rational *a,
487         const struct sr_rational *b)
488 {
489 #ifdef HAVE___INT128_T
490         __int128_t p;
491         __uint128_t q;
492
493         p = (__int128_t)(a->p) * (__int128_t)(b->p);
494         q = (__uint128_t)(a->q) * (__uint128_t)(b->q);
495
496         if ((p > INT64_MAX) || (p < INT64_MIN) || (q > UINT64_MAX)) {
497                 while (!((p & 1) || (q & 1))) {
498                         p /= 2;
499                         q /= 2;
500                 }
501         }
502
503         if ((p > INT64_MAX) || (p < INT64_MIN) || (q > UINT64_MAX)) {
504                 // TODO: determine gcd to do further reduction
505                 return SR_ERR_ARG;
506         }
507
508         res->p = (int64_t)(p);
509         res->q = (uint64_t)(q);
510
511         return SR_OK;
512
513 #else
514         struct sr_int128_t p;
515         struct sr_uint128_t q;
516
517         mult_int64(&p, a->p, b->p);
518         mult_uint64(&q, a->q, b->q);
519
520         while (!(p.low & 1) && !(q.low & 1)) {
521                 p.low /= 2;
522                 if (p.high & 1) p.low |= (1ll << 63);
523                 p.high >>= 1;
524                 q.low /= 2;
525                 if (q.high & 1) q.low |= (1ll << 63);
526                 q.high >>= 1;
527         }
528
529         if (q.high)
530                 return SR_ERR_ARG;
531         if ((p.high >= 0) && (p.low > INT64_MAX))
532                 return SR_ERR_ARG;
533         if (p.high < -1)
534                 return SR_ERR_ARG;
535
536         res->p = (int64_t)p.low;
537         res->q = q.low;
538
539         return SR_OK;
540 #endif
541 }
542
543 /**
544  * Divide rational a by rational b
545  *
546  * @param[in] num numerator
547  * @param[in] div divisor
548  * @param[out] res Result
549  *
550  * The resulting nominator/denominator are reduced if the result would not fit
551  * otherwise. If the resulting nominator/denominator are relatively prime,
552  * this may not be possible.
553  *
554  * It is save to use the same variable for result and input values
555  *
556  * @retval SR_OK Success.
557  * @retval SR_ERR_ARG Division by zero
558  * @retval SR_ERR_ARG Denominator of divisor to large
559  * @retval SR_ERR_ARG Resulting value to large
560  *
561  * @since 0.5.0
562  */
563 SR_API int sr_rational_div(struct sr_rational *res, const struct sr_rational *num,
564         const struct sr_rational *div)
565 {
566         struct sr_rational t;
567
568         if (div->q > INT64_MAX)
569                 return SR_ERR_ARG;
570         if (div->p == 0)
571                 return SR_ERR_ARG;
572
573         if (div->p > 0) {
574                 t.p = div->q;
575                 t.q = div->p;
576         } else {
577                 t.p = -div->q;
578                 t.q = -div->p;
579         }
580
581         return sr_rational_mult(res, num, &t);
582 }
583
584 /** @} */