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