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 GHashTable *pd_ann_visible = NULL;
51 static GByteArray *savebuf;
53 static gboolean opt_version = FALSE;
54 static gint opt_loglevel = SR_LOG_WARN; /* Show errors+warnings per default. */
55 static gboolean opt_scan_devs = FALSE;
56 static gboolean opt_wait_trigger = FALSE;
57 static gchar *opt_input_file = NULL;
58 static gchar *opt_output_file = NULL;
59 static gchar *opt_drv = NULL;
60 static gchar *opt_config = NULL;
61 static gchar *opt_probes = NULL;
62 static gchar *opt_triggers = NULL;
63 static gchar *opt_pds = NULL;
65 static gchar *opt_pd_stack = NULL;
66 static gchar *opt_pd_annotations = NULL;
68 static gchar *opt_input_format = NULL;
69 static gchar *opt_output_format = NULL;
70 static gchar *opt_show = NULL;
71 static gchar *opt_time = NULL;
72 static gchar *opt_samples = NULL;
73 static gchar *opt_frames = NULL;
74 static gchar *opt_continuous = NULL;
75 static gchar *opt_set = NULL;
77 static GOptionEntry optargs[] = {
78 {"version", 'V', 0, G_OPTION_ARG_NONE, &opt_version,
79 "Show version and support list", NULL},
80 {"loglevel", 'l', 0, G_OPTION_ARG_INT, &opt_loglevel,
81 "Set loglevel (5 is most verbose)", NULL},
82 {"driver", 'd', 0, G_OPTION_ARG_STRING, &opt_drv,
83 "The driver to use", NULL},
84 {"config", 'c', 0, G_OPTION_ARG_STRING, &opt_config,
85 "Specify device configuration options", NULL},
86 {"input-file", 'i', 0, G_OPTION_ARG_FILENAME, &opt_input_file,
87 "Load input from file", NULL},
88 {"input-format", 'I', 0, G_OPTION_ARG_STRING, &opt_input_format,
89 "Input format", NULL},
90 {"output-file", 'o', 0, G_OPTION_ARG_FILENAME, &opt_output_file,
91 "Save output to file", NULL},
92 {"output-format", 'O', 0, G_OPTION_ARG_STRING, &opt_output_format,
93 "Output format", NULL},
94 {"probes", 'p', 0, G_OPTION_ARG_STRING, &opt_probes,
95 "Probes to use", NULL},
96 {"triggers", 't', 0, G_OPTION_ARG_STRING, &opt_triggers,
97 "Trigger configuration", NULL},
98 {"wait-trigger", 'w', 0, G_OPTION_ARG_NONE, &opt_wait_trigger,
99 "Wait for trigger", NULL},
101 {"protocol-decoders", 'P', 0, G_OPTION_ARG_STRING, &opt_pds,
102 "Protocol decoders to run", NULL},
103 {"protocol-decoder-stack", 'S', 0, G_OPTION_ARG_STRING, &opt_pd_stack,
104 "Protocol decoder stack", NULL},
105 {"protocol-decoder-annotations", 'A', 0, G_OPTION_ARG_STRING, &opt_pd_annotations,
106 "Protocol decoder annotation(s) to show", NULL},
108 {"scan", 0, 0, G_OPTION_ARG_NONE, &opt_scan_devs,
109 "Scan for devices", NULL},
110 {"show", 0, 0, G_OPTION_ARG_NONE, &opt_show,
111 "Show device detail", NULL},
112 {"time", 0, 0, G_OPTION_ARG_STRING, &opt_time,
113 "How long to sample (ms)", NULL},
114 {"samples", 0, 0, G_OPTION_ARG_STRING, &opt_samples,
115 "Number of samples to acquire", NULL},
116 {"frames", 0, 0, G_OPTION_ARG_STRING, &opt_frames,
117 "Number of frames to acquire", NULL},
118 {"continuous", 0, 0, G_OPTION_ARG_NONE, &opt_continuous,
119 "Sample continuously", NULL},
120 {"set", 0, 0, G_OPTION_ARG_NONE, &opt_set, "Set device options only", NULL},
121 {NULL, 0, 0, 0, NULL, NULL, NULL}
125 /* Convert driver options hash to GSList of struct sr_config. */
126 static GSList *hash_to_hwopt(GHashTable *hash)
128 const struct sr_config_info *srci;
129 struct sr_config *src;
134 keys = g_hash_table_get_keys(hash);
136 for (gl = keys; gl; gl = gl->next) {
138 if (!(srci = sr_config_info_name_get(key))) {
139 g_critical("Unknown option %s", key);
142 src = g_try_malloc(sizeof(struct sr_config));
143 src->key = srci->key;
144 value = g_hash_table_lookup(hash, key);
145 src->data = g_variant_new_string(value);
146 opts = g_slist_append(opts, src);
153 static void free_drvopts(struct sr_config *src)
155 g_variant_unref(src->data);
159 static GSList *device_scan(void)
161 struct sr_dev_driver **drivers, *driver;
163 GSList *drvopts, *devices, *tmpdevs, *l;
168 drvargs = parse_generic_arg(opt_drv, TRUE);
169 drvname = g_strdup(g_hash_table_lookup(drvargs, "sigrok_key"));
170 g_hash_table_remove(drvargs, "sigrok_key");
172 drivers = sr_driver_list();
173 for (i = 0; drivers[i]; i++) {
174 if (strcmp(drivers[i]->name, drvname))
179 g_critical("Driver %s not found.", drvname);
183 if (sr_driver_init(sr_ctx, driver) != SR_OK) {
184 g_critical("Failed to initialize driver.");
188 if (g_hash_table_size(drvargs) > 0) {
189 if (!(drvopts = hash_to_hwopt(drvargs))) {
190 /* Unknown options, already logged. */
191 g_hash_table_destroy(drvargs);
195 g_hash_table_destroy(drvargs);
196 devices = sr_driver_scan(driver, drvopts);
197 g_slist_free_full(drvopts, (GDestroyNotify)free_drvopts);
199 /* No driver specified, let them all scan on their own. */
201 drivers = sr_driver_list();
202 for (i = 0; drivers[i]; i++) {
204 if (sr_driver_init(sr_ctx, driver) != SR_OK) {
205 g_critical("Failed to initialize driver.");
208 tmpdevs = sr_driver_scan(driver, NULL);
209 for (l = tmpdevs; l; l = l->next)
210 devices = g_slist_append(devices, l->data);
211 g_slist_free(tmpdevs);
218 static void show_version(void)
220 struct sr_dev_driver **drivers;
221 struct sr_input_format **inputs;
222 struct sr_output_format **outputs;
225 struct srd_decoder *dec;
229 printf("sigrok-cli %s\n\n", VERSION);
231 printf("Using libsigrok %s (lib version %s).\n",
232 sr_package_version_string_get(), sr_lib_version_string_get());
234 printf("Using libsigrokdecode %s (lib version %s).\n\n",
235 srd_package_version_string_get(), srd_lib_version_string_get());
238 printf("Supported hardware drivers:\n");
239 drivers = sr_driver_list();
240 for (i = 0; drivers[i]; i++) {
241 printf(" %-20s %s\n", drivers[i]->name, drivers[i]->longname);
245 printf("Supported input formats:\n");
246 inputs = sr_input_list();
247 for (i = 0; inputs[i]; i++)
248 printf(" %-20s %s\n", inputs[i]->id, inputs[i]->description);
251 printf("Supported output formats:\n");
252 outputs = sr_output_list();
253 for (i = 0; outputs[i]; i++)
254 printf(" %-20s %s\n", outputs[i]->id, outputs[i]->description);
258 if (srd_init(NULL) == SRD_OK) {
259 printf("Supported protocol decoders:\n");
260 srd_decoder_load_all();
261 for (l = srd_decoder_list(); l; l = l->next) {
263 printf(" %-20s %s\n", dec->id, dec->longname);
264 /* Print protocol description upon "-l 3" or higher. */
265 if (opt_loglevel >= SR_LOG_INFO)
266 printf(" %-20s %s\n", "", dec->desc);
274 static void print_dev_line(const struct sr_dev_inst *sdi)
276 struct sr_probe *probe;
281 s = g_string_sized_new(128);
282 g_string_assign(s, sdi->driver->name);
283 if (sr_config_get(sdi->driver, SR_CONF_CONN, &gvar, sdi) == SR_OK) {
284 g_string_append(s, ":conn=");
285 g_string_append(s, g_variant_get_string(gvar, NULL));
286 g_variant_unref(gvar);
288 g_string_append(s, " - ");
289 if (sdi->vendor && sdi->vendor[0])
290 g_string_append_printf(s, "%s ", sdi->vendor);
291 if (sdi->model && sdi->model[0])
292 g_string_append_printf(s, "%s ", sdi->model);
293 if (sdi->version && sdi->version[0])
294 g_string_append_printf(s, "%s ", sdi->version);
296 if (g_slist_length(sdi->probes) == 1) {
297 probe = sdi->probes->data;
298 g_string_append_printf(s, "with 1 probe: %s", probe->name);
300 g_string_append_printf(s, "with %d probes:", g_slist_length(sdi->probes));
301 for (l = sdi->probes; l; l = l->next) {
303 g_string_append_printf(s, " %s", probe->name);
307 g_string_append_printf(s, "\n");
308 printf("%s", s->str);
309 g_string_free(s, TRUE);
313 static void show_dev_list(void)
315 struct sr_dev_inst *sdi;
318 if (!(devices = device_scan()))
321 printf("The following devices were found:\n");
322 for (l = devices; l; l = l->next) {
326 g_slist_free(devices);
330 static void show_dev_detail(void)
332 struct sr_dev_inst *sdi;
333 const struct sr_config_info *srci;
335 GVariant *gvar_opts, *gvar_dict, *gvar_list, *gvar;
336 gsize num_opts, num_elements;
337 const uint64_t *uint64, p, q;
339 unsigned int num_devices, tmp_bool, o, i;
341 const char *charopts, **stropts;
343 if (!(devices = device_scan())) {
344 g_critical("No devices found.");
348 num_devices = g_slist_length(devices);
349 if (num_devices > 1) {
350 g_critical("%d devices found. Use --scan to show them, "
351 "and select one to show.", num_devices);
358 if (sr_dev_open(sdi) != SR_OK) {
359 g_critical("Failed to open device.");
363 if ((sr_config_list(sdi->driver, SR_CONF_SCAN_OPTIONS, &gvar_opts,
365 opts = g_variant_get_fixed_array(gvar_opts, &num_elements,
367 printf("Supported driver options:\n");
368 for (i = 0; i < num_elements; i++) {
369 if (!(srci = sr_config_info_get(opts[i])))
371 printf(" %s\n", srci->id);
373 g_variant_unref(gvar_opts);
376 if ((sr_config_list(sdi->driver, SR_CONF_DEVICE_OPTIONS, &gvar_opts,
378 /* Driver supports no device instance options. */
381 printf("Supported device options:\n");
382 opts = g_variant_get_fixed_array(gvar_opts, &num_opts, sizeof(int32_t));
383 for (o = 0; o < num_opts; o++) {
384 if (!(srci = sr_config_info_get(opts[o])))
387 if (srci->key == SR_CONF_TRIGGER_TYPE) {
388 if (sr_config_list(sdi->driver, srci->key, &gvar,
393 charopts = g_variant_get_string(gvar, NULL);
394 printf(" Supported triggers: ");
396 printf("%c ", *charopts);
400 g_variant_unref(gvar);
402 } else if (srci->key == SR_CONF_PATTERN_MODE) {
403 /* Pattern generator modes */
404 printf(" %s", srci->id);
405 if (sr_config_list(sdi->driver, srci->key, &gvar,
407 printf(" - supported patterns:\n");
408 stropts = g_variant_get_strv(gvar, &num_elements);
409 for (i = 0; i < num_elements; i++)
410 printf(" %s\n", stropts[i]);
411 g_variant_unref(gvar);
416 } else if (srci->key == SR_CONF_SAMPLERATE) {
417 /* Supported samplerates */
418 printf(" %s", srci->id);
419 if (sr_config_list(sdi->driver, SR_CONF_SAMPLERATE,
420 &gvar_dict, sdi) != SR_OK) {
424 if ((gvar_list = g_variant_lookup_value(gvar_dict,
425 "samplerates", G_VARIANT_TYPE("at")))) {
426 uint64 = g_variant_get_fixed_array(gvar_list,
427 &num_elements, sizeof(uint64_t));
428 printf(" - supported samplerates:\n");
429 for (i = 0; i < num_elements; i++) {
430 if (!(s = sr_samplerate_string(uint64[i])))
435 g_variant_unref(gvar_list);
436 } else if ((gvar_list = g_variant_lookup_value(gvar_dict,
437 "samplerate-steps", G_VARIANT_TYPE("at")))) {
438 uint64 = g_variant_get_fixed_array(gvar_list,
439 &num_elements, sizeof(uint64_t));
441 if (!(s = sr_samplerate_string(uint64[0])))
446 if (!(s = sr_samplerate_string(uint64[1])))
451 if (!(s = sr_samplerate_string(uint64[2])))
453 printf(" in steps of %s)\n", s);
455 g_variant_unref(gvar_list);
457 g_variant_unref(gvar_dict);
459 } else if (srci->key == SR_CONF_BUFFERSIZE) {
460 /* Supported buffer sizes */
461 printf(" %s", srci->id);
462 if (sr_config_list(sdi->driver, SR_CONF_BUFFERSIZE,
463 &gvar_list, sdi) != SR_OK) {
467 uint64 = g_variant_get_fixed_array(gvar_list,
468 &num_elements, sizeof(uint64_t));
469 printf(" - supported buffer sizes:\n");
470 for (i = 0; i < num_elements; i++)
471 printf(" %"PRIu64"\n", uint64[i]);
472 g_variant_unref(gvar_list);
474 } else if (srci->key == SR_CONF_TIMEBASE) {
475 /* Supported time bases */
476 printf(" %s", srci->id);
477 if (sr_config_list(sdi->driver, SR_CONF_TIMEBASE,
478 &gvar_list, sdi) != SR_OK) {
482 printf(" - supported time bases:\n");
483 num_elements = g_variant_n_children(gvar_list);
484 for (i = 0; i < num_elements; i++) {
485 gvar = g_variant_get_child_value(gvar_list, i);
486 g_variant_get(gvar, "(tt)", &p, &q);
487 s = sr_period_string(p * q);
491 g_variant_unref(gvar_list);
493 } else if (srci->key == SR_CONF_TRIGGER_SOURCE) {
494 /* Supported trigger sources */
495 printf(" %s", srci->id);
496 if (sr_config_list(sdi->driver, SR_CONF_TRIGGER_SOURCE,
497 &gvar, sdi) != SR_OK) {
501 printf(" - supported trigger sources:\n");
502 stropts = g_variant_get_strv(gvar, &num_elements);
503 for (i = 0; i < num_elements; i++)
504 printf(" %s\n", stropts[i]);
505 g_variant_unref(gvar);
507 } else if (srci->key == SR_CONF_FILTER) {
508 /* Supported filters */
509 printf(" %s", srci->id);
510 if (sr_config_list(sdi->driver, SR_CONF_FILTER,
511 &gvar, sdi) != SR_OK) {
515 printf(" - supported filter targets:\n");
516 stropts = g_variant_get_strv(gvar, &num_elements);
517 for (i = 0; i < num_elements; i++)
518 printf(" %s\n", stropts[i]);
519 g_variant_unref(gvar);
521 } else if (srci->key == SR_CONF_VDIV) {
522 /* Supported volts/div values */
523 printf(" %s", srci->id);
524 if (sr_config_list(sdi->driver, SR_CONF_VDIV,
525 &gvar_list, sdi) != SR_OK) {
529 printf(" - supported volts/div:\n");
530 num_elements = g_variant_n_children(gvar_list);
531 for (i = 0; i < num_elements; i++) {
532 gvar = g_variant_get_child_value(gvar_list, i);
533 g_variant_get(gvar, "(tt)", &p, &q);
534 s = sr_voltage_string(p, q);
538 g_variant_unref(gvar_list);
540 } else if (srci->key == SR_CONF_COUPLING) {
541 /* Supported coupling settings */
542 printf(" %s", srci->id);
543 if (sr_config_list(sdi->driver, SR_CONF_COUPLING,
544 &gvar, sdi) != SR_OK) {
548 printf(" - supported coupling options:\n");
549 stropts = g_variant_get_strv(gvar, &num_elements);
550 for (i = 0; i < num_elements; i++)
551 printf(" %s\n", stropts[i]);
552 g_variant_unref(gvar);
554 } else if (srci->key == SR_CONF_DATALOG) {
555 /* Turning on/off internal data logging. */
556 printf(" %s\t(on/off", srci->id);
557 if (sr_config_get(sdi->driver, SR_CONF_DATALOG,
558 &gvar, sdi) == SR_OK) {
559 tmp_bool = g_variant_get_boolean(gvar);
560 printf(", currently %s", tmp_bool ? "on" : "off");
561 g_variant_unref(gvar);
565 /* Everything else */
566 printf(" %s\n", srci->id);
569 g_variant_unref(gvar_opts);
572 g_slist_free(devices);
577 static void show_pd_detail(void)
580 struct srd_decoder *dec;
581 struct srd_decoder_option *o;
582 char **pdtokens, **pdtok, *optsep, **ann, *val, *doc;
585 pdtokens = g_strsplit(opt_pds, ",", -1);
586 for (pdtok = pdtokens; *pdtok; pdtok++) {
588 if ((optsep = strchr(*pdtok, ':')))
590 if (!(dec = srd_decoder_get_by_id(*pdtok))) {
591 g_critical("Protocol decoder %s not found.", *pdtok);
594 printf("ID: %s\nName: %s\nLong name: %s\nDescription: %s\n",
595 dec->id, dec->name, dec->longname, dec->desc);
596 printf("License: %s\n", dec->license);
597 printf("Annotations:\n");
598 if (dec->annotations) {
599 for (l = dec->annotations; l; l = l->next) {
601 printf("- %s\n %s\n", ann[0], ann[1]);
606 printf("Required probes:\n");
608 for (l = dec->probes; l; l = l->next) {
610 printf("- %s (%s): %s\n",
611 p->name, p->id, p->desc);
616 printf("Optional probes:\n");
617 if (dec->opt_probes) {
618 for (l = dec->opt_probes; l; l = l->next) {
620 printf("- %s (%s): %s\n",
621 p->name, p->id, p->desc);
627 printf("Options:\n");
628 for (l = dec->options; l; l = l->next) {
630 val = g_variant_print(o->def, FALSE);
631 printf("- %s: %s (default %s)\n", o->id, o->desc, val);
635 if ((doc = srd_decoder_doc_get(dec))) {
636 printf("Documentation:\n%s\n",
637 doc[0] == '\n' ? doc + 1 : doc);
642 g_strfreev(pdtokens);
646 static GArray *get_enabled_logic_probes(const struct sr_dev_inst *sdi)
648 struct sr_probe *probe;
652 probes = g_array_new(FALSE, FALSE, sizeof(int));
653 for (l = sdi->probes; l; l = l->next) {
655 if (probe->type != SR_PROBE_LOGIC)
657 if (probe->enabled != TRUE)
659 g_array_append_val(probes, probe->index);
665 static void datafeed_in(const struct sr_dev_inst *sdi,
666 const struct sr_datafeed_packet *packet, void *cb_data)
668 const struct sr_datafeed_meta *meta;
669 const struct sr_datafeed_logic *logic;
670 const struct sr_datafeed_analog *analog;
671 struct sr_config *src;
672 static struct sr_output *o = NULL;
673 static GArray *logic_probelist = NULL;
674 static uint64_t received_samples = 0;
675 static int unitsize = 0;
676 static int triggered = 0;
677 static FILE *outfile = NULL;
680 int sample_size, ret;
681 uint64_t samplerate, output_len, filter_out_len;
682 uint8_t *output_buf, *filter_out;
686 /* If the first packet to come in isn't a header, don't even try. */
687 if (packet->type != SR_DF_HEADER && o == NULL)
691 switch (packet->type) {
693 g_debug("cli: Received SR_DF_HEADER");
694 /* Initialize the output module. */
695 if (!(o = g_try_malloc(sizeof(struct sr_output)))) {
696 g_critical("Output module malloc failed.");
699 o->format = output_format;
700 o->sdi = (struct sr_dev_inst *)sdi;
701 o->param = output_format_param;
702 if (o->format->init) {
703 if (o->format->init(o) != SR_OK) {
704 g_critical("Output format initialization failed.");
709 /* Prepare non-stdout output. */
711 if (opt_output_file) {
712 if (default_output_format) {
713 /* output file is in session format, so we'll
714 * keep a copy of everything as it comes in
715 * and save from there after the session. */
717 savebuf = g_byte_array_new();
719 /* saving to a file in whatever format was set
720 * with --format, so all we need is a filehandle */
721 outfile = g_fopen(opt_output_file, "wb");
725 /* Prepare for logic data. */
726 logic_probelist = get_enabled_logic_probes(sdi);
727 /* How many bytes we need to store the packed samples. */
728 unitsize = (logic_probelist->len + 7) / 8;
732 if (opt_pds && logic_probelist->len) {
733 if (sr_config_get(sdi->driver, SR_CONF_SAMPLERATE,
734 &gvar, sdi) != SR_OK) {
735 g_critical("Unable to initialize protocol "
736 "decoders: no samplerate found.");
739 samplerate = g_variant_get_uint64(gvar);
740 g_variant_unref(gvar);
741 srd_session_start(logic_probelist->len, unitsize, samplerate);
747 g_debug("cli: received SR_DF_META");
748 meta = packet->payload;
749 for (l = meta->config; l; l = l->next) {
752 case SR_CONF_SAMPLERATE:
753 samplerate = g_variant_get_uint64(src->data);
754 g_debug("cli: got samplerate %"PRIu64" Hz", samplerate);
756 case SR_CONF_SAMPLE_INTERVAL:
757 samplerate = g_variant_get_uint64(src->data);
758 g_debug("cli: got sample interval %"PRIu64" ms", samplerate);
761 /* Unknown metadata is not an error. */
768 g_debug("cli: received SR_DF_TRIGGER");
769 if (o->format->event)
770 o->format->event(o, SR_DF_TRIGGER, &output_buf,
776 logic = packet->payload;
777 g_message("cli: received SR_DF_LOGIC, %"PRIu64" bytes", logic->length);
778 sample_size = logic->unitsize;
779 if (logic->length == 0)
782 /* Don't store any samples until triggered. */
783 if (opt_wait_trigger && !triggered)
786 if (limit_samples && received_samples >= limit_samples)
789 ret = sr_filter_probes(sample_size, unitsize, logic_probelist,
790 logic->data, logic->length,
791 &filter_out, &filter_out_len);
795 /* What comes out of the filter is guaranteed to be packed into the
796 * minimum size needed to support the number of samples at this sample
797 * size. however, the driver may have submitted too much -- cut off
798 * the buffer of the last packet according to the sample limit.
800 if (limit_samples && (received_samples + logic->length / sample_size >
801 limit_samples * sample_size))
802 filter_out_len = limit_samples * sample_size - received_samples;
804 if (opt_output_file && default_output_format) {
805 /* Saving to a session file. */
806 g_byte_array_append(savebuf, filter_out, filter_out_len);
810 if (srd_session_send(received_samples, (uint8_t*)filter_out,
811 filter_out_len) != SRD_OK)
816 if (o->format->data && packet->type == o->format->df_type)
817 o->format->data(o, filter_out, filter_out_len,
818 &output_buf, &output_len);
820 fwrite(output_buf, 1, output_len, outfile);
828 received_samples += logic->length / sample_size;
832 analog = packet->payload;
833 g_message("cli: received SR_DF_ANALOG, %d samples", analog->num_samples);
834 if (analog->num_samples == 0)
837 if (limit_samples && received_samples >= limit_samples)
840 if (o->format->data && packet->type == o->format->df_type) {
841 o->format->data(o, (const uint8_t *)analog->data,
842 analog->num_samples * sizeof(float),
843 &output_buf, &output_len);
845 fwrite(output_buf, 1, output_len, outfile);
851 received_samples += analog->num_samples;
854 case SR_DF_FRAME_BEGIN:
855 g_debug("cli: received SR_DF_FRAME_BEGIN");
856 if (o->format->event) {
857 o->format->event(o, SR_DF_FRAME_BEGIN, &output_buf,
860 fwrite(output_buf, 1, output_len, outfile);
867 case SR_DF_FRAME_END:
868 g_debug("cli: received SR_DF_FRAME_END");
869 if (o->format->event) {
870 o->format->event(o, SR_DF_FRAME_END, &output_buf,
873 fwrite(output_buf, 1, output_len, outfile);
884 if (o && o->format->receive) {
885 if (o->format->receive(o, sdi, packet, &out) == SR_OK && out) {
886 fwrite(out->str, 1, out->len, outfile);
888 g_string_free(out, TRUE);
892 /* SR_DF_END needs to be handled after the output module's receive()
893 * is called, so it can properly clean up that module etc. */
894 if (packet->type == SR_DF_END) {
895 g_debug("cli: Received SR_DF_END");
897 if (o->format->event) {
898 o->format->event(o, SR_DF_END, &output_buf, &output_len);
901 fwrite(output_buf, 1, output_len, outfile);
907 if (limit_samples && received_samples < limit_samples)
908 g_warning("Device only sent %" PRIu64 " samples.",
912 g_warning("Device stopped after %" PRIu64 " samples.",
915 g_array_free(logic_probelist, TRUE);
917 if (o->format->cleanup)
918 o->format->cleanup(o);
922 if (outfile && outfile != stdout)
925 if (opt_output_file && default_output_format) {
926 if (sr_session_save(opt_output_file, sdi, savebuf->data,
927 unitsize, savebuf->len / unitsize) != SR_OK)
928 g_critical("Failed to save session.");
929 g_byte_array_free(savebuf, FALSE);
936 static int opts_to_gvar(struct srd_decoder *dec, GHashTable *hash,
937 GHashTable **options)
939 struct srd_decoder_option *o;
944 char *val_str, *conv;
947 *options = g_hash_table_new_full(g_str_hash, g_str_equal, g_free,
948 (GDestroyNotify)g_variant_unref);
950 for (optl = dec->options; optl; optl = optl->next) {
952 if (!(val_str = g_hash_table_lookup(hash, o->id)))
955 if (g_variant_is_of_type(o->def, G_VARIANT_TYPE_STRING)) {
956 gvar = g_variant_new_string(val_str);
957 } else if (g_variant_is_of_type(o->def, G_VARIANT_TYPE_INT64)) {
958 val_int = strtoll(val_str, &conv, 10);
959 if (!conv || conv == val_str) {
960 g_critical("Protocol decoder '%s' option '%s' "
961 "requires a number.", dec->name, o->id);
965 gvar = g_variant_new_int64(val_int);
967 g_critical("Unsupported type for option '%s' (%s)",
968 o->id, g_variant_get_type_string(o->def));
972 g_variant_ref_sink(gvar);
973 g_hash_table_insert(*options, g_strdup(o->id), gvar);
974 g_hash_table_remove(hash, o->id);
980 static int probes_to_gvar(struct srd_decoder *dec, GHashTable *hash,
984 GSList *all_probes, *l;
988 char *val_str, *conv;
991 *probes = g_hash_table_new_full(g_str_hash, g_str_equal, g_free,
992 (GDestroyNotify)g_variant_unref);
994 all_probes = g_slist_copy(dec->probes);
995 all_probes = g_slist_concat(all_probes, dec->opt_probes);
996 for (l = all_probes; l; l = l->next) {
998 if (!(val_str = g_hash_table_lookup(hash, p->id)))
1001 val_int = strtoll(val_str, &conv, 10);
1002 if (!conv || conv == val_str) {
1003 g_critical("Protocol decoder '%s' probes '%s' "
1004 "is not a number.", dec->name, p->id);
1008 gvar = g_variant_new_int32(val_int);
1009 g_variant_ref_sink(gvar);
1010 g_hash_table_insert(*probes, g_strdup(p->id), gvar);
1011 g_hash_table_remove(hash, p->id);
1013 g_slist_free(all_probes);
1018 /* Register the given PDs for this session.
1019 * Accepts a string of the form: "spi:sck=3:sdata=4,spi:sck=3:sdata=5"
1020 * That will instantiate two SPI decoders on the clock but different data
1023 static int register_pds(struct sr_dev *dev, const char *pdstring)
1025 struct srd_decoder *dec;
1026 GHashTable *pd_opthash, *options, *probes;
1027 GList *leftover, *l;
1028 struct srd_decoder_inst *di;
1030 char **pdtokens, **pdtok, *pd_name;
1035 pd_ann_visible = g_hash_table_new_full(g_str_hash, g_int_equal,
1038 pd_opthash = options = probes = NULL;
1039 pdtokens = g_strsplit(pdstring, ",", 0);
1040 for (pdtok = pdtokens; *pdtok; pdtok++) {
1041 if (!(pd_opthash = parse_generic_arg(*pdtok, TRUE))) {
1042 g_critical("Invalid protocol decoder option '%s'.", *pdtok);
1046 pd_name = g_strdup(g_hash_table_lookup(pd_opthash, "sigrok_key"));
1047 g_hash_table_remove(pd_opthash, "sigrok_key");
1048 if (srd_decoder_load(pd_name) != SRD_OK) {
1049 g_critical("Failed to load protocol decoder %s.", pd_name);
1053 dec = srd_decoder_get_by_id(pd_name);
1055 /* Convert decoder option and probe values to GVariant. */
1056 if (!opts_to_gvar(dec, pd_opthash, &options)) {
1060 if (!probes_to_gvar(dec, pd_opthash, &probes)) {
1064 if (g_hash_table_size(pd_opthash) > 0) {
1065 leftover = g_hash_table_get_keys(pd_opthash);
1066 for (l = leftover; l; l = l->next)
1067 g_critical("Unknown option or probe '%s'", (char *)l->data);
1068 g_list_free(leftover);
1072 if (!(di = srd_inst_new(pd_name, options))) {
1073 g_critical("Failed to instantiate protocol decoder %s.", pd_name);
1078 /* If no annotation list was specified, add them all in now.
1079 * This will be pared down later to leave only the last PD
1082 if (!opt_pd_annotations)
1083 g_hash_table_insert(pd_ann_visible,
1084 g_strdup(di->inst_id), NULL);
1086 /* Remap the probes if needed. */
1087 if (srd_inst_probe_set_all(di, probes) != SRD_OK) {
1093 g_strfreev(pdtokens);
1095 g_hash_table_destroy(pd_opthash);
1097 g_hash_table_destroy(options);
1099 g_hash_table_destroy(probes);
1106 int setup_pd_stack(void)
1108 struct srd_decoder_inst *di_from, *di_to;
1112 /* Set up the protocol decoder stack. */
1113 pds = g_strsplit(opt_pds, ",", 0);
1114 if (g_strv_length(pds) > 1) {
1116 /* A stack setup was specified, use that. */
1118 pds = g_strsplit(opt_pd_stack, ",", 0);
1119 if (g_strv_length(pds) < 2) {
1121 g_critical("Specify at least two protocol decoders to stack.");
1126 /* First PD goes at the bottom of the stack. */
1127 ids = g_strsplit(pds[0], ":", 0);
1128 if (!(di_from = srd_inst_find_by_id(ids[0]))) {
1130 g_critical("Cannot stack protocol decoder '%s': "
1131 "instance not found.", pds[0]);
1136 /* Every subsequent PD goes on top. */
1137 for (i = 1; pds[i]; i++) {
1138 ids = g_strsplit(pds[i], ":", 0);
1139 if (!(di_to = srd_inst_find_by_id(ids[0]))) {
1141 g_critical("Cannot stack protocol decoder '%s': "
1142 "instance not found.", pds[i]);
1146 if ((ret = srd_inst_stack(di_from, di_to)) != SRD_OK)
1149 /* Don't show annotation from this PD. Only the last PD in
1150 * the stack will be left on the annotation list (unless
1151 * the annotation list was specifically provided).
1153 if (!opt_pd_annotations)
1154 g_hash_table_remove(pd_ann_visible,
1165 int setup_pd_annotations(void)
1168 struct srd_decoder *dec;
1170 char **pds, **pdtok, **keyval, **ann_descr;
1172 /* Set up custom list of PDs and annotations to show. */
1173 if (opt_pd_annotations) {
1174 pds = g_strsplit(opt_pd_annotations, ",", 0);
1175 for (pdtok = pds; *pdtok && **pdtok; pdtok++) {
1177 keyval = g_strsplit(*pdtok, "=", 0);
1178 if (!(dec = srd_decoder_get_by_id(keyval[0]))) {
1179 g_critical("Protocol decoder '%s' not found.", keyval[0]);
1182 if (!dec->annotations) {
1183 g_critical("Protocol decoder '%s' has no annotations.", keyval[0]);
1186 if (g_strv_length(keyval) == 2) {
1187 for (l = dec->annotations; l; l = l->next, ann++) {
1188 ann_descr = l->data;
1189 if (!canon_cmp(ann_descr[0], keyval[1]))
1194 g_critical("Annotation '%s' not found "
1195 "for protocol decoder '%s'.", keyval[1], keyval[0]);
1199 g_debug("cli: showing protocol decoder annotation %d from '%s'", ann, keyval[0]);
1200 g_hash_table_insert(pd_ann_visible, g_strdup(keyval[0]), GINT_TO_POINTER(ann));
1209 void show_pd_annotations(struct srd_proto_data *pdata, void *cb_data)
1213 gpointer ann_format;
1215 /* 'cb_data' is not used in this specific callback. */
1218 if (!pd_ann_visible)
1221 if (!g_hash_table_lookup_extended(pd_ann_visible, pdata->pdo->di->inst_id,
1223 /* Not in the list of PDs whose annotations we're showing. */
1226 if (pdata->ann_format != GPOINTER_TO_INT(ann_format))
1227 /* We don't want this particular format from the PD. */
1230 annotations = pdata->data;
1231 if (opt_loglevel > SR_LOG_WARN)
1232 printf("%"PRIu64"-%"PRIu64" ", pdata->start_sample, pdata->end_sample);
1233 printf("%s: ", pdata->pdo->proto_id);
1234 for (i = 0; annotations[i]; i++)
1235 printf("\"%s\" ", annotations[i]);
1241 int setup_output_format(void)
1243 GHashTable *fmtargs;
1244 GHashTableIter iter;
1245 gpointer key, value;
1246 struct sr_output_format **outputs;
1250 if (!opt_output_format) {
1251 opt_output_format = DEFAULT_OUTPUT_FORMAT;
1252 /* we'll need to remember this so when saving to a file
1253 * later, sigrok session format will be used.
1255 default_output_format = TRUE;
1258 fmtargs = parse_generic_arg(opt_output_format, TRUE);
1259 fmtspec = g_hash_table_lookup(fmtargs, "sigrok_key");
1261 g_critical("Invalid output format.");
1264 outputs = sr_output_list();
1265 for (i = 0; outputs[i]; i++) {
1266 if (strcmp(outputs[i]->id, fmtspec))
1268 g_hash_table_remove(fmtargs, "sigrok_key");
1269 output_format = outputs[i];
1270 g_hash_table_iter_init(&iter, fmtargs);
1271 while (g_hash_table_iter_next(&iter, &key, &value)) {
1272 /* only supporting one parameter per output module
1273 * for now, and only its value */
1274 output_format_param = g_strdup(value);
1279 if (!output_format) {
1280 g_critical("Invalid output format %s.", opt_output_format);
1283 g_hash_table_destroy(fmtargs);
1288 static int select_probes(struct sr_dev_inst *sdi)
1290 struct sr_probe *probe;
1291 GSList *selected_probes, *l;
1296 if (!(selected_probes = parse_probestring(sdi, opt_probes)))
1299 for (l = sdi->probes; l; l = l->next) {
1301 if (g_slist_find(selected_probes, probe))
1302 probe->enabled = TRUE;
1304 probe->enabled = FALSE;
1306 g_slist_free(selected_probes);
1312 * Return the input file format which the CLI tool should use.
1314 * If the user specified -I / --input-format, use that one. Otherwise, try to
1315 * autodetect the format as good as possible. Failing that, return NULL.
1317 * @param filename The filename of the input file. Must not be NULL.
1318 * @param opt The -I / --input-file option the user specified (or NULL).
1320 * @return A pointer to the 'struct sr_input_format' that should be used,
1321 * or NULL if no input format was selected or auto-detected.
1323 static struct sr_input_format *determine_input_file_format(
1324 const char *filename, const char *opt)
1327 struct sr_input_format **inputs;
1329 /* If there are no input formats, return NULL right away. */
1330 inputs = sr_input_list();
1332 g_critical("No supported input formats available.");
1336 /* If the user specified -I / --input-format, use that one. */
1338 for (i = 0; inputs[i]; i++) {
1339 if (strcasecmp(inputs[i]->id, opt))
1341 g_debug("Using user-specified input file format '%s'.",
1346 /* The user specified an unknown input format, return NULL. */
1347 g_critical("Error: specified input file format '%s' is "
1352 /* Otherwise, try to find an input module that can handle this file. */
1353 for (i = 0; inputs[i]; i++) {
1354 if (inputs[i]->format_match(filename))
1358 /* Return NULL if no input module wanted to touch this. */
1360 g_critical("Error: no matching input module found.");
1364 g_debug("cli: Autodetected '%s' input format for file '%s'.",
1365 inputs[i]->id, filename);
1370 static void load_input_file_format(void)
1372 GHashTable *fmtargs = NULL;
1374 struct sr_input *in;
1375 struct sr_input_format *input_format;
1376 char *fmtspec = NULL;
1378 if (opt_input_format) {
1379 fmtargs = parse_generic_arg(opt_input_format, TRUE);
1380 fmtspec = g_hash_table_lookup(fmtargs, "sigrok_key");
1383 if (!(input_format = determine_input_file_format(opt_input_file,
1385 /* The exact cause was already logged. */
1390 g_hash_table_remove(fmtargs, "sigrok_key");
1392 if (stat(opt_input_file, &st) == -1) {
1393 g_critical("Failed to load %s: %s", opt_input_file,
1398 /* Initialize the input module. */
1399 if (!(in = g_try_malloc(sizeof(struct sr_input)))) {
1400 g_critical("Failed to allocate input module.");
1403 in->format = input_format;
1404 in->param = fmtargs;
1405 if (in->format->init) {
1406 if (in->format->init(in, opt_input_file) != SR_OK) {
1407 g_critical("Input format init failed.");
1412 if (select_probes(in->sdi) > 0)
1416 sr_session_datafeed_callback_add(datafeed_in, NULL);
1417 if (sr_session_dev_add(in->sdi) != SR_OK) {
1418 g_critical("Failed to use device.");
1419 sr_session_destroy();
1423 input_format->loadfile(in, opt_input_file);
1425 sr_session_destroy();
1428 g_hash_table_destroy(fmtargs);
1431 static void load_input_file(void)
1434 if (sr_session_load(opt_input_file) == SR_OK) {
1435 /* sigrok session file */
1436 sr_session_datafeed_callback_add(datafeed_in, NULL);
1442 /* fall back on input modules */
1443 load_input_file_format();
1447 static int set_dev_options(struct sr_dev_inst *sdi, GHashTable *args)
1449 const struct sr_config_info *srci;
1450 GHashTableIter iter;
1451 gpointer key, value;
1454 uint64_t tmp_u64, p, q;
1456 GVariant *val, *rational[2];
1458 g_hash_table_iter_init(&iter, args);
1459 while (g_hash_table_iter_next(&iter, &key, &value)) {
1460 if (!(srci = sr_config_info_name_get(key))) {
1461 g_critical("Unknown device option '%s'.", (char *) key);
1465 if ((value == NULL) &&
1466 (srci->datatype != SR_T_BOOL)) {
1467 g_critical("Option '%s' needs a value.", (char *)key);
1471 switch (srci->datatype) {
1473 ret = sr_parse_sizestring(value, &tmp_u64);
1476 val = g_variant_new_uint64(tmp_u64);
1479 val = g_variant_new_string(value);
1485 tmp_bool = sr_parse_boolstring(value);
1486 val = g_variant_new_boolean(tmp_bool);
1489 tmp_double = strtof(value, NULL);
1490 val = g_variant_new_double(tmp_double);
1492 case SR_T_RATIONAL_PERIOD:
1493 if ((ret = sr_parse_period(value, &p, &q)) != SR_OK)
1495 rational[0] = g_variant_new_uint64(p);
1496 rational[1] = g_variant_new_uint64(q);
1497 val = g_variant_new_tuple(rational, 2);
1499 case SR_T_RATIONAL_VOLT:
1500 if ((ret = sr_parse_voltage(value, &p, &q)) != SR_OK)
1502 rational[0] = g_variant_new_uint64(p);
1503 rational[1] = g_variant_new_uint64(q);
1504 val = g_variant_new_tuple(rational, 2);
1510 ret = sr_config_set(sdi, srci->key, val);
1512 g_critical("Failed to set device option '%s'.", (char *)key);
1520 static void set_options(void)
1522 struct sr_dev_inst *sdi;
1524 GHashTable *devargs;
1527 g_critical("No setting specified.");
1531 if (!(devargs = parse_generic_arg(opt_config, FALSE)))
1534 if (!(devices = device_scan())) {
1535 g_critical("No devices found.");
1538 sdi = devices->data;
1540 if (sr_dev_open(sdi) != SR_OK) {
1541 g_critical("Failed to open device.");
1545 set_dev_options(sdi, devargs);
1548 g_slist_free(devices);
1549 g_hash_table_destroy(devargs);
1553 static int set_limit_time(const struct sr_dev_inst *sdi)
1557 uint64_t samplerate;
1559 if (!(time_msec = sr_parse_timestring(opt_time))) {
1560 g_critical("Invalid time '%s'", opt_time);
1564 if (sr_dev_has_option(sdi, SR_CONF_LIMIT_MSEC)) {
1565 gvar = g_variant_new_uint64(time_msec);
1566 if (sr_config_set(sdi, SR_CONF_LIMIT_MSEC, gvar) != SR_OK) {
1567 g_critical("Failed to configure time limit.");
1570 } else if (sr_dev_has_option(sdi, SR_CONF_SAMPLERATE)) {
1571 /* Convert to samples based on the samplerate. */
1572 sr_config_get(sdi->driver, SR_CONF_SAMPLERATE, &gvar, sdi);
1573 samplerate = g_variant_get_uint64(gvar);
1574 g_variant_unref(gvar);
1575 limit_samples = (samplerate) * time_msec / (uint64_t)1000;
1576 if (limit_samples == 0) {
1577 g_critical("Not enough time at this samplerate.");
1580 gvar = g_variant_new_uint64(limit_samples);
1581 if (sr_config_set(sdi, SR_CONF_LIMIT_SAMPLES, gvar) != SR_OK) {
1582 g_critical("Failed to configure time-based sample limit.");
1586 g_critical("This device does not support time limits.");
1593 static void run_session(void)
1596 GHashTable *devargs;
1598 struct sr_dev_inst *sdi;
1602 devices = device_scan();
1604 g_critical("No devices found.");
1607 if (g_slist_length(devices) > 1) {
1608 g_critical("sigrok-cli only supports one device for capturing.");
1611 sdi = devices->data;
1614 sr_session_datafeed_callback_add(datafeed_in, NULL);
1616 if (sr_dev_open(sdi) != SR_OK) {
1617 g_critical("Failed to open device.");
1621 if (sr_session_dev_add(sdi) != SR_OK) {
1622 g_critical("Failed to add device to session.");
1623 sr_session_destroy();
1628 if ((devargs = parse_generic_arg(opt_config, FALSE))) {
1629 if (set_dev_options(sdi, devargs) != SR_OK)
1631 g_hash_table_destroy(devargs);
1635 if (select_probes(sdi) != SR_OK) {
1636 g_critical("Failed to set probes.");
1637 sr_session_destroy();
1642 if (!(triggerlist = sr_parse_triggerstring(sdi, opt_triggers))) {
1643 sr_session_destroy();
1646 max_probes = g_slist_length(sdi->probes);
1647 for (i = 0; i < max_probes; i++) {
1648 if (triggerlist[i]) {
1649 sr_dev_trigger_set(sdi, i, triggerlist[i]);
1650 g_free(triggerlist[i]);
1653 g_free(triggerlist);
1656 if (opt_continuous) {
1657 if (!sr_dev_has_option(sdi, SR_CONF_CONTINUOUS)) {
1658 g_critical("This device does not support continuous sampling.");
1659 sr_session_destroy();
1665 if (set_limit_time(sdi) != SR_OK) {
1666 sr_session_destroy();
1672 if ((sr_parse_sizestring(opt_samples, &limit_samples) != SR_OK)) {
1673 g_critical("Invalid sample limit '%s'.", opt_samples);
1674 sr_session_destroy();
1677 gvar = g_variant_new_uint64(limit_samples);
1678 if (sr_config_set(sdi, SR_CONF_LIMIT_SAMPLES, gvar) != SR_OK) {
1679 g_critical("Failed to configure sample limit.");
1680 sr_session_destroy();
1686 if ((sr_parse_sizestring(opt_frames, &limit_frames) != SR_OK)) {
1687 g_critical("Invalid sample limit '%s'.", opt_samples);
1688 sr_session_destroy();
1691 gvar = g_variant_new_uint64(limit_frames);
1692 if (sr_config_set(sdi, SR_CONF_LIMIT_FRAMES, gvar) != SR_OK) {
1693 g_critical("Failed to configure frame limit.");
1694 sr_session_destroy();
1699 if (sr_session_start() != SR_OK) {
1700 g_critical("Failed to start session.");
1701 sr_session_destroy();
1713 sr_session_destroy();
1714 g_slist_free(devices);
1718 static void logger(const gchar *log_domain, GLogLevelFlags log_level,
1719 const gchar *message, gpointer cb_data)
1725 * All messages, warnings, errors etc. go to stderr (not stdout) in
1726 * order to not mess up the CLI tool data output, e.g. VCD output.
1728 if (log_level & (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING)
1729 || opt_loglevel > SR_LOG_WARN) {
1730 fprintf(stderr, "%s\n", message);
1735 int main(int argc, char **argv)
1737 GOptionContext *context;
1742 g_log_set_default_handler(logger, NULL);
1744 context = g_option_context_new(NULL);
1745 g_option_context_add_main_entries(context, optargs, NULL);
1749 if (!g_option_context_parse(context, &argc, &argv, &error)) {
1750 g_critical("%s", error->message);
1754 /* Set the loglevel (amount of messages to output) for libsigrok. */
1755 if (sr_log_loglevel_set(opt_loglevel) != SR_OK)
1758 if (sr_init(&sr_ctx) != SR_OK)
1762 /* Set the loglevel (amount of messages to output) for libsigrokdecode. */
1763 if (srd_log_loglevel_set(opt_loglevel) != SRD_OK)
1767 if (srd_init(NULL) != SRD_OK)
1769 if (register_pds(NULL, opt_pds) != 0)
1771 if (srd_pd_output_callback_add(SRD_OUTPUT_ANN,
1772 show_pd_annotations, NULL) != SRD_OK)
1774 if (setup_pd_stack() != 0)
1776 if (setup_pd_annotations() != 0)
1781 if (setup_output_format() != 0)
1786 else if (opt_scan_devs)
1789 else if (opt_pds && opt_show)
1794 else if (opt_input_file)
1798 else if (opt_samples || opt_time || opt_frames || opt_continuous)
1801 help = g_option_context_get_help(context, TRUE, NULL);
1817 g_option_context_free(context);