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