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