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