]> sigrok.org Git - libsigrok.git/blob - src/analog.c
Various Doxygen fixes.
[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, "dBm" },
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 /** @private */
123 SR_PRIV int sr_analog_init(struct sr_datafeed_analog *analog,
124                 struct sr_analog_encoding *encoding,
125                 struct sr_analog_meaning *meaning,
126                 struct sr_analog_spec *spec,
127                 int digits)
128 {
129         memset(analog, 0, sizeof(*analog));
130         memset(encoding, 0, sizeof(*encoding));
131         memset(meaning, 0, sizeof(*meaning));
132         memset(spec, 0, sizeof(*spec));
133
134         analog->encoding = encoding;
135         analog->meaning = meaning;
136         analog->spec = spec;
137
138         encoding->unitsize = sizeof(float);
139         encoding->is_float = TRUE;
140 #ifdef WORDS_BIGENDIAN
141         encoding->is_bigendian = TRUE;
142 #else
143         encoding->is_bigendian = FALSE;
144 #endif
145         encoding->digits = digits;
146         encoding->is_digits_decimal = TRUE;
147         encoding->scale.p = 1;
148         encoding->scale.q = 1;
149         encoding->offset.p = 0;
150         encoding->offset.q = 1;
151
152         spec->spec_digits = digits;
153
154         return SR_OK;
155 }
156
157 /**
158  * Convert an analog datafeed payload to an array of floats.
159  *
160  * Sufficient memory for outbuf must have been pre-allocated by the caller,
161  * who is also responsible for freeing it when no longer needed.
162  *
163  * @param[in] analog The analog payload to convert. Must not be NULL.
164  *                   analog->data, analog->meaning, and analog->encoding
165  *                   must not be NULL.
166  * @param[out] outbuf Memory where to store the result. Must not be NULL.
167  *
168  * @retval SR_OK Success.
169  * @retval SR_ERR Unsupported encoding.
170  * @retval SR_ERR_ARG Invalid argument.
171  *
172  * @since 0.4.0
173  */
174 SR_API int sr_analog_to_float(const struct sr_datafeed_analog *analog,
175                 float *outbuf)
176 {
177         float offset;
178         unsigned int b, i, count;
179         gboolean bigendian;
180
181         if (!analog || !(analog->data) || !(analog->meaning)
182                         || !(analog->encoding) || !outbuf)
183                 return SR_ERR_ARG;
184
185         count = analog->num_samples * g_slist_length(analog->meaning->channels);
186
187 #ifdef WORDS_BIGENDIAN
188         bigendian = TRUE;
189 #else
190         bigendian = FALSE;
191 #endif
192
193         if (!analog->encoding->is_float) {
194                 float offset = analog->encoding->offset.p / (float)analog->encoding->offset.q;
195                 float scale = analog->encoding->scale.p / (float)analog->encoding->scale.q;
196                 gboolean is_signed = analog->encoding->is_signed;
197                 gboolean is_bigendian = analog->encoding->is_bigendian;
198                 int8_t *data8 = (int8_t *)(analog->data);
199                 int16_t *data16 = (int16_t *)(analog->data);
200                 int32_t *data32 = (int32_t *)(analog->data);
201
202                 switch (analog->encoding->unitsize) {
203                 case 1:
204                         if (is_signed) {
205                                 for (unsigned int i = 0; i < count; i++) {
206                                         outbuf[i] = scale * data8[i];
207                                         outbuf[i] += offset;
208                                 }
209                         } else {
210                                 for (unsigned int i = 0; i < count; i++) {
211                                         outbuf[i] = scale * R8(data8 + i);
212                                         outbuf[i] += offset;
213                                 }
214                         }
215                         break;
216                 case 2:
217                         if (is_signed && is_bigendian) {
218                                 for (unsigned int i = 0; i < count; i++) {
219                                         outbuf[i] = scale * RB16S(&data16[i]);
220                                         outbuf[i] += offset;
221                                 }
222                         } else if (is_bigendian) {
223                                 for (unsigned int i = 0; i < count; i++) {
224                                         outbuf[i] = scale * RB16(&data16[i]);
225                                         outbuf[i] += offset;
226                                 }
227                         } else if (is_signed) {
228                                 for (unsigned int i = 0; i < count; i++) {
229                                         outbuf[i] = scale * RL16S(&data16[i]);
230                                         outbuf[i] += offset;
231                                 }
232                         } else {
233                                 for (unsigned int i = 0; i < count; i++) {
234                                         outbuf[i] = scale * RL16(&data16[i]);
235                                         outbuf[i] += offset;
236                                 }
237                         }
238                         break;
239                 case 4:
240                         if (is_signed && is_bigendian) {
241                                 for (unsigned int i = 0; i < count; i++) {
242                                         outbuf[i] = scale * RB32S(&data32[i]);
243                                         outbuf[i] += offset;
244                                 }
245                         } else if (is_bigendian) {
246                                 for (unsigned int i = 0; i < count; i++) {
247                                         outbuf[i] = scale * RB32(&data32[i]);
248                                         outbuf[i] += offset;
249                                 }
250                         } else if (is_signed) {
251                                 for (unsigned int i = 0; i < count; i++) {
252                                         outbuf[i] = scale * RL32S(&data32[i]);
253                                         outbuf[i] += offset;
254                                 }
255                         } else {
256                                 for (unsigned int i = 0; i < count; i++) {
257                                         outbuf[i] = scale * RL32(&data32[i]);
258                                         outbuf[i] += offset;
259                                 }
260                         }
261                         break;
262                 default:
263                         sr_err("Unsupported unit size '%d' for analog-to-float"
264                                " conversion.", analog->encoding->unitsize);
265                         return SR_ERR;
266                 }
267                 return SR_OK;
268         }
269
270         if (analog->encoding->unitsize == sizeof(float)
271                         && analog->encoding->is_bigendian == bigendian
272                         && analog->encoding->scale.p == 1
273                         && analog->encoding->scale.q == 1
274                         && analog->encoding->offset.p / (float)analog->encoding->offset.q == 0) {
275                 /* The data is already in the right format. */
276                 memcpy(outbuf, analog->data, count * sizeof(float));
277         } else {
278                 for (i = 0; i < count; i += analog->encoding->unitsize) {
279                         for (b = 0; b < analog->encoding->unitsize; b++) {
280                                 if (analog->encoding->is_bigendian == bigendian)
281                                         ((uint8_t *)outbuf)[i + b] =
282                                                 ((uint8_t *)analog->data)[i * analog->encoding->unitsize + b];
283                                 else
284                                         ((uint8_t *)outbuf)[i + (analog->encoding->unitsize - b)] =
285                                                 ((uint8_t *)analog->data)[i * analog->encoding->unitsize + b];
286                         }
287                         if (analog->encoding->scale.p != 1
288                                         || analog->encoding->scale.q != 1)
289                                 outbuf[i] = (outbuf[i] * analog->encoding->scale.p) / analog->encoding->scale.q;
290                         offset = ((float)analog->encoding->offset.p / (float)analog->encoding->offset.q);
291                         outbuf[i] += offset;
292                 }
293         }
294
295         return SR_OK;
296 }
297
298 /**
299  * Scale a float value to the appropriate SI prefix.
300  *
301  * @param[in,out] value The float value to convert to appropriate SI prefix.
302  * @param[in,out] digits The number of significant decimal digits in value.
303  *
304  * @return The SI prefix to which value was scaled, as a printable string.
305  *
306  * @since 0.5.0
307  */
308 SR_API const char *sr_analog_si_prefix(float *value, int *digits)
309 {
310 /** @cond PRIVATE */
311 #define NEG_PREFIX_COUNT 5  /* number of prefixes below unity */
312 #define POS_PREFIX_COUNT (int)(ARRAY_SIZE(prefixes) - NEG_PREFIX_COUNT - 1)
313 /** @endcond */
314         static const char *prefixes[] = { "f", "p", "n", "µ", "m", "", "k", "M", "G", "T" };
315
316         if (!value || !digits || isnan(*value))
317                 return prefixes[NEG_PREFIX_COUNT];
318
319         float logval = log10f(fabsf(*value));
320         int prefix = (logval / 3) - (logval < 1);
321
322         if (prefix < -NEG_PREFIX_COUNT)
323                 prefix = -NEG_PREFIX_COUNT;
324         if (3 * prefix < -*digits)
325                 prefix = (-*digits + 2 * (*digits < 0)) / 3;
326         if (prefix > POS_PREFIX_COUNT)
327                 prefix = POS_PREFIX_COUNT;
328
329         *value *= powf(10, -3 * prefix);
330         *digits += 3 * prefix;
331
332         return prefixes[prefix + NEG_PREFIX_COUNT];
333 }
334
335 /**
336  * Check if a unit "accepts" an SI prefix.
337  *
338  * E.g. SR_UNIT_VOLT is SI prefix friendly while SR_UNIT_DECIBEL_MW or
339  * SR_UNIT_PERCENTAGE are not.
340  *
341  * @param[in] unit The unit to check for SI prefix "friendliness".
342  *
343  * @return TRUE if the unit "accept" an SI prefix.
344  *
345  * @since 0.5.0
346  */
347 SR_API gboolean sr_analog_si_prefix_friendly(enum sr_unit unit)
348 {
349         static const enum sr_unit prefix_friendly_units[] = {
350                 SR_UNIT_VOLT,
351                 SR_UNIT_AMPERE,
352                 SR_UNIT_OHM,
353                 SR_UNIT_FARAD,
354                 SR_UNIT_KELVIN,
355                 SR_UNIT_HERTZ,
356                 SR_UNIT_SECOND,
357                 SR_UNIT_SIEMENS,
358                 SR_UNIT_VOLT_AMPERE,
359                 SR_UNIT_WATT,
360                 SR_UNIT_WATT_HOUR,
361                 SR_UNIT_METER_SECOND,
362                 SR_UNIT_HENRY,
363                 SR_UNIT_GRAM
364         };
365         unsigned int i;
366
367         for (i = 0; i < ARRAY_SIZE(prefix_friendly_units); i++)
368                 if (unit == prefix_friendly_units[i])
369                         break;
370
371         if (unit != prefix_friendly_units[i])
372                 return FALSE;
373
374         return TRUE;
375 }
376
377 /**
378  * Convert the unit/MQ/MQ flags in the analog struct to a string.
379  *
380  * The string is allocated by the function and must be freed by the caller
381  * after use by calling g_free().
382  *
383  * @param[in] analog Struct containing the unit, MQ and MQ flags.
384  *                   Must not be NULL. analog->meaning must not be NULL.
385  * @param[out] result Pointer to store result. Must not be NULL.
386  *
387  * @retval SR_OK Success.
388  * @retval SR_ERR_ARG Invalid argument.
389  *
390  * @since 0.4.0
391  */
392 SR_API int sr_analog_unit_to_string(const struct sr_datafeed_analog *analog,
393                 char **result)
394 {
395         int i;
396         GString *buf;
397
398         if (!analog || !(analog->meaning) || !result)
399                 return SR_ERR_ARG;
400
401         buf = g_string_new(NULL);
402
403         for (i = 0; unit_strings[i].value; i++) {
404                 if (analog->meaning->unit == unit_strings[i].value) {
405                         g_string_assign(buf, unit_strings[i].str);
406                         break;
407                 }
408         }
409
410         /* More than one MQ flag may apply. */
411         for (i = 0; mq_strings[i].value; i++)
412                 if (analog->meaning->mqflags & mq_strings[i].value)
413                         g_string_append(buf, mq_strings[i].str);
414
415         *result = buf->str;
416         g_string_free(buf, FALSE);
417
418         return SR_OK;
419 }
420
421 /**
422  * Set sr_rational r to the given value.
423  *
424  * @param[out] r Rational number struct to set. Must not be NULL.
425  * @param[in] p Numerator.
426  * @param[in] q Denominator.
427  *
428  * @since 0.4.0
429  */
430 SR_API void sr_rational_set(struct sr_rational *r, int64_t p, uint64_t q)
431 {
432         if (!r)
433                 return;
434
435         r->p = p;
436         r->q = q;
437 }
438
439 #ifndef HAVE___INT128_T
440 struct sr_int128_t {
441         int64_t high;
442         uint64_t low;
443 };
444
445 struct sr_uint128_t {
446         uint64_t high;
447         uint64_t low;
448 };
449
450 static void mult_int64(struct sr_int128_t *res, const int64_t a,
451         const int64_t b)
452 {
453         uint64_t t1, t2, t3, t4;
454
455         t1 = (UINT32_MAX & a) * (UINT32_MAX & b);
456         t2 = (UINT32_MAX & a) * (b >> 32);
457         t3 = (a >> 32) * (UINT32_MAX & b);
458         t4 = (a >> 32) * (b >> 32);
459
460         res->low = t1 + (t2 << 32) + (t3 << 32);
461         res->high = (t1 >> 32) + (uint64_t)((uint32_t)(t2)) + (uint64_t)((uint32_t)(t3));
462         res->high >>= 32;
463         res->high += ((int64_t)t2 >> 32) + ((int64_t)t3 >> 32) + t4;
464 }
465
466 static void mult_uint64(struct sr_uint128_t *res, const uint64_t a,
467         const uint64_t b)
468 {
469         uint64_t t1, t2, t3, t4;
470
471         // (x1 + x2) * (y1 + y2) = x1*y1 + x1*y2 + x2*y1 + x2*y2
472         t1 = (UINT32_MAX & a) * (UINT32_MAX & b);
473         t2 = (UINT32_MAX & a) * (b >> 32);
474         t3 = (a >> 32) * (UINT32_MAX & b);
475         t4 = (a >> 32) * (b >> 32);
476
477         res->low = t1 + (t2 << 32) + (t3 << 32);
478         res->high = (t1 >> 32) + (uint64_t)((uint32_t)(t2)) + (uint64_t)((uint32_t)(t3));
479         res->high >>= 32;
480         res->high += ((int64_t)t2 >> 32) + ((int64_t)t3 >> 32) + t4;
481 }
482 #endif
483
484 /**
485  * Compare two sr_rational for equality.
486  *
487  * The values are compared for numerical equality, i.e. 2/10 == 1/5.
488  *
489  * @param[in] a First value.
490  * @param[in] b Second value.
491  *
492  * @retval 1 if both values are equal.
493  * @retval 0 Otherwise.
494  *
495  * @since 0.5.0
496  */
497 SR_API int sr_rational_eq(const struct sr_rational *a, const struct sr_rational *b)
498 {
499 #ifdef HAVE___INT128_T
500         __int128_t m1, m2;
501
502         /* p1/q1 = p2/q2  <=>  p1*q2 = p2*q1 */
503         m1 = ((__int128_t)(b->p)) * ((__uint128_t)a->q);
504         m2 = ((__int128_t)(a->p)) * ((__uint128_t)b->q);
505
506         return (m1 == m2);
507
508 #else
509         struct sr_int128_t m1, m2;
510
511         mult_int64(&m1, a->q, b->p);
512         mult_int64(&m2, a->p, b->q);
513
514         return (m1.high == m2.high) && (m1.low == m2.low);
515 #endif
516 }
517
518 /**
519  * Multiply two sr_rational.
520  *
521  * The resulting nominator/denominator are reduced if the result would not fit
522  * otherwise. If the resulting nominator/denominator are relatively prime,
523  * this may not be possible.
524  *
525  * It is safe to use the same variable for result and input values.
526  *
527  * @param[in] a First value.
528  * @param[in] b Second value.
529  * @param[out] res Result.
530  *
531  * @retval SR_OK Success.
532  * @retval SR_ERR_ARG Resulting value too large.
533  *
534  * @since 0.5.0
535  */
536 SR_API int sr_rational_mult(struct sr_rational *res, const struct sr_rational *a,
537         const struct sr_rational *b)
538 {
539 #ifdef HAVE___INT128_T
540         __int128_t p;
541         __uint128_t q;
542
543         p = (__int128_t)(a->p) * (__int128_t)(b->p);
544         q = (__uint128_t)(a->q) * (__uint128_t)(b->q);
545
546         if ((p > INT64_MAX) || (p < INT64_MIN) || (q > UINT64_MAX)) {
547                 while (!((p & 1) || (q & 1))) {
548                         p /= 2;
549                         q /= 2;
550                 }
551         }
552
553         if ((p > INT64_MAX) || (p < INT64_MIN) || (q > UINT64_MAX)) {
554                 // TODO: determine gcd to do further reduction
555                 return SR_ERR_ARG;
556         }
557
558         res->p = (int64_t)(p);
559         res->q = (uint64_t)(q);
560
561         return SR_OK;
562
563 #else
564         struct sr_int128_t p;
565         struct sr_uint128_t q;
566
567         mult_int64(&p, a->p, b->p);
568         mult_uint64(&q, a->q, b->q);
569
570         while (!(p.low & 1) && !(q.low & 1)) {
571                 p.low /= 2;
572                 if (p.high & 1)
573                         p.low |= (1ll << 63);
574                 p.high >>= 1;
575                 q.low /= 2;
576                 if (q.high & 1)
577                         q.low |= (1ll << 63);
578                 q.high >>= 1;
579         }
580
581         if (q.high)
582                 return SR_ERR_ARG;
583         if ((p.high >= 0) && (p.low > INT64_MAX))
584                 return SR_ERR_ARG;
585         if (p.high < -1)
586                 return SR_ERR_ARG;
587
588         res->p = (int64_t)p.low;
589         res->q = q.low;
590
591         return SR_OK;
592 #endif
593 }
594
595 /**
596  * Divide rational a by rational b.
597  *
598  * The resulting nominator/denominator are reduced if the result would not fit
599  * otherwise. If the resulting nominator/denominator are relatively prime,
600  * this may not be possible.
601  *
602  * It is safe to use the same variable for result and input values.
603  *
604  * @param[in] num Numerator.
605  * @param[in] div Divisor.
606  * @param[out] res Result.
607  *
608  * @retval SR_OK Success.
609  * @retval SR_ERR_ARG Division by zero.
610  * @retval SR_ERR_ARG Denominator of divisor too large.
611  * @retval SR_ERR_ARG Resulting value too large.
612  *
613  * @since 0.5.0
614  */
615 SR_API int sr_rational_div(struct sr_rational *res, const struct sr_rational *num,
616         const struct sr_rational *div)
617 {
618         struct sr_rational t;
619
620         if (div->q > INT64_MAX)
621                 return SR_ERR_ARG;
622         if (div->p == 0)
623                 return SR_ERR_ARG;
624
625         if (div->p > 0) {
626                 t.p = div->q;
627                 t.q = div->p;
628         } else {
629                 t.p = -div->q;
630                 t.q = -div->p;
631         }
632
633         return sr_rational_mult(res, num, &t);
634 }
635
636 /** @} */