2 * This file is part of the sigrok project.
4 * Copyright (C) 2012 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/>.
20 #include <sigrokdecode.h> /* First, so we avoid a _POSIX_C_SOURCE warning. */
28 #include <sys/types.h>
32 #include <glib/gstdio.h>
33 #include <libsigrok/libsigrok.h>
34 #include "sigrok-cli.h"
37 #define DEFAULT_OUTPUT_FORMAT "bits:width=64"
39 static struct sr_context *sr_ctx = NULL;
41 static uint64_t limit_samples = 0;
42 static uint64_t limit_frames = 0;
43 static struct sr_output_format *output_format = NULL;
44 static int default_output_format = FALSE;
45 static char *output_format_param = NULL;
46 static GHashTable *pd_ann_visible = NULL;
47 static struct sr_datastore *singleds = NULL;
49 static gboolean opt_version = FALSE;
50 static gint opt_loglevel = SR_LOG_WARN; /* Show errors+warnings per default. */
51 static gboolean opt_list_devs = FALSE;
52 static gboolean opt_wait_trigger = FALSE;
53 static gchar *opt_input_file = NULL;
54 static gchar *opt_output_file = NULL;
55 static gchar *opt_drv = NULL;
56 static gchar *opt_dev = NULL;
57 static gchar *opt_probes = NULL;
58 static gchar *opt_triggers = NULL;
59 static gchar *opt_pds = NULL;
60 static gchar *opt_pd_stack = NULL;
61 static gchar *opt_pd_annotations = NULL;
62 static gchar *opt_input_format = NULL;
63 static gchar *opt_output_format = NULL;
64 static gchar *opt_show = NULL;
65 static gchar *opt_time = NULL;
66 static gchar *opt_samples = NULL;
67 static gchar *opt_frames = NULL;
68 static gchar *opt_continuous = NULL;
70 static GOptionEntry optargs[] = {
71 {"version", 'V', 0, G_OPTION_ARG_NONE, &opt_version,
72 "Show version and support list", NULL},
73 {"loglevel", 'l', 0, G_OPTION_ARG_INT, &opt_loglevel,
74 "Set libsigrok/libsigrokdecode loglevel", NULL},
75 {"list-devices", 'D', 0, G_OPTION_ARG_NONE, &opt_list_devs,
76 "Scan for devices", NULL},
77 {"driver", 0, 0, G_OPTION_ARG_STRING, &opt_drv,
78 "Use only this driver", NULL},
79 {"device", 'd', 0, G_OPTION_ARG_STRING, &opt_dev,
80 "Use specified device", NULL},
81 {"input-file", 'i', 0, G_OPTION_ARG_FILENAME, &opt_input_file,
82 "Load input from file", NULL},
83 {"input-format", 'I', 0, G_OPTION_ARG_STRING, &opt_input_format,
84 "Input format", NULL},
85 {"output-file", 'o', 0, G_OPTION_ARG_FILENAME, &opt_output_file,
86 "Save output to file", NULL},
87 {"output-format", 'O', 0, G_OPTION_ARG_STRING, &opt_output_format,
88 "Output format", NULL},
89 {"probes", 'p', 0, G_OPTION_ARG_STRING, &opt_probes,
90 "Probes to use", NULL},
91 {"triggers", 't', 0, G_OPTION_ARG_STRING, &opt_triggers,
92 "Trigger configuration", NULL},
93 {"wait-trigger", 'w', 0, G_OPTION_ARG_NONE, &opt_wait_trigger,
94 "Wait for trigger", NULL},
95 {"protocol-decoders", 'a', 0, G_OPTION_ARG_STRING, &opt_pds,
96 "Protocol decoders to run", NULL},
97 {"protocol-decoder-stack", 's', 0, G_OPTION_ARG_STRING, &opt_pd_stack,
98 "Protocol decoder stack", NULL},
99 {"protocol-decoder-annotations", 'A', 0, G_OPTION_ARG_STRING, &opt_pd_annotations,
100 "Protocol decoder annotation(s) to show", NULL},
101 {"show", 0, 0, G_OPTION_ARG_NONE, &opt_show,
102 "Show device detail", NULL},
103 {"time", 0, 0, G_OPTION_ARG_STRING, &opt_time,
104 "How long to sample (ms)", NULL},
105 {"samples", 0, 0, G_OPTION_ARG_STRING, &opt_samples,
106 "Number of samples to acquire", NULL},
107 {"frames", 0, 0, G_OPTION_ARG_STRING, &opt_frames,
108 "Number of frames to acquire", NULL},
109 {"continuous", 0, 0, G_OPTION_ARG_NONE, &opt_continuous,
110 "Sample continuously", NULL},
111 {NULL, 0, 0, 0, NULL, NULL, NULL}
115 /* Convert driver options hash to GSList of struct sr_hwopt. */
116 static GSList *hash_to_hwopt(GHashTable *hash)
118 const struct sr_hwcap_option *hwo;
119 struct sr_hwopt *hwopt;
124 keys = g_hash_table_get_keys(hash);
126 for (gl = keys; gl; gl = gl->next) {
128 if (!(hwo = sr_drvopt_name_get(key))) {
129 g_critical("Unknown option %s", key);
132 hwopt = g_try_malloc(sizeof(struct sr_hwopt));
133 hwopt->hwopt = hwo->hwcap;
134 value = g_hash_table_lookup(hash, key);
135 hwopt->value = g_strdup(value);
136 opts = g_slist_append(opts, hwopt);
143 static void free_hwopt(struct sr_hwopt *hwopt)
145 g_free((void *)hwopt->value);
149 static GSList *device_scan(void)
151 struct sr_dev_driver **drivers, *driver;
153 GSList *drvopts, *devices, *tmpdevs, *l;
158 drvargs = parse_generic_arg(opt_drv, TRUE);
159 drvname = g_strdup(g_hash_table_lookup(drvargs, "sigrok_key"));
160 g_hash_table_remove(drvargs, "sigrok_key");
162 drivers = sr_driver_list();
163 for (i = 0; drivers[i]; i++) {
164 if (strcmp(drivers[i]->name, drvname))
169 g_critical("Driver %s not found.", drvname);
173 if (sr_driver_init(sr_ctx, driver) != SR_OK) {
174 g_critical("Failed to initialize driver.");
178 if (g_hash_table_size(drvargs) > 0)
179 if (!(drvopts = hash_to_hwopt(drvargs)))
180 /* Unknown options, already logged. */
182 devices = sr_driver_scan(driver, drvopts);
183 g_slist_free_full(drvopts, (GDestroyNotify)free_hwopt);
185 /* No driver specified, let them all scan on their own. */
187 drivers = sr_driver_list();
188 for (i = 0; drivers[i]; i++) {
190 if (sr_driver_init(sr_ctx, driver) != SR_OK) {
191 g_critical("Failed to initialize driver.");
194 tmpdevs = sr_driver_scan(driver, NULL);
195 for (l = tmpdevs; l; l = l->next)
196 devices = g_slist_append(devices, l->data);
197 g_slist_free(tmpdevs);
204 static void show_version(void)
207 struct sr_dev_driver **drivers;
208 struct sr_input_format **inputs;
209 struct sr_output_format **outputs;
210 struct srd_decoder *dec;
213 printf("sigrok-cli %s\n\n", VERSION);
215 printf("Using libsigrok %s (lib version %s).\n",
216 sr_package_version_string_get(), sr_lib_version_string_get());
217 printf("Using libsigrokdecode %s (lib version %s).\n\n",
218 srd_package_version_string_get(), srd_lib_version_string_get());
220 printf("Supported hardware drivers:\n");
221 drivers = sr_driver_list();
222 for (i = 0; drivers[i]; i++) {
223 printf(" %-20s %s\n", drivers[i]->name, drivers[i]->longname);
227 printf("Supported input formats:\n");
228 inputs = sr_input_list();
229 for (i = 0; inputs[i]; i++)
230 printf(" %-20s %s\n", inputs[i]->id, inputs[i]->description);
233 printf("Supported output formats:\n");
234 outputs = sr_output_list();
235 for (i = 0; outputs[i]; i++)
236 printf(" %-20s %s\n", outputs[i]->id, outputs[i]->description);
239 if (srd_init(NULL) == SRD_OK) {
240 printf("Supported protocol decoders:\n");
241 srd_decoder_load_all();
242 for (l = srd_decoder_list(); l; l = l->next) {
244 printf(" %-20s %s\n", dec->id, dec->longname);
245 /* Print protocol description upon "-l 3" or higher. */
246 if (opt_loglevel >= SR_LOG_INFO)
247 printf(" %-20s %s\n", "", dec->desc);
254 static void print_dev_line(const struct sr_dev_inst *sdi)
256 struct sr_probe *probe;
259 if (sdi->vendor && sdi->vendor[0])
260 printf("%s ", sdi->vendor);
261 if (sdi->model && sdi->model[0])
262 printf("%s ", sdi->model);
263 if (sdi->version && sdi->version[0])
264 printf("%s ", sdi->version);
266 if (g_slist_length(sdi->probes) == 1) {
267 probe = sdi->probes->data;
268 printf("with 1 probe: %s", probe->name);
270 printf("with %d probes:", g_slist_length(sdi->probes));
271 for (l = sdi->probes; l; l = l->next) {
273 printf(" %s", probe->name);
280 static void show_dev_list(void)
282 struct sr_dev_inst *sdi;
285 if (!(devices = device_scan()))
288 printf("The following devices were found:\n");
289 for (l = devices; l; l = l->next) {
293 g_slist_free(devices);
297 static void show_dev_detail(void)
299 struct sr_dev_inst *sdi;
300 const struct sr_hwcap_option *hwo;
301 const struct sr_samplerates *samplerates;
302 struct sr_rational *rationals;
305 const int *hwopts, *hwcaps;
306 int cap, num_devices, n, i;
308 const char *charopts, **stropts;
310 if (!(devices = device_scan())) {
311 g_critical("No devices found.");
315 num_devices = g_slist_length(devices);
316 if (num_devices > 1) {
318 g_critical("%d devices found. Use --list-devices to show them, "
319 "and --device to select one.", num_devices);
322 /* opt_dev is NULL if not specified, which is fine. */
323 n = strtol(opt_dev, NULL, 10);
324 if (n >= num_devices) {
325 g_critical("%d devices found, numbered starting from 0.",
329 sdi = g_slist_nth_data(devices, n);
331 sdi = g_slist_nth_data(devices, 0);
335 if (sr_info_get(sdi->driver, SR_DI_TRIGGER_TYPES, (const void **)&charopts,
336 sdi) == SR_OK && charopts) {
337 printf("Supported triggers: ");
339 printf("%c ", *charopts);
345 if ((sr_info_get(sdi->driver, SR_DI_HWOPTS, (const void **)&hwopts,
346 NULL) == SR_OK) && hwopts) {
347 printf("Supported driver options:\n");
348 for (i = 0; hwopts[i]; i++) {
349 if (!(hwo = sr_drvopt_get(hwopts[i])))
351 printf(" %s\n", hwo->shortname);
355 title = "Supported device options:\n";
356 if ((sr_info_get(sdi->driver, SR_DI_HWCAPS, (const void **)&hwcaps,
357 NULL) != SR_OK) || !hwcaps)
358 /* Driver supports no device instance options. */
361 for (cap = 0; hwcaps[cap]; cap++) {
362 if (!(hwo = sr_devopt_get(hwcaps[cap])))
370 if (hwo->hwcap == SR_HWCAP_PATTERN_MODE) {
371 /* Pattern generator modes */
372 printf(" %s", hwo->shortname);
373 if (sr_info_get(sdi->driver, SR_DI_PATTERNS,
374 (const void **)&stropts, sdi) == SR_OK) {
375 printf(" - supported patterns:\n");
376 for (i = 0; stropts[i]; i++)
377 printf(" %s\n", stropts[i]);
382 } else if (hwo->hwcap == SR_HWCAP_SAMPLERATE) {
383 /* Supported samplerates */
384 printf(" %s", hwo->shortname);
385 if (sr_info_get(sdi->driver, SR_DI_SAMPLERATES,
386 (const void **)&samplerates, sdi) != SR_OK) {
390 if (samplerates->step) {
392 if (!(s = sr_samplerate_string(samplerates->low)))
397 if (!(s = sr_samplerate_string(samplerates->high)))
402 if (!(s = sr_samplerate_string(samplerates->step)))
404 printf(" in steps of %s)\n", s);
407 printf(" - supported samplerates:\n");
408 for (i = 0; samplerates->list[i]; i++)
409 printf(" %s\n", sr_samplerate_string(samplerates->list[i]));
412 } else if (hwo->hwcap == SR_HWCAP_BUFFERSIZE) {
413 /* Supported buffer sizes */
414 printf(" %s", hwo->shortname);
415 if (sr_info_get(sdi->driver, SR_DI_BUFFERSIZES,
416 (const void **)&integers, sdi) != SR_OK) {
420 printf(" - supported buffer sizes:\n");
421 for (i = 0; integers[i]; i++)
422 printf(" %"PRIu64"\n", integers[i]);
424 } else if (hwo->hwcap == SR_HWCAP_TIMEBASE) {
425 /* Supported time bases */
426 printf(" %s", hwo->shortname);
427 if (sr_info_get(sdi->driver, SR_DI_TIMEBASES,
428 (const void **)&rationals, sdi) != SR_OK) {
432 printf(" - supported time bases:\n");
433 for (i = 0; rationals[i].p && rationals[i].q; i++)
434 printf(" %s\n", sr_period_string(
435 rationals[i].p * rationals[i].q));
437 } else if (hwo->hwcap == SR_HWCAP_TRIGGER_SOURCE) {
438 /* Supported trigger sources */
439 printf(" %s", hwo->shortname);
440 if (sr_info_get(sdi->driver, SR_DI_TRIGGER_SOURCES,
441 (const void **)&stropts, sdi) != SR_OK) {
445 printf(" - supported trigger sources:\n");
446 for (i = 0; stropts[i]; i++)
447 printf(" %s\n", stropts[i]);
449 } else if (hwo->hwcap == SR_HWCAP_FILTER) {
450 /* Supported filters */
451 printf(" %s", hwo->shortname);
452 if (sr_info_get(sdi->driver, SR_DI_FILTERS,
453 (const void **)&stropts, sdi) != SR_OK) {
457 printf(" - supported filter targets:\n");
458 for (i = 0; stropts[i]; i++)
459 printf(" %s\n", stropts[i]);
461 } else if (hwo->hwcap == SR_HWCAP_VDIV) {
462 /* Supported volts/div values */
463 printf(" %s", hwo->shortname);
464 if (sr_info_get(sdi->driver, SR_DI_VDIVS,
465 (const void **)&rationals, sdi) != SR_OK) {
469 printf(" - supported volts/div:\n");
470 for (i = 0; rationals[i].p && rationals[i].q; i++)
471 printf(" %s\n", sr_voltage_string( &rationals[i]));
473 } else if (hwo->hwcap == SR_HWCAP_COUPLING) {
474 /* Supported coupling settings */
475 printf(" %s", hwo->shortname);
476 if (sr_info_get(sdi->driver, SR_DI_COUPLING,
477 (const void **)&stropts, sdi) != SR_OK) {
481 printf(" - supported coupling options:\n");
482 for (i = 0; stropts[i]; i++)
483 printf(" %s\n", stropts[i]);
486 /* Everything else */
487 printf(" %s\n", hwo->shortname);
493 static void show_pd_detail(void)
496 struct srd_decoder *dec;
497 char **pdtokens, **pdtok, **ann, *doc;
500 pdtokens = g_strsplit(opt_pds, ",", -1);
501 for (pdtok = pdtokens; *pdtok; pdtok++) {
502 if (!(dec = srd_decoder_get_by_id(*pdtok))) {
503 g_critical("Protocol decoder %s not found.", *pdtok);
506 printf("ID: %s\nName: %s\nLong name: %s\nDescription: %s\n",
507 dec->id, dec->name, dec->longname, dec->desc);
508 printf("License: %s\n", dec->license);
509 printf("Annotations:\n");
510 if (dec->annotations) {
511 for (l = dec->annotations; l; l = l->next) {
513 printf("- %s\n %s\n", ann[0], ann[1]);
518 /* TODO: Print supported decoder options. */
519 printf("Required probes:\n");
521 for (l = dec->probes; l; l = l->next) {
523 printf("- %s (%s): %s\n",
524 p->name, p->id, p->desc);
529 printf("Optional probes:\n");
530 if (dec->opt_probes) {
531 for (l = dec->opt_probes; l; l = l->next) {
533 printf("- %s (%s): %s\n",
534 p->name, p->id, p->desc);
539 if ((doc = srd_decoder_doc_get(dec))) {
540 printf("Documentation:\n%s\n",
541 doc[0] == '\n' ? doc + 1 : doc);
546 g_strfreev(pdtokens);
549 static void datafeed_in(const struct sr_dev_inst *sdi,
550 const struct sr_datafeed_packet *packet)
552 static struct sr_output *o = NULL;
553 static int logic_probelist[SR_MAX_NUM_PROBES] = { -1 };
554 static uint64_t received_samples = 0;
555 static int unitsize = 0;
556 static int triggered = 0;
557 static FILE *outfile = NULL;
558 struct sr_probe *probe;
559 const struct sr_datafeed_logic *logic;
560 const struct sr_datafeed_meta_logic *meta_logic;
561 const struct sr_datafeed_analog *analog;
562 int num_enabled_probes, sample_size, ret, i;
563 uint64_t output_len, filter_out_len;
564 uint8_t *output_buf, *filter_out;
567 /* If the first packet to come in isn't a header, don't even try. */
568 if (packet->type != SR_DF_HEADER && o == NULL)
572 switch (packet->type) {
574 g_debug("cli: Received SR_DF_HEADER");
575 /* Initialize the output module. */
576 if (!(o = g_try_malloc(sizeof(struct sr_output)))) {
577 g_critical("Output module malloc failed.");
580 o->format = output_format;
581 o->sdi = (struct sr_dev_inst *)sdi;
582 o->param = output_format_param;
583 if (o->format->init) {
584 if (o->format->init(o) != SR_OK) {
585 g_critical("Output format initialization failed.");
592 g_debug("cli: Received SR_DF_END");
594 g_debug("cli: double end!");
597 if (o->format->event) {
598 o->format->event(o, SR_DF_END, &output_buf, &output_len);
601 fwrite(output_buf, 1, output_len, outfile);
606 if (limit_samples && received_samples < limit_samples)
607 g_warning("Device only sent %" PRIu64 " samples.",
610 g_warning("Device stopped after %" PRIu64 " samples.",
612 if (outfile && outfile != stdout)
615 if (o->format->cleanup)
616 o->format->cleanup(o);
622 g_debug("cli: received SR_DF_TRIGGER");
623 if (o->format->event)
624 o->format->event(o, SR_DF_TRIGGER, &output_buf,
629 case SR_DF_META_LOGIC:
630 g_message("cli: Received SR_DF_META_LOGIC");
631 meta_logic = packet->payload;
632 num_enabled_probes = 0;
633 for (i = 0; i < meta_logic->num_probes; i++) {
634 probe = g_slist_nth_data(sdi->probes, i);
636 logic_probelist[num_enabled_probes++] = probe->index;
638 logic_probelist[num_enabled_probes] = -1;
639 /* How many bytes we need to store num_enabled_probes bits */
640 unitsize = (num_enabled_probes + 7) / 8;
643 if (opt_output_file) {
644 if (default_output_format) {
645 /* output file is in session format, which means we'll
646 * dump everything in the datastore as it comes in,
647 * and save from there after the session. */
649 ret = sr_datastore_new(unitsize, &singleds);
651 g_critical("Failed to create datastore.");
655 /* saving to a file in whatever format was set
656 * with --format, so all we need is a filehandle */
657 outfile = g_fopen(opt_output_file, "wb");
661 srd_session_start(num_enabled_probes, unitsize,
662 meta_logic->samplerate);
666 logic = packet->payload;
667 g_message("cli: received SR_DF_LOGIC, %"PRIu64" bytes", logic->length);
668 sample_size = logic->unitsize;
669 if (logic->length == 0)
672 /* Don't store any samples until triggered. */
673 if (opt_wait_trigger && !triggered)
676 if (limit_samples && received_samples >= limit_samples)
679 ret = sr_filter_probes(sample_size, unitsize, logic_probelist,
680 logic->data, logic->length,
681 &filter_out, &filter_out_len);
685 /* what comes out of the filter is guaranteed to be packed into the
686 * minimum size needed to support the number of samples at this sample
687 * size. however, the driver may have submitted too much -- cut off
688 * the buffer of the last packet according to the sample limit.
690 if (limit_samples && (received_samples + logic->length / sample_size >
691 limit_samples * sample_size))
692 filter_out_len = limit_samples * sample_size - received_samples;
695 sr_datastore_put(singleds, filter_out,
696 filter_out_len, sample_size, logic_probelist);
698 if (opt_output_file && default_output_format)
699 /* saving to a session file, don't need to do anything else
700 * to this data for now. */
704 if (srd_session_send(received_samples, (uint8_t*)filter_out,
705 filter_out_len) != SRD_OK)
709 if (o->format->data && packet->type == o->format->df_type)
710 o->format->data(o, filter_out, filter_out_len, &output_buf, &output_len);
712 fwrite(output_buf, 1, output_len, outfile);
720 received_samples += logic->length / sample_size;
723 case SR_DF_META_ANALOG:
724 g_message("cli: Received SR_DF_META_ANALOG");
727 if (opt_output_file) {
728 if (default_output_format) {
729 /* output file is in session format, which means we'll
730 * dump everything in the datastore as it comes in,
731 * and save from there after the session. */
733 ret = sr_datastore_new(unitsize, &singleds);
735 g_critical("Failed to create datastore.");
739 /* saving to a file in whatever format was set
740 * with --format, so all we need is a filehandle */
741 outfile = g_fopen(opt_output_file, "wb");
747 analog = packet->payload;
748 g_message("cli: received SR_DF_ANALOG, %d samples", analog->num_samples);
749 if (analog->num_samples == 0)
752 if (limit_samples && received_samples >= limit_samples)
755 if (o->format->data && packet->type == o->format->df_type) {
756 o->format->data(o, (const uint8_t *)analog->data,
757 analog->num_samples * sizeof(float),
758 &output_buf, &output_len);
760 fwrite(output_buf, 1, output_len, outfile);
766 received_samples += analog->num_samples;
769 case SR_DF_FRAME_BEGIN:
770 g_debug("cli: received SR_DF_FRAME_BEGIN");
771 if (o->format->event) {
772 o->format->event(o, SR_DF_FRAME_BEGIN, &output_buf,
775 fwrite(output_buf, 1, output_len, outfile);
782 case SR_DF_FRAME_END:
783 g_debug("cli: received SR_DF_FRAME_END");
784 if (o->format->event) {
785 o->format->event(o, SR_DF_FRAME_END, &output_buf,
788 fwrite(output_buf, 1, output_len, outfile);
796 g_message("received unknown packet type %d", packet->type);
799 if (o && o->format->recv) {
800 out = o->format->recv(o, sdi, packet);
801 if (out && out->len) {
802 fwrite(out->str, 1, out->len, outfile);
809 /* Register the given PDs for this session.
810 * Accepts a string of the form: "spi:sck=3:sdata=4,spi:sck=3:sdata=5"
811 * That will instantiate two SPI decoders on the clock but different data
814 static int register_pds(struct sr_dev *dev, const char *pdstring)
816 GHashTable *pd_opthash;
817 struct srd_decoder_inst *di;
819 char **pdtokens, **pdtok, *pd_name;
824 pd_ann_visible = g_hash_table_new_full(g_str_hash, g_int_equal,
828 pdtokens = g_strsplit(pdstring, ",", 0);
829 for (pdtok = pdtokens; *pdtok; pdtok++) {
830 if (!(pd_opthash = parse_generic_arg(*pdtok, TRUE))) {
831 g_critical("Invalid protocol decoder option '%s'.", *pdtok);
835 pd_name = g_strdup(g_hash_table_lookup(pd_opthash, "sigrok_key"));
836 g_hash_table_remove(pd_opthash, "sigrok_key");
837 if (srd_decoder_load(pd_name) != SRD_OK) {
838 g_critical("Failed to load protocol decoder %s.", pd_name);
842 if (!(di = srd_inst_new(pd_name, pd_opthash))) {
843 g_critical("Failed to instantiate protocol decoder %s.", pd_name);
848 /* If no annotation list was specified, add them all in now.
849 * This will be pared down later to leave only the last PD
852 if (!opt_pd_annotations)
853 g_hash_table_insert(pd_ann_visible,
854 g_strdup(di->inst_id), NULL);
856 /* Any keys left in the options hash are probes, where the key
857 * is the probe name as specified in the decoder class, and the
858 * value is the probe number i.e. the order in which the PD's
859 * incoming samples are arranged. */
860 if (srd_inst_probe_set_all(di, pd_opthash) != SRD_OK) {
864 g_hash_table_destroy(pd_opthash);
869 g_strfreev(pdtokens);
871 g_hash_table_destroy(pd_opthash);
878 int setup_pd_stack(void)
880 struct srd_decoder_inst *di_from, *di_to;
884 /* Set up the protocol decoder stack. */
885 pds = g_strsplit(opt_pds, ",", 0);
886 if (g_strv_length(pds) > 1) {
888 /* A stack setup was specified, use that. */
890 pds = g_strsplit(opt_pd_stack, ",", 0);
891 if (g_strv_length(pds) < 2) {
893 g_critical("Specify at least two protocol decoders to stack.");
898 /* First PD goes at the bottom of the stack. */
899 ids = g_strsplit(pds[0], ":", 0);
900 if (!(di_from = srd_inst_find_by_id(ids[0]))) {
902 g_critical("Cannot stack protocol decoder '%s': "
903 "instance not found.", pds[0]);
908 /* Every subsequent PD goes on top. */
909 for (i = 1; pds[i]; i++) {
910 ids = g_strsplit(pds[i], ":", 0);
911 if (!(di_to = srd_inst_find_by_id(ids[0]))) {
913 g_critical("Cannot stack protocol decoder '%s': "
914 "instance not found.", pds[i]);
918 if ((ret = srd_inst_stack(di_from, di_to)) != SRD_OK)
921 /* Don't show annotation from this PD. Only the last PD in
922 * the stack will be left on the annotation list (unless
923 * the annotation list was specifically provided).
925 if (!opt_pd_annotations)
926 g_hash_table_remove(pd_ann_visible,
937 int setup_pd_annotations(void)
940 struct srd_decoder *dec;
942 char **pds, **pdtok, **keyval, **ann_descr;
944 /* Set up custom list of PDs and annotations to show. */
945 if (opt_pd_annotations) {
946 pds = g_strsplit(opt_pd_annotations, ",", 0);
947 for (pdtok = pds; *pdtok && **pdtok; pdtok++) {
949 keyval = g_strsplit(*pdtok, "=", 0);
950 if (!(dec = srd_decoder_get_by_id(keyval[0]))) {
951 g_critical("Protocol decoder '%s' not found.", keyval[0]);
954 if (!dec->annotations) {
955 g_critical("Protocol decoder '%s' has no annotations.", keyval[0]);
958 if (g_strv_length(keyval) == 2) {
959 for (l = dec->annotations; l; l = l->next, ann++) {
961 if (!canon_cmp(ann_descr[0], keyval[1]))
966 g_critical("Annotation '%s' not found "
967 "for protocol decoder '%s'.", keyval[1], keyval[0]);
971 g_debug("cli: showing protocol decoder annotation %d from '%s'", ann, keyval[0]);
972 g_hash_table_insert(pd_ann_visible, g_strdup(keyval[0]), GINT_TO_POINTER(ann));
981 int setup_output_format(void)
986 struct sr_output_format **outputs;
990 if (!opt_output_format) {
991 opt_output_format = DEFAULT_OUTPUT_FORMAT;
992 /* we'll need to remember this so when saving to a file
993 * later, sigrok session format will be used.
995 default_output_format = TRUE;
998 fmtargs = parse_generic_arg(opt_output_format, TRUE);
999 fmtspec = g_hash_table_lookup(fmtargs, "sigrok_key");
1001 g_critical("Invalid output format.");
1004 outputs = sr_output_list();
1005 for (i = 0; outputs[i]; i++) {
1006 if (strcmp(outputs[i]->id, fmtspec))
1008 g_hash_table_remove(fmtargs, "sigrok_key");
1009 output_format = outputs[i];
1010 g_hash_table_iter_init(&iter, fmtargs);
1011 while (g_hash_table_iter_next(&iter, &key, &value)) {
1012 /* only supporting one parameter per output module
1013 * for now, and only its value */
1014 output_format_param = g_strdup(value);
1019 if (!output_format) {
1020 g_critical("Invalid output format %s.", opt_output_format);
1023 g_hash_table_destroy(fmtargs);
1028 void show_pd_annotations(struct srd_proto_data *pdata, void *cb_data)
1032 gpointer ann_format;
1034 /* 'cb_data' is not used in this specific callback. */
1037 if (!pd_ann_visible)
1040 if (!g_hash_table_lookup_extended(pd_ann_visible, pdata->pdo->di->inst_id,
1042 /* Not in the list of PDs whose annotations we're showing. */
1045 if (pdata->ann_format != GPOINTER_TO_INT(ann_format))
1046 /* We don't want this particular format from the PD. */
1049 annotations = pdata->data;
1050 if (opt_loglevel > SR_LOG_WARN)
1051 printf("%"PRIu64"-%"PRIu64" ", pdata->start_sample, pdata->end_sample);
1052 printf("%s: ", pdata->pdo->proto_id);
1053 for (i = 0; annotations[i]; i++)
1054 printf("\"%s\" ", annotations[i]);
1059 static int select_probes(struct sr_dev_inst *sdi)
1061 struct sr_probe *probe;
1062 GSList *selected_probes, *l;
1067 if (!(selected_probes = parse_probestring(sdi, opt_probes)))
1070 for (l = sdi->probes; l; l = l->next) {
1072 if (g_slist_find(selected_probes, probe))
1073 probe->enabled = TRUE;
1075 probe->enabled = FALSE;
1077 g_slist_free(selected_probes);
1083 * Return the input file format which the CLI tool should use.
1085 * If the user specified -I / --input-format, use that one. Otherwise, try to
1086 * autodetect the format as good as possible. Failing that, return NULL.
1088 * @param filename The filename of the input file. Must not be NULL.
1089 * @param opt The -I / --input-file option the user specified (or NULL).
1091 * @return A pointer to the 'struct sr_input_format' that should be used,
1092 * or NULL if no input format was selected or auto-detected.
1094 static struct sr_input_format *determine_input_file_format(
1095 const char *filename, const char *opt)
1098 struct sr_input_format **inputs;
1100 /* If there are no input formats, return NULL right away. */
1101 inputs = sr_input_list();
1103 g_critical("No supported input formats available.");
1107 /* If the user specified -I / --input-format, use that one. */
1109 for (i = 0; inputs[i]; i++) {
1110 if (strcasecmp(inputs[i]->id, opt))
1112 g_debug("Using user-specified input file format '%s'.",
1117 /* The user specified an unknown input format, return NULL. */
1118 g_critical("Error: specified input file format '%s' is "
1123 /* Otherwise, try to find an input module that can handle this file. */
1124 for (i = 0; inputs[i]; i++) {
1125 if (inputs[i]->format_match(filename))
1129 /* Return NULL if no input module wanted to touch this. */
1131 g_critical("Error: no matching input module found.");
1135 g_debug("cli: Autodetected '%s' input format for file '%s'.",
1136 inputs[i]->id, filename);
1141 static void load_input_file_format(void)
1143 GHashTable *fmtargs = NULL;
1145 struct sr_input *in;
1146 struct sr_input_format *input_format;
1147 char *fmtspec = NULL;
1149 if (opt_input_format) {
1150 fmtargs = parse_generic_arg(opt_input_format, TRUE);
1151 fmtspec = g_hash_table_lookup(fmtargs, "sigrok_key");
1154 if (!(input_format = determine_input_file_format(opt_input_file,
1156 /* The exact cause was already logged. */
1161 g_hash_table_remove(fmtargs, "sigrok_key");
1163 if (stat(opt_input_file, &st) == -1) {
1164 g_critical("Failed to load %s: %s", opt_input_file,
1169 /* Initialize the input module. */
1170 if (!(in = g_try_malloc(sizeof(struct sr_input)))) {
1171 g_critical("Failed to allocate input module.");
1174 in->format = input_format;
1175 in->param = fmtargs;
1176 if (in->format->init) {
1177 if (in->format->init(in) != SR_OK) {
1178 g_critical("Input format init failed.");
1183 if (select_probes(in->sdi) > 0)
1187 sr_session_datafeed_callback_add(datafeed_in);
1188 if (sr_session_dev_add(in->sdi) != SR_OK) {
1189 g_critical("Failed to use device.");
1190 sr_session_destroy();
1194 input_format->loadfile(in, opt_input_file);
1195 if (opt_output_file && default_output_format) {
1196 if (sr_session_save(opt_output_file, in->sdi, singleds) != SR_OK)
1197 g_critical("Failed to save session.");
1199 sr_session_destroy();
1202 g_hash_table_destroy(fmtargs);
1205 static void load_input_file(void)
1208 if (sr_session_load(opt_input_file) == SR_OK) {
1209 /* sigrok session file */
1210 sr_session_datafeed_callback_add(datafeed_in);
1216 /* fall back on input modules */
1217 load_input_file_format();
1221 static int set_dev_options(struct sr_dev_inst *sdi, GHashTable *args)
1223 const struct sr_hwcap_option *hwo;
1224 GHashTableIter iter;
1225 gpointer key, value;
1229 struct sr_rational tmp_rat;
1233 g_hash_table_iter_init(&iter, args);
1234 while (g_hash_table_iter_next(&iter, &key, &value)) {
1235 if (!(hwo = sr_devopt_name_get(key))) {
1236 g_critical("Unknown device option '%s'.", (char *) key);
1240 if ((value == NULL) &&
1241 (hwo->type != SR_T_BOOL)) {
1242 g_critical("Option '%s' needs a value.", (char *)key);
1246 switch (hwo->type) {
1248 ret = sr_parse_sizestring(value, &tmp_u64);
1260 tmp_bool = sr_parse_boolstring(value);
1264 tmp_float = strtof(value, NULL);
1267 case SR_T_RATIONAL_PERIOD:
1268 if ((ret = sr_parse_period(value, &tmp_rat)) != SR_OK)
1272 case SR_T_RATIONAL_VOLT:
1273 if ((ret = sr_parse_voltage(value, &tmp_rat)) != SR_OK)
1281 ret = sr_dev_config_set(sdi, hwo->hwcap, val);
1283 g_critical("Failed to set device option '%s'.", (char *)key);
1291 static int set_limit_time(const struct sr_dev_inst *sdi)
1294 uint64_t *samplerate;
1296 time_msec = sr_parse_timestring(opt_time);
1297 if (time_msec == 0) {
1298 g_critical("Invalid time '%s'", opt_time);
1299 sr_session_destroy();
1303 if (sr_driver_hwcap_exists(sdi->driver, SR_HWCAP_LIMIT_MSEC)) {
1304 if (sr_dev_config_set(sdi, SR_HWCAP_LIMIT_MSEC, &time_msec) != SR_OK) {
1305 g_critical("Failed to configure time limit.");
1306 sr_session_destroy();
1311 /* time limit set, but device doesn't support this...
1312 * convert to samples based on the samplerate.
1315 if (sr_dev_has_hwcap(sdi, SR_HWCAP_SAMPLERATE)) {
1316 sr_info_get(sdi->driver, SR_DI_CUR_SAMPLERATE,
1317 (const void **)&samplerate, sdi);
1318 limit_samples = (*samplerate) * time_msec / (uint64_t)1000;
1320 if (limit_samples == 0) {
1321 g_critical("Not enough time at this samplerate.");
1322 sr_session_destroy();
1326 if (sr_dev_config_set(sdi, SR_HWCAP_LIMIT_SAMPLES,
1327 &limit_samples) != SR_OK) {
1328 g_critical("Failed to configure time-based sample limit.");
1329 sr_session_destroy();
1337 static void run_session(void)
1340 GHashTable *devargs;
1341 struct sr_dev_inst *sdi;
1345 devices = device_scan();
1347 g_critical("No devices found.");
1350 if (g_slist_length(devices) > 1) {
1351 g_critical("sigrok-cli only supports one device for capturing.");
1354 sdi = devices->data;
1357 sr_session_datafeed_callback_add(datafeed_in);
1359 if (sr_session_dev_add(sdi) != SR_OK) {
1360 g_critical("Failed to use device.");
1361 sr_session_destroy();
1366 if ((devargs = parse_generic_arg(opt_dev, FALSE))) {
1367 if (set_dev_options(sdi, devargs) != SR_OK)
1369 g_hash_table_destroy(devargs);
1373 if (select_probes(sdi) != SR_OK) {
1374 g_critical("Failed to set probes.");
1375 sr_session_destroy();
1380 if (!(triggerlist = sr_parse_triggerstring(sdi, opt_triggers))) {
1381 sr_session_destroy();
1384 max_probes = g_slist_length(sdi->probes);
1385 for (i = 0; i < max_probes; i++) {
1386 if (triggerlist[i]) {
1387 sr_dev_trigger_set(sdi, i, triggerlist[i]);
1388 g_free(triggerlist[i]);
1391 g_free(triggerlist);
1394 if (opt_continuous) {
1395 if (!sr_driver_hwcap_exists(sdi->driver, SR_HWCAP_CONTINUOUS)) {
1396 g_critical("This device does not support continuous sampling.");
1397 sr_session_destroy();
1403 if (set_limit_time(sdi) != SR_OK) {
1404 sr_session_destroy();
1410 if ((sr_parse_sizestring(opt_samples, &limit_samples) != SR_OK)
1411 || (sr_dev_config_set(sdi, SR_HWCAP_LIMIT_SAMPLES,
1412 &limit_samples) != SR_OK)) {
1413 g_critical("Failed to configure sample limit.");
1414 sr_session_destroy();
1420 if ((sr_parse_sizestring(opt_frames, &limit_frames) != SR_OK)
1421 || (sr_dev_config_set(sdi, SR_HWCAP_LIMIT_FRAMES,
1422 &limit_frames) != SR_OK)) {
1423 g_critical("Failed to configure frame limit.");
1424 sr_session_destroy();
1429 if (sr_session_start() != SR_OK) {
1430 g_critical("Failed to start session.");
1431 sr_session_destroy();
1443 if (opt_output_file && default_output_format) {
1444 if (sr_session_save(opt_output_file, sdi, singleds) != SR_OK)
1445 g_critical("Failed to save session.");
1447 sr_session_destroy();
1448 g_slist_free(devices);
1452 static void logger(const gchar *log_domain, GLogLevelFlags log_level,
1453 const gchar *message, gpointer cb_data)
1459 * All messages, warnings, errors etc. go to stderr (not stdout) in
1460 * order to not mess up the CLI tool data output, e.g. VCD output.
1462 if (log_level & (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING)
1463 || opt_loglevel > SR_LOG_WARN) {
1464 fprintf(stderr, "%s\n", message);
1469 int main(int argc, char **argv)
1472 GOptionContext *context;
1475 g_log_set_default_handler(logger, NULL);
1478 context = g_option_context_new(NULL);
1479 g_option_context_add_main_entries(context, optargs, NULL);
1481 if (!g_option_context_parse(context, &argc, &argv, &error)) {
1482 g_critical("%s", error->message);
1486 /* Set the loglevel (amount of messages to output) for libsigrok. */
1487 if (sr_log_loglevel_set(opt_loglevel) != SR_OK)
1490 /* Set the loglevel (amount of messages to output) for libsigrokdecode. */
1491 if (srd_log_loglevel_set(opt_loglevel) != SRD_OK)
1494 if (sr_init(&sr_ctx) != SR_OK)
1498 if (srd_init(NULL) != SRD_OK)
1500 if (register_pds(NULL, opt_pds) != 0)
1502 if (srd_pd_output_callback_add(SRD_OUTPUT_ANN,
1503 show_pd_annotations, NULL) != SRD_OK)
1505 if (setup_pd_stack() != 0)
1507 if (setup_pd_annotations() != 0)
1511 if (setup_output_format() != 0)
1516 else if (opt_list_devs)
1518 else if (opt_pds && opt_show)
1522 else if (opt_input_file)
1524 else if (opt_samples || opt_time || opt_frames || opt_continuous)
1527 printf("%s", g_option_context_get_help(context, TRUE, NULL));
1538 g_option_context_free(context);