doc: update manpage for channel groups in --get/--config options
[sigrok-cli.git] / parsers.c
1 /*
2  * This file is part of the sigrok-cli project.
3  *
4  * Copyright (C) 2011 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 <stdlib.h>
23 #include <stdint.h>
24 #include <string.h>
25 #include <glib.h>
26 #include "sigrok-cli.h"
27
28 struct sr_channel *find_channel(GSList *channellist, const char *channelname)
29 {
30         struct sr_channel *ch;
31         GSList *l;
32
33         ch = NULL;
34         for (l = channellist; l; l = l->next) {
35                 ch = l->data;
36                 if (!strcmp(ch->name, channelname))
37                         break;
38         }
39         ch = l ? l->data : NULL;
40
41         return ch;
42 }
43
44 GSList *parse_channelstring(struct sr_dev_inst *sdi, const char *channelstring)
45 {
46         struct sr_channel *ch;
47         GSList *channellist, *channels;
48         int ret, n, b, e, i;
49         char **tokens, **range, **names, *eptr, str[8];
50
51         channels = sr_dev_inst_channels_get(sdi);
52
53         if (!channelstring || !channelstring[0])
54                 /* Use all channels by default. */
55                 return g_slist_copy(channels);
56
57         ret = SR_OK;
58         range = NULL;
59         names = NULL;
60         channellist = NULL;
61         tokens = g_strsplit(channelstring, ",", 0);
62         for (i = 0; tokens[i]; i++) {
63                 if (tokens[i][0] == '\0') {
64                         g_critical("Invalid empty channel.");
65                         ret = SR_ERR;
66                         break;
67                 }
68                 if (strchr(tokens[i], '-')) {
69                         /*
70                          * A range of channels in the form a-b. This will only work
71                          * if the channels are named as numbers -- so every channel
72                          * in the range must exist as a channel name string in the
73                          * device.
74                          */
75                         range = g_strsplit(tokens[i], "-", 2);
76                         if (!range[0] || !range[1] || range[2]) {
77                                 /* Need exactly two arguments. */
78                                 g_critical("Invalid channel syntax '%s'.", tokens[i]);
79                                 ret = SR_ERR;
80                                 goto range_fail;
81                         }
82
83                         b = strtol(range[0], &eptr, 10);
84                         if (eptr == range[0] || *eptr != '\0') {
85                                 g_critical("Invalid channel '%s'.", range[0]);
86                                 ret = SR_ERR;
87                                 goto range_fail;
88                         }
89                         e = strtol(range[1], NULL, 10);
90                         if (eptr == range[1] || *eptr != '\0') {
91                                 g_critical("Invalid channel '%s'.", range[1]);
92                                 ret = SR_ERR;
93                                 goto range_fail;
94                         }
95                         if (b < 0 || b >= e) {
96                                 g_critical("Invalid channel range '%s'.", tokens[i]);
97                                 ret = SR_ERR;
98                                 goto range_fail;
99                         }
100
101                         while (b <= e) {
102                                 n = snprintf(str, 8, "%d", b);
103                                 if (n < 0 || n > 8) {
104                                         g_critical("Invalid channel '%d'.", b);
105                                         ret = SR_ERR;
106                                         break;
107                                 }
108                                 ch = find_channel(channels, str);
109                                 if (!ch) {
110                                         g_critical("unknown channel '%d'.", b);
111                                         ret = SR_ERR;
112                                         break;
113                                 }
114                                 channellist = g_slist_append(channellist, ch);
115                                 b++;
116                         }
117 range_fail:
118                         if (range)
119                                 g_strfreev(range);
120
121                         if (ret != SR_OK)
122                                 break;
123                 } else {
124                         names = g_strsplit(tokens[i], "=", 2);
125                         if (!names[0] || (names[1] && names[2])) {
126                                 /* Need one or two arguments. */
127                                 g_critical("Invalid channel '%s'.", tokens[i]);
128                                 g_strfreev(names);
129                                 ret = SR_ERR;
130                                 break;
131                         }
132
133                         ch = find_channel(channels, names[0]);
134                         if (!ch) {
135                                 g_critical("unknown channel '%s'.", names[0]);
136                                 g_strfreev(names);
137                                 ret = SR_ERR;
138                                 break;
139                         }
140                         if (names[1]) {
141                                 /* Rename channel. */
142                                 g_free(ch->name);
143                                 ch->name = g_strdup(names[1]);
144                         }
145                         channellist = g_slist_append(channellist, ch);
146
147                         g_strfreev(names);
148                 }
149         }
150
151         if (ret != SR_OK) {
152                 g_slist_free(channellist);
153                 channellist = NULL;
154         }
155
156         g_strfreev(tokens);
157
158         return channellist;
159 }
160
161 int parse_trigger_match(char c)
162 {
163         int match;
164
165         if (c == '0')
166                 match = SR_TRIGGER_ZERO;
167         else if (c == '1')
168                 match = SR_TRIGGER_ONE;
169         else if (c == 'r')
170                 match = SR_TRIGGER_RISING;
171         else if (c == 'f')
172                 match = SR_TRIGGER_FALLING;
173         else if (c == 'e')
174                 match = SR_TRIGGER_EDGE;
175         else if (c == 'o')
176                 match = SR_TRIGGER_OVER;
177         else if (c == 'u')
178                 match = SR_TRIGGER_UNDER;
179         else
180                 match = 0;
181
182         return match;
183 }
184
185 int parse_triggerstring(const struct sr_dev_inst *sdi, const char *s,
186                 struct sr_trigger **trigger)
187 {
188         struct sr_channel *ch;
189         struct sr_trigger_stage *stage;
190         GVariant *gvar;
191         GSList *l, *channels;
192         gsize num_matches;
193         gboolean found_match, error;
194         const int32_t *matches;
195         int32_t match;
196         unsigned int j;
197         int t, i;
198         char **tokens, *sep;
199         struct sr_dev_driver *driver;
200
201         driver = sr_dev_inst_driver_get(sdi);
202         channels = sr_dev_inst_channels_get(sdi);
203
204         if (maybe_config_list(driver, sdi, NULL, SR_CONF_TRIGGER_MATCH,
205                         &gvar) != SR_OK) {
206                 g_critical("Device doesn't support any triggers.");
207                 return FALSE;
208         }
209         matches = g_variant_get_fixed_array(gvar, &num_matches, sizeof(int32_t));
210
211         *trigger = sr_trigger_new(NULL);
212         error = FALSE;
213         tokens = g_strsplit(s, ",", -1);
214         for (i = 0; tokens[i]; i++) {
215                 if (!(sep = strchr(tokens[i], '='))) {
216                         g_critical("Invalid trigger '%s'.", tokens[i]);
217                         error = TRUE;
218                         break;
219                 }
220                 *sep++ = 0;
221                 ch = NULL;
222                 for (l = channels; l; l = l->next) {
223                         ch = l->data;
224                         if (ch->enabled && !strcmp(ch->name, tokens[i]))
225                                 break;
226                         ch = NULL;
227                 }
228                 if (!ch) {
229                         g_critical("Invalid channel '%s'.", tokens[i]);
230                         error = TRUE;
231                         break;
232                 }
233                 for (t = 0; sep[t]; t++) {
234                         if (!(match = parse_trigger_match(sep[t]))) {
235                                 g_critical("Invalid trigger match '%c'.", sep[t]);
236                                 error = TRUE;
237                                 break;
238                         }
239                         found_match = FALSE;
240                         for (j = 0; j < num_matches; j++) {
241                                 if (matches[j] == match) {
242                                         found_match = TRUE;
243                                         break;
244                                 }
245                         }
246                         if (!found_match) {
247                                 g_critical("Trigger match '%c' not supported by device.", sep[t]);
248                                 error = TRUE;
249                                 break;
250                         }
251                         /* Make sure this ends up in the right stage, creating
252                          * them as needed. */
253                         while (!(stage = g_slist_nth_data((*trigger)->stages, t)))
254                                 sr_trigger_stage_add(*trigger);
255                         if (sr_trigger_match_add(stage, ch, match, 0) != SR_OK) {
256                                 error = TRUE;
257                                 break;
258                         }
259                 }
260         }
261         g_strfreev(tokens);
262         g_variant_unref(gvar);
263
264         if (error)
265                 sr_trigger_free(*trigger);
266
267         return !error;
268 }
269
270 /**
271  * Split an input text into a key and value respectively ('=' separator).
272  *
273  * @param[in] text Writeable copy of the input text, gets modified.
274  * @param[out] key Position of the keyword.
275  * @param[out] val Position of the value.
276  *
277  * TODO In theory the returned key/value locations could be const pointers.
278  * Which even would be preferrable. Unfortunately most call sites deal with
279  * glib hashes, and their insert API seriously lacks the const attribute.
280  * So we drop it here as well to avoid clutter at callers'.
281  */
282 static void split_key_value(char *text, char **key, char **val)
283 {
284         char *k, *v;
285         char *pos;
286
287         if (key)
288                 *key = NULL;
289         if (val)
290                 *val = NULL;
291         if (!text || !*text)
292                 return;
293
294         k = text;
295         v = NULL;
296         pos = strchr(k, '=');
297         if (pos) {
298                 *pos = '\0';
299                 v = ++pos;
300         }
301         if (key)
302                 *key = k;
303         if (val)
304                 *val = v;
305 }
306
307 /**
308  * Create hash table from colon separated key-value pairs input text.
309  *
310  * Accepts input text as it was specified by users. Splits the colon
311  * separated key-value pairs and creates a hash table from these items.
312  * Optionally supports special forms which are useful for different CLI
313  * features.
314  *
315  * Typical form: <key>=<val>[:<key>=<val>]*
316  * Generic list of key-value pairs, all items being equal. Mere set.
317  *
318  * ID form: <id>[:<key>=<val>]*
319  * First item is not a key-value pair, instead it's an identifier. Used
320  * to specify a protocol decoder, or a device driver, or an input/output
321  * file format, optionally followed by more parameters' values. The ID
322  * part of the input spec is not optional.
323  *
324  * Optional ID: [<sel>=<id>][:<key>=<val>]*
325  * All items are key-value pairs. The first item _may_ be an identifier,
326  * if its key matches a caller specified key name. Otherwise the input
327  * text is the above typical form, a mere list of key-value pairs while
328  * none of them is special.
329  *
330  * @param[in] arg Input text.
331  * @param[in] sep_first Boolean, whether ID form is required.
332  * @param[in] key_first Keyword name if optional ID is applicable.
333  *
334  * @returns A hash table which contains the key/value pairs, or #NULL
335  *   when the input is invalid.
336  */
337 GHashTable *parse_generic_arg(const char *arg,
338         gboolean sep_first, const char *key_first)
339 {
340         GHashTable *hash;
341         char **elements;
342         int i;
343         char *k, *v;
344
345         if (!arg || !arg[0])
346                 return NULL;
347         if (key_first && !key_first[0])
348                 key_first = NULL;
349
350         hash = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, g_free);
351         elements = g_strsplit(arg, ":", 0);
352         i = 0;
353         if (sep_first) {
354                 k = g_strdup("sigrok_key");
355                 v = g_strdup(elements[i++]);
356                 g_hash_table_insert(hash, k, v);
357         } else if (key_first) {
358                 split_key_value(elements[i], &k, &v);
359                 if (g_ascii_strcasecmp(k, key_first) == 0) {
360                         k = "sigrok_key";
361                 }
362                 k = g_strdup(k);
363                 v = g_strdup(v);
364                 g_hash_table_insert(hash, k, v);
365                 i++;
366         }
367         for (; elements[i]; i++) {
368                 split_key_value(elements[i], &k, &v);
369                 k = g_strdup(k);
370                 v = v ? g_strdup(v) : NULL;
371                 g_hash_table_insert(hash, k, v);
372         }
373         g_strfreev(elements);
374
375         return hash;
376 }
377
378 GSList *check_unknown_keys(const struct sr_option **avail, GHashTable *used)
379 {
380         GSList *unknown;
381         GHashTableIter iter;
382         void *key;
383         const char *used_id;
384         size_t avail_idx;
385         const char *avail_id, *found_id;
386
387         /* Collect a list of used but not available keywords. */
388         unknown = NULL;
389         g_hash_table_iter_init(&iter, used);
390         while (g_hash_table_iter_next(&iter, &key, NULL)) {
391                 used_id = key;
392                 found_id = NULL;
393                 for (avail_idx = 0; avail[avail_idx] && avail[avail_idx]->id; avail_idx++) {
394                         avail_id = avail[avail_idx]->id;
395                         if (strcmp(avail_id, used_id) == 0) {
396                                 found_id = avail_id;
397                                 break;
398                         }
399                 }
400                 if (!found_id)
401                         unknown = g_slist_append(unknown, g_strdup(used_id));
402         }
403
404         /* Return the list of unknown keywords, or NULL if empty. */
405         return unknown;
406 }
407
408 gboolean warn_unknown_keys(const struct sr_option **avail, GHashTable *used,
409         const char *caption)
410 {
411         GSList *unknown, *l;
412         gboolean had_unknown;
413         const char *s;
414
415         if (!caption || !*caption)
416                 caption = "Unknown keyword";
417
418         unknown = check_unknown_keys(avail, used);
419         had_unknown = unknown != NULL;
420         for (l = unknown; l; l = l->next) {
421                 s = l->data;
422                 g_warning("%s: %s.", caption, s);
423         }
424         g_slist_free_full(unknown, g_free);
425
426         return had_unknown;
427 }
428
429 GHashTable *generic_arg_to_opt(const struct sr_option **opts, GHashTable *genargs)
430 {
431         GHashTable *hash;
432         GVariant *gvar;
433         int i;
434         char *s;
435         gboolean b;
436
437         hash = g_hash_table_new_full(g_str_hash, g_str_equal, g_free,
438                         (GDestroyNotify)g_variant_unref);
439         for (i = 0; opts[i]; i++) {
440                 if (!(s = g_hash_table_lookup(genargs, opts[i]->id)))
441                         continue;
442                 if (g_variant_is_of_type(opts[i]->def, G_VARIANT_TYPE_UINT32)) {
443                         gvar = g_variant_new_uint32(strtoul(s, NULL, 10));
444                         g_hash_table_insert(hash, g_strdup(opts[i]->id),
445                                         g_variant_ref_sink(gvar));
446                 } else if (g_variant_is_of_type(opts[i]->def, G_VARIANT_TYPE_INT32)) {
447                         gvar = g_variant_new_int32(strtoul(s, NULL, 10));
448                         g_hash_table_insert(hash, g_strdup(opts[i]->id),
449                                         g_variant_ref_sink(gvar));
450                 } else if (g_variant_is_of_type(opts[i]->def, G_VARIANT_TYPE_UINT64)) {
451                         gvar = g_variant_new_uint64(strtoul(s, NULL, 10));
452                         g_hash_table_insert(hash, g_strdup(opts[i]->id),
453                                         g_variant_ref_sink(gvar));
454                 } else if (g_variant_is_of_type(opts[i]->def, G_VARIANT_TYPE_DOUBLE)) {
455                         gvar = g_variant_new_double(strtod(s, NULL));
456                         g_hash_table_insert(hash, g_strdup(opts[i]->id),
457                                         g_variant_ref_sink(gvar));
458                 } else if (g_variant_is_of_type(opts[i]->def, G_VARIANT_TYPE_STRING)) {
459                         gvar = g_variant_new_string(s);
460                         g_hash_table_insert(hash, g_strdup(opts[i]->id),
461                                         g_variant_ref_sink(gvar));
462                 } else if (g_variant_is_of_type(opts[i]->def, G_VARIANT_TYPE_BOOLEAN)) {
463                         b = TRUE;
464                         if (0 == strcmp(s, "false") || 0 == strcmp(s, "no")) {
465                                 b = FALSE;
466                         } else if (!(0 == strcmp(s, "true") || 0 == strcmp(s, "yes"))) {
467                                 g_critical("Unable to convert '%s' to boolean!", s);
468                         }
469
470                         gvar = g_variant_new_boolean(b);
471                         g_hash_table_insert(hash, g_strdup(opts[i]->id),
472                                         g_variant_ref_sink(gvar));
473                 } else {
474                         g_critical("Don't know GVariant type for option '%s'!", opts[i]->id);
475                  }
476         }
477
478         return hash;
479 }
480
481 static char *strcanon(const char *str)
482 {
483         int p0, p1;
484         char *s;
485
486         /* Returns newly allocated string. */
487         s = g_ascii_strdown(str, -1);
488         for (p0 = p1 = 0; str[p0]; p0++) {
489                 if ((s[p0] >= 'a' && s[p0] <= 'z')
490                                 || (s[p0] >= '0' && s[p0] <= '9'))
491                         s[p1++] = s[p0];
492         }
493         s[p1] = '\0';
494
495         return s;
496 }
497
498 int canon_cmp(const char *str1, const char *str2)
499 {
500         int ret;
501         char *s1, *s2;
502
503         s1 = strcanon(str1);
504         s2 = strcanon(str2);
505         ret = g_ascii_strcasecmp(s1, s2);
506         g_free(s2);
507         g_free(s1);
508
509         return ret;
510 }
511
512 /* Convert driver options hash to GSList of struct sr_config. */
513 static GSList *hash_to_hwopt(GHashTable *hash)
514 {
515         struct sr_config *src;
516         GList *gl, *keys;
517         GSList *opts;
518         char *key;
519
520         keys = g_hash_table_get_keys(hash);
521         opts = NULL;
522         for (gl = keys; gl; gl = gl->next) {
523                 key = gl->data;
524                 src = g_malloc(sizeof(struct sr_config));
525                 if (opt_to_gvar(key, g_hash_table_lookup(hash, key), src) != 0)
526                         return NULL;
527                 opts = g_slist_append(opts, src);
528         }
529         g_list_free(keys);
530
531         return opts;
532 }
533
534 int parse_driver(char *arg, struct sr_dev_driver **driver, GSList **drvopts)
535 {
536         struct sr_dev_driver **drivers;
537         GHashTable *drvargs;
538         int i;
539         char *drvname;
540
541         if (!arg)
542                 return FALSE;
543
544         drvargs = parse_generic_arg(arg, TRUE, NULL);
545
546         drvname = g_strdup(g_hash_table_lookup(drvargs, "sigrok_key"));
547         g_hash_table_remove(drvargs, "sigrok_key");
548         *driver = NULL;
549         drivers = sr_driver_list(sr_ctx);
550         for (i = 0; drivers[i]; i++) {
551                 if (strcmp(drivers[i]->name, drvname))
552                         continue;
553                 *driver = drivers[i];
554         }
555         if (!*driver) {
556                 g_critical("Driver %s not found.", drvname);
557                 g_hash_table_destroy(drvargs);
558                 g_free(drvname);
559                 return FALSE;
560         }
561         g_free(drvname);
562         if (sr_driver_init(sr_ctx, *driver) != SR_OK) {
563                 g_critical("Failed to initialize driver.");
564                 g_hash_table_destroy(drvargs);
565                 return FALSE;
566         }
567
568         if (drvopts) {
569                 *drvopts = NULL;
570                 if (g_hash_table_size(drvargs) > 0) {
571                         if (!(*drvopts = hash_to_hwopt(drvargs))) {
572                                 /* Unknown options, already logged. */
573                                 g_hash_table_destroy(drvargs);
574                                 return FALSE;
575                         }
576                 }
577         }
578
579         g_hash_table_destroy(drvargs);
580
581         return TRUE;
582 }