2 * This file is part of the sigrok-cli project.
4 * Copyright (C) 2013 Bert Vermeulen <bert@biot.com>
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.
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.
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/>.
24 #include "sigrok-cli.h"
27 static GHashTable *pd_ann_visible = NULL;
28 static GHashTable *pd_meta_visible = NULL;
29 static GHashTable *pd_binary_visible = NULL;
30 static GHashTable *pd_channel_maps = NULL;
32 uint64_t pd_samplerate = 0;
34 extern struct srd_session *srd_sess;
36 static int opts_to_gvar(struct srd_decoder *dec, GHashTable *hash,
39 struct srd_decoder_option *o;
48 *options = g_hash_table_new_full(g_str_hash, g_str_equal, g_free,
49 (GDestroyNotify)g_variant_unref);
51 for (optl = dec->options; optl; optl = optl->next) {
53 if (!(val_str = g_hash_table_lookup(hash, o->id)))
56 if (g_variant_is_of_type(o->def, G_VARIANT_TYPE_STRING)) {
57 gvar = g_variant_new_string(val_str);
58 } else if (g_variant_is_of_type(o->def, G_VARIANT_TYPE_INT64)) {
60 val_int = strtoll(val_str, &conv, 0);
61 if (!conv || conv == val_str || *conv) {
62 g_critical("Protocol decoder '%s' option '%s' "
63 "requires a number.", dec->name, o->id);
67 gvar = g_variant_new_int64(val_int);
68 } else if (g_variant_is_of_type(o->def, G_VARIANT_TYPE_DOUBLE)) {
70 val_dbl = strtod(val_str, &conv);
71 if (!conv || conv == val_str || *conv) {
72 g_critical("Protocol decoder '%s' option '%s' requires a float number.",
77 gvar = g_variant_new_double(val_dbl);
79 g_critical("Unsupported type for option '%s' (%s)",
80 o->id, g_variant_get_type_string(o->def));
84 g_variant_ref_sink(gvar);
85 g_hash_table_insert(*options, g_strdup(o->id), gvar);
86 g_hash_table_remove(hash, o->id);
92 static int move_hash_element(GHashTable *src, GHashTable *dest, void *key)
94 void *orig_key, *value;
96 if (!g_hash_table_lookup_extended(src, key, &orig_key, &value))
99 g_hash_table_steal(src, orig_key);
100 g_hash_table_insert(dest, orig_key, value);
105 static GHashTable *extract_channel_map(struct srd_decoder *dec, GHashTable *hash)
107 GHashTable *channel_map;
108 struct srd_channel *pdch;
111 channel_map = g_hash_table_new_full(g_str_hash, g_str_equal,
114 for (l = dec->channels; l; l = l->next) {
116 move_hash_element(hash, channel_map, pdch->id);
118 for (l = dec->opt_channels; l; l = l->next) {
120 move_hash_element(hash, channel_map, pdch->id);
126 static int register_pd(char *opt_pds, char *opt_pd_annotations)
129 struct srd_decoder *dec;
130 struct srd_decoder_inst *di, *di_prior;
131 char **pdtokens, **pdtok, *pd_name;
132 GHashTable *pd_opthash, *options, *channels;
138 pd_opthash = options = channels = NULL;
140 pdtokens = g_strsplit(opt_pds, ",", 0);
141 for (pdtok = pdtokens; *pdtok; pdtok++) {
142 if (!(pd_opthash = parse_generic_arg(*pdtok, TRUE))) {
143 g_critical("Invalid protocol decoder option '%s'.", *pdtok);
147 pd_name = g_strdup(g_hash_table_lookup(pd_opthash, "sigrok_key"));
148 g_hash_table_remove(pd_opthash, "sigrok_key");
149 if (srd_decoder_load(pd_name) != SRD_OK) {
150 g_critical("Failed to load protocol decoder %s.", pd_name);
154 if (!(dec = srd_decoder_get_by_id(pd_name))) {
155 g_critical("Failed to get decoder %s by id.", pd_name);
160 /* Convert decoder option and channel values to GVariant. */
161 if (!opts_to_gvar(dec, pd_opthash, &options)) {
165 channels = extract_channel_map(dec, pd_opthash);
167 if (g_hash_table_size(pd_opthash) > 0) {
168 leftover = g_hash_table_get_keys(pd_opthash);
169 for (l = leftover; l; l = l->next)
170 g_critical("Unknown option or channel '%s'", (char *)l->data);
171 g_list_free(leftover);
175 if (!(di = srd_inst_new(srd_sess, pd_name, options))) {
176 g_critical("Failed to instantiate protocol decoder %s.", pd_name);
181 if (pdtok == pdtokens) {
183 * Save the channel setup for later, but only on the
184 * first decoder (stacked decoders don't get channels).
186 g_hash_table_insert(pd_channel_maps, g_strdup(di->inst_id), channels);
191 * If no annotation list was specified, add them all in now.
192 * This will be pared down later to leave only the last PD
195 if (!opt_pd_annotations) {
196 g_hash_table_insert(pd_ann_visible, g_strdup(di->decoder->id),
197 g_slist_append(NULL, GINT_TO_POINTER(-1)));
200 if (srd_inst_stack(srd_sess, di_prior, di) != SRD_OK) {
201 g_critical("Failed to stack %s -> %s.",
202 di_prior->inst_id, di->inst_id);
206 /* Remove annotations from prior levels. */
207 if (!opt_pd_annotations)
208 g_hash_table_remove(pd_ann_visible, di_prior->inst_id);
212 g_hash_table_destroy(pd_opthash);
213 g_hash_table_destroy(options);
214 pd_opthash = options = NULL;
218 g_hash_table_destroy(pd_opthash);
220 g_hash_table_destroy(options);
222 g_hash_table_destroy(channels);
224 g_strfreev(pdtokens);
230 * Register all the PDs from all stacks.
232 * Each PD string is a single stack such as "uart:baudrate=19200,modbus".
234 int register_pds(gchar **all_pds, char *opt_pd_annotations)
239 pd_ann_visible = g_hash_table_new_full(g_str_hash, g_str_equal,
241 pd_channel_maps = g_hash_table_new_full(g_str_hash,
242 g_str_equal, g_free, (GDestroyNotify)g_hash_table_destroy);
244 for (int i = 0; all_pds[i]; i++)
245 ret += register_pd(all_pds[i], opt_pd_annotations);
250 static void map_pd_inst_channels(void *key, void *value, void *user_data)
252 GHashTable *channel_map;
253 GHashTable *channel_indices;
254 GSList *channel_list;
255 struct srd_decoder_inst *di;
258 void *channel_target;
259 struct sr_channel *ch;
263 channel_list = user_data;
265 di = srd_inst_find_by_id(srd_sess, key);
267 g_critical("Protocol decoder instance \"%s\" not found.",
271 channel_indices = g_hash_table_new_full(g_str_hash, g_str_equal, g_free,
272 (GDestroyNotify)g_variant_unref);
274 g_hash_table_iter_init(&iter, channel_map);
275 while (g_hash_table_iter_next(&iter, &channel_id, &channel_target)) {
276 if (!channel_target) {
277 g_printerr("cli: Channel name for \"%s\" missing.\n",
281 ch = find_channel(channel_list, channel_target);
283 g_printerr("cli: No channel with name \"%s\" found.\n",
284 (char *)channel_target);
288 g_printerr("cli: Target channel \"%s\" not enabled.\n",
289 (char *)channel_target);
291 var = g_variant_new_int32(ch->index);
292 g_variant_ref_sink(var);
293 g_hash_table_insert(channel_indices, g_strdup(channel_id), var);
296 srd_inst_channel_set_all(di, channel_indices);
297 g_hash_table_destroy(channel_indices);
300 void map_pd_channels(struct sr_dev_inst *sdi)
304 channels = sr_dev_inst_channels_get(sdi);
306 if (pd_channel_maps) {
307 g_hash_table_foreach(pd_channel_maps, &map_pd_inst_channels,
309 g_hash_table_destroy(pd_channel_maps);
310 pd_channel_maps = NULL;
314 int setup_pd_annotations(char *opt_pd_annotations)
317 struct srd_decoder *dec;
319 char **pds, **pdtok, **keyval, **annlist, **ann, **ann_descr;
323 const struct srd_decoder_annotation_row *row_desc;
326 /* Set up custom list of PDs and annotations to show. */
327 pds = g_strsplit(opt_pd_annotations, ",", 0);
328 for (pdtok = pds; *pdtok && **pdtok; pdtok++) {
329 keyval = g_strsplit(*pdtok, "=", 0);
331 if (!(dec = srd_decoder_get_by_id(dec_id))) {
332 g_critical("Protocol decoder '%s' not found.", dec_id);
337 if (!dec->annotations) {
338 g_critical("Protocol decoder '%s' has no annotations.", dec_id);
343 ann_txt = (g_strv_length(keyval) == 2) ? keyval[1] : NULL;
344 if (ann_txt && *ann_txt) {
345 annlist = g_strsplit(ann_txt, ":", 0);
346 for (ann = annlist; *ann && **ann; ann++) {
348 g_debug("cli: Lookup decoder %s annotation %s.", dec_id, ann_id);
349 /* Lookup annotation class. */
351 for (l = dec->annotations; l; l = l->next, ann_class++) {
353 if (!canon_cmp(ann_descr[0], ann_id))
358 l_ann = g_hash_table_lookup(pd_ann_visible, dec_id);
359 l_ann = g_slist_append(l_ann, GINT_TO_POINTER(ann_class));
360 g_hash_table_replace(pd_ann_visible, g_strdup(dec_id), l_ann);
361 g_debug("cli: Showing protocol decoder %s annotation "
362 "class %d (%s).", dec_id, ann_class, ann_descr[0]);
365 /* Lookup annotation row. */
366 for (l = dec->annotation_rows; l; l = l->next) {
368 if (!canon_cmp(row_desc->id, ann_id))
372 g_debug("cli: Showing decoder %s annotation row %s (%s).",
373 dec_id, row_desc->id, row_desc->desc);
374 l_ann = g_hash_table_lookup(pd_ann_visible, dec_id);
375 for (l = row_desc->ann_classes; l; l = l->next) {
377 * This could just be:
378 * l_ann = g_slist_append(l_ann, l->data);
379 * But we are explicit for readability
380 * and to access details for diagnostics.
382 ann_class = GPOINTER_TO_INT(l->data);
383 l_ann = g_slist_append(l_ann, GINT_TO_POINTER(ann_class));
384 ann_diag = g_slist_nth_data(dec->annotations, ann_class);
385 g_debug("cli: Adding class %d/%s from row %s.",
386 ann_class, ann_diag[0], row_desc->id);
388 g_hash_table_replace(pd_ann_visible, g_strdup(dec_id), l_ann);
391 /* No match found. */
392 g_critical("Annotation '%s' not found "
393 "for protocol decoder '%s'.", ann_id, dec_id);
399 /* No class specified: show all of them. */
401 l_ann = g_slist_append(NULL, GINT_TO_POINTER(ann_class));
402 g_hash_table_insert(pd_ann_visible, g_strdup(dec_id), l_ann);
403 g_debug("cli: Showing all annotation classes for protocol "
404 "decoder %s.", dec_id);
413 int setup_pd_meta(char *opt_pd_meta)
415 struct srd_decoder *dec;
418 pd_meta_visible = g_hash_table_new_full(g_str_hash, g_int_equal,
420 pds = g_strsplit(opt_pd_meta, ",", 0);
421 for (pdtok = pds; *pdtok && **pdtok; pdtok++) {
422 if (!(dec = srd_decoder_get_by_id(*pdtok))) {
423 g_critical("Protocol decoder '%s' not found.", *pdtok);
426 g_debug("cli: Showing protocol decoder meta output from '%s'.", *pdtok);
427 g_hash_table_insert(pd_meta_visible, g_strdup(*pdtok), NULL);
434 int setup_pd_binary(char *opt_pd_binary)
437 struct srd_decoder *dec;
439 char **pds, **pdtok, **keyval, **bin_name;
441 pd_binary_visible = g_hash_table_new_full(g_str_hash, g_int_equal,
443 pds = g_strsplit(opt_pd_binary, ",", 0);
444 for (pdtok = pds; *pdtok && **pdtok; pdtok++) {
445 keyval = g_strsplit(*pdtok, "=", 0);
446 if (!(dec = srd_decoder_get_by_id(keyval[0]))) {
447 g_critical("Protocol decoder '%s' not found.", keyval[0]);
451 g_critical("Protocol decoder '%s' has no binary output.", keyval[0]);
455 if (g_strv_length(keyval) == 2) {
456 for (l = dec->binary; l; l = l->next, bin_class++) {
458 if (!strcmp(bin_name[0], keyval[1]))
463 g_critical("binary output '%s' not found "
464 "for protocol decoder '%s'.", keyval[1], keyval[0]);
467 g_debug("cli: Showing protocol decoder %s binary class "
468 "%d (%s).", keyval[0], bin_class, bin_name[0]);
470 /* No class specified: output all of them. */
472 g_debug("cli: Showing all binary classes for protocol "
473 "decoder %s.", keyval[0]);
475 g_hash_table_insert(pd_binary_visible, g_strdup(keyval[0]), GINT_TO_POINTER(bin_class));
484 * Balance JSON object and array parentheses, and separate array items.
485 * Somewhat convoluted API to re-use the routine for individual items as
486 * well as the surrounding array and object, including deferred start of
487 * the output and late flush (and to keep the state strictly local to the
488 * routine). Some additional complexity due to JSON's inability to handle
489 * a trailing comma at the last item. Code phrased such that text literals
490 * are kept in their order of appearance in the output text.
492 static void jsontrace_open_close(gboolean is_close_req)
494 static gboolean is_opened;
498 printf("{\"traceEvents\": [\n");
513 /* Convert uint64 sample number to double timestamp in microseconds. */
514 static double jsontrace_ts_usec(uint64_t snum)
520 ts_usec /= pd_samplerate;
524 /* Emit two Google Trace Events (JSON) for one PD annotation (ss, es). */
525 static void jsontrace_annotation(struct srd_decoder *dec,
526 struct srd_proto_data_annotation *pda, struct srd_proto_data *pdata)
530 struct srd_decoder_annotation_row *row;
535 * Search for an annotation row for this index, or use the
536 * annotation's descriptor.
539 if (dec->annotation_rows) {
540 for (lrow = dec->annotation_rows; lrow; lrow = lrow->next) {
542 for (lcls = row->ann_classes; lcls; lcls = lcls->next) {
543 cls = GPOINTER_TO_INT(lcls->data);
544 if (cls == pda->ann_class) {
545 row_text = row->desc;
554 ann_descr = g_slist_nth_data(dec->annotations, pda->ann_class);
555 row_text = ann_descr[0];
559 * Emit two Google Trace Events for the start and end times.
560 * Set the 'pid' (process ID) to the decoder name to group a
561 * decoder's annotations. Set the 'tid' (thread ID) to the
562 * annotation row's description. The 'ts' (timestamp) is in
563 * microseconds. Set 'name' to the longest annotation text.
565 * BEWARE of the unfortunate JSON format comma limitation. And
566 * some of the output formatting is motivated by the desire to
567 * further reduce text size, by eliminating some of the spaces.
569 * This implementation is strictly compatible to the initial
570 * implementation. Which might change in the future to increase
571 * readability of the output to humans, by generating a layout
572 * which is closer to other output modes.
574 jsontrace_open_close(FALSE);
576 printf("\"%s\": \"%s\"", "name", pda->ann_text[0]);
577 printf(", \"%s\": \"%s\"", "ph", "B");
578 printf(", \"%s\": \"%s\"", "pid", pdata->pdo->proto_id);
579 printf(", \"%s\": \"%s\"", "tid", row_text);
580 printf(", \"%s\": %lf", "ts", jsontrace_ts_usec(pdata->start_sample));
583 jsontrace_open_close(FALSE);
585 printf("\"%s\": \"%s\"", "name", pda->ann_text[0]);
586 printf(", \"%s\": \"%s\"", "ph", "E");
587 printf(", \"%s\": \"%s\"", "pid", pdata->pdo->proto_id);
588 printf(", \"%s\": \"%s\"", "tid", row_text);
589 printf(", \"%s\": %lf", "ts", jsontrace_ts_usec(pdata->end_sample));
593 void show_pd_annotations(struct srd_proto_data *pdata, void *cb_data)
595 struct srd_decoder *dec;
596 struct srd_proto_data_annotation *pda;
597 GSList *ann_list, *l;
600 gboolean show_ann, show_snum, show_class, show_quotes, show_abbrev;
608 if (!g_hash_table_lookup_extended(pd_ann_visible, pdata->pdo->di->decoder->id,
609 NULL, (void **)&ann_list)) {
610 /* Not in the list of PDs whose annotations we're showing. */
614 dec = pdata->pdo->di->decoder;
617 for (l = ann_list; l; l = l->next) {
618 if (GPOINTER_TO_INT(l->data) == -1
619 || GPOINTER_TO_INT(l->data) == pda->ann_class) {
627 /* Google Trace Events are rather special. Use a separate code path. */
628 if (opt_pd_jsontrace) {
629 jsontrace_annotation(dec, pda, pdata);
634 * Determine which fields of the annotation to display. Inspect
635 * user specified options as well as the verbosity of the log level:
636 * - Optionally show the sample numbers for the annotation's span.
637 * - Always show the protocol decoder ID.
638 * - Optionally show the annotation's class description.
639 * - Always show the longest annotation text.
640 * - Optionally show alternative annotation text (abbreviations
641 * for different zoom levels).
642 * - Optionally put quote marks around annotation text, when
643 * recipients might have to deal with a set of text variants.
645 show_snum = show_class = show_quotes = show_abbrev = FALSE;
646 if (opt_pd_samplenum || opt_loglevel > SR_LOG_WARN) {
649 if (opt_loglevel > SR_LOG_WARN) {
652 if (opt_loglevel > SR_LOG_INFO) {
658 * Display the annotation's fields after the layout was
662 printf("%" PRIu64 "-%" PRIu64 " ",
663 pdata->start_sample, pdata->end_sample);
665 printf("%s: ", pdata->pdo->proto_id);
667 ann_descr = g_slist_nth_data(dec->annotations, pda->ann_class);
668 printf("%s: ", ann_descr[0]);
670 quote = show_quotes ? "\"" : "";
671 printf("%s%s%s", quote, pda->ann_text[0], quote);
673 for (i = 1; pda->ann_text[i]; i++)
674 printf(" %s%s%s", quote, pda->ann_text[i], quote);
680 void show_pd_meta(struct srd_proto_data *pdata, void *cb_data)
684 if (!g_hash_table_lookup_extended(pd_meta_visible,
685 pdata->pdo->di->decoder->id, NULL, NULL))
686 /* Not in the list of PDs whose meta output we're showing. */
689 if (opt_pd_samplenum || opt_loglevel > SR_LOG_WARN)
690 printf("%"PRIu64"-%"PRIu64" ", pdata->start_sample, pdata->end_sample);
691 printf("%s: ", pdata->pdo->proto_id);
692 printf("%s: %s", pdata->pdo->meta_name, g_variant_print(pdata->data, FALSE));
697 void show_pd_binary(struct srd_proto_data *pdata, void *cb_data)
699 struct srd_proto_data_binary *pdb;
705 if (!g_hash_table_lookup_extended(pd_binary_visible,
706 pdata->pdo->di->decoder->id, NULL, (void **)&classp))
707 /* Not in the list of PDs whose meta output we're showing. */
710 classi = GPOINTER_TO_INT(classp);
712 if (classi != -1 && classi != pdb->bin_class)
713 /* Not showing this binary class. */
716 /* Just send the binary output to stdout, no embellishments. */
717 fwrite(pdb->data, pdb->size, 1, stdout);
721 void show_pd_prepare(void)
723 if (opt_pd_jsontrace)
724 jsontrace_open_close(TRUE);
727 void show_pd_close(void)
729 if (opt_pd_jsontrace)
730 jsontrace_open_close(TRUE);