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 GByteArray *savebuf;
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;
69 static gchar *opt_set = NULL;
71 static GOptionEntry optargs[] = {
72 {"version", 'V', 0, G_OPTION_ARG_NONE, &opt_version,
73 "Show version and support list", NULL},
74 {"loglevel", 'l', 0, G_OPTION_ARG_INT, &opt_loglevel,
75 "Set libsigrok/libsigrokdecode loglevel", NULL},
76 {"list-devices", 'D', 0, G_OPTION_ARG_NONE, &opt_list_devs,
77 "Scan for devices", NULL},
78 {"driver", 0, 0, G_OPTION_ARG_STRING, &opt_drv,
79 "Use only this driver", NULL},
80 {"device", 'd', 0, G_OPTION_ARG_STRING, &opt_dev,
81 "Use specified device", NULL},
82 {"input-file", 'i', 0, G_OPTION_ARG_FILENAME, &opt_input_file,
83 "Load input from file", NULL},
84 {"input-format", 'I', 0, G_OPTION_ARG_STRING, &opt_input_format,
85 "Input format", NULL},
86 {"output-file", 'o', 0, G_OPTION_ARG_FILENAME, &opt_output_file,
87 "Save output to file", NULL},
88 {"output-format", 'O', 0, G_OPTION_ARG_STRING, &opt_output_format,
89 "Output format", NULL},
90 {"probes", 'p', 0, G_OPTION_ARG_STRING, &opt_probes,
91 "Probes to use", NULL},
92 {"triggers", 't', 0, G_OPTION_ARG_STRING, &opt_triggers,
93 "Trigger configuration", NULL},
94 {"wait-trigger", 'w', 0, G_OPTION_ARG_NONE, &opt_wait_trigger,
95 "Wait for trigger", NULL},
96 {"protocol-decoders", 'a', 0, G_OPTION_ARG_STRING, &opt_pds,
97 "Protocol decoders to run", NULL},
98 {"protocol-decoder-stack", 's', 0, G_OPTION_ARG_STRING, &opt_pd_stack,
99 "Protocol decoder stack", NULL},
100 {"protocol-decoder-annotations", 'A', 0, G_OPTION_ARG_STRING, &opt_pd_annotations,
101 "Protocol decoder annotation(s) to show", NULL},
102 {"show", 0, 0, G_OPTION_ARG_NONE, &opt_show,
103 "Show device detail", NULL},
104 {"time", 0, 0, G_OPTION_ARG_STRING, &opt_time,
105 "How long to sample (ms)", NULL},
106 {"samples", 0, 0, G_OPTION_ARG_STRING, &opt_samples,
107 "Number of samples to acquire", NULL},
108 {"frames", 0, 0, G_OPTION_ARG_STRING, &opt_frames,
109 "Number of frames to acquire", NULL},
110 {"continuous", 0, 0, G_OPTION_ARG_NONE, &opt_continuous,
111 "Sample continuously", NULL},
112 {"set", 0, 0, G_OPTION_ARG_NONE, &opt_set, "Set device options only", NULL},
113 {NULL, 0, 0, 0, NULL, NULL, NULL}
117 /* Convert driver options hash to GSList of struct sr_config. */
118 static GSList *hash_to_hwopt(GHashTable *hash)
120 const struct sr_config_info *srci;
121 struct sr_config *src;
126 keys = g_hash_table_get_keys(hash);
128 for (gl = keys; gl; gl = gl->next) {
130 if (!(srci = sr_config_info_name_get(key))) {
131 g_critical("Unknown option %s", key);
134 src = g_try_malloc(sizeof(struct sr_config));
135 src->key = srci->key;
136 value = g_hash_table_lookup(hash, key);
137 src->value = g_strdup(value);
138 opts = g_slist_append(opts, src);
145 static void free_drvopts(struct sr_config *src)
147 g_free((void *)src->value);
151 static GSList *device_scan(void)
153 struct sr_dev_driver **drivers, *driver;
155 GSList *drvopts, *devices, *tmpdevs, *l;
160 drvargs = parse_generic_arg(opt_drv, TRUE);
161 drvname = g_strdup(g_hash_table_lookup(drvargs, "sigrok_key"));
162 g_hash_table_remove(drvargs, "sigrok_key");
164 drivers = sr_driver_list();
165 for (i = 0; drivers[i]; i++) {
166 if (strcmp(drivers[i]->name, drvname))
171 g_critical("Driver %s not found.", drvname);
175 if (sr_driver_init(sr_ctx, driver) != SR_OK) {
176 g_critical("Failed to initialize driver.");
180 if (g_hash_table_size(drvargs) > 0)
181 if (!(drvopts = hash_to_hwopt(drvargs)))
182 /* Unknown options, already logged. */
184 devices = sr_driver_scan(driver, drvopts);
185 g_slist_free_full(drvopts, (GDestroyNotify)free_drvopts);
187 /* No driver specified, let them all scan on their own. */
189 drivers = sr_driver_list();
190 for (i = 0; drivers[i]; i++) {
192 if (sr_driver_init(sr_ctx, driver) != SR_OK) {
193 g_critical("Failed to initialize driver.");
196 tmpdevs = sr_driver_scan(driver, NULL);
197 for (l = tmpdevs; l; l = l->next)
198 devices = g_slist_append(devices, l->data);
199 g_slist_free(tmpdevs);
206 static void show_version(void)
209 struct sr_dev_driver **drivers;
210 struct sr_input_format **inputs;
211 struct sr_output_format **outputs;
212 struct srd_decoder *dec;
215 printf("sigrok-cli %s\n\n", VERSION);
217 printf("Using libsigrok %s (lib version %s).\n",
218 sr_package_version_string_get(), sr_lib_version_string_get());
219 printf("Using libsigrokdecode %s (lib version %s).\n\n",
220 srd_package_version_string_get(), srd_lib_version_string_get());
222 printf("Supported hardware drivers:\n");
223 drivers = sr_driver_list();
224 for (i = 0; drivers[i]; i++) {
225 printf(" %-20s %s\n", drivers[i]->name, drivers[i]->longname);
229 printf("Supported input formats:\n");
230 inputs = sr_input_list();
231 for (i = 0; inputs[i]; i++)
232 printf(" %-20s %s\n", inputs[i]->id, inputs[i]->description);
235 printf("Supported output formats:\n");
236 outputs = sr_output_list();
237 for (i = 0; outputs[i]; i++)
238 printf(" %-20s %s\n", outputs[i]->id, outputs[i]->description);
241 if (srd_init(NULL) == SRD_OK) {
242 printf("Supported protocol decoders:\n");
243 srd_decoder_load_all();
244 for (l = srd_decoder_list(); l; l = l->next) {
246 printf(" %-20s %s\n", dec->id, dec->longname);
247 /* Print protocol description upon "-l 3" or higher. */
248 if (opt_loglevel >= SR_LOG_INFO)
249 printf(" %-20s %s\n", "", dec->desc);
256 static void print_dev_line(const struct sr_dev_inst *sdi)
258 struct sr_probe *probe;
261 if (sdi->vendor && sdi->vendor[0])
262 printf("%s ", sdi->vendor);
263 if (sdi->model && sdi->model[0])
264 printf("%s ", sdi->model);
265 if (sdi->version && sdi->version[0])
266 printf("%s ", sdi->version);
268 if (g_slist_length(sdi->probes) == 1) {
269 probe = sdi->probes->data;
270 printf("with 1 probe: %s", probe->name);
272 printf("with %d probes:", g_slist_length(sdi->probes));
273 for (l = sdi->probes; l; l = l->next) {
275 printf(" %s", probe->name);
282 static void show_dev_list(void)
284 struct sr_dev_inst *sdi;
287 if (!(devices = device_scan()))
290 printf("The following devices were found:\n");
291 for (l = devices; l; l = l->next) {
295 g_slist_free(devices);
299 static void show_dev_detail(void)
301 struct sr_dev_inst *sdi;
302 const struct sr_config_info *srci;
303 const struct sr_samplerates *samplerates;
304 struct sr_rational *rationals;
307 const int *hwopts, *hwcaps;
308 int cap, num_devices, *tmp_bool, i;
310 const char *charopts, **stropts;
312 if (!(devices = device_scan())) {
313 g_critical("No devices found.");
317 num_devices = g_slist_length(devices);
318 if (num_devices > 1) {
319 g_critical("%d devices found. Use --list-devices to show them, "
320 "and --device to select one.", num_devices);
327 /* This properly opens and initializes the device, so we can get
328 * current settings. */
330 if (sr_session_dev_add(sdi) != SR_OK) {
331 g_critical("Failed to use device.");
335 if (sr_config_list(sdi->driver, SR_CONF_TRIGGER_TYPE, (const void **)&charopts,
336 sdi) == SR_OK && charopts) {
337 printf("Supported triggers: ");
339 printf("%c ", *charopts);
345 if ((sr_config_list(sdi->driver, SR_CONF_SCAN_OPTIONS, (const void **)&hwopts,
346 NULL) == SR_OK) && hwopts) {
347 printf("Supported driver options:\n");
348 for (i = 0; hwopts[i]; i++) {
349 if (!(srci = sr_config_info_get(hwopts[i])))
351 printf(" %s\n", srci->id);
355 title = "Supported device options:\n";
356 if ((sr_config_list(sdi->driver, SR_CONF_DEVICE_OPTIONS, (const void **)&hwcaps,
357 NULL) != SR_OK) || !hwcaps)
358 /* Driver supports no device instance options. */
361 for (cap = 0; hwcaps[cap]; cap++) {
362 if (!(srci = sr_config_info_get(hwcaps[cap])))
370 if (srci->key == SR_CONF_PATTERN_MODE) {
371 /* Pattern generator modes */
372 printf(" %s", srci->id);
373 if (sr_config_list(sdi->driver, SR_CONF_PATTERN_MODE,
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 (srci->key == SR_CONF_SAMPLERATE) {
383 /* Supported samplerates */
384 printf(" %s", srci->id);
385 if (sr_config_list(sdi->driver, SR_CONF_SAMPLERATE,
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 (srci->key == SR_CONF_BUFFERSIZE) {
413 /* Supported buffer sizes */
414 printf(" %s", srci->id);
415 if (sr_config_list(sdi->driver, SR_CONF_BUFFERSIZE,
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 (srci->key == SR_CONF_TIMEBASE) {
425 /* Supported time bases */
426 printf(" %s", srci->id);
427 if (sr_config_list(sdi->driver, SR_CONF_TIMEBASE,
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 (srci->key == SR_CONF_TRIGGER_SOURCE) {
438 /* Supported trigger sources */
439 printf(" %s", srci->id);
440 if (sr_config_list(sdi->driver, SR_CONF_TRIGGER_SOURCE,
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 (srci->key == SR_CONF_FILTER) {
450 /* Supported filters */
451 printf(" %s", srci->id);
452 if (sr_config_list(sdi->driver, SR_CONF_FILTER,
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 (srci->key == SR_CONF_VDIV) {
462 /* Supported volts/div values */
463 printf(" %s", srci->id);
464 if (sr_config_list(sdi->driver, SR_CONF_VDIV,
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 (srci->key == SR_CONF_COUPLING) {
474 /* Supported coupling settings */
475 printf(" %s", srci->id);
476 if (sr_config_list(sdi->driver, SR_CONF_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]);
485 } else if (srci->key == SR_CONF_DATALOG) {
486 /* Turning on/off internal data logging. */
487 printf(" %s\t(on/off", srci->id);
488 if (sr_config_get(sdi->driver, SR_CONF_DATALOG,
489 (const void **)&tmp_bool, sdi) == SR_OK) {
490 printf(", currently %s", *tmp_bool ? "on" : "off");
494 /* Everything else */
495 printf(" %s\n", srci->id);
499 sr_session_destroy();
503 static void show_pd_detail(void)
506 struct srd_decoder *dec;
507 char **pdtokens, **pdtok, **ann, *doc;
510 pdtokens = g_strsplit(opt_pds, ",", -1);
511 for (pdtok = pdtokens; *pdtok; pdtok++) {
512 if (!(dec = srd_decoder_get_by_id(*pdtok))) {
513 g_critical("Protocol decoder %s not found.", *pdtok);
516 printf("ID: %s\nName: %s\nLong name: %s\nDescription: %s\n",
517 dec->id, dec->name, dec->longname, dec->desc);
518 printf("License: %s\n", dec->license);
519 printf("Annotations:\n");
520 if (dec->annotations) {
521 for (l = dec->annotations; l; l = l->next) {
523 printf("- %s\n %s\n", ann[0], ann[1]);
528 /* TODO: Print supported decoder options. */
529 printf("Required probes:\n");
531 for (l = dec->probes; l; l = l->next) {
533 printf("- %s (%s): %s\n",
534 p->name, p->id, p->desc);
539 printf("Optional probes:\n");
540 if (dec->opt_probes) {
541 for (l = dec->opt_probes; l; l = l->next) {
543 printf("- %s (%s): %s\n",
544 p->name, p->id, p->desc);
549 if ((doc = srd_decoder_doc_get(dec))) {
550 printf("Documentation:\n%s\n",
551 doc[0] == '\n' ? doc + 1 : doc);
556 g_strfreev(pdtokens);
559 static GArray *get_enabled_logic_probes(const struct sr_dev_inst *sdi)
561 struct sr_probe *probe;
565 probes = g_array_new(FALSE, FALSE, sizeof(int));
566 for (l = sdi->probes; l; l = l->next) {
568 if (probe->type != SR_PROBE_LOGIC)
570 if (probe->enabled != TRUE)
572 g_array_append_val(probes, probe->index);
578 static void datafeed_in(const struct sr_dev_inst *sdi,
579 const struct sr_datafeed_packet *packet)
581 const struct sr_datafeed_meta *meta;
582 const struct sr_datafeed_logic *logic;
583 const struct sr_datafeed_analog *analog;
584 struct sr_config *src;
585 static struct sr_output *o = NULL;
586 static GArray *logic_probelist = NULL;
587 static uint64_t received_samples = 0;
588 static int unitsize = 0;
589 static int triggered = 0;
590 static FILE *outfile = NULL;
591 int sample_size, ret;
592 uint64_t *samplerate, output_len, filter_out_len;
593 uint8_t *output_buf, *filter_out;
597 /* If the first packet to come in isn't a header, don't even try. */
598 if (packet->type != SR_DF_HEADER && o == NULL)
602 switch (packet->type) {
604 g_debug("cli: Received SR_DF_HEADER");
605 /* Initialize the output module. */
606 if (!(o = g_try_malloc(sizeof(struct sr_output)))) {
607 g_critical("Output module malloc failed.");
610 o->format = output_format;
611 o->sdi = (struct sr_dev_inst *)sdi;
612 o->param = output_format_param;
613 if (o->format->init) {
614 if (o->format->init(o) != SR_OK) {
615 g_critical("Output format initialization failed.");
620 /* Prepare non-stdout output. */
622 if (opt_output_file) {
623 if (default_output_format) {
624 /* output file is in session format, so we'll
625 * keep a copy of everything as it comes in
626 * and save from there after the session. */
628 savebuf = g_byte_array_new();
630 /* saving to a file in whatever format was set
631 * with --format, so all we need is a filehandle */
632 outfile = g_fopen(opt_output_file, "wb");
636 /* Prepare for logic data. */
637 logic_probelist = get_enabled_logic_probes(sdi);
638 /* How many bytes we need to store the packed samples. */
639 unitsize = (logic_probelist->len + 7) / 8;
641 if (opt_pds && logic_probelist->len) {
642 if (sr_config_get(sdi->driver, SR_CONF_SAMPLERATE,
643 (const void **)&samplerate, sdi) != SR_OK) {
644 g_critical("Unable to initialize protocol "
645 "decoders: no samplerate found.");
648 srd_session_start(logic_probelist->len, unitsize,
654 g_debug("cli: received SR_DF_META");
655 meta = packet->payload;
656 for (l = meta->config; l; l = l->next) {
659 case SR_CONF_SAMPLERATE:
660 samplerate = (uint64_t *)src->value;
661 g_debug("cli: got samplerate %"PRIu64, *samplerate);
664 /* Unknown metadata is not an error. */
671 g_debug("cli: received SR_DF_TRIGGER");
672 if (o->format->event)
673 o->format->event(o, SR_DF_TRIGGER, &output_buf,
679 logic = packet->payload;
680 g_message("cli: received SR_DF_LOGIC, %"PRIu64" bytes", logic->length);
681 sample_size = logic->unitsize;
682 if (logic->length == 0)
685 /* Don't store any samples until triggered. */
686 if (opt_wait_trigger && !triggered)
689 if (limit_samples && received_samples >= limit_samples)
692 ret = sr_filter_probes(sample_size, unitsize, logic_probelist,
693 logic->data, logic->length,
694 &filter_out, &filter_out_len);
698 /* What comes out of the filter is guaranteed to be packed into the
699 * minimum size needed to support the number of samples at this sample
700 * size. however, the driver may have submitted too much -- cut off
701 * the buffer of the last packet according to the sample limit.
703 if (limit_samples && (received_samples + logic->length / sample_size >
704 limit_samples * sample_size))
705 filter_out_len = limit_samples * sample_size - received_samples;
707 if (opt_output_file && default_output_format) {
708 /* Saving to a session file. */
709 g_byte_array_append(savebuf, filter_out, filter_out_len);
712 if (srd_session_send(received_samples, (uint8_t*)filter_out,
713 filter_out_len) != SRD_OK)
717 if (o->format->data && packet->type == o->format->df_type)
718 o->format->data(o, filter_out, filter_out_len,
719 &output_buf, &output_len);
721 fwrite(output_buf, 1, output_len, outfile);
729 received_samples += logic->length / sample_size;
733 analog = packet->payload;
734 g_message("cli: received SR_DF_ANALOG, %d samples", analog->num_samples);
735 if (analog->num_samples == 0)
738 if (limit_samples && received_samples >= limit_samples)
741 if (o->format->data && packet->type == o->format->df_type) {
742 o->format->data(o, (const uint8_t *)analog->data,
743 analog->num_samples * sizeof(float),
744 &output_buf, &output_len);
746 fwrite(output_buf, 1, output_len, outfile);
752 received_samples += analog->num_samples;
755 case SR_DF_FRAME_BEGIN:
756 g_debug("cli: received SR_DF_FRAME_BEGIN");
757 if (o->format->event) {
758 o->format->event(o, SR_DF_FRAME_BEGIN, &output_buf,
761 fwrite(output_buf, 1, output_len, outfile);
768 case SR_DF_FRAME_END:
769 g_debug("cli: received SR_DF_FRAME_END");
770 if (o->format->event) {
771 o->format->event(o, SR_DF_FRAME_END, &output_buf,
774 fwrite(output_buf, 1, output_len, outfile);
785 if (o && o->format->recv) {
786 out = o->format->recv(o, sdi, packet);
787 if (out && out->len) {
788 fwrite(out->str, 1, out->len, outfile);
793 /* SR_DF_END needs to be handled after the output module's recv()
794 * is called, so it can properly clean up that module etc. */
795 if (packet->type == SR_DF_END) {
796 g_debug("cli: Received SR_DF_END");
798 if (o->format->event) {
799 o->format->event(o, SR_DF_END, &output_buf, &output_len);
802 fwrite(output_buf, 1, output_len, outfile);
808 if (limit_samples && received_samples < limit_samples)
809 g_warning("Device only sent %" PRIu64 " samples.",
813 g_warning("Device stopped after %" PRIu64 " samples.",
816 g_array_free(logic_probelist, TRUE);
818 if (o->format->cleanup)
819 o->format->cleanup(o);
823 if (outfile && outfile != stdout)
826 if (opt_output_file && default_output_format) {
827 if (sr_session_save(opt_output_file, sdi, savebuf->data,
828 unitsize, savebuf->len / unitsize) != SR_OK)
829 g_critical("Failed to save session.");
830 g_byte_array_free(savebuf, FALSE);
836 /* Register the given PDs for this session.
837 * Accepts a string of the form: "spi:sck=3:sdata=4,spi:sck=3:sdata=5"
838 * That will instantiate two SPI decoders on the clock but different data
841 static int register_pds(struct sr_dev *dev, const char *pdstring)
843 GHashTable *pd_opthash;
844 struct srd_decoder_inst *di;
846 char **pdtokens, **pdtok, *pd_name;
851 pd_ann_visible = g_hash_table_new_full(g_str_hash, g_int_equal,
855 pdtokens = g_strsplit(pdstring, ",", 0);
856 for (pdtok = pdtokens; *pdtok; pdtok++) {
857 if (!(pd_opthash = parse_generic_arg(*pdtok, TRUE))) {
858 g_critical("Invalid protocol decoder option '%s'.", *pdtok);
862 pd_name = g_strdup(g_hash_table_lookup(pd_opthash, "sigrok_key"));
863 g_hash_table_remove(pd_opthash, "sigrok_key");
864 if (srd_decoder_load(pd_name) != SRD_OK) {
865 g_critical("Failed to load protocol decoder %s.", pd_name);
869 if (!(di = srd_inst_new(pd_name, pd_opthash))) {
870 g_critical("Failed to instantiate protocol decoder %s.", pd_name);
875 /* If no annotation list was specified, add them all in now.
876 * This will be pared down later to leave only the last PD
879 if (!opt_pd_annotations)
880 g_hash_table_insert(pd_ann_visible,
881 g_strdup(di->inst_id), NULL);
883 /* Any keys left in the options hash are probes, where the key
884 * is the probe name as specified in the decoder class, and the
885 * value is the probe number i.e. the order in which the PD's
886 * incoming samples are arranged. */
887 if (srd_inst_probe_set_all(di, pd_opthash) != SRD_OK) {
891 g_hash_table_destroy(pd_opthash);
896 g_strfreev(pdtokens);
898 g_hash_table_destroy(pd_opthash);
905 int setup_pd_stack(void)
907 struct srd_decoder_inst *di_from, *di_to;
911 /* Set up the protocol decoder stack. */
912 pds = g_strsplit(opt_pds, ",", 0);
913 if (g_strv_length(pds) > 1) {
915 /* A stack setup was specified, use that. */
917 pds = g_strsplit(opt_pd_stack, ",", 0);
918 if (g_strv_length(pds) < 2) {
920 g_critical("Specify at least two protocol decoders to stack.");
925 /* First PD goes at the bottom of the stack. */
926 ids = g_strsplit(pds[0], ":", 0);
927 if (!(di_from = srd_inst_find_by_id(ids[0]))) {
929 g_critical("Cannot stack protocol decoder '%s': "
930 "instance not found.", pds[0]);
935 /* Every subsequent PD goes on top. */
936 for (i = 1; pds[i]; i++) {
937 ids = g_strsplit(pds[i], ":", 0);
938 if (!(di_to = srd_inst_find_by_id(ids[0]))) {
940 g_critical("Cannot stack protocol decoder '%s': "
941 "instance not found.", pds[i]);
945 if ((ret = srd_inst_stack(di_from, di_to)) != SRD_OK)
948 /* Don't show annotation from this PD. Only the last PD in
949 * the stack will be left on the annotation list (unless
950 * the annotation list was specifically provided).
952 if (!opt_pd_annotations)
953 g_hash_table_remove(pd_ann_visible,
964 int setup_pd_annotations(void)
967 struct srd_decoder *dec;
969 char **pds, **pdtok, **keyval, **ann_descr;
971 /* Set up custom list of PDs and annotations to show. */
972 if (opt_pd_annotations) {
973 pds = g_strsplit(opt_pd_annotations, ",", 0);
974 for (pdtok = pds; *pdtok && **pdtok; pdtok++) {
976 keyval = g_strsplit(*pdtok, "=", 0);
977 if (!(dec = srd_decoder_get_by_id(keyval[0]))) {
978 g_critical("Protocol decoder '%s' not found.", keyval[0]);
981 if (!dec->annotations) {
982 g_critical("Protocol decoder '%s' has no annotations.", keyval[0]);
985 if (g_strv_length(keyval) == 2) {
986 for (l = dec->annotations; l; l = l->next, ann++) {
988 if (!canon_cmp(ann_descr[0], keyval[1]))
993 g_critical("Annotation '%s' not found "
994 "for protocol decoder '%s'.", keyval[1], keyval[0]);
998 g_debug("cli: showing protocol decoder annotation %d from '%s'", ann, keyval[0]);
999 g_hash_table_insert(pd_ann_visible, g_strdup(keyval[0]), GINT_TO_POINTER(ann));
1008 int setup_output_format(void)
1010 GHashTable *fmtargs;
1011 GHashTableIter iter;
1012 gpointer key, value;
1013 struct sr_output_format **outputs;
1017 if (!opt_output_format) {
1018 opt_output_format = DEFAULT_OUTPUT_FORMAT;
1019 /* we'll need to remember this so when saving to a file
1020 * later, sigrok session format will be used.
1022 default_output_format = TRUE;
1025 fmtargs = parse_generic_arg(opt_output_format, TRUE);
1026 fmtspec = g_hash_table_lookup(fmtargs, "sigrok_key");
1028 g_critical("Invalid output format.");
1031 outputs = sr_output_list();
1032 for (i = 0; outputs[i]; i++) {
1033 if (strcmp(outputs[i]->id, fmtspec))
1035 g_hash_table_remove(fmtargs, "sigrok_key");
1036 output_format = outputs[i];
1037 g_hash_table_iter_init(&iter, fmtargs);
1038 while (g_hash_table_iter_next(&iter, &key, &value)) {
1039 /* only supporting one parameter per output module
1040 * for now, and only its value */
1041 output_format_param = g_strdup(value);
1046 if (!output_format) {
1047 g_critical("Invalid output format %s.", opt_output_format);
1050 g_hash_table_destroy(fmtargs);
1055 void show_pd_annotations(struct srd_proto_data *pdata, void *cb_data)
1059 gpointer ann_format;
1061 /* 'cb_data' is not used in this specific callback. */
1064 if (!pd_ann_visible)
1067 if (!g_hash_table_lookup_extended(pd_ann_visible, pdata->pdo->di->inst_id,
1069 /* Not in the list of PDs whose annotations we're showing. */
1072 if (pdata->ann_format != GPOINTER_TO_INT(ann_format))
1073 /* We don't want this particular format from the PD. */
1076 annotations = pdata->data;
1077 if (opt_loglevel > SR_LOG_WARN)
1078 printf("%"PRIu64"-%"PRIu64" ", pdata->start_sample, pdata->end_sample);
1079 printf("%s: ", pdata->pdo->proto_id);
1080 for (i = 0; annotations[i]; i++)
1081 printf("\"%s\" ", annotations[i]);
1086 static int select_probes(struct sr_dev_inst *sdi)
1088 struct sr_probe *probe;
1089 GSList *selected_probes, *l;
1094 if (!(selected_probes = parse_probestring(sdi, opt_probes)))
1097 for (l = sdi->probes; l; l = l->next) {
1099 if (g_slist_find(selected_probes, probe))
1100 probe->enabled = TRUE;
1102 probe->enabled = FALSE;
1104 g_slist_free(selected_probes);
1110 * Return the input file format which the CLI tool should use.
1112 * If the user specified -I / --input-format, use that one. Otherwise, try to
1113 * autodetect the format as good as possible. Failing that, return NULL.
1115 * @param filename The filename of the input file. Must not be NULL.
1116 * @param opt The -I / --input-file option the user specified (or NULL).
1118 * @return A pointer to the 'struct sr_input_format' that should be used,
1119 * or NULL if no input format was selected or auto-detected.
1121 static struct sr_input_format *determine_input_file_format(
1122 const char *filename, const char *opt)
1125 struct sr_input_format **inputs;
1127 /* If there are no input formats, return NULL right away. */
1128 inputs = sr_input_list();
1130 g_critical("No supported input formats available.");
1134 /* If the user specified -I / --input-format, use that one. */
1136 for (i = 0; inputs[i]; i++) {
1137 if (strcasecmp(inputs[i]->id, opt))
1139 g_debug("Using user-specified input file format '%s'.",
1144 /* The user specified an unknown input format, return NULL. */
1145 g_critical("Error: specified input file format '%s' is "
1150 /* Otherwise, try to find an input module that can handle this file. */
1151 for (i = 0; inputs[i]; i++) {
1152 if (inputs[i]->format_match(filename))
1156 /* Return NULL if no input module wanted to touch this. */
1158 g_critical("Error: no matching input module found.");
1162 g_debug("cli: Autodetected '%s' input format for file '%s'.",
1163 inputs[i]->id, filename);
1168 static void load_input_file_format(void)
1170 GHashTable *fmtargs = NULL;
1172 struct sr_input *in;
1173 struct sr_input_format *input_format;
1174 char *fmtspec = NULL;
1176 if (opt_input_format) {
1177 fmtargs = parse_generic_arg(opt_input_format, TRUE);
1178 fmtspec = g_hash_table_lookup(fmtargs, "sigrok_key");
1181 if (!(input_format = determine_input_file_format(opt_input_file,
1183 /* The exact cause was already logged. */
1188 g_hash_table_remove(fmtargs, "sigrok_key");
1190 if (stat(opt_input_file, &st) == -1) {
1191 g_critical("Failed to load %s: %s", opt_input_file,
1196 /* Initialize the input module. */
1197 if (!(in = g_try_malloc(sizeof(struct sr_input)))) {
1198 g_critical("Failed to allocate input module.");
1201 in->format = input_format;
1202 in->param = fmtargs;
1203 if (in->format->init) {
1204 if (in->format->init(in, opt_input_file) != SR_OK) {
1205 g_critical("Input format init failed.");
1210 if (select_probes(in->sdi) > 0)
1214 sr_session_datafeed_callback_add(datafeed_in);
1215 if (sr_session_dev_add(in->sdi) != SR_OK) {
1216 g_critical("Failed to use device.");
1217 sr_session_destroy();
1221 input_format->loadfile(in, opt_input_file);
1223 sr_session_destroy();
1226 g_hash_table_destroy(fmtargs);
1229 static void load_input_file(void)
1232 if (sr_session_load(opt_input_file) == SR_OK) {
1233 /* sigrok session file */
1234 sr_session_datafeed_callback_add(datafeed_in);
1240 /* fall back on input modules */
1241 load_input_file_format();
1245 static int set_dev_options(struct sr_dev_inst *sdi, GHashTable *args)
1247 const struct sr_config_info *srci;
1248 GHashTableIter iter;
1249 gpointer key, value;
1253 struct sr_rational tmp_rat;
1257 g_hash_table_iter_init(&iter, args);
1258 while (g_hash_table_iter_next(&iter, &key, &value)) {
1259 if (!(srci = sr_config_info_name_get(key))) {
1260 g_critical("Unknown device option '%s'.", (char *) key);
1264 if ((value == NULL) &&
1265 (srci->datatype != SR_T_BOOL)) {
1266 g_critical("Option '%s' needs a value.", (char *)key);
1270 switch (srci->datatype) {
1272 ret = sr_parse_sizestring(value, &tmp_u64);
1284 tmp_bool = sr_parse_boolstring(value);
1288 tmp_float = strtof(value, NULL);
1291 case SR_T_RATIONAL_PERIOD:
1292 if ((ret = sr_parse_period(value, &tmp_rat)) != SR_OK)
1296 case SR_T_RATIONAL_VOLT:
1297 if ((ret = sr_parse_voltage(value, &tmp_rat)) != SR_OK)
1305 ret = sr_config_set(sdi, srci->key, val);
1307 g_critical("Failed to set device option '%s'.", (char *)key);
1315 static void set_options(void)
1317 struct sr_dev_inst *sdi;
1319 GHashTable *devargs;
1322 g_critical("No setting specified.");
1326 if (!(devargs = parse_generic_arg(opt_dev, FALSE)))
1329 if (!(devices = device_scan())) {
1330 g_critical("No devices found.");
1333 sdi = devices->data;
1336 if (sr_session_dev_add(sdi) != SR_OK) {
1337 g_critical("Failed to use device.");
1341 set_dev_options(sdi, devargs);
1343 sr_session_destroy();
1344 g_slist_free(devices);
1345 g_hash_table_destroy(devargs);
1349 static int set_limit_time(const struct sr_dev_inst *sdi)
1352 uint64_t *samplerate;
1354 time_msec = sr_parse_timestring(opt_time);
1355 if (time_msec == 0) {
1356 g_critical("Invalid time '%s'", opt_time);
1357 sr_session_destroy();
1361 if (sr_dev_has_option(sdi, SR_CONF_LIMIT_MSEC)) {
1362 if (sr_config_set(sdi, SR_CONF_LIMIT_MSEC, &time_msec) != SR_OK) {
1363 g_critical("Failed to configure time limit.");
1364 sr_session_destroy();
1369 /* time limit set, but device doesn't support this...
1370 * convert to samples based on the samplerate.
1373 if (sr_dev_has_option(sdi, SR_CONF_SAMPLERATE)) {
1374 sr_config_get(sdi->driver, SR_CONF_SAMPLERATE,
1375 (const void **)&samplerate, sdi);
1376 limit_samples = (*samplerate) * time_msec / (uint64_t)1000;
1378 if (limit_samples == 0) {
1379 g_critical("Not enough time at this samplerate.");
1380 sr_session_destroy();
1384 if (sr_config_set(sdi, SR_CONF_LIMIT_SAMPLES,
1385 &limit_samples) != SR_OK) {
1386 g_critical("Failed to configure time-based sample limit.");
1387 sr_session_destroy();
1395 static void run_session(void)
1398 GHashTable *devargs;
1399 struct sr_dev_inst *sdi;
1403 devices = device_scan();
1405 g_critical("No devices found.");
1408 if (g_slist_length(devices) > 1) {
1409 g_critical("sigrok-cli only supports one device for capturing.");
1412 sdi = devices->data;
1415 sr_session_datafeed_callback_add(datafeed_in);
1417 if (sr_session_dev_add(sdi) != SR_OK) {
1418 g_critical("Failed to use device.");
1419 sr_session_destroy();
1424 if ((devargs = parse_generic_arg(opt_dev, FALSE))) {
1425 if (set_dev_options(sdi, devargs) != SR_OK)
1427 g_hash_table_destroy(devargs);
1431 if (select_probes(sdi) != SR_OK) {
1432 g_critical("Failed to set probes.");
1433 sr_session_destroy();
1438 if (!(triggerlist = sr_parse_triggerstring(sdi, opt_triggers))) {
1439 sr_session_destroy();
1442 max_probes = g_slist_length(sdi->probes);
1443 for (i = 0; i < max_probes; i++) {
1444 if (triggerlist[i]) {
1445 sr_dev_trigger_set(sdi, i, triggerlist[i]);
1446 g_free(triggerlist[i]);
1449 g_free(triggerlist);
1452 if (opt_continuous) {
1453 if (!sr_dev_has_option(sdi, SR_CONF_CONTINUOUS)) {
1454 g_critical("This device does not support continuous sampling.");
1455 sr_session_destroy();
1461 if (set_limit_time(sdi) != SR_OK) {
1462 sr_session_destroy();
1468 if ((sr_parse_sizestring(opt_samples, &limit_samples) != SR_OK)
1469 || (sr_config_set(sdi, SR_CONF_LIMIT_SAMPLES,
1470 &limit_samples) != SR_OK)) {
1471 g_critical("Failed to configure sample limit.");
1472 sr_session_destroy();
1478 if ((sr_parse_sizestring(opt_frames, &limit_frames) != SR_OK)
1479 || (sr_config_set(sdi, SR_CONF_LIMIT_FRAMES,
1480 &limit_frames) != SR_OK)) {
1481 g_critical("Failed to configure frame limit.");
1482 sr_session_destroy();
1487 if (sr_session_start() != SR_OK) {
1488 g_critical("Failed to start session.");
1489 sr_session_destroy();
1501 sr_session_destroy();
1502 g_slist_free(devices);
1506 static void logger(const gchar *log_domain, GLogLevelFlags log_level,
1507 const gchar *message, gpointer cb_data)
1513 * All messages, warnings, errors etc. go to stderr (not stdout) in
1514 * order to not mess up the CLI tool data output, e.g. VCD output.
1516 if (log_level & (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING)
1517 || opt_loglevel > SR_LOG_WARN) {
1518 fprintf(stderr, "%s\n", message);
1523 int main(int argc, char **argv)
1526 GOptionContext *context;
1529 g_log_set_default_handler(logger, NULL);
1532 context = g_option_context_new(NULL);
1533 g_option_context_add_main_entries(context, optargs, NULL);
1535 if (!g_option_context_parse(context, &argc, &argv, &error)) {
1536 g_critical("%s", error->message);
1540 /* Set the loglevel (amount of messages to output) for libsigrok. */
1541 if (sr_log_loglevel_set(opt_loglevel) != SR_OK)
1544 /* Set the loglevel (amount of messages to output) for libsigrokdecode. */
1545 if (srd_log_loglevel_set(opt_loglevel) != SRD_OK)
1548 if (sr_init(&sr_ctx) != SR_OK)
1552 if (srd_init(NULL) != SRD_OK)
1554 if (register_pds(NULL, opt_pds) != 0)
1556 if (srd_pd_output_callback_add(SRD_OUTPUT_ANN,
1557 show_pd_annotations, NULL) != SRD_OK)
1559 if (setup_pd_stack() != 0)
1561 if (setup_pd_annotations() != 0)
1565 if (setup_output_format() != 0)
1570 else if (opt_list_devs)
1572 else if (opt_pds && opt_show)
1576 else if (opt_input_file)
1580 else if (opt_samples || opt_time || opt_frames || opt_continuous)
1583 printf("%s", g_option_context_get_help(context, TRUE, NULL));
1594 g_option_context_free(context);