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 const char *keyword_assign = "assign_channels";
37 static const char *assign_by_index = "auto_index";
38 static const char *assign_by_name = "auto_names";
40 static int opts_to_gvar(struct srd_decoder *dec, GHashTable *hash,
43 struct srd_decoder_option *o;
52 *options = g_hash_table_new_full(g_str_hash, g_str_equal, g_free,
53 (GDestroyNotify)g_variant_unref);
55 for (optl = dec->options; optl; optl = optl->next) {
57 if (!(val_str = g_hash_table_lookup(hash, o->id)))
60 if (g_variant_is_of_type(o->def, G_VARIANT_TYPE_STRING)) {
61 gvar = g_variant_new_string(val_str);
62 } else if (g_variant_is_of_type(o->def, G_VARIANT_TYPE_INT64)) {
64 val_int = strtoll(val_str, &conv, 0);
65 if (!conv || conv == val_str || *conv) {
66 g_critical("Protocol decoder '%s' option '%s' "
67 "requires a number.", dec->name, o->id);
71 gvar = g_variant_new_int64(val_int);
72 } else if (g_variant_is_of_type(o->def, G_VARIANT_TYPE_DOUBLE)) {
74 val_dbl = strtod(val_str, &conv);
75 if (!conv || conv == val_str || *conv) {
76 g_critical("Protocol decoder '%s' option '%s' requires a float number.",
81 gvar = g_variant_new_double(val_dbl);
83 g_critical("Unsupported type for option '%s' (%s)",
84 o->id, g_variant_get_type_string(o->def));
88 g_variant_ref_sink(gvar);
89 g_hash_table_insert(*options, g_strdup(o->id), gvar);
90 g_hash_table_remove(hash, o->id);
96 static int move_hash_element(GHashTable *src, GHashTable *dest, const void *key)
98 void *orig_key, *value;
100 if (!g_hash_table_lookup_extended(src, key, &orig_key, &value))
103 g_hash_table_steal(src, orig_key);
104 g_hash_table_insert(dest, orig_key, value);
109 static GHashTable *extract_channel_map(struct srd_decoder *dec, GHashTable *hash)
111 GHashTable *channel_map;
112 struct srd_channel *pdch;
115 channel_map = g_hash_table_new_full(g_str_hash, g_str_equal,
118 move_hash_element(hash, channel_map, keyword_assign);
119 for (l = dec->channels; l; l = l->next) {
121 move_hash_element(hash, channel_map, pdch->id);
123 for (l = dec->opt_channels; l; l = l->next) {
125 move_hash_element(hash, channel_map, pdch->id);
131 static int register_pd(char *opt_pds, char *opt_pd_annotations)
134 struct srd_decoder *dec;
135 struct srd_decoder_inst *di, *di_prior;
136 char **pdtokens, **pdtok, *pd_name;
137 GHashTable *pd_opthash, *options, *channels;
143 pd_opthash = options = channels = NULL;
145 pdtokens = g_strsplit(opt_pds, ",", 0);
146 for (pdtok = pdtokens; *pdtok; pdtok++) {
147 if (!(pd_opthash = parse_generic_arg(*pdtok, TRUE, NULL))) {
148 g_critical("Invalid protocol decoder option '%s'.", *pdtok);
152 pd_name = g_strdup(g_hash_table_lookup(pd_opthash, "sigrok_key"));
153 g_hash_table_remove(pd_opthash, "sigrok_key");
154 if (srd_decoder_load(pd_name) != SRD_OK) {
155 g_critical("Failed to load protocol decoder %s.", pd_name);
159 if (!(dec = srd_decoder_get_by_id(pd_name))) {
160 g_critical("Failed to get decoder %s by id.", pd_name);
165 /* Convert decoder option and channel values to GVariant. */
166 if (!opts_to_gvar(dec, pd_opthash, &options)) {
170 channels = extract_channel_map(dec, pd_opthash);
172 if (g_hash_table_size(pd_opthash) > 0) {
173 leftover = g_hash_table_get_keys(pd_opthash);
174 for (l = leftover; l; l = l->next)
175 g_critical("Unknown option or channel '%s'", (char *)l->data);
176 g_list_free(leftover);
180 if (!(di = srd_inst_new(srd_sess, pd_name, options))) {
181 g_critical("Failed to instantiate protocol decoder %s.", pd_name);
186 if (pdtok == pdtokens) {
188 * Save the channel setup for later, but only on the
189 * first decoder (stacked decoders don't get channels).
191 g_hash_table_insert(pd_channel_maps, g_strdup(di->inst_id), channels);
196 * If no annotation list was specified, add them all in now.
197 * This will be pared down later to leave only the last PD
200 if (!opt_pd_annotations) {
201 g_hash_table_insert(pd_ann_visible, g_strdup(di->decoder->id),
202 g_slist_append(NULL, GINT_TO_POINTER(-1)));
205 if (srd_inst_stack(srd_sess, di_prior, di) != SRD_OK) {
206 g_critical("Failed to stack %s -> %s.",
207 di_prior->inst_id, di->inst_id);
211 /* Remove annotations from prior levels. */
212 if (!opt_pd_annotations)
213 g_hash_table_remove(pd_ann_visible, di_prior->inst_id);
217 g_hash_table_destroy(pd_opthash);
218 g_hash_table_destroy(options);
219 pd_opthash = options = NULL;
223 g_hash_table_destroy(pd_opthash);
225 g_hash_table_destroy(options);
227 g_hash_table_destroy(channels);
229 g_strfreev(pdtokens);
235 * Register all the PDs from all stacks.
237 * Each PD string is a single stack such as "uart:baudrate=19200,modbus".
239 int register_pds(gchar **all_pds, char *opt_pd_annotations)
244 pd_ann_visible = g_hash_table_new_full(g_str_hash, g_str_equal,
246 pd_channel_maps = g_hash_table_new_full(g_str_hash,
247 g_str_equal, g_free, (GDestroyNotify)g_hash_table_destroy);
249 for (int i = 0; all_pds[i]; i++)
250 ret += register_pd(all_pds[i], opt_pd_annotations);
255 static void map_pd_inst_channels(void *key, void *value, void *user_data)
257 GHashTable *channel_map;
258 GHashTable *channel_indices;
259 GSList *channel_list;
260 struct srd_decoder_inst *di;
261 struct srd_decoder *pd;
264 void *channel_target;
265 struct sr_channel *ch;
274 GSList *l_pd, *l_pdo, *l_ch;
275 struct srd_channel *pdch;
278 channel_list = user_data;
280 di = srd_inst_find_by_id(srd_sess, key);
282 g_critical("Protocol decoder instance \"%s\" not found.",
286 channel_indices = g_hash_table_new_full(g_str_hash, g_str_equal, g_free,
287 (GDestroyNotify)g_variant_unref);
290 * The typical mode of operation is to apply a user specified
291 * mapping of sigrok channels to decoder inputs. Lack of mapping
292 * specs will assign no signals (compatible behaviour to earlier
295 * Alternatively we can assign sigrok logic channels to decoder
296 * inputs in the strict order of channel indices, or when their
297 * names match. Users need to request this automatic assignment
298 * though, because this behaviour differs from earlier versions.
300 * Even more sophisticated heuristics of mapping sigrok channels
301 * to decoder inputs are not implemented here. Later versions
302 * could translate the Pulseview approach to the C language, but
303 * it's better to stabilize that logic first before porting it.
305 assign = ASSIGN_USER_SPEC;
306 keyword = g_hash_table_lookup(channel_map, keyword_assign);
307 if (g_hash_table_size(channel_map) != 1) {
308 assign = ASSIGN_USER_SPEC;
309 } else if (!keyword) {
310 assign = ASSIGN_USER_SPEC;
311 } else if (strcmp(keyword, assign_by_index) == 0) {
312 assign = ASSIGN_BY_INDEX;
313 } else if (strcmp(keyword, assign_by_name) == 0) {
314 assign = ASSIGN_BY_NAMES;
316 g_critical("Unknown type of decoder channel assignment: %s.",
322 if (assign == ASSIGN_BY_INDEX) {
324 * Iterate the protocol decoder's list of input signals
325 * (mandatory and optional, never more than the decoder's
326 * total channels count). Assign sigrok logic channels
327 * until either is exhausted. Use sigrok channels in the
328 * very order of their declaration in the input stream.
332 while (l_ch && l_pd) {
335 if (ch->type != SR_CHANNEL_LOGIC)
337 if (ch->index >= di->dec_num_channels)
342 l_pd = pd->opt_channels;
343 /* TODO Emit an INFO message. */
344 g_hash_table_insert(channel_map,
345 g_strdup(pdch->id), g_strdup(ch->name));
347 } else if (assign == ASSIGN_BY_NAMES) {
349 * Iterate the protocol decoder's list of input signals.
350 * Search for sigrok logic channels that have matching
351 * names (case insensitive comparison). Not finding a
352 * sigrok channel of a given name is non-fatal (could be
353 * an optional channel, the decoder will check later for
354 * all mandatory channels to be assigned).
357 l_pdo = pd->opt_channels;
365 ch = find_channel(channel_list, pdch->id, FALSE);
367 /* TODO Emit a WARN message. */
368 /* if (l_pdo) ...; */
371 if (ch->type != SR_CHANNEL_LOGIC) {
372 /* TODO Emit a WARN message. */
375 /* TODO Emit an INFO message. */
376 g_hash_table_insert(channel_map,
377 g_strdup(pdch->id), g_strdup(ch->name));
381 g_hash_table_iter_init(&iter, channel_map);
382 while (g_hash_table_iter_next(&iter, &channel_id, &channel_target)) {
383 if (strcmp(channel_id, keyword_assign) == 0)
385 if (!channel_target) {
386 g_printerr("cli: Channel name for \"%s\" missing.\n",
390 ch = find_channel(channel_list, channel_target, TRUE);
392 g_printerr("cli: No channel with name \"%s\" found.\n",
393 (char *)channel_target);
397 g_printerr("cli: Target channel \"%s\" not enabled.\n",
398 (char *)channel_target);
400 var = g_variant_new_int32(ch->index);
401 g_variant_ref_sink(var);
402 g_hash_table_insert(channel_indices, g_strdup(channel_id), var);
405 srd_inst_channel_set_all(di, channel_indices);
406 g_hash_table_destroy(channel_indices);
409 void map_pd_channels(struct sr_dev_inst *sdi)
413 channels = sr_dev_inst_channels_get(sdi);
415 if (pd_channel_maps) {
416 g_hash_table_foreach(pd_channel_maps, &map_pd_inst_channels,
418 g_hash_table_destroy(pd_channel_maps);
419 pd_channel_maps = NULL;
423 int setup_pd_annotations(char *opt_pd_annotations)
426 struct srd_decoder *dec;
428 char **pds, **pdtok, **keyval, **annlist, **ann, **ann_descr;
432 const struct srd_decoder_annotation_row *row_desc;
435 /* Set up custom list of PDs and annotations to show. */
436 pds = g_strsplit(opt_pd_annotations, ",", 0);
437 for (pdtok = pds; *pdtok && **pdtok; pdtok++) {
438 keyval = g_strsplit(*pdtok, "=", 0);
440 if (!(dec = srd_decoder_get_by_id(dec_id))) {
441 g_critical("Protocol decoder '%s' not found.", dec_id);
446 if (!dec->annotations) {
447 g_critical("Protocol decoder '%s' has no annotations.", dec_id);
452 ann_txt = (g_strv_length(keyval) == 2) ? keyval[1] : NULL;
453 if (ann_txt && *ann_txt) {
454 annlist = g_strsplit(ann_txt, ":", 0);
455 for (ann = annlist; *ann && **ann; ann++) {
457 g_debug("cli: Lookup decoder %s annotation %s.", dec_id, ann_id);
458 /* Lookup annotation class. */
460 for (l = dec->annotations; l; l = l->next, ann_class++) {
462 if (!canon_cmp(ann_descr[0], ann_id))
467 l_ann = g_hash_table_lookup(pd_ann_visible, dec_id);
468 l_ann = g_slist_append(l_ann, GINT_TO_POINTER(ann_class));
469 g_hash_table_replace(pd_ann_visible, g_strdup(dec_id), l_ann);
470 g_debug("cli: Showing protocol decoder %s annotation "
471 "class %d (%s).", dec_id, ann_class, ann_descr[0]);
474 /* Lookup annotation row. */
475 for (l = dec->annotation_rows; l; l = l->next) {
477 if (!canon_cmp(row_desc->id, ann_id))
481 g_debug("cli: Showing decoder %s annotation row %s (%s).",
482 dec_id, row_desc->id, row_desc->desc);
483 l_ann = g_hash_table_lookup(pd_ann_visible, dec_id);
484 for (l = row_desc->ann_classes; l; l = l->next) {
486 * This could just be:
487 * l_ann = g_slist_append(l_ann, l->data);
488 * But we are explicit for readability
489 * and to access details for diagnostics.
491 ann_class = GPOINTER_TO_INT(l->data);
492 l_ann = g_slist_append(l_ann, GINT_TO_POINTER(ann_class));
493 ann_diag = g_slist_nth_data(dec->annotations, ann_class);
494 g_debug("cli: Adding class %d/%s from row %s.",
495 ann_class, ann_diag[0], row_desc->id);
497 g_hash_table_replace(pd_ann_visible, g_strdup(dec_id), l_ann);
500 /* No match found. */
501 g_critical("Annotation '%s' not found "
502 "for protocol decoder '%s'.", ann_id, dec_id);
508 /* No class specified: show all of them. */
510 l_ann = g_slist_append(NULL, GINT_TO_POINTER(ann_class));
511 g_hash_table_insert(pd_ann_visible, g_strdup(dec_id), l_ann);
512 g_debug("cli: Showing all annotation classes for protocol "
513 "decoder %s.", dec_id);
522 int setup_pd_meta(char *opt_pd_meta)
524 struct srd_decoder *dec;
527 pd_meta_visible = g_hash_table_new_full(g_str_hash, g_int_equal,
529 pds = g_strsplit(opt_pd_meta, ",", 0);
530 for (pdtok = pds; *pdtok && **pdtok; pdtok++) {
531 if (!(dec = srd_decoder_get_by_id(*pdtok))) {
532 g_critical("Protocol decoder '%s' not found.", *pdtok);
535 g_debug("cli: Showing protocol decoder meta output from '%s'.", *pdtok);
536 g_hash_table_insert(pd_meta_visible, g_strdup(*pdtok), NULL);
543 int setup_pd_binary(char *opt_pd_binary)
546 struct srd_decoder *dec;
548 char **pds, **pdtok, **keyval, **bin_name;
550 pd_binary_visible = g_hash_table_new_full(g_str_hash, g_int_equal,
552 pds = g_strsplit(opt_pd_binary, ",", 0);
553 for (pdtok = pds; *pdtok && **pdtok; pdtok++) {
554 keyval = g_strsplit(*pdtok, "=", 0);
555 if (!(dec = srd_decoder_get_by_id(keyval[0]))) {
556 g_critical("Protocol decoder '%s' not found.", keyval[0]);
560 g_critical("Protocol decoder '%s' has no binary output.", keyval[0]);
564 if (g_strv_length(keyval) == 2) {
565 for (l = dec->binary; l; l = l->next, bin_class++) {
567 if (!strcmp(bin_name[0], keyval[1]))
572 g_critical("binary output '%s' not found "
573 "for protocol decoder '%s'.", keyval[1], keyval[0]);
576 g_debug("cli: Showing protocol decoder %s binary class "
577 "%d (%s).", keyval[0], bin_class, bin_name[0]);
579 /* No class specified: output all of them. */
581 g_debug("cli: Showing all binary classes for protocol "
582 "decoder %s.", keyval[0]);
584 g_hash_table_insert(pd_binary_visible, g_strdup(keyval[0]), GINT_TO_POINTER(bin_class));
593 * Balance JSON object and array parentheses, and separate array items.
594 * Somewhat convoluted API to re-use the routine for individual items as
595 * well as the surrounding array and object, including deferred start of
596 * the output and late flush (and to keep the state strictly local to the
597 * routine). Some additional complexity due to JSON's inability to handle
598 * a trailing comma at the last item. Code phrased such that text literals
599 * are kept in their order of appearance in the output (where possible).
601 static void jsontrace_open_close(gboolean is_close_req,
602 gboolean open_item, gboolean close_item)
604 static gboolean is_file_open;
605 static gboolean is_item_open;
607 if (is_close_req && is_item_open)
610 /* Automatic file header, and array item separation. */
613 printf("{\"traceEvents\": [\n");
616 is_item_open = FALSE;
624 /* Array item open/append/close. */
629 if (!open_item && !close_item && !is_close_req) {
635 is_item_open = FALSE;
638 /* Automatic file footer on shutdown. */
639 if (is_close_req && is_file_open) {
644 is_file_open = FALSE;
646 /* Flush at end of lines, or end of file. */
647 if (close_item || is_close_req)
651 /* Convert uint64 sample number to double timestamp in microseconds. */
652 static double jsontrace_ts_usec(uint64_t snum)
658 ts_usec /= pd_samplerate;
662 /* Emit two Google Trace Events (JSON) for one PD annotation (ss, es). */
663 static void jsontrace_annotation(struct srd_decoder *dec,
664 struct srd_proto_data_annotation *pda, struct srd_proto_data *pdata)
668 struct srd_decoder_annotation_row *row;
673 * Search for an annotation row for this index, or use the
674 * annotation's descriptor.
677 if (dec->annotation_rows) {
678 for (lrow = dec->annotation_rows; lrow; lrow = lrow->next) {
680 for (lcls = row->ann_classes; lcls; lcls = lcls->next) {
681 cls = GPOINTER_TO_INT(lcls->data);
682 if (cls == pda->ann_class) {
683 row_text = row->desc;
692 ann_descr = g_slist_nth_data(dec->annotations, pda->ann_class);
693 row_text = ann_descr[0];
697 * Emit two Google Trace Events for the start and end times.
698 * Set the 'pid' (process ID) to the decoder name to group a
699 * decoder's annotations. Set the 'tid' (thread ID) to the
700 * annotation row's description. The 'ts' (timestamp) is in
701 * microseconds. Set 'name' to the longest annotation text.
703 * BEWARE of the unfortunate JSON format limitation, which
704 * clutters data output calls with format helper calls.
705 * TODO Want to introduce a cJSON dependency to delegate the
706 * construction of output text?
708 jsontrace_open_close(FALSE, TRUE, FALSE);
709 printf("\"%s\": \"%s\"", "ph", "B");
710 jsontrace_open_close(FALSE, FALSE, FALSE);
711 printf("\"%s\": %lf", "ts", jsontrace_ts_usec(pdata->start_sample));
712 jsontrace_open_close(FALSE, FALSE, FALSE);
713 printf("\"%s\": \"%s\"", "pid", pdata->pdo->proto_id);
714 jsontrace_open_close(FALSE, FALSE, FALSE);
715 printf("\"%s\": \"%s\"", "tid", row_text);
716 jsontrace_open_close(FALSE, FALSE, FALSE);
717 printf("\"%s\": \"%s\"", "name", pda->ann_text[0]);
719 jsontrace_open_close(FALSE, TRUE, FALSE);
720 printf("\"%s\": \"%s\"", "ph", "E");
721 jsontrace_open_close(FALSE, FALSE, FALSE);
722 printf("\"%s\": %lf", "ts", jsontrace_ts_usec(pdata->end_sample));
723 jsontrace_open_close(FALSE, FALSE, FALSE);
724 printf("\"%s\": \"%s\"", "pid", pdata->pdo->proto_id);
725 jsontrace_open_close(FALSE, FALSE, FALSE);
726 printf("\"%s\": \"%s\"", "tid", row_text);
727 jsontrace_open_close(FALSE, FALSE, FALSE);
728 printf("\"%s\": \"%s\"", "name", pda->ann_text[0]);
730 jsontrace_open_close(FALSE, FALSE, TRUE);
733 void show_pd_annotations(struct srd_proto_data *pdata, void *cb_data)
735 struct srd_decoder *dec;
736 struct srd_proto_data_annotation *pda;
737 GSList *ann_list, *l;
740 gboolean show_ann, show_snum, show_class, show_quotes, show_abbrev;
748 if (!g_hash_table_lookup_extended(pd_ann_visible, pdata->pdo->di->decoder->id,
749 NULL, (void **)&ann_list)) {
750 /* Not in the list of PDs whose annotations we're showing. */
754 dec = pdata->pdo->di->decoder;
757 for (l = ann_list; l; l = l->next) {
758 if (GPOINTER_TO_INT(l->data) == -1
759 || GPOINTER_TO_INT(l->data) == pda->ann_class) {
767 /* Google Trace Events are rather special. Use a separate code path. */
768 if (opt_pd_jsontrace) {
769 jsontrace_annotation(dec, pda, pdata);
774 * Determine which fields of the annotation to display. Inspect
775 * user specified options as well as the verbosity of the log level:
776 * - Optionally show the sample numbers for the annotation's span.
777 * - Always show the protocol decoder ID.
778 * - Optionally show the annotation's class description.
779 * - Always show the longest annotation text.
780 * - Optionally show alternative annotation text (abbreviations
781 * for different zoom levels).
782 * - Optionally put quote marks around annotation text, when
783 * recipients might have to deal with a set of text variants.
785 show_snum = show_class = show_quotes = show_abbrev = FALSE;
786 if (opt_pd_samplenum || opt_loglevel > SR_LOG_WARN) {
789 if (opt_loglevel > SR_LOG_WARN) {
792 if (opt_loglevel > SR_LOG_INFO) {
796 if (opt_pd_ann_class)
800 * Display the annotation's fields after the layout was
804 printf("%" PRIu64 "-%" PRIu64 " ",
805 pdata->start_sample, pdata->end_sample);
807 printf("%s: ", pdata->pdo->proto_id);
809 ann_descr = g_slist_nth_data(dec->annotations, pda->ann_class);
810 printf("%s: ", ann_descr[0]);
812 quote = show_quotes ? "\"" : "";
813 printf("%s%s%s", quote, pda->ann_text[0], quote);
815 for (i = 1; pda->ann_text[i]; i++)
816 printf(" %s%s%s", quote, pda->ann_text[i], quote);
822 void show_pd_meta(struct srd_proto_data *pdata, void *cb_data)
826 if (!g_hash_table_lookup_extended(pd_meta_visible,
827 pdata->pdo->di->decoder->id, NULL, NULL))
828 /* Not in the list of PDs whose meta output we're showing. */
831 if (opt_pd_samplenum || opt_loglevel > SR_LOG_WARN)
832 printf("%"PRIu64"-%"PRIu64" ", pdata->start_sample, pdata->end_sample);
833 printf("%s: ", pdata->pdo->proto_id);
834 printf("%s: %s", pdata->pdo->meta_name, g_variant_print(pdata->data, FALSE));
839 void show_pd_binary(struct srd_proto_data *pdata, void *cb_data)
841 struct srd_proto_data_binary *pdb;
847 if (!g_hash_table_lookup_extended(pd_binary_visible,
848 pdata->pdo->di->decoder->id, NULL, (void **)&classp))
849 /* Not in the list of PDs whose meta output we're showing. */
852 classi = GPOINTER_TO_INT(classp);
854 if (classi != -1 && classi != pdb->bin_class)
855 /* Not showing this binary class. */
858 /* Just send the binary output to stdout, no embellishments. */
859 fwrite(pdb->data, pdb->size, 1, stdout);
863 void show_pd_prepare(void)
865 if (opt_pd_jsontrace)
866 jsontrace_open_close(TRUE, FALSE, FALSE);
869 void show_pd_close(void)
871 if (opt_pd_jsontrace)
872 jsontrace_open_close(TRUE, FALSE, FALSE);