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_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 struct sr_hwcap_option *ho;
119 struct sr_hwopt *hwopt;
124 keys = g_hash_table_get_keys(hash);
126 for (gl = keys; gl; gl = gl->next) {
128 for (ho = sr_drvopts; ho->shortname; ho++) {
129 if (!strcmp(key, ho->shortname)) {
130 hwopt = g_try_malloc(sizeof(struct sr_hwopt));
131 hwopt->hwopt = ho->hwcap;
132 value = g_hash_table_lookup(hash, key);
133 hwopt->value = g_strdup(value);
134 opts = g_slist_append(opts, hwopt);
138 if (!ho->shortname) {
139 g_critical("Unknown option %s", key);
148 static GSList *device_scan(void)
150 struct sr_dev_driver **drivers, *driver;
152 GSList *drvopts, *devices, *tmpdevs, *l;
157 drvargs = parse_generic_arg(opt_drv, TRUE);
158 drvname = g_strdup(g_hash_table_lookup(drvargs, "sigrok_key"));
159 g_hash_table_remove(drvargs, "sigrok_key");
161 drivers = sr_driver_list();
162 for (i = 0; drivers[i]; i++) {
163 if (strcmp(drivers[i]->name, drvname))
168 g_critical("Driver %s not found.", drvname);
172 if (sr_driver_init(driver) != SR_OK) {
173 g_critical("Failed to initialize driver.");
177 if (g_hash_table_size(drvargs) > 0)
178 if (!(drvopts = hash_to_hwopt(drvargs)))
179 /* Unknown options, already logged. */
181 devices = sr_driver_scan(driver, drvopts);
183 /* No driver specified, let them all scan on their own. */
185 drivers = sr_driver_list();
186 for (i = 0; drivers[i]; i++) {
188 if (sr_driver_init(driver) != SR_OK) {
189 g_critical("Failed to initialize driver.");
192 tmpdevs = sr_driver_scan(driver, NULL);
193 for (l = tmpdevs; l; l = l->next)
194 devices = g_slist_append(devices, l->data);
195 g_slist_free(tmpdevs);
202 static void show_version(void)
205 struct sr_dev_driver **drivers;
206 struct sr_input_format **inputs;
207 struct sr_output_format **outputs;
208 struct srd_decoder *dec;
211 printf("sigrok-cli %s\n\n", VERSION);
213 printf("Using libsigrok %s (lib version %s).\n",
214 sr_package_version_string_get(), sr_lib_version_string_get());
215 printf("Using libsigrokdecode %s (lib version %s).\n\n",
216 srd_package_version_string_get(), srd_lib_version_string_get());
218 printf("Supported hardware drivers:\n");
219 drivers = sr_driver_list();
220 for (i = 0; drivers[i]; i++) {
221 printf(" %-20s %s\n", drivers[i]->name, drivers[i]->longname);
225 printf("Supported input formats:\n");
226 inputs = sr_input_list();
227 for (i = 0; inputs[i]; i++)
228 printf(" %-20s %s\n", inputs[i]->id, inputs[i]->description);
231 printf("Supported output formats:\n");
232 outputs = sr_output_list();
233 for (i = 0; outputs[i]; i++)
234 printf(" %-20s %s\n", outputs[i]->id, outputs[i]->description);
237 if (srd_init(NULL) == SRD_OK) {
238 printf("Supported protocol decoders:\n");
239 srd_decoder_load_all();
240 for (l = srd_decoder_list(); l; l = l->next) {
242 printf(" %-20s %s\n", dec->id, dec->longname);
243 /* Print protocol description upon "-l 3" or higher. */
244 if (opt_loglevel >= SR_LOG_INFO)
245 printf(" %-20s %s\n", "", dec->desc);
252 static void print_dev_line(const struct sr_dev_inst *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(sdi->probes));
266 static void show_dev_list(void)
268 struct sr_dev_inst *sdi;
271 if (!(devices = device_scan()))
274 printf("The following devices were found:\n");
275 for (l = devices; l; l = l->next) {
279 g_slist_free(devices);
283 static void show_dev_detail(void)
285 struct sr_dev_inst *sdi;
286 const struct sr_hwcap_option *hwo;
287 const struct sr_samplerates *samplerates;
288 struct sr_rational *rationals;
291 const int *hwopts, *hwcaps;
292 int cap, num_devices, n, i;
294 const char *charopts, **stropts;
296 if (!(devices = device_scan())) {
297 g_critical("No devices found.");
301 num_devices = g_slist_length(devices);
302 if (num_devices > 1) {
304 g_critical("%d devices found. Use --list-devices to show them, "
305 "and --device to select one.", num_devices);
308 /* opt_dev is NULL if not specified, which is fine. */
309 n = strtol(opt_dev, NULL, 10);
310 if (n >= num_devices) {
311 g_critical("%d devices found, numbered starting from 0.",
315 sdi = g_slist_nth_data(devices, n);
317 sdi = g_slist_nth_data(devices, 0);
321 if (sr_info_get(sdi->driver, SR_DI_TRIGGER_TYPES, (const void **)&charopts,
322 sdi) == SR_OK && charopts) {
323 printf("Supported triggers: ");
325 printf("%c ", *charopts);
331 if ((sr_info_get(sdi->driver, SR_DI_HWOPTS, (const void **)&hwopts,
332 NULL) == SR_OK) && hwopts) {
333 printf("Supported driver options:\n");
334 for (i = 0; hwopts[i]; i++) {
335 if (!(hwo = sr_drvopt_get(hwopts[i])))
337 printf(" %s\n", hwo->shortname);
341 title = "Supported device options:\n";
342 if ((sr_info_get(sdi->driver, SR_DI_HWCAPS, (const void **)&hwcaps,
343 NULL) != SR_OK) || !hwcaps)
344 /* Driver supports no device instance options. */
347 for (cap = 0; hwcaps[cap]; cap++) {
348 if (!(hwo = sr_hw_hwcap_get(hwcaps[cap])))
356 if (hwo->hwcap == SR_HWCAP_PATTERN_MODE) {
357 /* Pattern generator modes */
358 printf(" %s", hwo->shortname);
359 if (sr_info_get(sdi->driver, SR_DI_PATTERNS,
360 (const void **)&stropts, sdi) == SR_OK) {
361 printf(" - supported patterns:\n");
362 for (i = 0; stropts[i]; i++)
363 printf(" %s\n", stropts[i]);
368 } else if (hwo->hwcap == SR_HWCAP_SAMPLERATE) {
369 /* Supported samplerates */
370 printf(" %s", hwo->shortname);
371 if (sr_info_get(sdi->driver, SR_DI_SAMPLERATES,
372 (const void **)&samplerates, sdi) != SR_OK) {
376 if (samplerates->step) {
378 if (!(s = sr_samplerate_string(samplerates->low)))
383 if (!(s = sr_samplerate_string(samplerates->high)))
388 if (!(s = sr_samplerate_string(samplerates->step)))
390 printf(" in steps of %s)\n", s);
393 printf(" - supported samplerates:\n");
394 for (i = 0; samplerates->list[i]; i++)
395 printf(" %s\n", sr_samplerate_string(samplerates->list[i]));
398 } else if (hwo->hwcap == SR_HWCAP_BUFFERSIZE) {
399 /* Supported buffer sizes */
400 printf(" %s", hwo->shortname);
401 if (sr_info_get(sdi->driver, SR_DI_BUFFERSIZES,
402 (const void **)&integers, sdi) != SR_OK) {
406 printf(" - supported buffer sizes:\n");
407 for (i = 0; integers[i]; i++)
408 printf(" %"PRIu64"\n", integers[i]);
410 } else if (hwo->hwcap == SR_HWCAP_TIMEBASE) {
411 /* Supported time bases */
412 printf(" %s", hwo->shortname);
413 if (sr_info_get(sdi->driver, SR_DI_TIMEBASES,
414 (const void **)&rationals, sdi) != SR_OK) {
418 printf(" - supported time bases:\n");
419 for (i = 0; rationals[i].p && rationals[i].q; i++)
420 printf(" %s\n", sr_period_string(
421 rationals[i].p * rationals[i].q));
423 } else if (hwo->hwcap == SR_HWCAP_TRIGGER_SOURCE) {
424 /* Supported trigger sources */
425 printf(" %s", hwo->shortname);
426 if (sr_info_get(sdi->driver, SR_DI_TRIGGER_SOURCES,
427 (const void **)&stropts, sdi) != SR_OK) {
431 printf(" - supported trigger sources:\n");
432 for (i = 0; stropts[i]; i++)
433 printf(" %s\n", stropts[i]);
435 } else if (hwo->hwcap == SR_HWCAP_FILTER) {
436 /* Supported trigger sources */
437 printf(" %s", hwo->shortname);
438 if (sr_info_get(sdi->driver, SR_DI_FILTERS,
439 (const void **)&stropts, sdi) != SR_OK) {
443 printf(" - supported filter targets:\n");
444 for (i = 0; stropts[i]; i++)
445 printf(" %s\n", stropts[i]);
447 } else if (hwo->hwcap == SR_HWCAP_VDIV) {
448 /* Supported volts/div values */
449 printf(" %s", hwo->shortname);
450 if (sr_info_get(sdi->driver, SR_DI_VDIVS,
451 (const void **)&rationals, sdi) != SR_OK) {
455 printf(" - supported volts/div:\n");
456 for (i = 0; rationals[i].p && rationals[i].q; i++)
457 printf(" %s\n", sr_voltage_string( &rationals[i]));
459 } else if (hwo->hwcap == SR_HWCAP_COUPLING) {
460 /* Supported coupling settings */
461 printf(" %s", hwo->shortname);
462 if (sr_info_get(sdi->driver, SR_DI_COUPLING,
463 (const void **)&stropts, sdi) != SR_OK) {
467 printf(" - supported coupling options:\n");
468 for (i = 0; stropts[i]; i++)
469 printf(" %s\n", stropts[i]);
472 /* Everything else */
473 printf(" %s\n", hwo->shortname);
479 static void show_pd_detail(void)
482 struct srd_decoder *dec;
483 char **pdtokens, **pdtok, **ann, *doc;
486 pdtokens = g_strsplit(opt_pds, ",", -1);
487 for (pdtok = pdtokens; *pdtok; pdtok++) {
488 if (!(dec = srd_decoder_get_by_id(*pdtok))) {
489 printf("Protocol decoder %s not found.\n", *pdtok);
492 printf("ID: %s\nName: %s\nLong name: %s\nDescription: %s\n",
493 dec->id, dec->name, dec->longname, dec->desc);
494 printf("License: %s\n", dec->license);
495 printf("Annotations:\n");
496 if (dec->annotations) {
497 for (l = dec->annotations; l; l = l->next) {
499 printf("- %s\n %s\n", ann[0], ann[1]);
504 /* TODO: Print supported decoder options. */
505 printf("Required probes:\n");
507 for (l = dec->probes; l; l = l->next) {
509 printf("- %s (%s): %s\n",
510 p->name, p->id, p->desc);
515 printf("Optional probes:\n");
516 if (dec->opt_probes) {
517 for (l = dec->opt_probes; l; l = l->next) {
519 printf("- %s (%s): %s\n",
520 p->name, p->id, p->desc);
525 if ((doc = srd_decoder_doc_get(dec))) {
526 printf("Documentation:\n%s\n",
527 doc[0] == '\n' ? doc + 1 : doc);
532 g_strfreev(pdtokens);
535 static void datafeed_in(const struct sr_dev_inst *sdi,
536 struct sr_datafeed_packet *packet)
538 static struct sr_output *o = NULL;
539 static int logic_probelist[SR_MAX_NUM_PROBES] = { 0 };
540 static struct sr_probe *analog_probelist[SR_MAX_NUM_PROBES];
541 static uint64_t received_samples = 0;
542 static int unitsize = 0;
543 static int triggered = 0;
544 static FILE *outfile = NULL;
545 static int num_analog_probes = 0;
546 struct sr_probe *probe;
547 struct sr_datafeed_logic *logic;
548 struct sr_datafeed_meta_logic *meta_logic;
549 struct sr_datafeed_analog *analog;
550 struct sr_datafeed_meta_analog *meta_analog;
551 static int num_enabled_analog_probes = 0;
552 int num_enabled_probes, sample_size, ret, i;
553 uint64_t output_len, filter_out_len;
554 uint8_t *output_buf, *filter_out;
556 /* If the first packet to come in isn't a header, don't even try. */
557 if (packet->type != SR_DF_HEADER && o == NULL)
561 switch (packet->type) {
563 g_debug("cli: Received SR_DF_HEADER");
564 /* Initialize the output module. */
565 if (!(o = g_try_malloc(sizeof(struct sr_output)))) {
566 g_critical("Output module malloc failed.");
569 o->format = output_format;
570 o->sdi = (struct sr_dev_inst *)sdi;
571 o->param = output_format_param;
572 if (o->format->init) {
573 if (o->format->init(o) != SR_OK) {
574 g_critical("Output format initialization failed.");
581 g_debug("cli: Received SR_DF_END");
583 g_debug("cli: double end!");
586 if (o->format->event) {
587 o->format->event(o, SR_DF_END, &output_buf, &output_len);
590 fwrite(output_buf, 1, output_len, outfile);
595 if (limit_samples && received_samples < limit_samples)
596 g_warning("Device only sent %" PRIu64 " samples.",
599 g_warning("Device stopped after %" PRIu64 " samples.",
602 if (outfile && outfile != stdout)
609 g_debug("cli: received SR_DF_TRIGGER");
610 if (o->format->event)
611 o->format->event(o, SR_DF_TRIGGER, &output_buf,
616 case SR_DF_META_LOGIC:
617 g_message("cli: Received SR_DF_META_LOGIC");
618 meta_logic = packet->payload;
619 num_enabled_probes = 0;
620 for (i = 0; i < meta_logic->num_probes; i++) {
621 probe = g_slist_nth_data(sdi->probes, i);
623 logic_probelist[num_enabled_probes++] = probe->index;
625 logic_probelist[num_enabled_probes] = -1;
626 /* How many bytes we need to store num_enabled_probes bits */
627 unitsize = (num_enabled_probes + 7) / 8;
630 if (opt_output_file) {
631 if (default_output_format) {
632 /* output file is in session format, which means we'll
633 * dump everything in the datastore as it comes in,
634 * and save from there after the session. */
636 ret = sr_datastore_new(unitsize, &(dev->datastore));
638 printf("Failed to create datastore.\n");
642 /* saving to a file in whatever format was set
643 * with --format, so all we need is a filehandle */
644 outfile = g_fopen(opt_output_file, "wb");
648 srd_session_start(num_enabled_probes, unitsize,
649 meta_logic->samplerate);
653 logic = packet->payload;
654 g_message("cli: received SR_DF_LOGIC, %"PRIu64" bytes", logic->length);
655 sample_size = logic->unitsize;
656 if (logic->length == 0)
659 /* Don't store any samples until triggered. */
660 if (opt_wait_trigger && !triggered)
663 if (limit_samples && received_samples >= limit_samples)
666 ret = sr_filter_probes(sample_size, unitsize, logic_probelist,
667 logic->data, logic->length,
668 &filter_out, &filter_out_len);
672 /* what comes out of the filter is guaranteed to be packed into the
673 * minimum size needed to support the number of samples at this sample
674 * size. however, the driver may have submitted too much -- cut off
675 * the buffer of the last packet according to the sample limit.
677 if (limit_samples && (received_samples + logic->length / sample_size >
678 limit_samples * sample_size))
679 filter_out_len = limit_samples * sample_size - received_samples;
682 sr_datastore_put(dev->datastore, filter_out,
683 filter_out_len, sample_size, logic_probelist);
685 if (opt_output_file && default_output_format)
686 /* saving to a session file, don't need to do anything else
687 * to this data for now. */
691 if (srd_session_send(received_samples, (uint8_t*)filter_out,
692 filter_out_len) != SRD_OK)
696 if (o->format->data && packet->type == o->format->df_type)
697 o->format->data(o, filter_out, filter_out_len, &output_buf, &output_len);
699 fwrite(output_buf, 1, output_len, outfile);
707 received_samples += logic->length / sample_size;
710 case SR_DF_META_ANALOG:
711 g_message("cli: Received SR_DF_META_ANALOG");
712 meta_analog = packet->payload;
713 num_analog_probes = meta_analog->num_probes;
714 num_enabled_analog_probes = 0;
715 for (i = 0; i < num_analog_probes; i++) {
716 probe = g_slist_nth_data(sdi->probes, i);
718 analog_probelist[num_enabled_analog_probes++] = probe;
722 if (opt_output_file) {
723 if (default_output_format) {
724 /* output file is in session format, which means we'll
725 * dump everything in the datastore as it comes in,
726 * and save from there after the session. */
728 ret = sr_datastore_new(unitsize, &(dev->datastore));
730 printf("Failed to create datastore.\n");
734 /* saving to a file in whatever format was set
735 * with --format, so all we need is a filehandle */
736 outfile = g_fopen(opt_output_file, "wb");
742 analog = packet->payload;
743 g_message("cli: received SR_DF_ANALOG, %d samples", analog->num_samples);
744 if (analog->num_samples == 0)
747 if (limit_samples && received_samples >= limit_samples)
750 if (o->format->data && packet->type == o->format->df_type) {
751 o->format->data(o, (const uint8_t *)analog->data,
752 analog->num_samples * sizeof(float),
753 &output_buf, &output_len);
755 fwrite(output_buf, 1, output_len, outfile);
761 received_samples += analog->num_samples;
764 case SR_DF_FRAME_BEGIN:
765 g_debug("cli: received SR_DF_FRAME_BEGIN");
766 if (o->format->event) {
767 o->format->event(o, SR_DF_FRAME_BEGIN, &output_buf,
770 fwrite(output_buf, 1, output_len, outfile);
777 case SR_DF_FRAME_END:
778 g_debug("cli: received SR_DF_FRAME_END");
779 if (o->format->event) {
780 o->format->event(o, SR_DF_FRAME_END, &output_buf,
783 fwrite(output_buf, 1, output_len, outfile);
791 g_message("received unknown packet type %d", packet->type);
796 /* Register the given PDs for this session.
797 * Accepts a string of the form: "spi:sck=3:sdata=4,spi:sck=3:sdata=5"
798 * That will instantiate two SPI decoders on the clock but different data
801 static int register_pds(struct sr_dev *dev, const char *pdstring)
803 GHashTable *pd_opthash;
804 struct srd_decoder_inst *di;
806 char **pdtokens, **pdtok, *pd_name;
808 /* Avoid compiler warnings. */
812 pd_ann_visible = g_hash_table_new_full(g_str_hash, g_int_equal,
816 pdtokens = g_strsplit(pdstring, ",", 0);
817 for (pdtok = pdtokens; *pdtok; pdtok++) {
818 if (!(pd_opthash = parse_generic_arg(*pdtok, TRUE))) {
819 g_critical("Invalid protocol decoder option '%s'.", *pdtok);
823 pd_name = g_strdup(g_hash_table_lookup(pd_opthash, "sigrok_key"));
824 g_hash_table_remove(pd_opthash, "sigrok_key");
825 if (srd_decoder_load(pd_name) != SRD_OK) {
826 g_critical("Failed to load protocol decoder %s.", pd_name);
830 if (!(di = srd_inst_new(pd_name, pd_opthash))) {
831 g_critical("Failed to instantiate protocol decoder %s.", pd_name);
836 /* If no annotation list was specified, add them all in now.
837 * This will be pared down later to leave only the last PD
840 if (!opt_pd_annotations)
841 g_hash_table_insert(pd_ann_visible,
842 g_strdup(di->inst_id), NULL);
844 /* Any keys left in the options hash are probes, where the key
845 * is the probe name as specified in the decoder class, and the
846 * value is the probe number i.e. the order in which the PD's
847 * incoming samples are arranged. */
848 if (srd_inst_probe_set_all(di, pd_opthash) != SRD_OK) {
852 g_hash_table_destroy(pd_opthash);
857 g_strfreev(pdtokens);
859 g_hash_table_destroy(pd_opthash);
866 int setup_pd_stack(void)
868 struct srd_decoder_inst *di_from, *di_to;
872 /* Set up the protocol decoder stack. */
873 pds = g_strsplit(opt_pds, ",", 0);
874 if (g_strv_length(pds) > 1) {
876 /* A stack setup was specified, use that. */
878 pds = g_strsplit(opt_pd_stack, ",", 0);
879 if (g_strv_length(pds) < 2) {
881 g_critical("Specify at least two protocol decoders to stack.");
886 /* First PD goes at the bottom of the stack. */
887 ids = g_strsplit(pds[0], ":", 0);
888 if (!(di_from = srd_inst_find_by_id(ids[0]))) {
890 g_critical("Cannot stack protocol decoder '%s': "
891 "instance not found.", pds[0]);
896 /* Every subsequent PD goes on top. */
897 for (i = 1; pds[i]; i++) {
898 ids = g_strsplit(pds[i], ":", 0);
899 if (!(di_to = srd_inst_find_by_id(ids[0]))) {
901 g_critical("Cannot stack protocol decoder '%s': "
902 "instance not found.", pds[i]);
906 if ((ret = srd_inst_stack(di_from, di_to)) != SRD_OK)
909 /* Don't show annotation from this PD. Only the last PD in
910 * the stack will be left on the annotation list (unless
911 * the annotation list was specifically provided).
913 if (!opt_pd_annotations)
914 g_hash_table_remove(pd_ann_visible,
925 int setup_pd_annotations(void)
928 struct srd_decoder *dec;
930 char **pds, **pdtok, **keyval, **ann_descr;
932 /* Set up custom list of PDs and annotations to show. */
933 if (opt_pd_annotations) {
934 pds = g_strsplit(opt_pd_annotations, ",", 0);
935 for (pdtok = pds; *pdtok && **pdtok; pdtok++) {
937 keyval = g_strsplit(*pdtok, "=", 0);
938 if (!(dec = srd_decoder_get_by_id(keyval[0]))) {
939 g_critical("Protocol decoder '%s' not found.", keyval[0]);
942 if (!dec->annotations) {
943 g_critical("Protocol decoder '%s' has no annotations.", keyval[0]);
946 if (g_strv_length(keyval) == 2) {
947 for (l = dec->annotations; l; l = l->next, ann++) {
949 if (!canon_cmp(ann_descr[0], keyval[1]))
954 g_critical("Annotation '%s' not found "
955 "for protocol decoder '%s'.", keyval[1], keyval[0]);
959 g_debug("cli: showing protocol decoder annotation %d from '%s'", ann, keyval[0]);
960 g_hash_table_insert(pd_ann_visible, g_strdup(keyval[0]), GINT_TO_POINTER(ann));
969 int setup_output_format(void)
974 struct sr_output_format **outputs;
978 if (!opt_output_format) {
979 opt_output_format = DEFAULT_OUTPUT_FORMAT;
980 /* we'll need to remember this so when saving to a file
981 * later, sigrok session format will be used.
983 default_output_format = TRUE;
986 fmtargs = parse_generic_arg(opt_output_format, TRUE);
987 fmtspec = g_hash_table_lookup(fmtargs, "sigrok_key");
989 g_critical("Invalid output format.");
992 outputs = sr_output_list();
993 for (i = 0; outputs[i]; i++) {
994 if (strcmp(outputs[i]->id, fmtspec))
996 g_hash_table_remove(fmtargs, "sigrok_key");
997 output_format = outputs[i];
998 g_hash_table_iter_init(&iter, fmtargs);
999 while (g_hash_table_iter_next(&iter, &key, &value)) {
1000 /* only supporting one parameter per output module
1001 * for now, and only its value */
1002 output_format_param = g_strdup(value);
1007 if (!output_format) {
1008 g_critical("Invalid output format %s.", opt_output_format);
1011 g_hash_table_destroy(fmtargs);
1016 void show_pd_annotations(struct srd_proto_data *pdata, void *cb_data)
1020 gpointer ann_format;
1022 /* 'cb_data' is not used in this specific callback. */
1025 if (!pd_ann_visible)
1028 if (!g_hash_table_lookup_extended(pd_ann_visible, pdata->pdo->di->inst_id,
1030 /* Not in the list of PDs whose annotations we're showing. */
1033 if (pdata->ann_format != GPOINTER_TO_INT(ann_format))
1034 /* We don't want this particular format from the PD. */
1037 annotations = pdata->data;
1038 if (opt_loglevel > SR_LOG_WARN)
1039 printf("%"PRIu64"-%"PRIu64" ", pdata->start_sample, pdata->end_sample);
1040 printf("%s: ", pdata->pdo->proto_id);
1041 for (i = 0; annotations[i]; i++)
1042 printf("\"%s\" ", annotations[i]);
1047 static int select_probes(struct sr_dev_inst *sdi)
1056 * This only works because a device by default initializes
1057 * and enables all its probes.
1059 max_probes = g_slist_length(sdi->probes);
1060 probelist = parse_probestring(max_probes, opt_probes);
1065 for (i = 0; i < max_probes; i++) {
1067 sr_dev_probe_name_set(sdi, i, probelist[i]);
1068 g_free(probelist[i]);
1070 sr_dev_probe_enable(sdi, i, FALSE);
1079 * Return the input file format which the CLI tool should use.
1081 * If the user specified -I / --input-format, use that one. Otherwise, try to
1082 * autodetect the format as good as possible. Failing that, return NULL.
1084 * @param filename The filename of the input file. Must not be NULL.
1085 * @param opt The -I / --input-file option the user specified (or NULL).
1087 * @return A pointer to the 'struct sr_input_format' that should be used,
1088 * or NULL if no input format was selected or auto-detected.
1090 static struct sr_input_format *determine_input_file_format(
1091 const char *filename, const char *opt)
1094 struct sr_input_format **inputs;
1096 /* If there are no input formats, return NULL right away. */
1097 inputs = sr_input_list();
1099 g_critical("No supported input formats available.");
1103 /* If the user specified -I / --input-format, use that one. */
1105 for (i = 0; inputs[i]; i++) {
1106 if (strcasecmp(inputs[i]->id, opt))
1108 g_debug("Using user-specified input file format '%s'.",
1113 /* The user specified an unknown input format, return NULL. */
1114 g_critical("Error: specified input file format '%s' is "
1119 /* Otherwise, try to find an input module that can handle this file. */
1120 for (i = 0; inputs[i]; i++) {
1121 if (inputs[i]->format_match(filename))
1125 /* Return NULL if no input module wanted to touch this. */
1127 g_critical("Error: no matching input module found.");
1131 g_debug("cli: Autodetected '%s' input format for file '%s'.",
1132 inputs[i]->id, filename);
1137 static void load_input_file_format(void)
1139 GHashTable *fmtargs = NULL;
1141 struct sr_input *in;
1142 struct sr_input_format *input_format;
1143 char *fmtspec = NULL;
1145 if (opt_input_format) {
1146 fmtargs = parse_generic_arg(opt_input_format);
1147 fmtspec = g_hash_table_lookup(fmtargs, "sigrok_key");
1150 if (!(input_format = determine_input_file_format(opt_input_file,
1152 /* The exact cause was already logged. */
1157 g_hash_table_remove(fmtargs, "sigrok_key");
1159 if (stat(opt_input_file, &st) == -1) {
1160 g_critical("Failed to load %s: %s", opt_input_file,
1165 /* Initialize the input module. */
1166 if (!(in = g_try_malloc(sizeof(struct sr_input)))) {
1167 g_critical("Failed to allocate input module.");
1170 in->format = input_format;
1171 in->param = fmtargs;
1172 if (in->format->init) {
1173 if (in->format->init(in) != SR_OK) {
1174 g_critical("Input format init failed.");
1179 if (select_probes(in->sdi) > 0)
1183 sr_session_datafeed_callback_add(datafeed_in);
1184 if (sr_session_dev_add(in->sdi) != SR_OK) {
1185 g_critical("Failed to use device.");
1186 sr_session_destroy();
1190 input_format->loadfile(in, opt_input_file);
1191 if (opt_output_file && default_output_format) {
1192 if (sr_session_save(opt_output_file) != SR_OK)
1193 g_critical("Failed to save session.");
1195 sr_session_destroy();
1198 g_hash_table_destroy(fmtargs);
1201 static void load_input_file(void)
1204 if (sr_session_load(opt_input_file) == SR_OK) {
1205 /* sigrok session file */
1206 sr_session_datafeed_callback_add(datafeed_in);
1212 /* fall back on input modules */
1213 load_input_file_format();
1217 static int set_dev_options(struct sr_dev_inst *sdi, GHashTable *args)
1219 GHashTableIter iter;
1220 gpointer key, value;
1224 struct sr_rational tmp_rat;
1229 g_hash_table_iter_init(&iter, args);
1230 while (g_hash_table_iter_next(&iter, &key, &value)) {
1232 for (i = 0; sr_hwcap_options[i].hwcap; i++) {
1233 if (strcmp(sr_hwcap_options[i].shortname, key))
1235 if ((value == NULL) &&
1236 (sr_hwcap_options[i].type != SR_T_BOOL)) {
1237 g_critical("Option '%s' needs a value.", (char *)key);
1242 switch (sr_hwcap_options[i].type) {
1244 ret = sr_parse_sizestring(value, &tmp_u64);
1256 tmp_bool = sr_parse_boolstring(value);
1260 tmp_float = strtof(value, NULL);
1263 case SR_T_RATIONAL_PERIOD:
1264 if ((ret = sr_parse_period(value, &tmp_rat)) != SR_OK)
1268 case SR_T_RATIONAL_VOLT:
1269 if ((ret = sr_parse_voltage(value, &tmp_rat)) != SR_OK)
1277 ret = sdi->driver->dev_config_set(sdi,
1278 sr_hwcap_options[i].hwcap, val);
1280 g_critical("Failed to set device option '%s'.", (char *)key);
1287 g_critical("Unknown device option '%s'.", (char *) key);
1295 static int set_limit_time(const struct sr_dev_inst *sdi)
1298 uint64_t *samplerate;
1300 time_msec = sr_parse_timestring(opt_time);
1301 if (time_msec == 0) {
1302 g_critical("Invalid time '%s'", opt_time);
1303 sr_session_destroy();
1307 if (sr_driver_hwcap_exists(sdi->driver, SR_HWCAP_LIMIT_MSEC)) {
1308 if (sdi->driver->dev_config_set(sdi,
1309 SR_HWCAP_LIMIT_MSEC, &time_msec) != SR_OK) {
1310 g_critical("Failed to configure time limit.");
1311 sr_session_destroy();
1316 /* time limit set, but device doesn't support this...
1317 * convert to samples based on the samplerate.
1320 if (sr_dev_has_hwcap(sdi, SR_HWCAP_SAMPLERATE)) {
1321 sr_info_get(sdi->driver, SR_DI_CUR_SAMPLERATE,
1322 (const void **)&samplerate, sdi);
1323 limit_samples = (*samplerate) * time_msec / (uint64_t)1000;
1325 if (limit_samples == 0) {
1326 g_critical("Not enough time at this samplerate.");
1327 sr_session_destroy();
1331 if (sdi->driver->dev_config_set(sdi,
1332 SR_HWCAP_LIMIT_SAMPLES, &limit_samples) != SR_OK) {
1333 g_critical("Failed to configure time-based sample limit.");
1334 sr_session_destroy();
1342 static void run_session(void)
1345 GHashTable *devargs;
1346 struct sr_dev_inst *sdi;
1350 devices = device_scan();
1352 g_critical("No devices found.");
1355 if (g_slist_length(devices) > 1) {
1356 g_critical("sigrok-cli only supports one device for capturing.");
1359 sdi = devices->data;
1362 sr_session_datafeed_callback_add(datafeed_in);
1365 if ((devargs = parse_generic_arg(opt_dev, FALSE))) {
1366 if (set_dev_options(sdi, devargs) != SR_OK)
1368 g_hash_table_destroy(devargs);
1372 if (sr_session_dev_add(sdi) != SR_OK) {
1373 g_critical("Failed to use device.");
1374 sr_session_destroy();
1378 if (select_probes(sdi) != SR_OK) {
1379 g_critical("Failed to set probes.");
1380 sr_session_destroy();
1385 if (!(triggerlist = sr_parse_triggerstring(sdi, opt_triggers))) {
1386 sr_session_destroy();
1389 max_probes = g_slist_length(sdi->probes);
1390 for (i = 0; i < max_probes; i++) {
1391 if (triggerlist[i]) {
1392 sr_dev_trigger_set(sdi, i, triggerlist[i]);
1393 g_free(triggerlist[i]);
1396 g_free(triggerlist);
1399 if (sdi->driver->dev_config_set(sdi, SR_HWCAP_PROBECONFIG,
1400 (char *)sdi->probes) != SR_OK) {
1401 g_critical("Failed to configure probes.");
1402 sr_session_destroy();
1406 if (opt_continuous) {
1407 if (!sr_driver_hwcap_exists(sdi->driver, SR_HWCAP_CONTINUOUS)) {
1408 g_critical("This device does not support continuous sampling.");
1409 sr_session_destroy();
1415 if (set_limit_time(sdi) != SR_OK) {
1416 sr_session_destroy();
1422 if ((sr_parse_sizestring(opt_samples, &limit_samples) != SR_OK)
1423 || (sdi->driver->dev_config_set(sdi, SR_HWCAP_LIMIT_SAMPLES,
1424 &limit_samples) != SR_OK)) {
1425 g_critical("Failed to configure sample limit.");
1426 sr_session_destroy();
1432 if ((sr_parse_sizestring(opt_frames, &limit_frames) != SR_OK)
1433 || (sdi->driver->dev_config_set(sdi,
1434 SR_HWCAP_LIMIT_FRAMES, &limit_frames) != SR_OK)) {
1435 printf("Failed to configure frame limit.\n");
1436 sr_session_destroy();
1441 if (sr_session_start() != SR_OK) {
1442 g_critical("Failed to start session.");
1443 sr_session_destroy();
1455 if (opt_output_file && default_output_format) {
1456 if (sr_session_save(opt_output_file) != SR_OK)
1457 g_critical("Failed to save session.");
1459 sr_session_destroy();
1460 g_slist_free(devices);
1464 static void logger(const gchar *log_domain, GLogLevelFlags log_level,
1465 const gchar *message, gpointer cb_data)
1467 /* Avoid compiler warnings. */
1472 * All messages, warnings, errors etc. go to stderr (not stdout) in
1473 * order to not mess up the CLI tool data output, e.g. VCD output.
1475 if (log_level & (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING)
1476 || opt_loglevel > SR_LOG_WARN) {
1477 fprintf(stderr, "%s\n", message);
1482 int main(int argc, char **argv)
1484 GOptionContext *context;
1487 g_log_set_default_handler(logger, NULL);
1490 context = g_option_context_new(NULL);
1491 g_option_context_add_main_entries(context, optargs, NULL);
1493 if (!g_option_context_parse(context, &argc, &argv, &error)) {
1494 g_critical("%s", error->message);
1498 /* Set the loglevel (amount of messages to output) for libsigrok. */
1499 if (sr_log_loglevel_set(opt_loglevel) != SR_OK)
1502 /* Set the loglevel (amount of messages to output) for libsigrokdecode. */
1503 if (srd_log_loglevel_set(opt_loglevel) != SRD_OK)
1506 if (sr_init() != SR_OK)
1510 if (srd_init(NULL) != SRD_OK)
1512 if (register_pds(NULL, opt_pds) != 0)
1514 if (srd_pd_output_callback_add(SRD_OUTPUT_ANN,
1515 show_pd_annotations, NULL) != SRD_OK)
1517 if (setup_pd_stack() != 0)
1519 if (setup_pd_annotations() != 0)
1523 if (setup_output_format() != 0)
1528 else if (opt_list_devs)
1534 else if (opt_input_file)
1536 else if (opt_samples || opt_time || opt_frames || opt_continuous)
1539 printf("%s", g_option_context_get_help(context, TRUE, NULL));
1544 g_option_context_free(context);