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 extern struct sr_hwcap_option sr_drvopts[];
40 extern struct sr_hwcap_option sr_hwcap_options[];
42 static uint64_t limit_samples = 0;
43 static uint64_t limit_frames = 0;
44 static struct sr_output_format *output_format = NULL;
45 static int default_output_format = FALSE;
46 static char *output_format_param = NULL;
47 static GHashTable *pd_ann_visible = 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_time = NULL;
65 static gchar *opt_samples = NULL;
66 static gchar *opt_frames = NULL;
67 static gchar *opt_continuous = NULL;
69 static GOptionEntry optargs[] = {
70 {"version", 'V', 0, G_OPTION_ARG_NONE, &opt_version,
71 "Show version and support list", NULL},
72 {"loglevel", 'l', 0, G_OPTION_ARG_INT, &opt_loglevel,
73 "Set libsigrok/libsigrokdecode loglevel", NULL},
74 {"list-devices", 'D', 0, G_OPTION_ARG_NONE, &opt_list_devs,
75 "Scan for devices", NULL},
76 {"driver", 0, 0, G_OPTION_ARG_STRING, &opt_drv,
77 "Use only this driver", NULL},
78 {"device", 'd', 0, G_OPTION_ARG_STRING, &opt_dev,
79 "Use specified device", NULL},
80 {"input-file", 'i', 0, G_OPTION_ARG_FILENAME, &opt_input_file,
81 "Load input from file", NULL},
82 {"input-format", 'I', 0, G_OPTION_ARG_STRING, &opt_input_format,
83 "Input format", NULL},
84 {"output-file", 'o', 0, G_OPTION_ARG_FILENAME, &opt_output_file,
85 "Save output to file", NULL},
86 {"output-format", 'O', 0, G_OPTION_ARG_STRING, &opt_output_format,
87 "Output format", NULL},
88 {"probes", 'p', 0, G_OPTION_ARG_STRING, &opt_probes,
89 "Probes to use", NULL},
90 {"triggers", 't', 0, G_OPTION_ARG_STRING, &opt_triggers,
91 "Trigger configuration", NULL},
92 {"wait-trigger", 'w', 0, G_OPTION_ARG_NONE, &opt_wait_trigger,
93 "Wait for trigger", NULL},
94 {"protocol-decoders", 'a', 0, G_OPTION_ARG_STRING, &opt_pds,
95 "Protocol decoders to run", NULL},
96 {"protocol-decoder-stack", 's', 0, G_OPTION_ARG_STRING, &opt_pd_stack,
97 "Protocol decoder stack", NULL},
98 {"protocol-decoder-annotations", 'A', 0, G_OPTION_ARG_STRING, &opt_pd_annotations,
99 "Protocol decoder annotation(s) to show", NULL},
100 {"time", 0, 0, G_OPTION_ARG_STRING, &opt_time,
101 "How long to sample (ms)", NULL},
102 {"samples", 0, 0, G_OPTION_ARG_STRING, &opt_samples,
103 "Number of samples to acquire", NULL},
104 {"frames", 0, 0, G_OPTION_ARG_STRING, &opt_frames,
105 "Number of frames to acquire", NULL},
106 {"continuous", 0, 0, G_OPTION_ARG_NONE, &opt_continuous,
107 "Sample continuously", NULL},
108 {NULL, 0, 0, 0, NULL, NULL, NULL}
112 /* Convert driver options hash to GSList of struct sr_hwopt. */
113 static GSList *hash_to_hwopt(GHashTable *hash)
115 struct sr_hwcap_option *ho;
116 struct sr_hwopt *hwopt;
121 keys = g_hash_table_get_keys(hash);
123 for (gl = keys; gl; gl = gl->next) {
125 for (ho = sr_drvopts; ho->shortname; ho++) {
126 if (!strcmp(key, ho->shortname)) {
127 hwopt = g_try_malloc(sizeof(struct sr_hwopt));
128 hwopt->hwopt = ho->hwcap;
129 value = g_hash_table_lookup(hash, key);
130 hwopt->value = g_strdup(value);
131 opts = g_slist_append(opts, hwopt);
135 if (!ho->shortname) {
136 g_critical("Unknown option %s", key);
145 static GSList *device_scan(void)
147 struct sr_dev_driver **drivers, *driver;
149 GSList *drvopts, *devices, *tmpdevs, *l;
154 drvargs = parse_generic_arg(opt_drv, TRUE);
155 drvname = g_strdup(g_hash_table_lookup(drvargs, "sigrok_key"));
156 g_hash_table_remove(drvargs, "sigrok_key");
158 drivers = sr_driver_list();
159 for (i = 0; drivers[i]; i++) {
160 if (strcmp(drivers[i]->name, drvname))
165 g_critical("Driver %s not found.", drvname);
169 if (sr_driver_init(driver) != SR_OK) {
170 g_critical("Failed to initialize driver.");
174 if (g_hash_table_size(drvargs) > 0)
175 if (!(drvopts = hash_to_hwopt(drvargs)))
176 /* Unknown options, already logged. */
178 devices = sr_driver_scan(driver, drvopts);
180 /* No driver specified, let them all scan on their own. */
182 drivers = sr_driver_list();
183 for (i = 0; drivers[i]; i++) {
185 if (sr_driver_init(driver) != SR_OK) {
186 g_critical("Failed to initialize driver.");
189 tmpdevs = sr_driver_scan(driver, NULL);
190 for (l = tmpdevs; l; l = l->next)
191 devices = g_slist_append(devices, l->data);
192 g_slist_free(tmpdevs);
199 static void show_version(void)
202 struct sr_dev_driver **drivers;
203 struct sr_input_format **inputs;
204 struct sr_output_format **outputs;
205 struct srd_decoder *dec;
208 printf("sigrok-cli %s\n\n", VERSION);
210 printf("Using libsigrok %s (lib version %s).\n",
211 sr_package_version_string_get(), sr_lib_version_string_get());
212 printf("Using libsigrokdecode %s (lib version %s).\n\n",
213 srd_package_version_string_get(), srd_lib_version_string_get());
215 printf("Supported hardware drivers:\n");
216 drivers = sr_driver_list();
217 for (i = 0; drivers[i]; i++) {
218 printf(" %-20s %s\n", drivers[i]->name, drivers[i]->longname);
222 printf("Supported input formats:\n");
223 inputs = sr_input_list();
224 for (i = 0; inputs[i]; i++)
225 printf(" %-20s %s\n", inputs[i]->id, inputs[i]->description);
228 printf("Supported output formats:\n");
229 outputs = sr_output_list();
230 for (i = 0; outputs[i]; i++)
231 printf(" %-20s %s\n", outputs[i]->id, outputs[i]->description);
234 if (srd_init(NULL) == SRD_OK) {
235 printf("Supported protocol decoders:\n");
236 srd_decoder_load_all();
237 for (l = srd_decoder_list(); l; l = l->next) {
239 printf(" %-20s %s\n", dec->id, dec->longname);
240 /* Print protocol description upon "-l 3" or higher. */
241 if (opt_loglevel >= SR_LOG_INFO)
242 printf(" %-20s %s\n", "", dec->desc);
249 static void print_dev_line(const struct sr_dev *dev)
251 const struct sr_dev_inst *sdi;
253 sr_dev_info_get(dev, SR_DI_INST, (const void **)&sdi);
255 if (sdi->vendor && sdi->vendor[0])
256 printf("%s ", sdi->vendor);
257 if (sdi->model && sdi->model[0])
258 printf("%s ", sdi->model);
259 if (sdi->version && sdi->version[0])
260 printf("%s ", sdi->version);
262 printf("with %d probes", g_slist_length(dev->probes));
266 static void show_dev_list(void)
268 struct sr_dev *dev, *demo_dev;
273 devs = sr_dev_list();
275 if (g_slist_length(devs) == 0)
278 printf("The following devices were found:\nID Device\n");
280 for (l = devs; l; l = l->next) {
282 if (sr_dev_has_hwcap(dev, SR_HWCAP_DEMO_DEV)) {
286 printf("%-3d ", devcnt++);
291 print_dev_line(demo_dev);
295 static void show_dev_detail(void)
298 const struct sr_hwcap_option *hwo;
299 const struct sr_samplerates *samplerates;
300 struct sr_rational *rationals;
305 const char *charopts, **stropts;
307 dev = parse_devstring(opt_dev);
309 printf("No such device. Use -D to list all devices.\n");
315 if (sr_dev_info_get(dev, SR_DI_TRIGGER_TYPES,
316 (const void **)&charopts) == SR_OK) {
317 printf("Supported triggers: ");
319 printf("%c ", *charopts);
325 title = "Supported options:\n";
326 hwcaps = dev->driver->hwcap_get_all();
327 for (cap = 0; hwcaps[cap]; cap++) {
328 if (!(hwo = sr_hw_hwcap_get(hwcaps[cap])))
336 if (hwo->hwcap == SR_HWCAP_PATTERN_MODE) {
337 /* Pattern generator modes */
338 printf(" %s", hwo->shortname);
339 if (sr_dev_info_get(dev, SR_DI_PATTERNS,
340 (const void **)&stropts) == SR_OK) {
341 printf(" - supported patterns:\n");
342 for (i = 0; stropts[i]; i++)
343 printf(" %s\n", stropts[i]);
348 } else if (hwo->hwcap == SR_HWCAP_SAMPLERATE) {
349 /* Supported samplerates */
350 printf(" %s", hwo->shortname);
351 if (sr_dev_info_get(dev, SR_DI_SAMPLERATES,
352 (const void **)&samplerates) != SR_OK) {
356 if (samplerates->step) {
358 if (!(s = sr_samplerate_string(samplerates->low)))
363 if (!(s = sr_samplerate_string(samplerates->high)))
368 if (!(s = sr_samplerate_string(samplerates->step)))
370 printf(" in steps of %s)\n", s);
373 printf(" - supported samplerates:\n");
374 for (i = 0; samplerates->list[i]; i++)
375 printf(" %s\n", sr_samplerate_string(samplerates->list[i]));
378 } else if (hwo->hwcap == SR_HWCAP_BUFFERSIZE) {
379 /* Supported buffer sizes */
380 printf(" %s", hwo->shortname);
381 if (sr_dev_info_get(dev, SR_DI_BUFFERSIZES,
382 (const void **)&integers) != SR_OK) {
386 printf(" - supported buffer sizes:\n");
387 for (i = 0; integers[i]; i++)
388 printf(" %"PRIu64"\n", integers[i]);
390 } else if (hwo->hwcap == SR_HWCAP_TIMEBASE) {
391 /* Supported time bases */
392 printf(" %s", hwo->shortname);
393 if (sr_dev_info_get(dev, SR_DI_TIMEBASES,
394 (const void **)&rationals) != SR_OK) {
398 printf(" - supported time bases:\n");
399 for (i = 0; rationals[i].p && rationals[i].q; i++)
400 printf(" %s\n", sr_period_string(
401 rationals[i].p * rationals[i].q));
403 } else if (hwo->hwcap == SR_HWCAP_TRIGGER_SOURCE) {
404 /* Supported trigger sources */
405 printf(" %s", hwo->shortname);
406 if (sr_dev_info_get(dev, SR_DI_TRIGGER_SOURCES,
407 (const void **)&stropts) != SR_OK) {
411 printf(" - supported trigger sources:\n");
412 for (i = 0; stropts[i]; i++)
413 printf(" %s\n", stropts[i]);
415 } else if (hwo->hwcap == SR_HWCAP_FILTER) {
416 /* Supported trigger sources */
417 printf(" %s", hwo->shortname);
418 if (sr_dev_info_get(dev, SR_DI_FILTERS,
419 (const void **)&stropts) != SR_OK) {
423 printf(" - supported filter targets:\n");
424 for (i = 0; stropts[i]; i++)
425 printf(" %s\n", stropts[i]);
427 } else if (hwo->hwcap == SR_HWCAP_VDIV) {
428 /* Supported volts/div values */
429 printf(" %s", hwo->shortname);
430 if (sr_dev_info_get(dev, SR_DI_VDIVS,
431 (const void **)&rationals) != SR_OK) {
435 printf(" - supported volts/div:\n");
436 for (i = 0; rationals[i].p && rationals[i].q; i++)
437 printf(" %s\n", sr_voltage_string( &rationals[i]));
439 } else if (hwo->hwcap == SR_HWCAP_COUPLING) {
440 /* Supported coupling settings */
441 printf(" %s", hwo->shortname);
442 if (sr_dev_info_get(dev, SR_DI_COUPLING,
443 (const void **)&stropts) != SR_OK) {
447 printf(" - supported coupling options:\n");
448 for (i = 0; stropts[i]; i++)
449 printf(" %s\n", stropts[i]);
452 /* Everything else */
453 printf(" %s\n", hwo->shortname);
458 static void show_pd_detail(void)
461 struct srd_decoder *dec;
462 char **pdtokens, **pdtok, **ann, *doc;
465 pdtokens = g_strsplit(opt_pds, ",", -1);
466 for (pdtok = pdtokens; *pdtok; pdtok++) {
467 if (!(dec = srd_decoder_get_by_id(*pdtok))) {
468 printf("Protocol decoder %s not found.\n", *pdtok);
471 printf("ID: %s\nName: %s\nLong name: %s\nDescription: %s\n",
472 dec->id, dec->name, dec->longname, dec->desc);
473 printf("License: %s\n", dec->license);
474 printf("Annotations:\n");
475 if (dec->annotations) {
476 for (l = dec->annotations; l; l = l->next) {
478 printf("- %s\n %s\n", ann[0], ann[1]);
483 /* TODO: Print supported decoder options. */
484 printf("Required probes:\n");
486 for (l = dec->probes; l; l = l->next) {
488 printf("- %s (%s): %s\n",
489 p->name, p->id, p->desc);
494 printf("Optional probes:\n");
495 if (dec->opt_probes) {
496 for (l = dec->opt_probes; l; l = l->next) {
498 printf("- %s (%s): %s\n",
499 p->name, p->id, p->desc);
504 if ((doc = srd_decoder_doc_get(dec))) {
505 printf("Documentation:\n%s\n",
506 doc[0] == '\n' ? doc + 1 : doc);
511 g_strfreev(pdtokens);
514 static void datafeed_in(struct sr_dev *dev, struct sr_datafeed_packet *packet)
516 static struct sr_output *o = NULL;
517 static int logic_probelist[SR_MAX_NUM_PROBES] = { 0 };
518 static struct sr_probe *analog_probelist[SR_MAX_NUM_PROBES];
519 static uint64_t received_samples = 0;
520 static int unitsize = 0;
521 static int triggered = 0;
522 static FILE *outfile = NULL;
523 static int num_analog_probes = 0;
524 struct sr_probe *probe;
525 struct sr_datafeed_logic *logic;
526 struct sr_datafeed_meta_logic *meta_logic;
527 struct sr_datafeed_analog *analog;
528 struct sr_datafeed_meta_analog *meta_analog;
529 static int num_enabled_analog_probes = 0;
530 int num_enabled_probes, sample_size, ret, i;
531 uint64_t output_len, filter_out_len;
532 uint8_t *output_buf, *filter_out;
534 /* If the first packet to come in isn't a header, don't even try. */
535 if (packet->type != SR_DF_HEADER && o == NULL)
539 switch (packet->type) {
541 g_debug("cli: Received SR_DF_HEADER");
542 /* Initialize the output module. */
543 if (!(o = g_try_malloc(sizeof(struct sr_output)))) {
544 g_critical("Output module malloc failed.");
547 o->format = output_format;
549 o->param = output_format_param;
550 if (o->format->init) {
551 if (o->format->init(o) != SR_OK) {
552 g_critical("Output format initialization failed.");
559 g_debug("cli: Received SR_DF_END");
561 g_debug("cli: double end!");
564 if (o->format->event) {
565 o->format->event(o, SR_DF_END, &output_buf, &output_len);
568 fwrite(output_buf, 1, output_len, outfile);
573 if (limit_samples && received_samples < limit_samples)
574 g_warning("Device only sent %" PRIu64 " samples.",
577 g_warning("Device stopped after %" PRIu64 " samples.",
580 if (outfile && outfile != stdout)
587 g_debug("cli: received SR_DF_TRIGGER");
588 if (o->format->event)
589 o->format->event(o, SR_DF_TRIGGER, &output_buf,
594 case SR_DF_META_LOGIC:
595 g_message("cli: Received SR_DF_META_LOGIC");
596 meta_logic = packet->payload;
597 num_enabled_probes = 0;
598 for (i = 0; i < meta_logic->num_probes; i++) {
599 probe = g_slist_nth_data(dev->probes, i);
601 logic_probelist[num_enabled_probes++] = probe->index;
603 /* How many bytes we need to store num_enabled_probes bits */
604 unitsize = (num_enabled_probes + 7) / 8;
607 if (opt_output_file) {
608 if (default_output_format) {
609 /* output file is in session format, which means we'll
610 * dump everything in the datastore as it comes in,
611 * and save from there after the session. */
613 ret = sr_datastore_new(unitsize, &(dev->datastore));
615 printf("Failed to create datastore.\n");
619 /* saving to a file in whatever format was set
620 * with --format, so all we need is a filehandle */
621 outfile = g_fopen(opt_output_file, "wb");
625 srd_session_start(num_enabled_probes, unitsize,
626 meta_logic->samplerate);
630 logic = packet->payload;
631 g_message("cli: received SR_DF_LOGIC, %"PRIu64" bytes", logic->length);
632 sample_size = logic->unitsize;
633 if (logic->length == 0)
636 /* Don't store any samples until triggered. */
637 if (opt_wait_trigger && !triggered)
640 if (limit_samples && received_samples >= limit_samples)
643 ret = sr_filter_probes(sample_size, unitsize, logic_probelist,
644 logic->data, logic->length,
645 &filter_out, &filter_out_len);
649 /* what comes out of the filter is guaranteed to be packed into the
650 * minimum size needed to support the number of samples at this sample
651 * size. however, the driver may have submitted too much -- cut off
652 * the buffer of the last packet according to the sample limit.
654 if (limit_samples && (received_samples + logic->length / sample_size >
655 limit_samples * sample_size))
656 filter_out_len = limit_samples * sample_size - received_samples;
659 sr_datastore_put(dev->datastore, filter_out,
660 filter_out_len, sample_size, logic_probelist);
662 if (opt_output_file && default_output_format)
663 /* saving to a session file, don't need to do anything else
664 * to this data for now. */
668 if (srd_session_send(received_samples, (uint8_t*)filter_out,
669 filter_out_len) != SRD_OK)
673 if (o->format->data && packet->type == o->format->df_type)
674 o->format->data(o, filter_out, filter_out_len, &output_buf, &output_len);
676 fwrite(output_buf, 1, output_len, outfile);
684 received_samples += logic->length / sample_size;
687 case SR_DF_META_ANALOG:
688 g_message("cli: Received SR_DF_META_ANALOG");
689 meta_analog = packet->payload;
690 num_analog_probes = meta_analog->num_probes;
691 num_enabled_analog_probes = 0;
692 for (i = 0; i < num_analog_probes; i++) {
693 probe = g_slist_nth_data(dev->probes, i);
695 analog_probelist[num_enabled_analog_probes++] = probe;
699 if (opt_output_file) {
700 if (default_output_format) {
701 /* output file is in session format, which means we'll
702 * dump everything in the datastore as it comes in,
703 * and save from there after the session. */
705 ret = sr_datastore_new(unitsize, &(dev->datastore));
707 printf("Failed to create datastore.\n");
711 /* saving to a file in whatever format was set
712 * with --format, so all we need is a filehandle */
713 outfile = g_fopen(opt_output_file, "wb");
719 analog = packet->payload;
720 g_message("cli: received SR_DF_ANALOG, %d samples", analog->num_samples);
721 if (analog->num_samples == 0)
724 if (limit_samples && received_samples >= limit_samples)
727 if (o->format->data && packet->type == o->format->df_type) {
728 o->format->data(o, (const uint8_t *)analog->data,
729 analog->num_samples * sizeof(float),
730 &output_buf, &output_len);
732 fwrite(output_buf, 1, output_len, outfile);
738 received_samples += analog->num_samples;
741 case SR_DF_FRAME_BEGIN:
742 g_debug("cli: received SR_DF_FRAME_BEGIN");
743 if (o->format->event) {
744 o->format->event(o, SR_DF_FRAME_BEGIN, &output_buf,
747 fwrite(output_buf, 1, output_len, outfile);
754 case SR_DF_FRAME_END:
755 g_debug("cli: received SR_DF_FRAME_END");
756 if (o->format->event) {
757 o->format->event(o, SR_DF_FRAME_END, &output_buf,
760 fwrite(output_buf, 1, output_len, outfile);
768 g_message("received unknown packet type %d", packet->type);
773 /* Register the given PDs for this session.
774 * Accepts a string of the form: "spi:sck=3:sdata=4,spi:sck=3:sdata=5"
775 * That will instantiate two SPI decoders on the clock but different data
778 static int register_pds(struct sr_dev *dev, const char *pdstring)
780 GHashTable *pd_opthash;
781 struct srd_decoder_inst *di;
783 char **pdtokens, **pdtok, *pd_name;
785 /* Avoid compiler warnings. */
789 pd_ann_visible = g_hash_table_new_full(g_str_hash, g_int_equal,
793 pdtokens = g_strsplit(pdstring, ",", 0);
794 for (pdtok = pdtokens; *pdtok; pdtok++) {
795 if (!(pd_opthash = parse_generic_arg(*pdtok, TRUE))) {
796 g_critical("Invalid protocol decoder option '%s'.", *pdtok);
800 pd_name = g_strdup(g_hash_table_lookup(pd_opthash, "sigrok_key"));
801 g_hash_table_remove(pd_opthash, "sigrok_key");
802 if (srd_decoder_load(pd_name) != SRD_OK) {
803 g_critical("Failed to load protocol decoder %s.", pd_name);
807 if (!(di = srd_inst_new(pd_name, pd_opthash))) {
808 g_critical("Failed to instantiate protocol decoder %s.", pd_name);
813 /* If no annotation list was specified, add them all in now.
814 * This will be pared down later to leave only the last PD
817 if (!opt_pd_annotations)
818 g_hash_table_insert(pd_ann_visible,
819 g_strdup(di->inst_id), NULL);
821 /* Any keys left in the options hash are probes, where the key
822 * is the probe name as specified in the decoder class, and the
823 * value is the probe number i.e. the order in which the PD's
824 * incoming samples are arranged. */
825 if (srd_inst_probe_set_all(di, pd_opthash) != SRD_OK) {
829 g_hash_table_destroy(pd_opthash);
834 g_strfreev(pdtokens);
836 g_hash_table_destroy(pd_opthash);
843 int setup_pd_stack(void)
845 struct srd_decoder_inst *di_from, *di_to;
849 /* Set up the protocol decoder stack. */
850 pds = g_strsplit(opt_pds, ",", 0);
851 if (g_strv_length(pds) > 1) {
853 /* A stack setup was specified, use that. */
855 pds = g_strsplit(opt_pd_stack, ",", 0);
856 if (g_strv_length(pds) < 2) {
858 g_critical("Specify at least two protocol decoders to stack.");
863 /* First PD goes at the bottom of the stack. */
864 ids = g_strsplit(pds[0], ":", 0);
865 if (!(di_from = srd_inst_find_by_id(ids[0]))) {
867 g_critical("Cannot stack protocol decoder '%s': "
868 "instance not found.", pds[0]);
873 /* Every subsequent PD goes on top. */
874 for (i = 1; pds[i]; i++) {
875 ids = g_strsplit(pds[i], ":", 0);
876 if (!(di_to = srd_inst_find_by_id(ids[0]))) {
878 g_critical("Cannot stack protocol decoder '%s': "
879 "instance not found.", pds[i]);
883 if ((ret = srd_inst_stack(di_from, di_to)) != SRD_OK)
886 /* Don't show annotation from this PD. Only the last PD in
887 * the stack will be left on the annotation list (unless
888 * the annotation list was specifically provided).
890 if (!opt_pd_annotations)
891 g_hash_table_remove(pd_ann_visible,
902 int setup_pd_annotations(void)
905 struct srd_decoder *dec;
907 char **pds, **pdtok, **keyval, **ann_descr;
909 /* Set up custom list of PDs and annotations to show. */
910 if (opt_pd_annotations) {
911 pds = g_strsplit(opt_pd_annotations, ",", 0);
912 for (pdtok = pds; *pdtok && **pdtok; pdtok++) {
914 keyval = g_strsplit(*pdtok, "=", 0);
915 if (!(dec = srd_decoder_get_by_id(keyval[0]))) {
916 g_critical("Protocol decoder '%s' not found.", keyval[0]);
919 if (!dec->annotations) {
920 g_critical("Protocol decoder '%s' has no annotations.", keyval[0]);
923 if (g_strv_length(keyval) == 2) {
924 for (l = dec->annotations; l; l = l->next, ann++) {
926 if (!canon_cmp(ann_descr[0], keyval[1]))
931 g_critical("Annotation '%s' not found "
932 "for protocol decoder '%s'.", keyval[1], keyval[0]);
936 g_debug("cli: showing protocol decoder annotation %d from '%s'", ann, keyval[0]);
937 g_hash_table_insert(pd_ann_visible, g_strdup(keyval[0]), GINT_TO_POINTER(ann));
946 int setup_output_format(void)
951 struct sr_output_format **outputs;
955 if (!opt_output_format) {
956 opt_output_format = DEFAULT_OUTPUT_FORMAT;
957 /* we'll need to remember this so when saving to a file
958 * later, sigrok session format will be used.
960 default_output_format = TRUE;
963 fmtargs = parse_generic_arg(opt_output_format, TRUE);
964 fmtspec = g_hash_table_lookup(fmtargs, "sigrok_key");
966 g_critical("Invalid output format.");
969 outputs = sr_output_list();
970 for (i = 0; outputs[i]; i++) {
971 if (strcmp(outputs[i]->id, fmtspec))
973 g_hash_table_remove(fmtargs, "sigrok_key");
974 output_format = outputs[i];
975 g_hash_table_iter_init(&iter, fmtargs);
976 while (g_hash_table_iter_next(&iter, &key, &value)) {
977 /* only supporting one parameter per output module
978 * for now, and only its value */
979 output_format_param = g_strdup(value);
984 if (!output_format) {
985 g_critical("Invalid output format %s.", opt_output_format);
988 g_hash_table_destroy(fmtargs);
993 void show_pd_annotations(struct srd_proto_data *pdata, void *cb_data)
999 /* 'cb_data' is not used in this specific callback. */
1002 if (!pd_ann_visible)
1005 if (!g_hash_table_lookup_extended(pd_ann_visible, pdata->pdo->di->inst_id,
1007 /* Not in the list of PDs whose annotations we're showing. */
1010 if (pdata->ann_format != GPOINTER_TO_INT(ann_format))
1011 /* We don't want this particular format from the PD. */
1014 annotations = pdata->data;
1015 if (opt_loglevel > SR_LOG_WARN)
1016 printf("%"PRIu64"-%"PRIu64" ", pdata->start_sample, pdata->end_sample);
1017 printf("%s: ", pdata->pdo->proto_id);
1018 for (i = 0; annotations[i]; i++)
1019 printf("\"%s\" ", annotations[i]);
1024 static int select_probes(struct sr_dev *dev)
1026 struct sr_probe *probe;
1034 * This only works because a device by default initializes
1035 * and enables all its probes.
1037 max_probes = g_slist_length(dev->probes);
1038 probelist = parse_probestring(max_probes, opt_probes);
1043 for (i = 0; i < max_probes; i++) {
1045 sr_dev_probe_name_set(dev, i + 1, probelist[i]);
1046 g_free(probelist[i]);
1048 probe = sr_dev_probe_find(dev, i + 1);
1049 probe->enabled = FALSE;
1058 * Return the input file format which the CLI tool should use.
1060 * If the user specified -I / --input-format, use that one. Otherwise, try to
1061 * autodetect the format as good as possible. Failing that, return NULL.
1063 * @param filename The filename of the input file. Must not be NULL.
1064 * @param opt The -I / --input-file option the user specified (or NULL).
1066 * @return A pointer to the 'struct sr_input_format' that should be used,
1067 * or NULL if no input format was selected or auto-detected.
1069 static struct sr_input_format *determine_input_file_format(
1070 const char *filename, const char *opt)
1073 struct sr_input_format **inputs;
1075 /* If there are no input formats, return NULL right away. */
1076 inputs = sr_input_list();
1078 g_critical("No supported input formats available.");
1082 /* If the user specified -I / --input-format, use that one. */
1084 for (i = 0; inputs[i]; i++) {
1085 if (strcasecmp(inputs[i]->id, opt))
1087 g_debug("Using user-specified input file format '%s'.",
1092 /* The user specified an unknown input format, return NULL. */
1093 g_critical("Error: specified input file format '%s' is "
1098 /* Otherwise, try to find an input module that can handle this file. */
1099 for (i = 0; inputs[i]; i++) {
1100 if (inputs[i]->format_match(filename))
1104 /* Return NULL if no input module wanted to touch this. */
1106 g_critical("Error: no matching input module found.");
1110 g_debug("cli: Autodetected '%s' input format for file '%s'.",
1111 inputs[i]->id, filename);
1116 static void load_input_file_format(void)
1118 GHashTable *fmtargs = NULL;
1120 struct sr_input *in;
1121 struct sr_input_format *input_format;
1122 char *fmtspec = NULL;
1124 if (opt_input_format) {
1125 fmtargs = parse_generic_arg(opt_input_format);
1126 fmtspec = g_hash_table_lookup(fmtargs, "sigrok_key");
1129 if (!(input_format = determine_input_file_format(opt_input_file,
1131 /* The exact cause was already logged. */
1136 g_hash_table_remove(fmtargs, "sigrok_key");
1138 if (stat(opt_input_file, &st) == -1) {
1139 g_critical("Failed to load %s: %s", opt_input_file,
1144 /* Initialize the input module. */
1145 if (!(in = g_try_malloc(sizeof(struct sr_input)))) {
1146 g_critical("Failed to allocate input module.");
1149 in->format = input_format;
1150 in->param = fmtargs;
1151 if (in->format->init) {
1152 if (in->format->init(in) != SR_OK) {
1153 g_critical("Input format init failed.");
1158 if (select_probes(in->vdev) > 0)
1162 sr_session_datafeed_callback_add(datafeed_in);
1163 if (sr_session_dev_add(in->vdev) != SR_OK) {
1164 g_critical("Failed to use device.");
1165 sr_session_destroy();
1169 input_format->loadfile(in, opt_input_file);
1170 if (opt_output_file && default_output_format) {
1171 if (sr_session_save(opt_output_file) != SR_OK)
1172 g_critical("Failed to save session.");
1174 sr_session_destroy();
1177 g_hash_table_destroy(fmtargs);
1180 static void load_input_file(void)
1183 if (sr_session_load(opt_input_file) == SR_OK) {
1184 /* sigrok session file */
1185 sr_session_datafeed_callback_add(datafeed_in);
1191 /* fall back on input modules */
1192 load_input_file_format();
1196 int num_real_devs(void)
1203 devs = sr_dev_list();
1204 for (l = devs; l; l = l->next) {
1206 if (!sr_dev_has_hwcap(dev, SR_HWCAP_DEMO_DEV))
1213 static int set_dev_options(struct sr_dev *dev, GHashTable *args)
1215 GHashTableIter iter;
1216 gpointer key, value;
1220 struct sr_rational tmp_rat;
1224 g_hash_table_iter_init(&iter, args);
1225 while (g_hash_table_iter_next(&iter, &key, &value)) {
1227 for (i = 0; sr_hwcap_options[i].hwcap; i++) {
1228 if (strcmp(sr_hwcap_options[i].shortname, key))
1230 if ((value == NULL) &&
1231 (sr_hwcap_options[i].type != SR_T_BOOL)) {
1232 g_critical("Option '%s' needs a value.", (char *)key);
1236 switch (sr_hwcap_options[i].type) {
1238 ret = sr_parse_sizestring(value, &tmp_u64);
1241 ret = dev->driver->dev_config_set(dev->driver_index,
1242 sr_hwcap_options[i].hwcap, &tmp_u64);
1245 ret = dev->driver->dev_config_set(dev->driver_index,
1246 sr_hwcap_options[i].hwcap, value);
1252 tmp_bool = sr_parse_boolstring(value);
1253 ret = dev->driver->dev_config_set(dev->driver_index,
1254 sr_hwcap_options[i].hwcap,
1255 GINT_TO_POINTER(tmp_bool));
1258 tmp_float = strtof(value, NULL);
1259 ret = dev->driver->dev_config_set(dev->driver_index,
1260 sr_hwcap_options[i].hwcap, &tmp_float);
1262 case SR_T_RATIONAL_PERIOD:
1263 if ((ret = sr_parse_period(value, &tmp_rat)) != SR_OK)
1265 ret = dev->driver->dev_config_set(dev->driver_index,
1266 sr_hwcap_options[i].hwcap, &tmp_rat);
1268 case SR_T_RATIONAL_VOLT:
1269 if ((ret = sr_parse_voltage(value, &tmp_rat)) != SR_OK)
1271 ret = dev->driver->dev_config_set(dev->driver_index,
1272 sr_hwcap_options[i].hwcap, &tmp_rat);
1279 g_critical("Failed to set device option '%s'.", (char *)key);
1286 g_critical("Unknown device option '%s'.", (char *) key);
1294 static void run_session(void)
1297 GHashTable *devargs;
1298 int num_devs, max_probes, i;
1300 char **probelist, *devspec;
1304 devargs = parse_generic_arg(opt_dev);
1305 devspec = g_hash_table_lookup(devargs, "sigrok_key");
1306 dev = parse_devstring(devspec);
1308 g_critical("Device not found.");
1311 g_hash_table_remove(devargs, "sigrok_key");
1313 num_devs = num_real_devs();
1314 if (num_devs == 1) {
1315 /* No device specified, but there is only one. */
1317 dev = parse_devstring("0");
1318 } else if (num_devs == 0) {
1319 g_critical("No devices found.");
1322 g_critical("%d devices found, please select one.", num_devs);
1328 sr_session_datafeed_callback_add(datafeed_in);
1330 if (sr_session_dev_add(dev) != SR_OK) {
1331 g_critical("Failed to use device.");
1332 sr_session_destroy();
1337 if (set_dev_options(dev, devargs) != SR_OK) {
1338 sr_session_destroy();
1341 g_hash_table_destroy(devargs);
1344 if (select_probes(dev) != SR_OK)
1347 if (opt_continuous) {
1348 if (!sr_driver_hwcap_exists(dev->driver, SR_HWCAP_CONTINUOUS)) {
1349 g_critical("This device does not support continuous sampling.");
1350 sr_session_destroy();
1356 probelist = sr_parse_triggerstring(dev, opt_triggers);
1358 sr_session_destroy();
1362 max_probes = g_slist_length(dev->probes);
1363 for (i = 0; i < max_probes; i++) {
1365 sr_dev_trigger_set(dev, i + 1, probelist[i]);
1366 g_free(probelist[i]);
1373 time_msec = sr_parse_timestring(opt_time);
1374 if (time_msec == 0) {
1375 g_critical("Invalid time '%s'", opt_time);
1376 sr_session_destroy();
1380 if (sr_driver_hwcap_exists(dev->driver, SR_HWCAP_LIMIT_MSEC)) {
1381 if (dev->driver->dev_config_set(dev->driver_index,
1382 SR_HWCAP_LIMIT_MSEC, &time_msec) != SR_OK) {
1383 g_critical("Failed to configure time limit.");
1384 sr_session_destroy();
1389 /* time limit set, but device doesn't support this...
1390 * convert to samples based on the samplerate.
1393 if (sr_dev_has_hwcap(dev, SR_HWCAP_SAMPLERATE)) {
1394 const uint64_t *samplerate;
1396 sr_dev_info_get(dev, SR_DI_CUR_SAMPLERATE,
1397 (const void **)&samplerate);
1398 limit_samples = (*samplerate) * time_msec / (uint64_t)1000;
1400 if (limit_samples == 0) {
1401 g_critical("Not enough time at this samplerate.");
1402 sr_session_destroy();
1406 if (dev->driver->dev_config_set(dev->driver_index,
1407 SR_HWCAP_LIMIT_SAMPLES, &limit_samples) != SR_OK) {
1408 g_critical("Failed to configure time-based sample limit.");
1409 sr_session_destroy();
1416 if ((sr_parse_sizestring(opt_samples, &limit_samples) != SR_OK)
1417 || (dev->driver->dev_config_set(dev->driver_index,
1418 SR_HWCAP_LIMIT_SAMPLES, &limit_samples) != SR_OK)) {
1419 g_critical("Failed to configure sample limit.");
1420 sr_session_destroy();
1426 if ((sr_parse_sizestring(opt_frames, &limit_frames) != SR_OK)
1427 || (dev->driver->dev_config_set(dev->driver_index,
1428 SR_HWCAP_LIMIT_FRAMES, &limit_frames) != SR_OK)) {
1429 printf("Failed to configure frame limit.\n");
1430 sr_session_destroy();
1435 if (dev->driver->dev_config_set(dev->driver_index,
1436 SR_HWCAP_PROBECONFIG, (char *)dev->probes) != SR_OK) {
1437 g_critical("Failed to configure probes.");
1438 sr_session_destroy();
1442 if (sr_session_start() != SR_OK) {
1443 g_critical("Failed to start session.");
1444 sr_session_destroy();
1456 if (opt_output_file && default_output_format) {
1457 if (sr_session_save(opt_output_file) != SR_OK)
1458 g_critical("Failed to save session.");
1460 sr_session_destroy();
1463 static void logger(const gchar *log_domain, GLogLevelFlags log_level,
1464 const gchar *message, gpointer cb_data)
1466 /* Avoid compiler warnings. */
1471 * All messages, warnings, errors etc. go to stderr (not stdout) in
1472 * order to not mess up the CLI tool data output, e.g. VCD output.
1474 if (log_level & (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING)
1475 || opt_loglevel > SR_LOG_WARN) {
1476 fprintf(stderr, "%s\n", message);
1481 int main(int argc, char **argv)
1483 GOptionContext *context;
1486 g_log_set_default_handler(logger, NULL);
1489 context = g_option_context_new(NULL);
1490 g_option_context_add_main_entries(context, optargs, NULL);
1492 if (!g_option_context_parse(context, &argc, &argv, &error)) {
1493 g_critical("%s", error->message);
1497 /* Set the loglevel (amount of messages to output) for libsigrok. */
1498 if (sr_log_loglevel_set(opt_loglevel) != SR_OK)
1501 /* Set the loglevel (amount of messages to output) for libsigrokdecode. */
1502 if (srd_log_loglevel_set(opt_loglevel) != SRD_OK)
1505 if (sr_init() != SR_OK)
1509 if (srd_init(NULL) != SRD_OK)
1511 if (register_pds(NULL, opt_pds) != 0)
1513 if (srd_pd_output_callback_add(SRD_OUTPUT_ANN,
1514 show_pd_annotations, NULL) != SRD_OK)
1516 if (setup_pd_stack() != 0)
1518 if (setup_pd_annotations() != 0)
1522 if (setup_output_format() != 0)
1527 else if (opt_list_devs)
1529 else if (opt_input_file)
1531 else if (opt_samples || opt_time || opt_frames || opt_continuous)
1538 printf("%s", g_option_context_get_help(context, TRUE, NULL));
1543 g_option_context_free(context);