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;
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_config. */
116 static GSList *hash_to_hwopt(GHashTable *hash)
118 const struct sr_config_info *srci;
119 struct sr_config *src;
124 keys = g_hash_table_get_keys(hash);
126 for (gl = keys; gl; gl = gl->next) {
128 if (!(srci = sr_config_info_name_get(key))) {
129 g_critical("Unknown option %s", key);
132 src = g_try_malloc(sizeof(struct sr_config));
133 src->key = srci->key;
134 value = g_hash_table_lookup(hash, key);
135 src->value = g_strdup(value);
136 opts = g_slist_append(opts, src);
143 static void free_drvopts(struct sr_config *src)
145 g_free((void *)src->value);
149 static GSList *device_scan(void)
151 struct sr_dev_driver **drivers, *driver;
153 GSList *drvopts, *devices, *tmpdevs, *l;
158 drvargs = parse_generic_arg(opt_drv, TRUE);
159 drvname = g_strdup(g_hash_table_lookup(drvargs, "sigrok_key"));
160 g_hash_table_remove(drvargs, "sigrok_key");
162 drivers = sr_driver_list();
163 for (i = 0; drivers[i]; i++) {
164 if (strcmp(drivers[i]->name, drvname))
169 g_critical("Driver %s not found.", drvname);
173 if (sr_driver_init(sr_ctx, driver) != SR_OK) {
174 g_critical("Failed to initialize driver.");
178 if (g_hash_table_size(drvargs) > 0)
179 if (!(drvopts = hash_to_hwopt(drvargs)))
180 /* Unknown options, already logged. */
182 devices = sr_driver_scan(driver, drvopts);
183 g_slist_free_full(drvopts, (GDestroyNotify)free_drvopts);
185 /* No driver specified, let them all scan on their own. */
187 drivers = sr_driver_list();
188 for (i = 0; drivers[i]; i++) {
190 if (sr_driver_init(sr_ctx, driver) != SR_OK) {
191 g_critical("Failed to initialize driver.");
194 tmpdevs = sr_driver_scan(driver, NULL);
195 for (l = tmpdevs; l; l = l->next)
196 devices = g_slist_append(devices, l->data);
197 g_slist_free(tmpdevs);
204 static void show_version(void)
207 struct sr_dev_driver **drivers;
208 struct sr_input_format **inputs;
209 struct sr_output_format **outputs;
210 struct srd_decoder *dec;
213 printf("sigrok-cli %s\n\n", VERSION);
215 printf("Using libsigrok %s (lib version %s).\n",
216 sr_package_version_string_get(), sr_lib_version_string_get());
217 printf("Using libsigrokdecode %s (lib version %s).\n\n",
218 srd_package_version_string_get(), srd_lib_version_string_get());
220 printf("Supported hardware drivers:\n");
221 drivers = sr_driver_list();
222 for (i = 0; drivers[i]; i++) {
223 printf(" %-20s %s\n", drivers[i]->name, drivers[i]->longname);
227 printf("Supported input formats:\n");
228 inputs = sr_input_list();
229 for (i = 0; inputs[i]; i++)
230 printf(" %-20s %s\n", inputs[i]->id, inputs[i]->description);
233 printf("Supported output formats:\n");
234 outputs = sr_output_list();
235 for (i = 0; outputs[i]; i++)
236 printf(" %-20s %s\n", outputs[i]->id, outputs[i]->description);
239 if (srd_init(NULL) == SRD_OK) {
240 printf("Supported protocol decoders:\n");
241 srd_decoder_load_all();
242 for (l = srd_decoder_list(); l; l = l->next) {
244 printf(" %-20s %s\n", dec->id, dec->longname);
245 /* Print protocol description upon "-l 3" or higher. */
246 if (opt_loglevel >= SR_LOG_INFO)
247 printf(" %-20s %s\n", "", dec->desc);
254 static void print_dev_line(const struct sr_dev_inst *sdi)
256 struct sr_probe *probe;
259 if (sdi->vendor && sdi->vendor[0])
260 printf("%s ", sdi->vendor);
261 if (sdi->model && sdi->model[0])
262 printf("%s ", sdi->model);
263 if (sdi->version && sdi->version[0])
264 printf("%s ", sdi->version);
266 if (g_slist_length(sdi->probes) == 1) {
267 probe = sdi->probes->data;
268 printf("with 1 probe: %s", probe->name);
270 printf("with %d probes:", g_slist_length(sdi->probes));
271 for (l = sdi->probes; l; l = l->next) {
273 printf(" %s", probe->name);
280 static void show_dev_list(void)
282 struct sr_dev_inst *sdi;
285 if (!(devices = device_scan()))
288 printf("The following devices were found:\n");
289 for (l = devices; l; l = l->next) {
293 g_slist_free(devices);
297 static void show_dev_detail(void)
299 struct sr_dev_inst *sdi;
300 const struct sr_config_info *srci;
301 const struct sr_samplerates *samplerates;
302 struct sr_rational *rationals;
305 const int *hwopts, *hwcaps;
306 int cap, num_devices, n, i;
308 const char *charopts, **stropts;
310 if (!(devices = device_scan())) {
311 g_critical("No devices found.");
315 num_devices = g_slist_length(devices);
316 if (num_devices > 1) {
317 g_critical("%d devices found. Use --list-devices to show them, "
318 "and --device to select one.", num_devices);
325 if (sr_config_list(sdi->driver, SR_CONF_TRIGGER_TYPE, (const void **)&charopts,
326 sdi) == SR_OK && charopts) {
327 printf("Supported triggers: ");
329 printf("%c ", *charopts);
335 if ((sr_config_list(sdi->driver, SR_CONF_SCAN_OPTIONS, (const void **)&hwopts,
336 NULL) == SR_OK) && hwopts) {
337 printf("Supported driver options:\n");
338 for (i = 0; hwopts[i]; i++) {
339 if (!(srci = sr_config_info_get(hwopts[i])))
341 printf(" %s\n", srci->id);
345 title = "Supported device options:\n";
346 if ((sr_config_list(sdi->driver, SR_CONF_DEVICE_OPTIONS, (const void **)&hwcaps,
347 NULL) != SR_OK) || !hwcaps)
348 /* Driver supports no device instance options. */
351 for (cap = 0; hwcaps[cap]; cap++) {
352 if (!(srci = sr_config_info_get(hwcaps[cap])))
360 if (srci->key == SR_CONF_PATTERN_MODE) {
361 /* Pattern generator modes */
362 printf(" %s", srci->id);
363 if (sr_config_list(sdi->driver, SR_CONF_PATTERN_MODE,
364 (const void **)&stropts, sdi) == SR_OK) {
365 printf(" - supported patterns:\n");
366 for (i = 0; stropts[i]; i++)
367 printf(" %s\n", stropts[i]);
372 } else if (srci->key == SR_CONF_SAMPLERATE) {
373 /* Supported samplerates */
374 printf(" %s", srci->id);
375 if (sr_config_list(sdi->driver, SR_CONF_SAMPLERATE,
376 (const void **)&samplerates, sdi) != SR_OK) {
380 if (samplerates->step) {
382 if (!(s = sr_samplerate_string(samplerates->low)))
387 if (!(s = sr_samplerate_string(samplerates->high)))
392 if (!(s = sr_samplerate_string(samplerates->step)))
394 printf(" in steps of %s)\n", s);
397 printf(" - supported samplerates:\n");
398 for (i = 0; samplerates->list[i]; i++)
399 printf(" %s\n", sr_samplerate_string(samplerates->list[i]));
402 } else if (srci->key == SR_CONF_BUFFERSIZE) {
403 /* Supported buffer sizes */
404 printf(" %s", srci->id);
405 if (sr_config_list(sdi->driver, SR_CONF_BUFFERSIZE,
406 (const void **)&integers, sdi) != SR_OK) {
410 printf(" - supported buffer sizes:\n");
411 for (i = 0; integers[i]; i++)
412 printf(" %"PRIu64"\n", integers[i]);
414 } else if (srci->key == SR_CONF_TIMEBASE) {
415 /* Supported time bases */
416 printf(" %s", srci->id);
417 if (sr_config_list(sdi->driver, SR_CONF_TIMEBASE,
418 (const void **)&rationals, sdi) != SR_OK) {
422 printf(" - supported time bases:\n");
423 for (i = 0; rationals[i].p && rationals[i].q; i++)
424 printf(" %s\n", sr_period_string(
425 rationals[i].p * rationals[i].q));
427 } else if (srci->key == SR_CONF_TRIGGER_SOURCE) {
428 /* Supported trigger sources */
429 printf(" %s", srci->id);
430 if (sr_config_list(sdi->driver, SR_CONF_TRIGGER_SOURCE,
431 (const void **)&stropts, sdi) != SR_OK) {
435 printf(" - supported trigger sources:\n");
436 for (i = 0; stropts[i]; i++)
437 printf(" %s\n", stropts[i]);
439 } else if (srci->key == SR_CONF_FILTER) {
440 /* Supported filters */
441 printf(" %s", srci->id);
442 if (sr_config_list(sdi->driver, SR_CONF_FILTER,
443 (const void **)&stropts, sdi) != SR_OK) {
447 printf(" - supported filter targets:\n");
448 for (i = 0; stropts[i]; i++)
449 printf(" %s\n", stropts[i]);
451 } else if (srci->key == SR_CONF_VDIV) {
452 /* Supported volts/div values */
453 printf(" %s", srci->id);
454 if (sr_config_list(sdi->driver, SR_CONF_VDIV,
455 (const void **)&rationals, sdi) != SR_OK) {
459 printf(" - supported volts/div:\n");
460 for (i = 0; rationals[i].p && rationals[i].q; i++)
461 printf(" %s\n", sr_voltage_string( &rationals[i]));
463 } else if (srci->key == SR_CONF_COUPLING) {
464 /* Supported coupling settings */
465 printf(" %s", srci->id);
466 if (sr_config_list(sdi->driver, SR_CONF_COUPLING,
467 (const void **)&stropts, sdi) != SR_OK) {
471 printf(" - supported coupling options:\n");
472 for (i = 0; stropts[i]; i++)
473 printf(" %s\n", stropts[i]);
476 /* Everything else */
477 printf(" %s\n", srci->id);
483 static void show_pd_detail(void)
486 struct srd_decoder *dec;
487 char **pdtokens, **pdtok, **ann, *doc;
490 pdtokens = g_strsplit(opt_pds, ",", -1);
491 for (pdtok = pdtokens; *pdtok; pdtok++) {
492 if (!(dec = srd_decoder_get_by_id(*pdtok))) {
493 g_critical("Protocol decoder %s not found.", *pdtok);
496 printf("ID: %s\nName: %s\nLong name: %s\nDescription: %s\n",
497 dec->id, dec->name, dec->longname, dec->desc);
498 printf("License: %s\n", dec->license);
499 printf("Annotations:\n");
500 if (dec->annotations) {
501 for (l = dec->annotations; l; l = l->next) {
503 printf("- %s\n %s\n", ann[0], ann[1]);
508 /* TODO: Print supported decoder options. */
509 printf("Required probes:\n");
511 for (l = dec->probes; l; l = l->next) {
513 printf("- %s (%s): %s\n",
514 p->name, p->id, p->desc);
519 printf("Optional probes:\n");
520 if (dec->opt_probes) {
521 for (l = dec->opt_probes; l; l = l->next) {
523 printf("- %s (%s): %s\n",
524 p->name, p->id, p->desc);
529 if ((doc = srd_decoder_doc_get(dec))) {
530 printf("Documentation:\n%s\n",
531 doc[0] == '\n' ? doc + 1 : doc);
536 g_strfreev(pdtokens);
539 static GArray *get_enabled_logic_probes(const struct sr_dev_inst *sdi)
541 struct sr_probe *probe;
545 probes = g_array_new(FALSE, FALSE, sizeof(int));
546 for (l = sdi->probes; l; l = l->next) {
548 if (probe->type != SR_PROBE_LOGIC)
550 if (probe->enabled != TRUE)
552 g_array_append_val(probes, probe->index);
558 static void datafeed_in(const struct sr_dev_inst *sdi,
559 const struct sr_datafeed_packet *packet)
561 const struct sr_datafeed_meta *meta;
562 const struct sr_datafeed_logic *logic;
563 const struct sr_datafeed_analog *analog;
564 struct sr_config *src;
565 static struct sr_output *o = NULL;
566 static GArray *logic_probelist = NULL;
567 static uint64_t received_samples = 0;
568 static int unitsize = 0;
569 static int triggered = 0;
570 static FILE *outfile = NULL;
571 int sample_size, ret;
572 uint64_t *samplerate, output_len, filter_out_len;
573 uint8_t *output_buf, *filter_out;
577 /* If the first packet to come in isn't a header, don't even try. */
578 if (packet->type != SR_DF_HEADER && o == NULL)
582 switch (packet->type) {
584 g_debug("cli: Received SR_DF_HEADER");
585 /* Initialize the output module. */
586 if (!(o = g_try_malloc(sizeof(struct sr_output)))) {
587 g_critical("Output module malloc failed.");
590 o->format = output_format;
591 o->sdi = (struct sr_dev_inst *)sdi;
592 o->param = output_format_param;
593 if (o->format->init) {
594 if (o->format->init(o) != SR_OK) {
595 g_critical("Output format initialization failed.");
600 /* Prepare non-stdout output. */
602 if (opt_output_file) {
603 if (default_output_format) {
604 /* output file is in session format, so we'll
605 * keep a copy of everything as it comes in
606 * and save from there after the session. */
608 savebuf = g_byte_array_new();
610 /* saving to a file in whatever format was set
611 * with --format, so all we need is a filehandle */
612 outfile = g_fopen(opt_output_file, "wb");
616 /* Prepare for logic data. */
617 logic_probelist = get_enabled_logic_probes(sdi);
618 /* How many bytes we need to store the packed samples. */
619 unitsize = (logic_probelist->len + 7) / 8;
621 if (opt_pds && logic_probelist->len) {
622 if (sr_config_get(sdi->driver, SR_CONF_SAMPLERATE,
623 (const void **)&samplerate, sdi) != SR_OK) {
624 g_critical("Unable to initialize protocol "
625 "decoders: no samplerate found.");
628 srd_session_start(logic_probelist->len, unitsize,
634 g_debug("cli: received SR_DF_META");
635 meta = packet->payload;
636 for (l = meta->config; l; l = l->next) {
639 case SR_CONF_SAMPLERATE:
640 samplerate = (uint64_t *)src->value;
641 g_debug("cli: got samplerate %"PRIu64, *samplerate);
644 /* Unknown metadata is not an error. */
651 g_debug("cli: received SR_DF_TRIGGER");
652 if (o->format->event)
653 o->format->event(o, SR_DF_TRIGGER, &output_buf,
659 logic = packet->payload;
660 g_message("cli: received SR_DF_LOGIC, %"PRIu64" bytes", logic->length);
661 sample_size = logic->unitsize;
662 if (logic->length == 0)
665 /* Don't store any samples until triggered. */
666 if (opt_wait_trigger && !triggered)
669 if (limit_samples && received_samples >= limit_samples)
672 ret = sr_filter_probes(sample_size, unitsize, logic_probelist,
673 logic->data, logic->length,
674 &filter_out, &filter_out_len);
678 /* What comes out of the filter is guaranteed to be packed into the
679 * minimum size needed to support the number of samples at this sample
680 * size. however, the driver may have submitted too much -- cut off
681 * the buffer of the last packet according to the sample limit.
683 if (limit_samples && (received_samples + logic->length / sample_size >
684 limit_samples * sample_size))
685 filter_out_len = limit_samples * sample_size - received_samples;
687 if (opt_output_file && default_output_format) {
688 /* Saving to a session file. */
689 g_byte_array_append(savebuf, filter_out, filter_out_len);
692 if (srd_session_send(received_samples, (uint8_t*)filter_out,
693 filter_out_len) != SRD_OK)
697 if (o->format->data && packet->type == o->format->df_type)
698 o->format->data(o, filter_out, filter_out_len,
699 &output_buf, &output_len);
701 fwrite(output_buf, 1, output_len, outfile);
709 received_samples += logic->length / sample_size;
713 analog = packet->payload;
714 g_message("cli: received SR_DF_ANALOG, %d samples", analog->num_samples);
715 if (analog->num_samples == 0)
718 if (limit_samples && received_samples >= limit_samples)
721 if (o->format->data && packet->type == o->format->df_type) {
722 o->format->data(o, (const uint8_t *)analog->data,
723 analog->num_samples * sizeof(float),
724 &output_buf, &output_len);
726 fwrite(output_buf, 1, output_len, outfile);
732 received_samples += analog->num_samples;
735 case SR_DF_FRAME_BEGIN:
736 g_debug("cli: received SR_DF_FRAME_BEGIN");
737 if (o->format->event) {
738 o->format->event(o, SR_DF_FRAME_BEGIN, &output_buf,
741 fwrite(output_buf, 1, output_len, outfile);
748 case SR_DF_FRAME_END:
749 g_debug("cli: received SR_DF_FRAME_END");
750 if (o->format->event) {
751 o->format->event(o, SR_DF_FRAME_END, &output_buf,
754 fwrite(output_buf, 1, output_len, outfile);
765 if (o && o->format->recv) {
766 out = o->format->recv(o, sdi, packet);
767 if (out && out->len) {
768 fwrite(out->str, 1, out->len, outfile);
773 /* SR_DF_END needs to be handled after the output module's recv()
774 * is called, so it can properly clean up that module etc. */
775 if (packet->type == SR_DF_END) {
776 g_debug("cli: Received SR_DF_END");
778 if (o->format->event) {
779 o->format->event(o, SR_DF_END, &output_buf, &output_len);
782 fwrite(output_buf, 1, output_len, outfile);
788 if (limit_samples && received_samples < limit_samples)
789 g_warning("Device only sent %" PRIu64 " samples.",
793 g_warning("Device stopped after %" PRIu64 " samples.",
796 g_array_free(logic_probelist, TRUE);
798 if (o->format->cleanup)
799 o->format->cleanup(o);
803 if (outfile && outfile != stdout)
806 if (opt_output_file && default_output_format) {
807 if (sr_session_save(opt_output_file, sdi, savebuf->data,
808 unitsize, savebuf->len / unitsize) != SR_OK)
809 g_critical("Failed to save session.");
810 g_byte_array_free(savebuf, FALSE);
816 /* Register the given PDs for this session.
817 * Accepts a string of the form: "spi:sck=3:sdata=4,spi:sck=3:sdata=5"
818 * That will instantiate two SPI decoders on the clock but different data
821 static int register_pds(struct sr_dev *dev, const char *pdstring)
823 GHashTable *pd_opthash;
824 struct srd_decoder_inst *di;
826 char **pdtokens, **pdtok, *pd_name;
831 pd_ann_visible = g_hash_table_new_full(g_str_hash, g_int_equal,
835 pdtokens = g_strsplit(pdstring, ",", 0);
836 for (pdtok = pdtokens; *pdtok; pdtok++) {
837 if (!(pd_opthash = parse_generic_arg(*pdtok, TRUE))) {
838 g_critical("Invalid protocol decoder option '%s'.", *pdtok);
842 pd_name = g_strdup(g_hash_table_lookup(pd_opthash, "sigrok_key"));
843 g_hash_table_remove(pd_opthash, "sigrok_key");
844 if (srd_decoder_load(pd_name) != SRD_OK) {
845 g_critical("Failed to load protocol decoder %s.", pd_name);
849 if (!(di = srd_inst_new(pd_name, pd_opthash))) {
850 g_critical("Failed to instantiate protocol decoder %s.", pd_name);
855 /* If no annotation list was specified, add them all in now.
856 * This will be pared down later to leave only the last PD
859 if (!opt_pd_annotations)
860 g_hash_table_insert(pd_ann_visible,
861 g_strdup(di->inst_id), NULL);
863 /* Any keys left in the options hash are probes, where the key
864 * is the probe name as specified in the decoder class, and the
865 * value is the probe number i.e. the order in which the PD's
866 * incoming samples are arranged. */
867 if (srd_inst_probe_set_all(di, pd_opthash) != SRD_OK) {
871 g_hash_table_destroy(pd_opthash);
876 g_strfreev(pdtokens);
878 g_hash_table_destroy(pd_opthash);
885 int setup_pd_stack(void)
887 struct srd_decoder_inst *di_from, *di_to;
891 /* Set up the protocol decoder stack. */
892 pds = g_strsplit(opt_pds, ",", 0);
893 if (g_strv_length(pds) > 1) {
895 /* A stack setup was specified, use that. */
897 pds = g_strsplit(opt_pd_stack, ",", 0);
898 if (g_strv_length(pds) < 2) {
900 g_critical("Specify at least two protocol decoders to stack.");
905 /* First PD goes at the bottom of the stack. */
906 ids = g_strsplit(pds[0], ":", 0);
907 if (!(di_from = srd_inst_find_by_id(ids[0]))) {
909 g_critical("Cannot stack protocol decoder '%s': "
910 "instance not found.", pds[0]);
915 /* Every subsequent PD goes on top. */
916 for (i = 1; pds[i]; i++) {
917 ids = g_strsplit(pds[i], ":", 0);
918 if (!(di_to = srd_inst_find_by_id(ids[0]))) {
920 g_critical("Cannot stack protocol decoder '%s': "
921 "instance not found.", pds[i]);
925 if ((ret = srd_inst_stack(di_from, di_to)) != SRD_OK)
928 /* Don't show annotation from this PD. Only the last PD in
929 * the stack will be left on the annotation list (unless
930 * the annotation list was specifically provided).
932 if (!opt_pd_annotations)
933 g_hash_table_remove(pd_ann_visible,
944 int setup_pd_annotations(void)
947 struct srd_decoder *dec;
949 char **pds, **pdtok, **keyval, **ann_descr;
951 /* Set up custom list of PDs and annotations to show. */
952 if (opt_pd_annotations) {
953 pds = g_strsplit(opt_pd_annotations, ",", 0);
954 for (pdtok = pds; *pdtok && **pdtok; pdtok++) {
956 keyval = g_strsplit(*pdtok, "=", 0);
957 if (!(dec = srd_decoder_get_by_id(keyval[0]))) {
958 g_critical("Protocol decoder '%s' not found.", keyval[0]);
961 if (!dec->annotations) {
962 g_critical("Protocol decoder '%s' has no annotations.", keyval[0]);
965 if (g_strv_length(keyval) == 2) {
966 for (l = dec->annotations; l; l = l->next, ann++) {
968 if (!canon_cmp(ann_descr[0], keyval[1]))
973 g_critical("Annotation '%s' not found "
974 "for protocol decoder '%s'.", keyval[1], keyval[0]);
978 g_debug("cli: showing protocol decoder annotation %d from '%s'", ann, keyval[0]);
979 g_hash_table_insert(pd_ann_visible, g_strdup(keyval[0]), GINT_TO_POINTER(ann));
988 int setup_output_format(void)
993 struct sr_output_format **outputs;
997 if (!opt_output_format) {
998 opt_output_format = DEFAULT_OUTPUT_FORMAT;
999 /* we'll need to remember this so when saving to a file
1000 * later, sigrok session format will be used.
1002 default_output_format = TRUE;
1005 fmtargs = parse_generic_arg(opt_output_format, TRUE);
1006 fmtspec = g_hash_table_lookup(fmtargs, "sigrok_key");
1008 g_critical("Invalid output format.");
1011 outputs = sr_output_list();
1012 for (i = 0; outputs[i]; i++) {
1013 if (strcmp(outputs[i]->id, fmtspec))
1015 g_hash_table_remove(fmtargs, "sigrok_key");
1016 output_format = outputs[i];
1017 g_hash_table_iter_init(&iter, fmtargs);
1018 while (g_hash_table_iter_next(&iter, &key, &value)) {
1019 /* only supporting one parameter per output module
1020 * for now, and only its value */
1021 output_format_param = g_strdup(value);
1026 if (!output_format) {
1027 g_critical("Invalid output format %s.", opt_output_format);
1030 g_hash_table_destroy(fmtargs);
1035 void show_pd_annotations(struct srd_proto_data *pdata, void *cb_data)
1039 gpointer ann_format;
1041 /* 'cb_data' is not used in this specific callback. */
1044 if (!pd_ann_visible)
1047 if (!g_hash_table_lookup_extended(pd_ann_visible, pdata->pdo->di->inst_id,
1049 /* Not in the list of PDs whose annotations we're showing. */
1052 if (pdata->ann_format != GPOINTER_TO_INT(ann_format))
1053 /* We don't want this particular format from the PD. */
1056 annotations = pdata->data;
1057 if (opt_loglevel > SR_LOG_WARN)
1058 printf("%"PRIu64"-%"PRIu64" ", pdata->start_sample, pdata->end_sample);
1059 printf("%s: ", pdata->pdo->proto_id);
1060 for (i = 0; annotations[i]; i++)
1061 printf("\"%s\" ", annotations[i]);
1066 static int select_probes(struct sr_dev_inst *sdi)
1068 struct sr_probe *probe;
1069 GSList *selected_probes, *l;
1074 if (!(selected_probes = parse_probestring(sdi, opt_probes)))
1077 for (l = sdi->probes; l; l = l->next) {
1079 if (g_slist_find(selected_probes, probe))
1080 probe->enabled = TRUE;
1082 probe->enabled = FALSE;
1084 g_slist_free(selected_probes);
1090 * Return the input file format which the CLI tool should use.
1092 * If the user specified -I / --input-format, use that one. Otherwise, try to
1093 * autodetect the format as good as possible. Failing that, return NULL.
1095 * @param filename The filename of the input file. Must not be NULL.
1096 * @param opt The -I / --input-file option the user specified (or NULL).
1098 * @return A pointer to the 'struct sr_input_format' that should be used,
1099 * or NULL if no input format was selected or auto-detected.
1101 static struct sr_input_format *determine_input_file_format(
1102 const char *filename, const char *opt)
1105 struct sr_input_format **inputs;
1107 /* If there are no input formats, return NULL right away. */
1108 inputs = sr_input_list();
1110 g_critical("No supported input formats available.");
1114 /* If the user specified -I / --input-format, use that one. */
1116 for (i = 0; inputs[i]; i++) {
1117 if (strcasecmp(inputs[i]->id, opt))
1119 g_debug("Using user-specified input file format '%s'.",
1124 /* The user specified an unknown input format, return NULL. */
1125 g_critical("Error: specified input file format '%s' is "
1130 /* Otherwise, try to find an input module that can handle this file. */
1131 for (i = 0; inputs[i]; i++) {
1132 if (inputs[i]->format_match(filename))
1136 /* Return NULL if no input module wanted to touch this. */
1138 g_critical("Error: no matching input module found.");
1142 g_debug("cli: Autodetected '%s' input format for file '%s'.",
1143 inputs[i]->id, filename);
1148 static void load_input_file_format(void)
1150 GHashTable *fmtargs = NULL;
1152 struct sr_input *in;
1153 struct sr_input_format *input_format;
1154 char *fmtspec = NULL;
1156 if (opt_input_format) {
1157 fmtargs = parse_generic_arg(opt_input_format, TRUE);
1158 fmtspec = g_hash_table_lookup(fmtargs, "sigrok_key");
1161 if (!(input_format = determine_input_file_format(opt_input_file,
1163 /* The exact cause was already logged. */
1168 g_hash_table_remove(fmtargs, "sigrok_key");
1170 if (stat(opt_input_file, &st) == -1) {
1171 g_critical("Failed to load %s: %s", opt_input_file,
1176 /* Initialize the input module. */
1177 if (!(in = g_try_malloc(sizeof(struct sr_input)))) {
1178 g_critical("Failed to allocate input module.");
1181 in->format = input_format;
1182 in->param = fmtargs;
1183 if (in->format->init) {
1184 if (in->format->init(in, opt_input_file) != SR_OK) {
1185 g_critical("Input format init failed.");
1190 if (select_probes(in->sdi) > 0)
1194 sr_session_datafeed_callback_add(datafeed_in);
1195 if (sr_session_dev_add(in->sdi) != SR_OK) {
1196 g_critical("Failed to use device.");
1197 sr_session_destroy();
1201 input_format->loadfile(in, opt_input_file);
1203 sr_session_destroy();
1206 g_hash_table_destroy(fmtargs);
1209 static void load_input_file(void)
1212 if (sr_session_load(opt_input_file) == SR_OK) {
1213 /* sigrok session file */
1214 sr_session_datafeed_callback_add(datafeed_in);
1220 /* fall back on input modules */
1221 load_input_file_format();
1225 static int set_dev_options(struct sr_dev_inst *sdi, GHashTable *args)
1227 const struct sr_config_info *srci;
1228 GHashTableIter iter;
1229 gpointer key, value;
1233 struct sr_rational tmp_rat;
1237 g_hash_table_iter_init(&iter, args);
1238 while (g_hash_table_iter_next(&iter, &key, &value)) {
1239 if (!(srci = sr_config_info_name_get(key))) {
1240 g_critical("Unknown device option '%s'.", (char *) key);
1244 if ((value == NULL) &&
1245 (srci->datatype != SR_T_BOOL)) {
1246 g_critical("Option '%s' needs a value.", (char *)key);
1250 switch (srci->datatype) {
1252 ret = sr_parse_sizestring(value, &tmp_u64);
1264 tmp_bool = sr_parse_boolstring(value);
1268 tmp_float = strtof(value, NULL);
1271 case SR_T_RATIONAL_PERIOD:
1272 if ((ret = sr_parse_period(value, &tmp_rat)) != SR_OK)
1276 case SR_T_RATIONAL_VOLT:
1277 if ((ret = sr_parse_voltage(value, &tmp_rat)) != SR_OK)
1285 ret = sr_config_set(sdi, srci->key, val);
1287 g_critical("Failed to set 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_dev_has_option(sdi, SR_CONF_LIMIT_MSEC)) {
1308 if (sr_config_set(sdi, SR_CONF_LIMIT_MSEC, &time_msec) != SR_OK) {
1309 g_critical("Failed to configure time limit.");
1310 sr_session_destroy();
1315 /* time limit set, but device doesn't support this...
1316 * convert to samples based on the samplerate.
1319 if (sr_dev_has_option(sdi, SR_CONF_SAMPLERATE)) {
1320 sr_config_get(sdi->driver, SR_CONF_SAMPLERATE,
1321 (const void **)&samplerate, sdi);
1322 limit_samples = (*samplerate) * time_msec / (uint64_t)1000;
1324 if (limit_samples == 0) {
1325 g_critical("Not enough time at this samplerate.");
1326 sr_session_destroy();
1330 if (sr_config_set(sdi, SR_CONF_LIMIT_SAMPLES,
1331 &limit_samples) != SR_OK) {
1332 g_critical("Failed to configure time-based sample limit.");
1333 sr_session_destroy();
1341 static void run_session(void)
1344 GHashTable *devargs;
1345 struct sr_dev_inst *sdi;
1349 devices = device_scan();
1351 g_critical("No devices found.");
1354 if (g_slist_length(devices) > 1) {
1355 g_critical("sigrok-cli only supports one device for capturing.");
1358 sdi = devices->data;
1361 sr_session_datafeed_callback_add(datafeed_in);
1363 if (sr_session_dev_add(sdi) != SR_OK) {
1364 g_critical("Failed to use device.");
1365 sr_session_destroy();
1370 if ((devargs = parse_generic_arg(opt_dev, FALSE))) {
1371 if (set_dev_options(sdi, devargs) != SR_OK)
1373 g_hash_table_destroy(devargs);
1377 if (select_probes(sdi) != SR_OK) {
1378 g_critical("Failed to set probes.");
1379 sr_session_destroy();
1384 if (!(triggerlist = sr_parse_triggerstring(sdi, opt_triggers))) {
1385 sr_session_destroy();
1388 max_probes = g_slist_length(sdi->probes);
1389 for (i = 0; i < max_probes; i++) {
1390 if (triggerlist[i]) {
1391 sr_dev_trigger_set(sdi, i, triggerlist[i]);
1392 g_free(triggerlist[i]);
1395 g_free(triggerlist);
1398 if (opt_continuous) {
1399 if (!sr_dev_has_option(sdi, SR_CONF_CONTINUOUS)) {
1400 g_critical("This device does not support continuous sampling.");
1401 sr_session_destroy();
1407 if (set_limit_time(sdi) != SR_OK) {
1408 sr_session_destroy();
1414 if ((sr_parse_sizestring(opt_samples, &limit_samples) != SR_OK)
1415 || (sr_config_set(sdi, SR_CONF_LIMIT_SAMPLES,
1416 &limit_samples) != SR_OK)) {
1417 g_critical("Failed to configure sample limit.");
1418 sr_session_destroy();
1424 if ((sr_parse_sizestring(opt_frames, &limit_frames) != SR_OK)
1425 || (sr_config_set(sdi, SR_CONF_LIMIT_FRAMES,
1426 &limit_frames) != SR_OK)) {
1427 g_critical("Failed to configure frame limit.");
1428 sr_session_destroy();
1433 if (sr_session_start() != SR_OK) {
1434 g_critical("Failed to start session.");
1435 sr_session_destroy();
1447 sr_session_destroy();
1448 g_slist_free(devices);
1452 static void logger(const gchar *log_domain, GLogLevelFlags log_level,
1453 const gchar *message, gpointer cb_data)
1459 * All messages, warnings, errors etc. go to stderr (not stdout) in
1460 * order to not mess up the CLI tool data output, e.g. VCD output.
1462 if (log_level & (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING)
1463 || opt_loglevel > SR_LOG_WARN) {
1464 fprintf(stderr, "%s\n", message);
1469 int main(int argc, char **argv)
1472 GOptionContext *context;
1475 g_log_set_default_handler(logger, NULL);
1478 context = g_option_context_new(NULL);
1479 g_option_context_add_main_entries(context, optargs, NULL);
1481 if (!g_option_context_parse(context, &argc, &argv, &error)) {
1482 g_critical("%s", error->message);
1486 /* Set the loglevel (amount of messages to output) for libsigrok. */
1487 if (sr_log_loglevel_set(opt_loglevel) != SR_OK)
1490 /* Set the loglevel (amount of messages to output) for libsigrokdecode. */
1491 if (srd_log_loglevel_set(opt_loglevel) != SRD_OK)
1494 if (sr_init(&sr_ctx) != SR_OK)
1498 if (srd_init(NULL) != SRD_OK)
1500 if (register_pds(NULL, opt_pds) != 0)
1502 if (srd_pd_output_callback_add(SRD_OUTPUT_ANN,
1503 show_pd_annotations, NULL) != SRD_OK)
1505 if (setup_pd_stack() != 0)
1507 if (setup_pd_annotations() != 0)
1511 if (setup_output_format() != 0)
1516 else if (opt_list_devs)
1518 else if (opt_pds && opt_show)
1522 else if (opt_input_file)
1524 else if (opt_samples || opt_time || opt_frames || opt_continuous)
1527 printf("%s", g_option_context_get_help(context, TRUE, NULL));
1538 g_option_context_free(context);