2 * This file is part of the sigrok-cli 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/>.
22 #include <libsigrokdecode/libsigrokdecode.h> /* First, so we avoid a _POSIX_C_SOURCE warning. */
31 #include <sys/types.h>
35 #include <glib/gstdio.h>
36 #include <libsigrok/libsigrok.h>
37 #include "sigrok-cli.h"
39 #define DEFAULT_OUTPUT_FORMAT "bits:width=64"
41 static struct sr_context *sr_ctx = NULL;
43 static uint64_t limit_samples = 0;
44 static uint64_t limit_frames = 0;
45 static struct sr_output_format *output_format = NULL;
46 static int default_output_format = FALSE;
47 static char *output_format_param = NULL;
49 static struct srd_session *srd_sess = NULL;
50 static GHashTable *pd_ann_visible = NULL;
51 static GHashTable *pd_meta_visible = NULL;
52 static GHashTable *pd_binary_visible = NULL;
54 static GByteArray *savebuf;
56 static gboolean opt_version = FALSE;
57 static gint opt_loglevel = SR_LOG_WARN; /* Show errors+warnings per default. */
58 static gboolean opt_scan_devs = FALSE;
59 static gboolean opt_wait_trigger = FALSE;
60 static gchar *opt_input_file = NULL;
61 static gchar *opt_output_file = NULL;
62 static gchar *opt_drv = NULL;
63 static gchar *opt_config = NULL;
64 static gchar *opt_probes = NULL;
65 static gchar *opt_probe_group = NULL;
66 static gchar *opt_triggers = NULL;
67 static gchar *opt_pds = NULL;
69 static gchar *opt_pd_stack = NULL;
70 static gchar *opt_pd_annotations = NULL;
71 static gchar *opt_pd_meta = NULL;
72 static gchar *opt_pd_binary = NULL;
74 static gchar *opt_input_format = NULL;
75 static gchar *opt_output_format = NULL;
76 static gchar *opt_show = NULL;
77 static gchar *opt_time = NULL;
78 static gchar *opt_samples = NULL;
79 static gchar *opt_frames = NULL;
80 static gchar *opt_continuous = NULL;
81 static gchar *opt_set = NULL;
83 static GOptionEntry optargs[] = {
84 {"version", 'V', 0, G_OPTION_ARG_NONE, &opt_version,
85 "Show version and support list", NULL},
86 {"loglevel", 'l', 0, G_OPTION_ARG_INT, &opt_loglevel,
87 "Set loglevel (5 is most verbose)", NULL},
88 {"driver", 'd', 0, G_OPTION_ARG_STRING, &opt_drv,
89 "The driver to use", NULL},
90 {"config", 'c', 0, G_OPTION_ARG_STRING, &opt_config,
91 "Specify device configuration options", NULL},
92 {"input-file", 'i', 0, G_OPTION_ARG_FILENAME, &opt_input_file,
93 "Load input from file", NULL},
94 {"input-format", 'I', 0, G_OPTION_ARG_STRING, &opt_input_format,
95 "Input format", NULL},
96 {"output-file", 'o', 0, G_OPTION_ARG_FILENAME, &opt_output_file,
97 "Save output to file", NULL},
98 {"output-format", 'O', 0, G_OPTION_ARG_STRING, &opt_output_format,
99 "Output format", NULL},
100 {"probes", 'p', 0, G_OPTION_ARG_STRING, &opt_probes,
101 "Probes to use", NULL},
102 {"probe-group", 'g', 0, G_OPTION_ARG_STRING, &opt_probe_group,
103 "Probe groups", NULL},
104 {"triggers", 't', 0, G_OPTION_ARG_STRING, &opt_triggers,
105 "Trigger configuration", NULL},
106 {"wait-trigger", 'w', 0, G_OPTION_ARG_NONE, &opt_wait_trigger,
107 "Wait for trigger", NULL},
109 {"protocol-decoders", 'P', 0, G_OPTION_ARG_STRING, &opt_pds,
110 "Protocol decoders to run", NULL},
111 {"protocol-decoder-stack", 'S', 0, G_OPTION_ARG_STRING, &opt_pd_stack,
112 "Protocol decoder stack", NULL},
113 {"protocol-decoder-annotations", 'A', 0, G_OPTION_ARG_STRING, &opt_pd_annotations,
114 "Protocol decoder annotation(s) to show", NULL},
115 {"protocol-decoder-meta", 'M', 0, G_OPTION_ARG_STRING, &opt_pd_meta,
116 "Protocol decoder meta output to show", NULL},
117 {"protocol-decoder-binary", 'B', 0, G_OPTION_ARG_STRING, &opt_pd_binary,
118 "Protocol decoder binary output to show", NULL},
120 {"scan", 0, 0, G_OPTION_ARG_NONE, &opt_scan_devs,
121 "Scan for devices", NULL},
122 {"show", 0, 0, G_OPTION_ARG_NONE, &opt_show,
123 "Show device detail", NULL},
124 {"time", 0, 0, G_OPTION_ARG_STRING, &opt_time,
125 "How long to sample (ms)", NULL},
126 {"samples", 0, 0, G_OPTION_ARG_STRING, &opt_samples,
127 "Number of samples to acquire", NULL},
128 {"frames", 0, 0, G_OPTION_ARG_STRING, &opt_frames,
129 "Number of frames to acquire", NULL},
130 {"continuous", 0, 0, G_OPTION_ARG_NONE, &opt_continuous,
131 "Sample continuously", NULL},
132 {"set", 0, 0, G_OPTION_ARG_NONE, &opt_set, "Set device options only", NULL},
133 {NULL, 0, 0, 0, NULL, NULL, NULL}
137 /* Convert driver options hash to GSList of struct sr_config. */
138 static GSList *hash_to_hwopt(GHashTable *hash)
140 const struct sr_config_info *srci;
141 struct sr_config *src;
146 keys = g_hash_table_get_keys(hash);
148 for (gl = keys; gl; gl = gl->next) {
150 if (!(srci = sr_config_info_name_get(key))) {
151 g_critical("Unknown option %s", key);
154 src = g_try_malloc(sizeof(struct sr_config));
155 src->key = srci->key;
156 value = g_hash_table_lookup(hash, key);
157 src->data = g_variant_new_string(value);
158 opts = g_slist_append(opts, src);
165 static struct sr_probe_group *select_probe_group(struct sr_dev_inst *sdi)
167 struct sr_probe_group *pg;
170 if (!opt_probe_group)
173 if (!sdi->probe_groups) {
174 g_critical("This device does not have any probe groups.");
178 for (l = sdi->probe_groups; l; l = l->next) {
180 if (!strcasecmp(opt_probe_group, pg->name)) {
188 static void free_drvopts(struct sr_config *src)
190 g_variant_unref(src->data);
194 static GSList *device_scan(void)
196 struct sr_dev_driver **drivers, *driver;
198 GSList *drvopts, *devices, *tmpdevs, *l;
203 drvargs = parse_generic_arg(opt_drv, TRUE);
204 drvname = g_strdup(g_hash_table_lookup(drvargs, "sigrok_key"));
205 g_hash_table_remove(drvargs, "sigrok_key");
207 drivers = sr_driver_list();
208 for (i = 0; drivers[i]; i++) {
209 if (strcmp(drivers[i]->name, drvname))
214 g_critical("Driver %s not found.", drvname);
215 g_hash_table_destroy(drvargs);
220 if (sr_driver_init(sr_ctx, driver) != SR_OK) {
221 g_critical("Failed to initialize driver.");
222 g_hash_table_destroy(drvargs);
226 if (g_hash_table_size(drvargs) > 0) {
227 if (!(drvopts = hash_to_hwopt(drvargs))) {
228 /* Unknown options, already logged. */
229 g_hash_table_destroy(drvargs);
233 g_hash_table_destroy(drvargs);
234 devices = sr_driver_scan(driver, drvopts);
235 g_slist_free_full(drvopts, (GDestroyNotify)free_drvopts);
237 /* No driver specified, let them all scan on their own. */
239 drivers = sr_driver_list();
240 for (i = 0; drivers[i]; i++) {
242 if (sr_driver_init(sr_ctx, driver) != SR_OK) {
243 g_critical("Failed to initialize driver.");
246 tmpdevs = sr_driver_scan(driver, NULL);
247 for (l = tmpdevs; l; l = l->next)
248 devices = g_slist_append(devices, l->data);
249 g_slist_free(tmpdevs);
256 static void show_version(void)
258 struct sr_dev_driver **drivers;
259 struct sr_input_format **inputs;
260 struct sr_output_format **outputs;
263 struct srd_decoder *dec;
267 printf("sigrok-cli %s\n\n", VERSION);
269 printf("Using libsigrok %s (lib version %s).\n",
270 sr_package_version_string_get(), sr_lib_version_string_get());
272 printf("Using libsigrokdecode %s (lib version %s).\n\n",
273 srd_package_version_string_get(), srd_lib_version_string_get());
276 printf("Supported hardware drivers:\n");
277 drivers = sr_driver_list();
278 for (i = 0; drivers[i]; i++) {
279 printf(" %-20s %s\n", drivers[i]->name, drivers[i]->longname);
283 printf("Supported input formats:\n");
284 inputs = sr_input_list();
285 for (i = 0; inputs[i]; i++)
286 printf(" %-20s %s\n", inputs[i]->id, inputs[i]->description);
289 printf("Supported output formats:\n");
290 outputs = sr_output_list();
291 for (i = 0; outputs[i]; i++)
292 printf(" %-20s %s\n", outputs[i]->id, outputs[i]->description);
293 printf(" %-20s %s\n", "sigrok", "Default file output format");
297 if (srd_init(NULL) == SRD_OK) {
298 printf("Supported protocol decoders:\n");
299 srd_decoder_load_all();
300 for (l = srd_decoder_list(); l; l = l->next) {
302 printf(" %-20s %s\n", dec->id, dec->longname);
303 /* Print protocol description upon "-l 3" or higher. */
304 if (opt_loglevel >= SR_LOG_INFO)
305 printf(" %-20s %s\n", "", dec->desc);
313 static void print_dev_line(const struct sr_dev_inst *sdi)
315 struct sr_probe *probe;
320 s = g_string_sized_new(128);
321 g_string_assign(s, sdi->driver->name);
322 if (sr_config_get(sdi->driver, sdi, NULL, SR_CONF_CONN, &gvar) == SR_OK) {
323 g_string_append(s, ":conn=");
324 g_string_append(s, g_variant_get_string(gvar, NULL));
325 g_variant_unref(gvar);
327 g_string_append(s, " - ");
328 if (sdi->vendor && sdi->vendor[0])
329 g_string_append_printf(s, "%s ", sdi->vendor);
330 if (sdi->model && sdi->model[0])
331 g_string_append_printf(s, "%s ", sdi->model);
332 if (sdi->version && sdi->version[0])
333 g_string_append_printf(s, "%s ", sdi->version);
335 if (g_slist_length(sdi->probes) == 1) {
336 probe = sdi->probes->data;
337 g_string_append_printf(s, "with 1 probe: %s", probe->name);
339 g_string_append_printf(s, "with %d probes:", g_slist_length(sdi->probes));
340 for (l = sdi->probes; l; l = l->next) {
342 g_string_append_printf(s, " %s", probe->name);
346 g_string_append_printf(s, "\n");
347 printf("%s", s->str);
348 g_string_free(s, TRUE);
352 static void show_dev_list(void)
354 struct sr_dev_inst *sdi;
357 if (!(devices = device_scan()))
360 printf("The following devices were found:\n");
361 for (l = devices; l; l = l->next) {
365 g_slist_free(devices);
369 static void show_dev_detail(void)
371 struct sr_dev_inst *sdi;
372 const struct sr_config_info *srci;
373 struct sr_probe *probe;
374 struct sr_probe_group *probe_group, *pg;
375 GSList *devices, *pgl, *prl;
376 GVariant *gvar_opts, *gvar_dict, *gvar_list, *gvar;
377 gsize num_opts, num_elements;
378 const uint64_t *uint64, p, q, low, high;
379 uint64_t cur_low, cur_high;
381 unsigned int num_devices, o, i;
384 const char *charopts, **stropts;
386 if (!(devices = device_scan())) {
387 g_critical("No devices found.");
391 num_devices = g_slist_length(devices);
392 if (num_devices > 1) {
393 g_critical("%d devices found. Use --scan to show them, "
394 "and select one to show.", num_devices);
401 if (sr_dev_open(sdi) != SR_OK) {
402 g_critical("Failed to open device.");
406 if ((sr_config_list(sdi->driver, NULL, NULL, SR_CONF_SCAN_OPTIONS,
407 &gvar_opts) == SR_OK)) {
408 opts = g_variant_get_fixed_array(gvar_opts, &num_elements,
410 printf("Supported driver options:\n");
411 for (i = 0; i < num_elements; i++) {
412 if (!(srci = sr_config_info_get(opts[i])))
414 printf(" %s\n", srci->id);
416 g_variant_unref(gvar_opts);
419 probe_group = select_probe_group(sdi);
420 if ((sr_config_list(sdi->driver, sdi, probe_group, SR_CONF_DEVICE_OPTIONS,
421 &gvar_opts)) != SR_OK)
422 /* Driver supports no device instance options. */
425 if (sdi->probe_groups) {
426 printf("Probe groups:\n");
427 for (pgl = sdi->probe_groups; pgl; pgl = pgl->next) {
429 printf(" %s: channel%s", pg->name,
430 g_slist_length(pg->probes) > 1 ? "s" : "");
431 for (prl = pg->probes; prl; prl = prl->next) {
433 printf(" %s", probe->name);
439 printf("Supported configuration options");
440 if (sdi->probe_groups) {
442 printf(" across all probe groups");
444 printf(" on probe group %s", probe_group->name);
447 opts = g_variant_get_fixed_array(gvar_opts, &num_opts, sizeof(int32_t));
448 for (o = 0; o < num_opts; o++) {
449 if (!(srci = sr_config_info_get(opts[o])))
452 if (srci->key == SR_CONF_TRIGGER_TYPE) {
453 if (sr_config_list(sdi->driver, sdi, probe_group, srci->key,
458 charopts = g_variant_get_string(gvar, NULL);
459 printf(" Supported triggers: ");
461 printf("%c ", *charopts);
465 g_variant_unref(gvar);
467 } else if (srci->key == SR_CONF_PATTERN_MODE) {
468 /* Pattern generator modes */
469 printf(" %s", srci->id);
470 if (sr_config_list(sdi->driver, sdi, probe_group, srci->key,
472 printf(" - supported patterns:\n");
473 stropts = g_variant_get_strv(gvar, &num_elements);
474 for (i = 0; i < num_elements; i++)
475 printf(" %s\n", stropts[i]);
476 g_variant_unref(gvar);
481 } else if (srci->key == SR_CONF_SAMPLERATE) {
482 /* Supported samplerates */
483 printf(" %s", srci->id);
484 if (sr_config_list(sdi->driver, sdi, probe_group, SR_CONF_SAMPLERATE,
485 &gvar_dict) != SR_OK) {
489 if ((gvar_list = g_variant_lookup_value(gvar_dict,
490 "samplerates", G_VARIANT_TYPE("at")))) {
491 uint64 = g_variant_get_fixed_array(gvar_list,
492 &num_elements, sizeof(uint64_t));
493 printf(" - supported samplerates:\n");
494 for (i = 0; i < num_elements; i++) {
495 if (!(s = sr_samplerate_string(uint64[i])))
500 g_variant_unref(gvar_list);
501 } else if ((gvar_list = g_variant_lookup_value(gvar_dict,
502 "samplerate-steps", G_VARIANT_TYPE("at")))) {
503 uint64 = g_variant_get_fixed_array(gvar_list,
504 &num_elements, sizeof(uint64_t));
506 if (!(s = sr_samplerate_string(uint64[0])))
511 if (!(s = sr_samplerate_string(uint64[1])))
516 if (!(s = sr_samplerate_string(uint64[2])))
518 printf(" in steps of %s)\n", s);
520 g_variant_unref(gvar_list);
522 g_variant_unref(gvar_dict);
524 } else if (srci->key == SR_CONF_BUFFERSIZE) {
525 /* Supported buffer sizes */
526 printf(" %s", srci->id);
527 if (sr_config_list(sdi->driver, sdi, probe_group,
528 SR_CONF_BUFFERSIZE, &gvar_list) != SR_OK) {
532 uint64 = g_variant_get_fixed_array(gvar_list,
533 &num_elements, sizeof(uint64_t));
534 printf(" - supported buffer sizes:\n");
535 for (i = 0; i < num_elements; i++)
536 printf(" %"PRIu64"\n", uint64[i]);
537 g_variant_unref(gvar_list);
539 } else if (srci->key == SR_CONF_TIMEBASE) {
540 /* Supported time bases */
541 printf(" %s", srci->id);
542 if (sr_config_list(sdi->driver, sdi, probe_group,
543 SR_CONF_TIMEBASE, &gvar_list) != SR_OK) {
547 printf(" - supported time bases:\n");
548 num_elements = g_variant_n_children(gvar_list);
549 for (i = 0; i < num_elements; i++) {
550 gvar = g_variant_get_child_value(gvar_list, i);
551 g_variant_get(gvar, "(tt)", &p, &q);
552 s = sr_period_string(p * q);
556 g_variant_unref(gvar_list);
558 } else if (srci->key == SR_CONF_VDIV) {
559 /* Supported volts/div values */
560 printf(" %s", srci->id);
561 if (sr_config_list(sdi->driver, sdi, probe_group,
562 SR_CONF_VDIV, &gvar_list) != SR_OK) {
566 printf(" - supported volts/div:\n");
567 num_elements = g_variant_n_children(gvar_list);
568 for (i = 0; i < num_elements; i++) {
569 gvar = g_variant_get_child_value(gvar_list, i);
570 g_variant_get(gvar, "(tt)", &p, &q);
571 s = sr_voltage_string(p, q);
575 g_variant_unref(gvar_list);
577 } else if (srci->datatype == SR_T_CHAR) {
578 printf(" %s: ", srci->id);
579 if (sr_config_get(sdi->driver, sdi, probe_group, srci->key,
581 tmp_str = g_strdup(g_variant_get_string(gvar, NULL));
582 g_variant_unref(gvar);
586 if (sr_config_list(sdi->driver, sdi, probe_group, srci->key,
592 stropts = g_variant_get_strv(gvar, &num_elements);
593 for (i = 0; i < num_elements; i++) {
596 printf("%s", stropts[i]);
597 if (tmp_str && !strcmp(tmp_str, stropts[i]))
598 printf(" (current)");
603 g_variant_unref(gvar);
605 } else if (srci->datatype == SR_T_UINT64_RANGE) {
606 printf(" %s: ", srci->id);
607 if (sr_config_list(sdi->driver, sdi, probe_group, srci->key,
608 &gvar_list) != SR_OK) {
613 if (sr_config_get(sdi->driver, sdi, NULL, srci->key, &gvar) == SR_OK) {
614 g_variant_get(gvar, "(tt)", &cur_low, &cur_high);
615 g_variant_unref(gvar);
621 num_elements = g_variant_n_children(gvar_list);
622 for (i = 0; i < num_elements; i++) {
623 gvar = g_variant_get_child_value(gvar_list, i);
624 g_variant_get(gvar, "(tt)", &low, &high);
625 g_variant_unref(gvar);
628 printf("%"PRIu64"-%"PRIu64, low, high);
629 if (low == cur_low && high == cur_high)
630 printf(" (current)");
633 g_variant_unref(gvar_list);
635 } else if (srci->datatype == SR_T_BOOL) {
636 printf(" %s: ", srci->id);
637 if (sr_config_get(sdi->driver, sdi, NULL, srci->key,
639 if (g_variant_get_boolean(gvar))
640 printf("on (current), off\n");
642 printf("on, off (current)\n");
643 g_variant_unref(gvar);
649 /* Everything else */
650 printf(" %s\n", srci->id);
653 g_variant_unref(gvar_opts);
656 g_slist_free(devices);
661 static void show_pd_detail(void)
664 struct srd_decoder *dec;
665 struct srd_decoder_option *o;
666 char **pdtokens, **pdtok, *optsep, **ann, *val, *doc;
669 pdtokens = g_strsplit(opt_pds, ",", -1);
670 for (pdtok = pdtokens; *pdtok; pdtok++) {
672 if ((optsep = strchr(*pdtok, ':')))
674 if (!(dec = srd_decoder_get_by_id(*pdtok))) {
675 g_critical("Protocol decoder %s not found.", *pdtok);
678 printf("ID: %s\nName: %s\nLong name: %s\nDescription: %s\n",
679 dec->id, dec->name, dec->longname, dec->desc);
680 printf("License: %s\n", dec->license);
681 printf("Annotations:\n");
682 if (dec->annotations) {
683 for (l = dec->annotations; l; l = l->next) {
685 printf("- %s\n %s\n", ann[0], ann[1]);
690 printf("Required probes:\n");
692 for (l = dec->probes; l; l = l->next) {
694 printf("- %s (%s): %s\n",
695 p->name, p->id, p->desc);
700 printf("Optional probes:\n");
701 if (dec->opt_probes) {
702 for (l = dec->opt_probes; l; l = l->next) {
704 printf("- %s (%s): %s\n",
705 p->name, p->id, p->desc);
711 printf("Options:\n");
712 for (l = dec->options; l; l = l->next) {
714 val = g_variant_print(o->def, FALSE);
715 printf("- %s: %s (default %s)\n", o->id, o->desc, val);
719 if ((doc = srd_decoder_doc_get(dec))) {
720 printf("Documentation:\n%s\n",
721 doc[0] == '\n' ? doc + 1 : doc);
726 g_strfreev(pdtokens);
730 static GArray *get_enabled_logic_probes(const struct sr_dev_inst *sdi)
732 struct sr_probe *probe;
736 probes = g_array_new(FALSE, FALSE, sizeof(int));
737 for (l = sdi->probes; l; l = l->next) {
739 if (probe->type != SR_PROBE_LOGIC)
741 if (probe->enabled != TRUE)
743 g_array_append_val(probes, probe->index);
749 static void datafeed_in(const struct sr_dev_inst *sdi,
750 const struct sr_datafeed_packet *packet, void *cb_data)
752 const struct sr_datafeed_meta *meta;
753 const struct sr_datafeed_logic *logic;
754 const struct sr_datafeed_analog *analog;
755 struct sr_config *src;
756 static struct sr_output *o = NULL;
757 static GArray *logic_probelist = NULL;
758 static uint64_t received_samples = 0;
759 static int unitsize = 0;
760 static int triggered = 0;
761 static FILE *outfile = NULL;
764 int sample_size, ret;
765 uint64_t samplerate, output_len, filter_out_len, end_sample;
766 uint8_t *output_buf, *filter_out;
770 /* If the first packet to come in isn't a header, don't even try. */
771 if (packet->type != SR_DF_HEADER && o == NULL)
775 switch (packet->type) {
777 g_debug("cli: Received SR_DF_HEADER");
778 /* Initialize the output module. */
779 if (!(o = g_try_malloc(sizeof(struct sr_output)))) {
780 g_critical("Output module malloc failed.");
783 o->format = output_format;
784 o->sdi = (struct sr_dev_inst *)sdi;
785 o->param = output_format_param;
786 if (o->format->init) {
787 if (o->format->init(o) != SR_OK) {
788 g_critical("Output format initialization failed.");
793 /* Prepare non-stdout output. */
795 if (opt_output_file) {
796 if (default_output_format) {
797 /* output file is in session format, so we'll
798 * keep a copy of everything as it comes in
799 * and save from there after the session. */
801 savebuf = g_byte_array_new();
803 /* saving to a file in whatever format was set
804 * with --format, so all we need is a filehandle */
805 outfile = g_fopen(opt_output_file, "wb");
809 /* Prepare for logic data. */
810 logic_probelist = get_enabled_logic_probes(sdi);
811 /* How many bytes we need to store the packed samples. */
812 unitsize = (logic_probelist->len + 7) / 8;
816 if (opt_pds && logic_probelist->len) {
817 if (sr_config_get(sdi->driver, sdi, NULL, SR_CONF_SAMPLERATE,
819 samplerate = g_variant_get_uint64(gvar);
820 g_variant_unref(gvar);
821 if (srd_session_metadata_set(srd_sess, SRD_CONF_SAMPLERATE,
822 g_variant_new_uint64(samplerate)) != SRD_OK) {
823 g_critical("Failed to configure decode session.");
827 if (srd_session_start(srd_sess) != SRD_OK) {
828 g_critical("Failed to start decode session.");
836 g_debug("cli: received SR_DF_META");
837 meta = packet->payload;
838 for (l = meta->config; l; l = l->next) {
841 case SR_CONF_SAMPLERATE:
842 samplerate = g_variant_get_uint64(src->data);
843 g_debug("cli: got samplerate %"PRIu64" Hz", samplerate);
846 if (srd_session_metadata_set(srd_sess, SRD_CONF_SAMPLERATE,
847 g_variant_new_uint64(samplerate)) != SRD_OK) {
848 g_critical("Failed to pass samplerate to decoder.");
853 case SR_CONF_SAMPLE_INTERVAL:
854 samplerate = g_variant_get_uint64(src->data);
855 g_debug("cli: got sample interval %"PRIu64" ms", samplerate);
858 /* Unknown metadata is not an error. */
865 g_debug("cli: received SR_DF_TRIGGER");
866 if (o->format->event)
867 o->format->event(o, SR_DF_TRIGGER, &output_buf,
873 logic = packet->payload;
874 g_message("cli: received SR_DF_LOGIC, %"PRIu64" bytes", logic->length);
875 sample_size = logic->unitsize;
876 if (logic->length == 0)
879 /* Don't store any samples until triggered. */
880 if (opt_wait_trigger && !triggered)
883 if (limit_samples && received_samples >= limit_samples)
886 ret = sr_filter_probes(sample_size, unitsize, logic_probelist,
887 logic->data, logic->length,
888 &filter_out, &filter_out_len);
893 * What comes out of the filter is guaranteed to be packed into the
894 * minimum size needed to support the number of samples at this sample
895 * size. however, the driver may have submitted too much. Cut off
896 * the buffer of the last packet according to the sample limit.
898 if (limit_samples && (received_samples + logic->length / sample_size >
899 limit_samples * sample_size))
900 filter_out_len = limit_samples * sample_size - received_samples;
902 if (opt_output_file && default_output_format) {
903 /* Saving to a session file. */
904 g_byte_array_append(savebuf, filter_out, filter_out_len);
908 end_sample = received_samples + filter_out_len / unitsize;
909 if (srd_session_send(srd_sess, received_samples, end_sample,
910 (uint8_t*)filter_out, filter_out_len) != SRD_OK)
915 if (o->format->data && packet->type == o->format->df_type)
916 o->format->data(o, filter_out, filter_out_len,
917 &output_buf, &output_len);
919 fwrite(output_buf, 1, output_len, outfile);
927 received_samples += logic->length / sample_size;
931 analog = packet->payload;
932 g_message("cli: received SR_DF_ANALOG, %d samples", analog->num_samples);
933 if (analog->num_samples == 0)
936 if (limit_samples && received_samples >= limit_samples)
939 if (o->format->data && packet->type == o->format->df_type) {
940 o->format->data(o, (const uint8_t *)analog->data,
941 analog->num_samples * sizeof(float),
942 &output_buf, &output_len);
944 fwrite(output_buf, 1, output_len, outfile);
950 received_samples += analog->num_samples;
953 case SR_DF_FRAME_BEGIN:
954 g_debug("cli: received SR_DF_FRAME_BEGIN");
955 if (o->format->event) {
956 o->format->event(o, SR_DF_FRAME_BEGIN, &output_buf,
959 fwrite(output_buf, 1, output_len, outfile);
966 case SR_DF_FRAME_END:
967 g_debug("cli: received SR_DF_FRAME_END");
968 if (o->format->event) {
969 o->format->event(o, SR_DF_FRAME_END, &output_buf,
972 fwrite(output_buf, 1, output_len, outfile);
983 if (o && o->format->receive) {
984 if (o->format->receive(o, sdi, packet, &out) == SR_OK && out) {
985 fwrite(out->str, 1, out->len, outfile);
987 g_string_free(out, TRUE);
991 /* SR_DF_END needs to be handled after the output module's receive()
992 * is called, so it can properly clean up that module etc. */
993 if (packet->type == SR_DF_END) {
994 g_debug("cli: Received SR_DF_END");
996 if (o->format->event) {
997 o->format->event(o, SR_DF_END, &output_buf, &output_len);
1000 fwrite(output_buf, 1, output_len, outfile);
1006 if (limit_samples && received_samples < limit_samples)
1007 g_warning("Device only sent %" PRIu64 " samples.",
1011 g_warning("Device stopped after %" PRIu64 " samples.",
1014 g_array_free(logic_probelist, TRUE);
1016 if (o->format->cleanup)
1017 o->format->cleanup(o);
1021 if (outfile && outfile != stdout)
1024 if (opt_output_file && default_output_format && savebuf->len) {
1025 if (sr_session_save(opt_output_file, sdi, savebuf->data,
1026 unitsize, savebuf->len / unitsize) != SR_OK)
1027 g_critical("Failed to save session.");
1028 g_byte_array_free(savebuf, FALSE);
1035 static int opts_to_gvar(struct srd_decoder *dec, GHashTable *hash,
1036 GHashTable **options)
1038 struct srd_decoder_option *o;
1043 char *val_str, *conv;
1046 *options = g_hash_table_new_full(g_str_hash, g_str_equal, g_free,
1047 (GDestroyNotify)g_variant_unref);
1049 for (optl = dec->options; optl; optl = optl->next) {
1051 if (!(val_str = g_hash_table_lookup(hash, o->id)))
1052 /* Not specified. */
1054 if (g_variant_is_of_type(o->def, G_VARIANT_TYPE_STRING)) {
1055 gvar = g_variant_new_string(val_str);
1056 } else if (g_variant_is_of_type(o->def, G_VARIANT_TYPE_INT64)) {
1057 val_int = strtoll(val_str, &conv, 0);
1058 if (!conv || conv == val_str) {
1059 g_critical("Protocol decoder '%s' option '%s' "
1060 "requires a number.", dec->name, o->id);
1064 gvar = g_variant_new_int64(val_int);
1066 g_critical("Unsupported type for option '%s' (%s)",
1067 o->id, g_variant_get_type_string(o->def));
1071 g_variant_ref_sink(gvar);
1072 g_hash_table_insert(*options, g_strdup(o->id), gvar);
1073 g_hash_table_remove(hash, o->id);
1079 static int probes_to_gvar(struct srd_decoder *dec, GHashTable *hash,
1080 GHashTable **probes)
1082 struct srd_probe *p;
1083 GSList *all_probes, *l;
1087 char *val_str, *conv;
1090 *probes = g_hash_table_new_full(g_str_hash, g_str_equal, g_free,
1091 (GDestroyNotify)g_variant_unref);
1093 all_probes = g_slist_copy(dec->probes);
1094 all_probes = g_slist_concat(all_probes, g_slist_copy(dec->opt_probes));
1095 for (l = all_probes; l; l = l->next) {
1097 if (!(val_str = g_hash_table_lookup(hash, p->id)))
1098 /* Not specified. */
1100 val_int = strtoll(val_str, &conv, 10);
1101 if (!conv || conv == val_str) {
1102 g_critical("Protocol decoder '%s' probes '%s' "
1103 "is not a number.", dec->name, p->id);
1107 gvar = g_variant_new_int32(val_int);
1108 g_variant_ref_sink(gvar);
1109 g_hash_table_insert(*probes, g_strdup(p->id), gvar);
1110 g_hash_table_remove(hash, p->id);
1112 g_slist_free(all_probes);
1117 /* Register the given PDs for this session.
1118 * Accepts a string of the form: "spi:sck=3:sdata=4,spi:sck=3:sdata=5"
1119 * That will instantiate two SPI decoders on the clock but different data
1122 static int register_pds(struct sr_dev *dev, const char *pdstring)
1124 struct srd_decoder *dec;
1125 GHashTable *pd_opthash, *options, *probes;
1126 GList *leftover, *l;
1127 struct srd_decoder_inst *di;
1129 char **pdtokens, **pdtok, *pd_name;
1133 pd_ann_visible = g_hash_table_new_full(g_str_hash, g_int_equal,
1137 pd_opthash = options = probes = NULL;
1138 pdtokens = g_strsplit(pdstring, ",", 0);
1139 for (pdtok = pdtokens; *pdtok; pdtok++) {
1140 if (!(pd_opthash = parse_generic_arg(*pdtok, TRUE))) {
1141 g_critical("Invalid protocol decoder option '%s'.", *pdtok);
1145 pd_name = g_strdup(g_hash_table_lookup(pd_opthash, "sigrok_key"));
1146 g_hash_table_remove(pd_opthash, "sigrok_key");
1147 if (srd_decoder_load(pd_name) != SRD_OK) {
1148 g_critical("Failed to load protocol decoder %s.", pd_name);
1152 dec = srd_decoder_get_by_id(pd_name);
1154 /* Convert decoder option and probe values to GVariant. */
1155 if (!opts_to_gvar(dec, pd_opthash, &options)) {
1159 if (!probes_to_gvar(dec, pd_opthash, &probes)) {
1163 if (g_hash_table_size(pd_opthash) > 0) {
1164 leftover = g_hash_table_get_keys(pd_opthash);
1165 for (l = leftover; l; l = l->next)
1166 g_critical("Unknown option or probe '%s'", (char *)l->data);
1167 g_list_free(leftover);
1171 if (!(di = srd_inst_new(srd_sess, pd_name, options))) {
1172 g_critical("Failed to instantiate protocol decoder %s.", pd_name);
1177 /* If no annotation list was specified, add them all in now.
1178 * This will be pared down later to leave only the last PD
1181 if (!opt_pd_annotations)
1182 g_hash_table_insert(pd_ann_visible,
1183 g_strdup(di->inst_id), GINT_TO_POINTER(-1));
1185 /* Remap the probes if needed. */
1186 if (srd_inst_probe_set_all(di, probes) != SRD_OK) {
1192 g_strfreev(pdtokens);
1194 g_hash_table_destroy(pd_opthash);
1196 g_hash_table_destroy(options);
1198 g_hash_table_destroy(probes);
1205 int setup_pd_stack(void)
1207 struct srd_decoder_inst *di_from, *di_to;
1211 /* Set up the protocol decoder stack. */
1212 pds = g_strsplit(opt_pds, ",", 0);
1213 if (g_strv_length(pds) > 1) {
1215 /* A stack setup was specified, use that. */
1217 pds = g_strsplit(opt_pd_stack, ",", 0);
1218 if (g_strv_length(pds) < 2) {
1220 g_critical("Specify at least two protocol decoders to stack.");
1225 /* First PD goes at the bottom of the stack. */
1226 ids = g_strsplit(pds[0], ":", 0);
1227 if (!(di_from = srd_inst_find_by_id(srd_sess, ids[0]))) {
1229 g_critical("Cannot stack protocol decoder '%s': "
1230 "instance not found.", pds[0]);
1235 /* Every subsequent PD goes on top. */
1236 for (i = 1; pds[i]; i++) {
1237 ids = g_strsplit(pds[i], ":", 0);
1238 if (!(di_to = srd_inst_find_by_id(srd_sess, ids[0]))) {
1240 g_critical("Cannot stack protocol decoder '%s': "
1241 "instance not found.", pds[i]);
1245 if ((ret = srd_inst_stack(srd_sess, di_from, di_to)) != SRD_OK)
1248 /* Don't show annotation from this PD. Only the last PD in
1249 * the stack will be left on the annotation list (unless
1250 * the annotation list was specifically provided).
1252 if (!opt_pd_annotations)
1253 g_hash_table_remove(pd_ann_visible,
1264 int setup_pd_annotations(void)
1267 struct srd_decoder *dec;
1269 char **pds, **pdtok, **keyval, **ann_descr;
1271 /* Set up custom list of PDs and annotations to show. */
1272 pds = g_strsplit(opt_pd_annotations, ",", 0);
1273 for (pdtok = pds; *pdtok && **pdtok; pdtok++) {
1274 keyval = g_strsplit(*pdtok, "=", 0);
1275 if (!(dec = srd_decoder_get_by_id(keyval[0]))) {
1276 g_critical("Protocol decoder '%s' not found.", keyval[0]);
1279 if (!dec->annotations) {
1280 g_critical("Protocol decoder '%s' has no annotations.", keyval[0]);
1284 if (g_strv_length(keyval) == 2) {
1285 for (l = dec->annotations; l; l = l->next, ann_class++) {
1286 ann_descr = l->data;
1287 if (!canon_cmp(ann_descr[0], keyval[1]))
1292 g_critical("Annotation '%s' not found "
1293 "for protocol decoder '%s'.", keyval[1], keyval[0]);
1296 g_debug("cli: Showing protocol decoder %s annotation "
1297 "class %d (%s).", keyval[0], ann_class, ann_descr[0]);
1299 /* No class specified: show all of them. */
1301 g_debug("cli: Showing all annotation classes for protocol "
1302 "decoder %s.", keyval[0]);
1304 g_hash_table_insert(pd_ann_visible, g_strdup(keyval[0]), GINT_TO_POINTER(ann_class));
1312 int setup_pd_meta(void)
1314 struct srd_decoder *dec;
1315 char **pds, **pdtok;
1317 pd_meta_visible = g_hash_table_new_full(g_str_hash, g_int_equal,
1319 pds = g_strsplit(opt_pd_meta, ",", 0);
1320 for (pdtok = pds; *pdtok && **pdtok; pdtok++) {
1321 if (!(dec = srd_decoder_get_by_id(*pdtok))) {
1322 g_critical("Protocol decoder '%s' not found.", *pdtok);
1325 g_debug("cli: Showing protocol decoder meta output from '%s'.", *pdtok);
1326 g_hash_table_insert(pd_meta_visible, g_strdup(*pdtok), NULL);
1333 int setup_pd_binary(void)
1336 struct srd_decoder *dec;
1338 char **pds, **pdtok, **keyval, *bin_name;
1340 pd_binary_visible = g_hash_table_new_full(g_str_hash, g_int_equal,
1342 pds = g_strsplit(opt_pd_binary, ",", 0);
1343 for (pdtok = pds; *pdtok && **pdtok; pdtok++) {
1344 keyval = g_strsplit(*pdtok, "=", 0);
1345 if (!(dec = srd_decoder_get_by_id(keyval[0]))) {
1346 g_critical("Protocol decoder '%s' not found.", keyval[0]);
1350 g_critical("Protocol decoder '%s' has no binary output.", keyval[0]);
1354 if (g_strv_length(keyval) == 2) {
1355 for (l = dec->binary; l; l = l->next, bin_class++) {
1357 if (!canon_cmp(bin_name, keyval[1]))
1362 g_critical("binary output '%s' not found "
1363 "for protocol decoder '%s'.", keyval[1], keyval[0]);
1366 g_debug("cli: Showing protocol decoder %s binary class "
1367 "%d (%s).", keyval[0], bin_class, bin_name);
1369 /* No class specified: output all of them. */
1371 g_debug("cli: Showing all binary classes for protocol "
1372 "decoder %s.", keyval[0]);
1374 g_hash_table_insert(pd_binary_visible, g_strdup(keyval[0]), GINT_TO_POINTER(bin_class));
1382 void show_pd_annotations(struct srd_proto_data *pdata, void *cb_data)
1384 struct srd_proto_data_annotation *pda;
1385 gpointer ann_format;
1388 /* 'cb_data' is not used in this specific callback. */
1391 if (!pd_ann_visible)
1394 if (!g_hash_table_lookup_extended(pd_ann_visible, pdata->pdo->di->inst_id,
1396 /* Not in the list of PDs whose annotations we're showing. */
1399 format = GPOINTER_TO_INT(ann_format);
1401 if (format != -1 && pda->ann_format != format)
1402 /* We don't want this particular format from the PD. */
1405 if (opt_loglevel > SR_LOG_WARN)
1406 printf("%"PRIu64"-%"PRIu64" ", pdata->start_sample, pdata->end_sample);
1407 printf("%s: ", pdata->pdo->proto_id);
1408 /* Show only the longest annotation. */
1409 printf("\"%s\" ", pda->ann_text[0]);
1414 void show_pd_meta(struct srd_proto_data *pdata, void *cb_data)
1417 /* 'cb_data' is not used in this specific callback. */
1420 if (!g_hash_table_lookup_extended(pd_meta_visible,
1421 pdata->pdo->di->decoder->id, NULL, NULL))
1422 /* Not in the list of PDs whose meta output we're showing. */
1425 if (opt_loglevel > SR_LOG_WARN)
1426 printf("%"PRIu64"-%"PRIu64" ", pdata->start_sample, pdata->end_sample);
1427 printf("%s: ", pdata->pdo->proto_id);
1428 printf("%s: %s", pdata->pdo->meta_name, g_variant_print(pdata->data, FALSE));
1433 void show_pd_binary(struct srd_proto_data *pdata, void *cb_data)
1435 struct srd_proto_data_binary *pdb;
1439 /* 'cb_data' is not used in this specific callback. */
1442 if (!g_hash_table_lookup_extended(pd_binary_visible,
1443 pdata->pdo->di->decoder->id, NULL, (void **)&classp))
1444 /* Not in the list of PDs whose meta output we're showing. */
1447 class = GPOINTER_TO_INT(classp);
1449 if (class != -1 && class != pdb->bin_class)
1450 /* Not showing this binary class. */
1453 /* Just send the binary output to stdout, no embellishments. */
1454 fwrite(pdb->data, pdb->size, 1, stdout);
1459 int setup_output_format(void)
1461 GHashTable *fmtargs;
1462 GHashTableIter iter;
1463 gpointer key, value;
1464 struct sr_output_format **outputs;
1468 if (opt_output_format && !strcmp(opt_output_format, "sigrok")) {
1469 /* Doesn't really exist as an output module - this is
1470 * the session save mode. */
1471 g_free(opt_output_format);
1472 opt_output_format = NULL;
1475 if (!opt_output_format) {
1476 opt_output_format = DEFAULT_OUTPUT_FORMAT;
1477 /* we'll need to remember this so when saving to a file
1478 * later, sigrok session format will be used.
1480 default_output_format = TRUE;
1483 fmtargs = parse_generic_arg(opt_output_format, TRUE);
1484 fmtspec = g_hash_table_lookup(fmtargs, "sigrok_key");
1486 g_critical("Invalid output format.");
1489 outputs = sr_output_list();
1490 for (i = 0; outputs[i]; i++) {
1491 if (strcmp(outputs[i]->id, fmtspec))
1493 g_hash_table_remove(fmtargs, "sigrok_key");
1494 output_format = outputs[i];
1495 g_hash_table_iter_init(&iter, fmtargs);
1496 while (g_hash_table_iter_next(&iter, &key, &value)) {
1497 /* only supporting one parameter per output module
1498 * for now, and only its value */
1499 output_format_param = g_strdup(value);
1504 if (!output_format) {
1505 g_critical("Invalid output format %s.", opt_output_format);
1508 g_hash_table_destroy(fmtargs);
1513 static int select_probes(struct sr_dev_inst *sdi)
1515 struct sr_probe *probe;
1516 GSList *selected_probes, *l;
1521 if (!(selected_probes = parse_probestring(sdi, opt_probes)))
1524 for (l = sdi->probes; l; l = l->next) {
1526 if (g_slist_find(selected_probes, probe))
1527 probe->enabled = TRUE;
1529 probe->enabled = FALSE;
1531 g_slist_free(selected_probes);
1537 * Return the input file format which the CLI tool should use.
1539 * If the user specified -I / --input-format, use that one. Otherwise, try to
1540 * autodetect the format as good as possible. Failing that, return NULL.
1542 * @param filename The filename of the input file. Must not be NULL.
1543 * @param opt The -I / --input-file option the user specified (or NULL).
1545 * @return A pointer to the 'struct sr_input_format' that should be used,
1546 * or NULL if no input format was selected or auto-detected.
1548 static struct sr_input_format *determine_input_file_format(
1549 const char *filename, const char *opt)
1552 struct sr_input_format **inputs;
1554 /* If there are no input formats, return NULL right away. */
1555 inputs = sr_input_list();
1557 g_critical("No supported input formats available.");
1561 /* If the user specified -I / --input-format, use that one. */
1563 for (i = 0; inputs[i]; i++) {
1564 if (strcasecmp(inputs[i]->id, opt))
1566 g_debug("Using user-specified input file format '%s'.",
1571 /* The user specified an unknown input format, return NULL. */
1572 g_critical("Error: specified input file format '%s' is "
1577 /* Otherwise, try to find an input module that can handle this file. */
1578 for (i = 0; inputs[i]; i++) {
1579 if (inputs[i]->format_match(filename))
1583 /* Return NULL if no input module wanted to touch this. */
1585 g_critical("Error: no matching input module found.");
1589 g_debug("cli: Autodetected '%s' input format for file '%s'.",
1590 inputs[i]->id, filename);
1595 static void load_input_file_format(void)
1597 GHashTable *fmtargs = NULL;
1599 struct sr_input *in;
1600 struct sr_input_format *input_format;
1601 char *fmtspec = NULL;
1603 if (opt_input_format) {
1604 fmtargs = parse_generic_arg(opt_input_format, TRUE);
1605 fmtspec = g_hash_table_lookup(fmtargs, "sigrok_key");
1608 if (!(input_format = determine_input_file_format(opt_input_file,
1610 /* The exact cause was already logged. */
1615 g_hash_table_remove(fmtargs, "sigrok_key");
1617 if (stat(opt_input_file, &st) == -1) {
1618 g_critical("Failed to load %s: %s", opt_input_file,
1623 /* Initialize the input module. */
1624 if (!(in = g_try_malloc(sizeof(struct sr_input)))) {
1625 g_critical("Failed to allocate input module.");
1628 in->format = input_format;
1629 in->param = fmtargs;
1630 if (in->format->init) {
1631 if (in->format->init(in, opt_input_file) != SR_OK) {
1632 g_critical("Input format init failed.");
1637 if (select_probes(in->sdi) > 0)
1641 sr_session_datafeed_callback_add(datafeed_in, NULL);
1642 if (sr_session_dev_add(in->sdi) != SR_OK) {
1643 g_critical("Failed to use device.");
1644 sr_session_destroy();
1648 input_format->loadfile(in, opt_input_file);
1650 sr_session_destroy();
1653 g_hash_table_destroy(fmtargs);
1656 static void load_input_file(void)
1659 if (sr_session_load(opt_input_file) == SR_OK) {
1660 /* sigrok session file */
1661 sr_session_datafeed_callback_add(datafeed_in, NULL);
1667 /* fall back on input modules */
1668 load_input_file_format();
1672 static int set_dev_options(struct sr_dev_inst *sdi, GHashTable *args)
1674 const struct sr_config_info *srci;
1675 struct sr_probe_group *pg;
1676 GHashTableIter iter;
1677 gpointer key, value;
1680 uint64_t tmp_u64, p, q, low, high;
1682 GVariant *val, *rational[2], *range[2];
1684 g_hash_table_iter_init(&iter, args);
1685 while (g_hash_table_iter_next(&iter, &key, &value)) {
1686 if (!(srci = sr_config_info_name_get(key))) {
1687 g_critical("Unknown device option '%s'.", (char *) key);
1691 if ((value == NULL) &&
1692 (srci->datatype != SR_T_BOOL)) {
1693 g_critical("Option '%s' needs a value.", (char *)key);
1697 switch (srci->datatype) {
1699 ret = sr_parse_sizestring(value, &tmp_u64);
1702 val = g_variant_new_uint64(tmp_u64);
1705 val = g_variant_new_string(value);
1711 tmp_bool = sr_parse_boolstring(value);
1712 val = g_variant_new_boolean(tmp_bool);
1715 tmp_double = strtof(value, NULL);
1716 val = g_variant_new_double(tmp_double);
1718 case SR_T_RATIONAL_PERIOD:
1719 if ((ret = sr_parse_period(value, &p, &q)) != SR_OK)
1721 rational[0] = g_variant_new_uint64(p);
1722 rational[1] = g_variant_new_uint64(q);
1723 val = g_variant_new_tuple(rational, 2);
1725 case SR_T_RATIONAL_VOLT:
1726 if ((ret = sr_parse_voltage(value, &p, &q)) != SR_OK)
1728 rational[0] = g_variant_new_uint64(p);
1729 rational[1] = g_variant_new_uint64(q);
1730 val = g_variant_new_tuple(rational, 2);
1732 case SR_T_UINT64_RANGE:
1733 if (sscanf(value, "%"PRIu64"-%"PRIu64, &low, &high) != 2) {
1737 range[0] = g_variant_new_uint64(low);
1738 range[1] = g_variant_new_uint64(high);
1739 val = g_variant_new_tuple(range, 2);
1746 pg = select_probe_group(sdi);
1747 ret = sr_config_set(sdi, pg, srci->key, val);
1750 g_critical("Failed to set device option '%s'.", (char *)key);
1758 static void set_options(void)
1760 struct sr_dev_inst *sdi;
1762 GHashTable *devargs;
1765 g_critical("No setting specified.");
1769 if (!(devargs = parse_generic_arg(opt_config, FALSE)))
1772 if (!(devices = device_scan())) {
1773 g_critical("No devices found.");
1776 sdi = devices->data;
1778 if (sr_dev_open(sdi) != SR_OK) {
1779 g_critical("Failed to open device.");
1783 set_dev_options(sdi, devargs);
1786 g_slist_free(devices);
1787 g_hash_table_destroy(devargs);
1791 static int set_limit_time(const struct sr_dev_inst *sdi)
1795 uint64_t samplerate;
1797 if (!(time_msec = sr_parse_timestring(opt_time))) {
1798 g_critical("Invalid time '%s'", opt_time);
1802 if (sr_dev_has_option(sdi, SR_CONF_LIMIT_MSEC)) {
1803 gvar = g_variant_new_uint64(time_msec);
1804 if (sr_config_set(sdi, NULL, SR_CONF_LIMIT_MSEC, gvar) != SR_OK) {
1805 g_critical("Failed to configure time limit.");
1808 } else if (sr_dev_has_option(sdi, SR_CONF_SAMPLERATE)) {
1809 /* Convert to samples based on the samplerate. */
1810 sr_config_get(sdi->driver, sdi, NULL, SR_CONF_SAMPLERATE, &gvar);
1811 samplerate = g_variant_get_uint64(gvar);
1812 g_variant_unref(gvar);
1813 limit_samples = (samplerate) * time_msec / (uint64_t)1000;
1814 if (limit_samples == 0) {
1815 g_critical("Not enough time at this samplerate.");
1818 gvar = g_variant_new_uint64(limit_samples);
1819 if (sr_config_set(sdi, NULL, SR_CONF_LIMIT_SAMPLES, gvar) != SR_OK) {
1820 g_critical("Failed to configure time-based sample limit.");
1824 g_critical("This device does not support time limits.");
1831 static void run_session(void)
1834 GHashTable *devargs;
1836 struct sr_dev_inst *sdi;
1840 devices = device_scan();
1842 g_critical("No devices found.");
1845 if (g_slist_length(devices) > 1) {
1846 g_critical("sigrok-cli only supports one device for capturing.");
1849 sdi = devices->data;
1852 sr_session_datafeed_callback_add(datafeed_in, NULL);
1854 if (sr_dev_open(sdi) != SR_OK) {
1855 g_critical("Failed to open device.");
1859 if (sr_session_dev_add(sdi) != SR_OK) {
1860 g_critical("Failed to add device to session.");
1861 sr_session_destroy();
1866 if ((devargs = parse_generic_arg(opt_config, FALSE))) {
1867 if (set_dev_options(sdi, devargs) != SR_OK)
1869 g_hash_table_destroy(devargs);
1873 if (select_probes(sdi) != SR_OK) {
1874 g_critical("Failed to set probes.");
1875 sr_session_destroy();
1880 if (!(triggerlist = sr_parse_triggerstring(sdi, opt_triggers))) {
1881 sr_session_destroy();
1884 max_probes = g_slist_length(sdi->probes);
1885 for (i = 0; i < max_probes; i++) {
1886 if (triggerlist[i]) {
1887 sr_dev_trigger_set(sdi, i, triggerlist[i]);
1888 g_free(triggerlist[i]);
1891 g_free(triggerlist);
1894 if (opt_continuous) {
1895 if (!sr_dev_has_option(sdi, SR_CONF_CONTINUOUS)) {
1896 g_critical("This device does not support continuous sampling.");
1897 sr_session_destroy();
1903 if (set_limit_time(sdi) != SR_OK) {
1904 sr_session_destroy();
1910 if ((sr_parse_sizestring(opt_samples, &limit_samples) != SR_OK)) {
1911 g_critical("Invalid sample limit '%s'.", opt_samples);
1912 sr_session_destroy();
1915 gvar = g_variant_new_uint64(limit_samples);
1916 if (sr_config_set(sdi, NULL, SR_CONF_LIMIT_SAMPLES, gvar) != SR_OK) {
1917 g_critical("Failed to configure sample limit.");
1918 sr_session_destroy();
1924 if ((sr_parse_sizestring(opt_frames, &limit_frames) != SR_OK)) {
1925 g_critical("Invalid sample limit '%s'.", opt_samples);
1926 sr_session_destroy();
1929 gvar = g_variant_new_uint64(limit_frames);
1930 if (sr_config_set(sdi, NULL, SR_CONF_LIMIT_FRAMES, gvar) != SR_OK) {
1931 g_critical("Failed to configure frame limit.");
1932 sr_session_destroy();
1937 if (sr_session_start() != SR_OK) {
1938 g_critical("Failed to start session.");
1939 sr_session_destroy();
1951 sr_session_datafeed_callback_remove_all();
1952 sr_session_destroy();
1953 g_slist_free(devices);
1957 static void logger(const gchar *log_domain, GLogLevelFlags log_level,
1958 const gchar *message, gpointer cb_data)
1964 * All messages, warnings, errors etc. go to stderr (not stdout) in
1965 * order to not mess up the CLI tool data output, e.g. VCD output.
1967 if (log_level & (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING)
1968 || opt_loglevel > SR_LOG_WARN) {
1969 fprintf(stderr, "%s\n", message);
1973 if (log_level & (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL))
1978 int main(int argc, char **argv)
1980 GOptionContext *context;
1985 g_log_set_default_handler(logger, NULL);
1987 context = g_option_context_new(NULL);
1988 g_option_context_add_main_entries(context, optargs, NULL);
1992 if (!g_option_context_parse(context, &argc, &argv, &error)) {
1993 g_critical("%s", error->message);
1997 /* Set the loglevel (amount of messages to output) for libsigrok. */
1998 if (sr_log_loglevel_set(opt_loglevel) != SR_OK)
2001 if (sr_init(&sr_ctx) != SR_OK)
2005 /* Set the loglevel (amount of messages to output) for libsigrokdecode. */
2006 if (srd_log_loglevel_set(opt_loglevel) != SRD_OK)
2010 if (srd_init(NULL) != SRD_OK)
2012 if (srd_session_new(&srd_sess) != SRD_OK) {
2013 g_critical("Failed to create new decode session.");
2016 if (register_pds(NULL, opt_pds) != 0)
2018 if (setup_pd_stack() != 0)
2021 /* Only one output type is ever shown. */
2022 if (opt_pd_binary) {
2023 if (setup_pd_binary() != 0)
2025 if (srd_pd_output_callback_add(srd_sess, SRD_OUTPUT_BINARY,
2026 show_pd_binary, NULL) != SRD_OK)
2028 } else if (opt_pd_meta) {
2029 if (setup_pd_meta() != 0)
2031 if (srd_pd_output_callback_add(srd_sess, SRD_OUTPUT_META,
2032 show_pd_meta, NULL) != SRD_OK)
2035 if (opt_pd_annotations)
2036 if (setup_pd_annotations() != 0)
2038 if (srd_pd_output_callback_add(srd_sess, SRD_OUTPUT_ANN,
2039 show_pd_annotations, NULL) != SRD_OK)
2045 if (setup_output_format() != 0)
2050 else if (opt_scan_devs)
2053 else if (opt_pds && opt_show)
2058 else if (opt_input_file)
2062 else if (opt_samples || opt_time || opt_frames || opt_continuous)
2065 help = g_option_context_get_help(context, TRUE, NULL);
2081 g_option_context_free(context);