]> sigrok.org Git - sigrok-cli.git/blob - decode.c
decode: Prepare to rework text output for protocol decoder annotations
[sigrok-cli.git] / decode.c
1 /*
2  * This file is part of the sigrok-cli project.
3  *
4  * Copyright (C) 2013 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 <stdlib.h>
22 #include <string.h>
23 #include <glib.h>
24 #include <assert.h>
25 #include "sigrok-cli.h"
26
27 #ifdef HAVE_SRD
28 static GHashTable *pd_ann_visible = NULL;
29 static GHashTable *pd_meta_visible = NULL;
30 static GHashTable *pd_binary_visible = NULL;
31 static GHashTable *pd_channel_maps = NULL;
32
33 extern struct srd_session *srd_sess;
34
35 static int opts_to_gvar(struct srd_decoder *dec, GHashTable *hash,
36                 GHashTable **options)
37 {
38         struct srd_decoder_option *o;
39         GSList *optl;
40         GVariant *gvar;
41         gint64 val_int;
42         int ret;
43         char *val_str, *conv;
44
45         ret = TRUE;
46         *options = g_hash_table_new_full(g_str_hash, g_str_equal, g_free,
47                         (GDestroyNotify)g_variant_unref);
48
49         for (optl = dec->options; optl; optl = optl->next) {
50                 o = optl->data;
51                 if (!(val_str = g_hash_table_lookup(hash, o->id)))
52                         /* Not specified. */
53                         continue;
54                 if (g_variant_is_of_type(o->def, G_VARIANT_TYPE_STRING)) {
55                         gvar = g_variant_new_string(val_str);
56                 } else if (g_variant_is_of_type(o->def, G_VARIANT_TYPE_INT64)) {
57                         val_int = strtoll(val_str, &conv, 0);
58                         if (!conv || conv == val_str) {
59                                 g_critical("Protocol decoder '%s' option '%s' "
60                                                 "requires a number.", dec->name, o->id);
61                                 ret = FALSE;
62                                 break;
63                         }
64                         gvar = g_variant_new_int64(val_int);
65                 } else {
66                         g_critical("Unsupported type for option '%s' (%s)",
67                                         o->id, g_variant_get_type_string(o->def));
68                         ret = FALSE;
69                         break;
70                 }
71                 g_variant_ref_sink(gvar);
72                 g_hash_table_insert(*options, g_strdup(o->id), gvar);
73                 g_hash_table_remove(hash, o->id);
74         }
75
76         return ret;
77 }
78
79 static int move_hash_element(GHashTable *src, GHashTable *dest, void *key)
80 {
81         void *orig_key, *value;
82
83         if (!g_hash_table_lookup_extended(src, key, &orig_key, &value))
84                 /* Not specified. */
85                 return FALSE;
86         g_hash_table_steal(src, orig_key);
87         g_hash_table_insert(dest, orig_key, value);
88
89         return TRUE;
90 }
91
92 static GHashTable *extract_channel_map(struct srd_decoder *dec, GHashTable *hash)
93 {
94         GHashTable *channel_map;
95         struct srd_channel *pdch;
96         GSList *l;
97
98         channel_map = g_hash_table_new_full(g_str_hash, g_str_equal,
99                                           g_free, g_free);
100
101         for (l = dec->channels; l; l = l->next) {
102                 pdch = l->data;
103                 move_hash_element(hash, channel_map, pdch->id);
104         }
105         for (l = dec->opt_channels; l; l = l->next) {
106                 pdch = l->data;
107                 move_hash_element(hash, channel_map, pdch->id);
108         }
109
110         return channel_map;
111 }
112
113 static int register_pd(char *opt_pds, char *opt_pd_annotations)
114 {
115         int ret;
116         struct srd_decoder *dec;
117         struct srd_decoder_inst *di, *di_prior;
118         char **pdtokens, **pdtok, *pd_name;
119         GHashTable *pd_opthash, *options, *channels;
120         GList *leftover, *l;
121
122         ret = 0;
123         pd_name = NULL;
124         di_prior = NULL;
125         pd_opthash = options = channels = NULL;
126
127         pdtokens = g_strsplit(opt_pds, ",", 0);
128         for (pdtok = pdtokens; *pdtok; pdtok++) {
129                 if (!(pd_opthash = parse_generic_arg(*pdtok, TRUE))) {
130                         g_critical("Invalid protocol decoder option '%s'.", *pdtok);
131                         break;
132                 }
133
134                 pd_name = g_strdup(g_hash_table_lookup(pd_opthash, "sigrok_key"));
135                 g_hash_table_remove(pd_opthash, "sigrok_key");
136                 if (srd_decoder_load(pd_name) != SRD_OK) {
137                         g_critical("Failed to load protocol decoder %s.", pd_name);
138                         ret = 1;
139                         break;
140                 }
141                 if (!(dec = srd_decoder_get_by_id(pd_name))) {
142                         g_critical("Failed to get decoder %s by id.", pd_name);
143                         ret = 1;
144                         break;
145                 }
146
147                 /* Convert decoder option and channel values to GVariant. */
148                 if (!opts_to_gvar(dec, pd_opthash, &options)) {
149                         ret = 1;
150                         break;
151                 }
152                 channels = extract_channel_map(dec, pd_opthash);
153
154                 if (g_hash_table_size(pd_opthash) > 0) {
155                         leftover = g_hash_table_get_keys(pd_opthash);
156                         for (l = leftover; l; l = l->next)
157                                 g_critical("Unknown option or channel '%s'", (char *)l->data);
158                         g_list_free(leftover);
159                         break;
160                 }
161
162                 if (!(di = srd_inst_new(srd_sess, pd_name, options))) {
163                         g_critical("Failed to instantiate protocol decoder %s.", pd_name);
164                         ret = 1;
165                         break;
166                 }
167
168                 if (pdtok == pdtokens) {
169                         /*
170                          * Save the channel setup for later, but only on the
171                          * first decoder (stacked decoders don't get channels).
172                          */
173                         g_hash_table_insert(pd_channel_maps, g_strdup(di->inst_id), channels);
174                         channels = NULL;
175                 }
176
177                 /*
178                  * If no annotation list was specified, add them all in now.
179                  * This will be pared down later to leave only the last PD
180                  * in the stack.
181                  */
182                 if (!opt_pd_annotations) {
183                         g_hash_table_insert(pd_ann_visible, g_strdup(di->decoder->id),
184                                         g_slist_append(NULL, GINT_TO_POINTER(-1)));
185                 }
186                 if (di_prior) {
187                         if (srd_inst_stack(srd_sess, di_prior, di) != SRD_OK) {
188                                 g_critical("Failed to stack %s -> %s.",
189                                         di_prior->inst_id, di->inst_id);
190                                 ret = 1;
191                                 break;
192                         }
193                         /* Remove annotations from prior levels. */
194                         if (!opt_pd_annotations)
195                                 g_hash_table_remove(pd_ann_visible, di_prior->inst_id);
196                 }
197                 di_prior = di;
198                 g_free(pd_name);
199                 g_hash_table_destroy(pd_opthash);
200                 g_hash_table_destroy(options);
201                 pd_opthash = options = NULL;
202         }
203
204         if (pd_opthash)
205                 g_hash_table_destroy(pd_opthash);
206         if (options)
207                 g_hash_table_destroy(options);
208         if (channels)
209                 g_hash_table_destroy(channels);
210
211         g_strfreev(pdtokens);
212
213         return ret;
214 }
215
216 /*
217  * Register all the PDs from all stacks.
218  *
219  * Each PD string is a single stack such as "uart:baudrate=19200,modbus".
220  */
221 int register_pds(gchar **all_pds, char *opt_pd_annotations)
222 {
223         int ret;
224
225         ret = 0;
226         pd_ann_visible = g_hash_table_new_full(g_str_hash, g_str_equal,
227                                                g_free, NULL);
228         pd_channel_maps = g_hash_table_new_full(g_str_hash,
229                 g_str_equal, g_free, (GDestroyNotify)g_hash_table_destroy);
230
231         for (int i = 0; all_pds[i]; i++)
232                 ret += register_pd(all_pds[i], opt_pd_annotations);
233
234         return ret;
235 }
236
237 static void map_pd_inst_channels(void *key, void *value, void *user_data)
238 {
239         GHashTable *channel_map;
240         GHashTable *channel_indices;
241         GSList *channel_list;
242         struct srd_decoder_inst *di;
243         GVariant *var;
244         void *channel_id;
245         void *channel_target;
246         struct sr_channel *ch;
247         GHashTableIter iter;
248
249         channel_map = value;
250         channel_list = user_data;
251
252         di = srd_inst_find_by_id(srd_sess, key);
253         if (!di) {
254                 g_critical("Protocol decoder instance \"%s\" not found.",
255                            (char *)key);
256                 return;
257         }
258         channel_indices = g_hash_table_new_full(g_str_hash, g_str_equal, g_free,
259                                               (GDestroyNotify)g_variant_unref);
260
261         g_hash_table_iter_init(&iter, channel_map);
262         while (g_hash_table_iter_next(&iter, &channel_id, &channel_target)) {
263                 ch = find_channel(channel_list, channel_target);
264                 if (!ch) {
265                         g_printerr("cli: No channel with name \"%s\" found.\n",
266                                    (char *)channel_target);
267                         continue;
268                 }
269                 if (!ch->enabled)
270                         g_printerr("cli: Target channel \"%s\" not enabled.\n",
271                                    (char *)channel_target);
272
273                 var = g_variant_new_int32(ch->index);
274                 g_variant_ref_sink(var);
275                 g_hash_table_insert(channel_indices, g_strdup(channel_id), var);
276         }
277
278         srd_inst_channel_set_all(di, channel_indices);
279         g_hash_table_destroy(channel_indices);
280 }
281
282 void map_pd_channels(struct sr_dev_inst *sdi)
283 {
284         GSList *channels;
285
286         channels = sr_dev_inst_channels_get(sdi);
287
288         if (pd_channel_maps) {
289                 g_hash_table_foreach(pd_channel_maps, &map_pd_inst_channels,
290                                      channels);
291                 g_hash_table_destroy(pd_channel_maps);
292                 pd_channel_maps = NULL;
293         }
294 }
295
296 int setup_pd_annotations(char *opt_pd_annotations)
297 {
298         GSList *l, *l_ann;
299         struct srd_decoder *dec;
300         int ann_class;
301         char **pds, **pdtok, **keyval, **annlist, **ann, **ann_descr;
302
303         /* Set up custom list of PDs and annotations to show. */
304         pds = g_strsplit(opt_pd_annotations, ",", 0);
305         for (pdtok = pds; *pdtok && **pdtok; pdtok++) {
306                 keyval = g_strsplit(*pdtok, "=", 0);
307                 if (!(dec = srd_decoder_get_by_id(keyval[0]))) {
308                         g_critical("Protocol decoder '%s' not found.", keyval[0]);
309                         return 1;
310                 }
311                 if (!dec->annotations) {
312                         g_critical("Protocol decoder '%s' has no annotations.", keyval[0]);
313                         return 1;
314                 }
315                 if (g_strv_length(keyval) == 2 && keyval[1][0] != '\0') {
316                         annlist = g_strsplit(keyval[1], ":", 0);
317                         for (ann = annlist; *ann && **ann; ann++) {
318                                 ann_class = 0;
319                                 for (l = dec->annotations; l; l = l->next, ann_class++) {
320                                         ann_descr = l->data;
321                                         if (!canon_cmp(ann_descr[0], *ann))
322                                                 /* Found it. */
323                                                 break;
324                                 }
325                                 if (!l) {
326                                         g_critical("Annotation '%s' not found "
327                                                         "for protocol decoder '%s'.", *ann, keyval[0]);
328                                         return 1;
329                                 }
330                                 l_ann = g_hash_table_lookup(pd_ann_visible, keyval[0]);
331                                 l_ann = g_slist_append(l_ann, GINT_TO_POINTER(ann_class));
332                                 g_hash_table_replace(pd_ann_visible, g_strdup(keyval[0]), l_ann);
333                                 g_debug("cli: Showing protocol decoder %s annotation "
334                                                 "class %d (%s).", keyval[0], ann_class, ann_descr[0]);
335                         }
336                 } else {
337                         /* No class specified: show all of them. */
338                                 g_hash_table_insert(pd_ann_visible, g_strdup(keyval[0]),
339                                                 g_slist_append(NULL, GINT_TO_POINTER(-1)));
340                         g_debug("cli: Showing all annotation classes for protocol "
341                                         "decoder %s.", keyval[0]);
342                 }
343                 g_strfreev(keyval);
344         }
345         g_strfreev(pds);
346
347         return 0;
348 }
349
350 int setup_pd_meta(char *opt_pd_meta)
351 {
352         struct srd_decoder *dec;
353         char **pds, **pdtok;
354
355         pd_meta_visible = g_hash_table_new_full(g_str_hash, g_int_equal,
356                         g_free, NULL);
357         pds = g_strsplit(opt_pd_meta, ",", 0);
358         for (pdtok = pds; *pdtok && **pdtok; pdtok++) {
359                 if (!(dec = srd_decoder_get_by_id(*pdtok))) {
360                         g_critical("Protocol decoder '%s' not found.", *pdtok);
361                         return 1;
362                 }
363                 g_debug("cli: Showing protocol decoder meta output from '%s'.", *pdtok);
364                 g_hash_table_insert(pd_meta_visible, g_strdup(*pdtok), NULL);
365         }
366         g_strfreev(pds);
367
368         return 0;
369 }
370
371 int setup_pd_binary(char *opt_pd_binary)
372 {
373         GSList *l;
374         struct srd_decoder *dec;
375         int bin_class;
376         char **pds, **pdtok, **keyval, **bin_name;
377
378         pd_binary_visible = g_hash_table_new_full(g_str_hash, g_int_equal,
379                         g_free, NULL);
380         pds = g_strsplit(opt_pd_binary, ",", 0);
381         for (pdtok = pds; *pdtok && **pdtok; pdtok++) {
382                 keyval = g_strsplit(*pdtok, "=", 0);
383                 if (!(dec = srd_decoder_get_by_id(keyval[0]))) {
384                         g_critical("Protocol decoder '%s' not found.", keyval[0]);
385                         return 1;
386                 }
387                 if (!dec->binary) {
388                         g_critical("Protocol decoder '%s' has no binary output.", keyval[0]);
389                         return 1;
390                 }
391                 bin_class = 0;
392                 if (g_strv_length(keyval) == 2) {
393                         for (l = dec->binary; l; l = l->next, bin_class++) {
394                                 bin_name = l->data;
395                                 if (!strcmp(bin_name[0], keyval[1]))
396                                         /* Found it. */
397                                         break;
398                         }
399                         if (!l) {
400                                 g_critical("binary output '%s' not found "
401                                                 "for protocol decoder '%s'.", keyval[1], keyval[0]);
402                                 return 1;
403                         }
404                         g_debug("cli: Showing protocol decoder %s binary class "
405                                         "%d (%s).", keyval[0], bin_class, bin_name[0]);
406                 } else {
407                         /* No class specified: output all of them. */
408                         bin_class = -1;
409                         g_debug("cli: Showing all binary classes for protocol "
410                                         "decoder %s.", keyval[0]);
411                 }
412                 g_hash_table_insert(pd_binary_visible, g_strdup(keyval[0]), GINT_TO_POINTER(bin_class));
413                 g_strfreev(keyval);
414         }
415         g_strfreev(pds);
416
417         return 0;
418 }
419
420 static inline void pd_ann_check(gboolean chk)
421 {
422
423         assert(chk);
424 }
425
426 void show_pd_annotations(struct srd_proto_data *pdata, void *cb_data)
427 {
428         struct srd_decoder *dec;
429         struct srd_proto_data_annotation *pda;
430         GSList *ann_list, *l;
431         int i;
432         char **ann_descr;
433         gboolean show_ann, show_snum, show_class, show_quotes, show_abbrev;
434         gboolean show_id_colon;
435
436         (void)cb_data;
437
438         if (!pd_ann_visible)
439                 return;
440
441         if (!g_hash_table_lookup_extended(pd_ann_visible, pdata->pdo->di->decoder->id,
442                         NULL, (void **)&ann_list)) {
443                 /* Not in the list of PDs whose annotations we're showing. */
444                 return;
445         }
446
447         dec = pdata->pdo->di->decoder;
448         pda = pdata->data;
449         show_ann = FALSE;
450         for (l = ann_list; l; l = l->next) {
451                 if (GPOINTER_TO_INT(l->data) == -1
452                                 || GPOINTER_TO_INT(l->data) == pda->ann_class) {
453                         show_ann = TRUE;
454                         break;
455                 }
456         }
457         if (!show_ann)
458                 return;
459
460         /*
461          * Determine the annotation's layout from the verbosity of the
462          * log level:
463          * - Optionally show the sample numbers for the annotation's span.
464          * - Always show the protocol decoder ID.
465          * - Optionally show the annotation's class description.
466          * - Always show the longest annotation text.
467          * - Optionally show alternative annotation text (abbreviations
468          *   for different zoom levels).
469          * - Optionally put quote marks around annotation text, when
470          *   recipients might have to deal with a set of text variants.
471          */
472         show_snum = show_class = show_quotes = show_abbrev = FALSE;
473         if (opt_loglevel > SR_LOG_WARN) {
474                 show_snum = TRUE;
475         }
476         if (opt_loglevel > SR_LOG_WARN) {
477                 show_quotes = TRUE;
478         }
479         if (opt_loglevel > SR_LOG_INFO) {
480                 show_class = TRUE;
481                 show_abbrev = TRUE;
482         }
483         /* Backwards (bug?) compatibility. */
484         show_id_colon = show_abbrev || !show_quotes;
485
486         /*
487          * Display the annotation's fields after the layout was
488          * determined above.
489          */
490         pd_ann_check(show_ann);
491         if (opt_loglevel <= SR_LOG_WARN) {
492                 pd_ann_check(!show_snum);
493                 pd_ann_check(show_id_colon);
494                 pd_ann_check(!show_class);
495                 pd_ann_check(!show_quotes);
496                 pd_ann_check(!show_abbrev);
497                 /* Show only the longest annotation. */
498                 printf("%s: %s", pdata->pdo->proto_id, pda->ann_text[0]);
499         } else if (opt_loglevel >= SR_LOG_INFO) {
500                 /* Sample numbers and quotes around the longest annotation. */
501                 pd_ann_check(show_snum);
502                 printf("%"PRIu64"-%"PRIu64"", pdata->start_sample, pdata->end_sample);
503                 if (opt_loglevel == SR_LOG_INFO) {
504                         pd_ann_check(!show_id_colon);
505                         pd_ann_check(!show_class);
506                         pd_ann_check(show_quotes);
507                         pd_ann_check(!show_abbrev);
508                         printf(" %s \"%s\"", pdata->pdo->proto_id, pda->ann_text[0]);
509                 } else {
510                         pd_ann_check(show_id_colon);
511                         pd_ann_check(show_class);
512                         pd_ann_check(show_quotes);
513                         pd_ann_check(show_abbrev);
514                         /* Protocol decoder id, annotation class,
515                          * all annotation strings. */
516                         ann_descr = g_slist_nth_data(dec->annotations, pda->ann_class);
517                         printf(" %s: %s:", pdata->pdo->proto_id, ann_descr[0]);
518                         for (i = 0; pda->ann_text[i]; i++)
519                                 printf(" \"%s\"", pda->ann_text[i]);
520                 }
521         }
522         printf("\n");
523         fflush(stdout);
524 }
525
526 void show_pd_meta(struct srd_proto_data *pdata, void *cb_data)
527 {
528         (void)cb_data;
529
530         if (!g_hash_table_lookup_extended(pd_meta_visible,
531                         pdata->pdo->di->decoder->id, NULL, NULL))
532                 /* Not in the list of PDs whose meta output we're showing. */
533                 return;
534
535         if (opt_loglevel > SR_LOG_WARN)
536                 printf("%"PRIu64"-%"PRIu64" ", pdata->start_sample, pdata->end_sample);
537         printf("%s: ", pdata->pdo->proto_id);
538         printf("%s: %s", pdata->pdo->meta_name, g_variant_print(pdata->data, FALSE));
539         printf("\n");
540         fflush(stdout);
541 }
542
543 void show_pd_binary(struct srd_proto_data *pdata, void *cb_data)
544 {
545         struct srd_proto_data_binary *pdb;
546         gpointer classp;
547         int classi;
548
549         (void)cb_data;
550
551         if (!g_hash_table_lookup_extended(pd_binary_visible,
552                         pdata->pdo->di->decoder->id, NULL, (void **)&classp))
553                 /* Not in the list of PDs whose meta output we're showing. */
554                 return;
555
556         classi = GPOINTER_TO_INT(classp);
557         pdb = pdata->data;
558         if (classi != -1 && classi != pdb->bin_class)
559                 /* Not showing this binary class. */
560                 return;
561
562         /* Just send the binary output to stdout, no embellishments. */
563         fwrite(pdb->data, pdb->size, 1, stdout);
564         fflush(stdout);
565 }
566 #endif