]> sigrok.org Git - libsigrok.git/blob - strutil.c
We now require libusb >= 1.0.9.
[libsigrok.git] / strutil.c
1 /*
2  * This file is part of the sigrok project.
3  *
4  * Copyright (C) 2010 Uwe Hermann <uwe@hermann-uwe.de>
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 2 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, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
19  */
20
21 #include <stdint.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include "libsigrok.h"
25 #include "libsigrok-internal.h"
26
27 /**
28  * Convert a numeric value value to its "natural" string representation.
29  * in SI units
30  *
31  * E.g. a value of 3000000, with units set to "W", would be converted
32  * to "3 MW", 20000 to "20 kW", 31500 would become "31.5 kW".
33  *
34  * @param x The value to convert.
35  * @param unit The unit to append to the string, or NULL if the string
36  *             has no units.
37  *
38  * @return A g_try_malloc()ed string representation of the samplerate value,
39  *         or NULL upon errors. The caller is responsible to g_free() the
40  *         memory.
41  */
42 SR_API char *sr_si_string_u64(uint64_t x, const char *unit)
43 {
44         if(unit == NULL)
45                 unit = "";
46
47         if ((x >= SR_GHZ(1)) && (x % SR_GHZ(1) == 0)) {
48                 return g_strdup_printf("%" PRIu64 " G%s", x / SR_GHZ(1), unit);
49         } else if ((x >= SR_GHZ(1)) && (x % SR_GHZ(1) != 0)) {
50                 return g_strdup_printf("%" PRIu64 ".%" PRIu64 " G%s",
51                                        x / SR_GHZ(1), x % SR_GHZ(1), unit);
52         } else if ((x >= SR_MHZ(1)) && (x % SR_MHZ(1) == 0)) {
53                 return g_strdup_printf("%" PRIu64 " M%s",
54                                        x / SR_MHZ(1), unit);
55         } else if ((x >= SR_MHZ(1)) && (x % SR_MHZ(1) != 0)) {
56                 return g_strdup_printf("%" PRIu64 ".%" PRIu64 " M%s",
57                                     x / SR_MHZ(1), x % SR_MHZ(1), unit);
58         } else if ((x >= SR_KHZ(1)) && (x % SR_KHZ(1) == 0)) {
59                 return g_strdup_printf("%" PRIu64 " k%s",
60                                     x / SR_KHZ(1), unit);
61         } else if ((x >= SR_KHZ(1)) && (x % SR_KHZ(1) != 0)) {
62                 return g_strdup_printf("%" PRIu64 ".%" PRIu64 " k%s",
63                                     x / SR_KHZ(1), x % SR_KHZ(1), unit);
64         } else {
65                 return g_strdup_printf("%" PRIu64 " %s", x, unit);
66         }
67
68         sr_err("strutil: %s: Error creating SI units string.",
69                 __func__);
70         return NULL;
71 }
72
73 /**
74  * Convert a numeric samplerate value to its "natural" string representation.
75  *
76  * E.g. a value of 3000000 would be converted to "3 MHz", 20000 to "20 kHz",
77  * 31500 would become "31.5 kHz".
78  *
79  * @param samplerate The samplerate in Hz.
80  *
81  * @return A g_try_malloc()ed string representation of the samplerate value,
82  *         or NULL upon errors. The caller is responsible to g_free() the
83  *         memory.
84  */
85 SR_API char *sr_samplerate_string(uint64_t samplerate)
86 {
87         return sr_si_string_u64(samplerate, "Hz");
88 }
89
90 /**
91  * Convert a numeric frequency value to the "natural" string representation
92  * of its period.
93  *
94  * E.g. a value of 3000000 would be converted to "3 us", 20000 to "50 ms".
95  *
96  * @param frequency The frequency in Hz.
97  *
98  * @return A g_try_malloc()ed string representation of the frequency value,
99  *         or NULL upon errors. The caller is responsible to g_free() the
100  *         memory.
101  */
102 SR_API char *sr_period_string(uint64_t frequency)
103 {
104         char *o;
105         int r;
106
107         /* Allocate enough for a uint64_t as string + " ms". */
108         if (!(o = g_try_malloc0(30 + 1))) {
109                 sr_err("strutil: %s: o malloc failed", __func__);
110                 return NULL;
111         }
112
113         if (frequency >= SR_GHZ(1))
114                 r = snprintf(o, 30, "%" PRIu64 " ns", frequency / 1000000000);
115         else if (frequency >= SR_MHZ(1))
116                 r = snprintf(o, 30, "%" PRIu64 " us", frequency / 1000000);
117         else if (frequency >= SR_KHZ(1))
118                 r = snprintf(o, 30, "%" PRIu64 " ms", frequency / 1000);
119         else
120                 r = snprintf(o, 30, "%" PRIu64 " s", frequency);
121
122         if (r < 0) {
123                 /* Something went wrong... */
124                 g_free(o);
125                 return NULL;
126         }
127
128         return o;
129 }
130
131 /**
132  * Convert a numeric frequency value to the "natural" string representation
133  * of its voltage value.
134  *
135  * E.g. a value of 300000 would be converted to "300mV", 2 to "2V".
136  *
137  * @param voltage The voltage represented as a rational number, with the
138  *                denominator a divisor of 1V.
139  *
140  * @return A g_try_malloc()ed string representation of the voltage value,
141  *         or NULL upon errors. The caller is responsible to g_free() the
142  *         memory.
143  */
144 SR_API char *sr_voltage_string(struct sr_rational *voltage)
145 {
146         char *o;
147         int r;
148
149         if (!(o = g_try_malloc0(30 + 1))) {
150                 sr_err("strutil: %s: o malloc failed", __func__);
151                 return NULL;
152         }
153
154         if (voltage->q == 1000)
155                 r = snprintf(o, 30, "%" PRIu64 "mV", voltage->p);
156         else if (voltage->q == 1)
157                 r = snprintf(o, 30, "%" PRIu64 "V", voltage->p);
158         else
159                 r = -1;
160
161         if (r < 0) {
162                 /* Something went wrong... */
163                 g_free(o);
164                 return NULL;
165         }
166
167         return o;
168 }
169
170 /**
171  * Parse a trigger specification string.
172  *
173  * @param dev The device for which the trigger specification is intended.
174  * @param triggerstring The string containing the trigger specification for
175  *        one or more probes of this device. Entries for multiple probes are
176  *        comma-separated. Triggers are specified in the form key=value,
177  *        where the key is a probe number (or probe name) and the value is
178  *        the requested trigger type. Valid trigger types currently
179  *        include 'r' (rising edge), 'f' (falling edge), 'c' (any pin value
180  *        change), '0' (low value), or '1' (high value).
181  *        Example: "1=r,sck=f,miso=0,7=c"
182  *
183  * @return Pointer to a list of trigger types (strings), or NULL upon errors.
184  *         The pointer list (if non-NULL) has as many entries as the
185  *         respective device has probes (all physically available probes,
186  *         not just enabled ones). Entries of the list which don't have
187  *         a trigger value set in 'triggerstring' are NULL, the other entries
188  *         contain the respective trigger type which is requested for the
189  *         respective probe (e.g. "r", "c", and so on).
190  */
191 SR_API char **sr_parse_triggerstring(const struct sr_dev_inst *sdi,
192                                      const char *triggerstring)
193 {
194         GSList *l;
195         struct sr_probe *probe;
196         int max_probes, probenum, i;
197         char **tokens, **triggerlist, *trigger, *tc;
198         const char *trigger_types;
199         gboolean error;
200
201         max_probes = g_slist_length(sdi->probes);
202         error = FALSE;
203
204         if (!(triggerlist = g_try_malloc0(max_probes * sizeof(char *)))) {
205                 sr_err("strutil: %s: triggerlist malloc failed", __func__);
206                 return NULL;
207         }
208
209         if (sdi->driver->info_get(SR_DI_TRIGGER_TYPES,
210                         (const void **)&trigger_types, sdi) != SR_OK) {
211                 sr_err("strutil: %s: Device doesn't support any triggers.", __func__);
212                 return NULL;
213         }
214
215         tokens = g_strsplit(triggerstring, ",", max_probes);
216         for (i = 0; tokens[i]; i++) {
217                 probenum = -1;
218                 for (l = sdi->probes; l; l = l->next) {
219                         probe = (struct sr_probe *)l->data;
220                         if (probe->enabled
221                                 && !strncmp(probe->name, tokens[i],
222                                         strlen(probe->name))) {
223                                 probenum = probe->index;
224                                 break;
225                         }
226                 }
227
228                 if (probenum < 0 || probenum >= max_probes) {
229                         sr_err("strutil: Invalid probe.");
230                         error = TRUE;
231                         break;
232                 }
233
234                 if ((trigger = strchr(tokens[i], '='))) {
235                         for (tc = ++trigger; *tc; tc++) {
236                                 if (strchr(trigger_types, *tc) == NULL) {
237                                         sr_err("strutil: Unsupported trigger "
238                                                "type '%c'.", *tc);
239                                         error = TRUE;
240                                         break;
241                                 }
242                         }
243                         if (!error)
244                                 triggerlist[probenum] = g_strdup(trigger);
245                 }
246         }
247         g_strfreev(tokens);
248
249         if (error) {
250                 for (i = 0; i < max_probes; i++)
251                         g_free(triggerlist[i]);
252                 g_free(triggerlist);
253                 triggerlist = NULL;
254         }
255
256         return triggerlist;
257 }
258
259 /**
260  * Convert a "natural" string representation of a size value to uint64_t.
261  *
262  * E.g. a value of "3k" or "3 K" would be converted to 3000, a value
263  * of "15M" would be converted to 15000000.
264  *
265  * Value representations other than decimal (such as hex or octal) are not
266  * supported. Only 'k' (kilo), 'm' (mega), 'g' (giga) suffixes are supported.
267  * Spaces (but not other whitespace) between value and suffix are allowed.
268  *
269  * @param sizestring A string containing a (decimal) size value.
270  * @param size Pointer to uint64_t which will contain the string's size value.
271  *
272  * @return SR_OK upon success, SR_ERR upon errors.
273  */
274 SR_API int sr_parse_sizestring(const char *sizestring, uint64_t *size)
275 {
276         int multiplier, done;
277         char *s;
278
279         *size = strtoull(sizestring, &s, 10);
280         multiplier = 0;
281         done = FALSE;
282         while (s && *s && multiplier == 0 && !done) {
283                 switch (*s) {
284                 case ' ':
285                         break;
286                 case 'k':
287                 case 'K':
288                         multiplier = SR_KHZ(1);
289                         break;
290                 case 'm':
291                 case 'M':
292                         multiplier = SR_MHZ(1);
293                         break;
294                 case 'g':
295                 case 'G':
296                         multiplier = SR_GHZ(1);
297                         break;
298                 default:
299                         done = TRUE;
300                         s--;
301                 }
302                 s++;
303         }
304         if (multiplier > 0)
305                 *size *= multiplier;
306
307         if (*s && strcasecmp(s, "Hz"))
308                 return SR_ERR;
309
310         return SR_OK;
311 }
312
313 /**
314  * Convert a "natural" string representation of a time value to an
315  * uint64_t value in milliseconds.
316  *
317  * E.g. a value of "3s" or "3 s" would be converted to 3000, a value
318  * of "15ms" would be converted to 15.
319  *
320  * Value representations other than decimal (such as hex or octal) are not
321  * supported. Only lower-case "s" and "ms" time suffixes are supported.
322  * Spaces (but not other whitespace) between value and suffix are allowed.
323  *
324  * @param timestring A string containing a (decimal) time value.
325  * @return The string's time value as uint64_t, in milliseconds.
326  *
327  * TODO: Error handling.
328  * TODO: Add support for "m" (minutes) and others.
329  * TODO: picoseconds?
330  * TODO: Allow both lower-case and upper-case.
331  */
332 SR_API uint64_t sr_parse_timestring(const char *timestring)
333 {
334         uint64_t time_msec;
335         char *s;
336
337         time_msec = strtoull(timestring, &s, 10);
338         if (time_msec == 0 && s == timestring)
339                 return 0;
340
341         if (s && *s) {
342                 while (*s == ' ')
343                         s++;
344                 if (!strcmp(s, "s"))
345                         time_msec *= 1000;
346                 else if (!strcmp(s, "ms"))
347                         ; /* redundant */
348                 else
349                         return 0;
350         }
351
352         return time_msec;
353 }
354
355 SR_API gboolean sr_parse_boolstring(const char *boolstr)
356 {
357         if (!boolstr)
358                 return FALSE;
359
360         if (!g_ascii_strncasecmp(boolstr, "true", 4) ||
361             !g_ascii_strncasecmp(boolstr, "yes", 3) ||
362             !g_ascii_strncasecmp(boolstr, "on", 2) ||
363             !g_ascii_strncasecmp(boolstr, "1", 1))
364                 return TRUE;
365
366         return FALSE;
367 }
368
369 SR_API int sr_parse_period(const char *periodstr, struct sr_rational *r)
370 {
371         char *s;
372
373         r->p = strtoull(periodstr, &s, 10);
374         if (r->p == 0 && s == periodstr)
375                 /* No digits found. */
376                 return SR_ERR_ARG;
377
378         if (s && *s) {
379                 while (*s == ' ')
380                         s++;
381                 if (!strcmp(s, "ns"))
382                         r->q = 1000000000L;
383                 else if (!strcmp(s, "us"))
384                         r->q = 1000000;
385                 else if (!strcmp(s, "ms"))
386                         r->q = 1000;
387                 else if (!strcmp(s, "s"))
388                         r->q = 1;
389                 else
390                         /* Must have a time suffix. */
391                         return SR_ERR_ARG;
392         }
393
394         return SR_OK;
395 }
396
397
398 SR_API int sr_parse_voltage(const char *voltstr, struct sr_rational *r)
399 {
400         char *s;
401
402         r->p = strtoull(voltstr, &s, 10);
403         if (r->p == 0 && s == voltstr)
404                 /* No digits found. */
405                 return SR_ERR_ARG;
406
407         if (s && *s) {
408                 while (*s == ' ')
409                         s++;
410                 if (!strcasecmp(s, "mv"))
411                         r->q = 1000L;
412                 else if (!strcasecmp(s, "v"))
413                         r->q = 1;
414                 else
415                         /* Must have a base suffix. */
416                         return SR_ERR_ARG;
417         }
418
419         return SR_OK;
420 }
421
422