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>
34 #include "sigrok-cli.h"
37 #define DEFAULT_OUTPUT_FORMAT "bits:width=64"
39 extern struct sr_hwcap_option sr_hwcap_options[];
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 char *input_format_param = NULL;
47 static GHashTable *pd_ann_visible = NULL;
49 static gboolean opt_version = FALSE;
50 static gint opt_loglevel = SR_LOG_WARN; /* Show errors+warnings per default. */
51 static gboolean opt_list_devs = FALSE;
52 static gboolean opt_wait_trigger = FALSE;
53 static gchar *opt_input_file = NULL;
54 static gchar *opt_output_file = NULL;
55 static gchar *opt_dev = NULL;
56 static gchar *opt_probes = NULL;
57 static gchar *opt_triggers = NULL;
58 static gchar *opt_pds = NULL;
59 static gchar *opt_pd_stack = NULL;
60 static gchar *opt_pd_annotations = NULL;
61 static gchar *opt_input_format = NULL;
62 static gchar *opt_output_format = NULL;
63 static gchar *opt_time = NULL;
64 static gchar *opt_samples = NULL;
65 static gchar *opt_frames = NULL;
66 static gchar *opt_continuous = NULL;
68 static GOptionEntry optargs[] = {
69 {"version", 'V', 0, G_OPTION_ARG_NONE, &opt_version,
70 "Show version and support list", NULL},
71 {"loglevel", 'l', 0, G_OPTION_ARG_INT, &opt_loglevel,
72 "Set libsigrok/libsigrokdecode loglevel", NULL},
73 {"list-devices", 'D', 0, G_OPTION_ARG_NONE, &opt_list_devs,
74 "Scan for devices", NULL},
75 {"device", 'd', 0, G_OPTION_ARG_STRING, &opt_dev,
76 "Use specified device", NULL},
77 {"input-file", 'i', 0, G_OPTION_ARG_FILENAME, &opt_input_file,
78 "Load input from file", NULL},
79 {"input-format", 'I', 0, G_OPTION_ARG_STRING, &opt_input_format,
80 "Input format", NULL},
81 {"output-file", 'o', 0, G_OPTION_ARG_FILENAME, &opt_output_file,
82 "Save output to file", NULL},
83 {"output-format", 'O', 0, G_OPTION_ARG_STRING, &opt_output_format,
84 "Output format", NULL},
85 {"probes", 'p', 0, G_OPTION_ARG_STRING, &opt_probes,
86 "Probes to use", NULL},
87 {"triggers", 't', 0, G_OPTION_ARG_STRING, &opt_triggers,
88 "Trigger configuration", NULL},
89 {"wait-trigger", 'w', 0, G_OPTION_ARG_NONE, &opt_wait_trigger,
90 "Wait for trigger", NULL},
91 {"protocol-decoders", 'a', 0, G_OPTION_ARG_STRING, &opt_pds,
92 "Protocol decoders to run", NULL},
93 {"protocol-decoder-stack", 's', 0, G_OPTION_ARG_STRING, &opt_pd_stack,
94 "Protocol decoder stack", NULL},
95 {"protocol-decoder-annotations", 'A', 0, G_OPTION_ARG_STRING, &opt_pd_annotations,
96 "Protocol decoder annotation(s) to show", NULL},
97 {"time", 0, 0, G_OPTION_ARG_STRING, &opt_time,
98 "How long to sample (ms)", NULL},
99 {"samples", 0, 0, G_OPTION_ARG_STRING, &opt_samples,
100 "Number of samples to acquire", NULL},
101 {"frames", 0, 0, G_OPTION_ARG_STRING, &opt_frames,
102 "Number of frames to acquire", NULL},
103 {"continuous", 0, 0, G_OPTION_ARG_NONE, &opt_continuous,
104 "Sample continuously", NULL},
105 {NULL, 0, 0, 0, NULL, NULL, NULL}
108 static void show_version(void)
111 struct sr_dev_driver **drivers;
112 struct sr_input_format **inputs;
113 struct sr_output_format **outputs;
114 struct srd_decoder *dec;
117 printf("sigrok-cli %s\n\n", VERSION);
119 printf("Using libsigrok %s (lib version %s).\n",
120 sr_package_version_string_get(), sr_lib_version_string_get());
121 printf("Using libsigrokdecode %s (lib version %s).\n\n",
122 srd_package_version_string_get(), srd_lib_version_string_get());
124 printf("Supported hardware drivers:\n");
125 drivers = sr_driver_list();
126 for (i = 0; drivers[i]; i++) {
127 printf(" %-20s %s\n", drivers[i]->name, drivers[i]->longname);
131 printf("Supported input formats:\n");
132 inputs = sr_input_list();
133 for (i = 0; inputs[i]; i++)
134 printf(" %-20s %s\n", inputs[i]->id, inputs[i]->description);
137 printf("Supported output formats:\n");
138 outputs = sr_output_list();
139 for (i = 0; outputs[i]; i++)
140 printf(" %-20s %s\n", outputs[i]->id, outputs[i]->description);
143 if (srd_init(NULL) == SRD_OK) {
144 printf("Supported protocol decoders:\n");
145 srd_decoder_load_all();
146 for (l = srd_decoder_list(); l; l = l->next) {
148 printf(" %-20s %s\n", dec->id, dec->longname);
149 /* Print protocol description upon "-l 3" or higher. */
150 if (opt_loglevel >= SR_LOG_INFO)
151 printf(" %-20s %s\n", "", dec->desc);
158 static void print_dev_line(const struct sr_dev *dev)
160 const struct sr_dev_inst *sdi;
162 sr_dev_info_get(dev, SR_DI_INST, (const void **)&sdi);
164 if (sdi->vendor && sdi->vendor[0])
165 printf("%s ", sdi->vendor);
166 if (sdi->model && sdi->model[0])
167 printf("%s ", sdi->model);
168 if (sdi->version && sdi->version[0])
169 printf("%s ", sdi->version);
171 printf("with %d probes", g_slist_length(dev->probes));
175 static void show_dev_list(void)
177 struct sr_dev *dev, *demo_dev;
182 devs = sr_dev_list();
184 if (g_slist_length(devs) == 0)
187 printf("The following devices were found:\nID Device\n");
189 for (l = devs; l; l = l->next) {
191 if (sr_dev_has_hwcap(dev, SR_HWCAP_DEMO_DEV)) {
195 printf("%-3d ", devcnt++);
200 print_dev_line(demo_dev);
204 static void show_dev_detail(void)
207 const struct sr_hwcap_option *hwo;
208 const struct sr_samplerates *samplerates;
209 struct sr_rational *rationals;
214 const char *charopts, **stropts;
216 dev = parse_devstring(opt_dev);
218 printf("No such device. Use -D to list all devices.\n");
224 if (sr_dev_info_get(dev, SR_DI_TRIGGER_TYPES,
225 (const void **)&charopts) == SR_OK) {
226 printf("Supported triggers: ");
228 printf("%c ", *charopts);
234 title = "Supported options:\n";
235 hwcaps = dev->driver->hwcap_get_all();
236 for (cap = 0; hwcaps[cap]; cap++) {
237 if (!(hwo = sr_hw_hwcap_get(hwcaps[cap])))
245 if (hwo->hwcap == SR_HWCAP_PATTERN_MODE) {
246 /* Pattern generator modes */
247 printf(" %s", hwo->shortname);
248 if (sr_dev_info_get(dev, SR_DI_PATTERNS,
249 (const void **)&stropts) == SR_OK) {
250 printf(" - supported patterns:\n");
251 for (i = 0; stropts[i]; i++)
252 printf(" %s\n", stropts[i]);
257 } else if (hwo->hwcap == SR_HWCAP_SAMPLERATE) {
258 /* Supported samplerates */
259 printf(" %s", hwo->shortname);
260 if (sr_dev_info_get(dev, SR_DI_SAMPLERATES,
261 (const void **)&samplerates) != SR_OK) {
265 if (samplerates->step) {
267 if (!(s = sr_samplerate_string(samplerates->low)))
272 if (!(s = sr_samplerate_string(samplerates->high)))
277 if (!(s = sr_samplerate_string(samplerates->step)))
279 printf(" in steps of %s)\n", s);
282 printf(" - supported samplerates:\n");
283 for (i = 0; samplerates->list[i]; i++)
284 printf(" %s\n", sr_samplerate_string(samplerates->list[i]));
287 } else if (hwo->hwcap == SR_HWCAP_BUFFERSIZE) {
288 /* Supported buffer sizes */
289 printf(" %s", hwo->shortname);
290 if (sr_dev_info_get(dev, SR_DI_BUFFERSIZES,
291 (const void **)&integers) != SR_OK) {
295 printf(" - supported buffer sizes:\n");
296 for (i = 0; integers[i]; i++)
297 printf(" %"PRIu64"\n", integers[i]);
299 } else if (hwo->hwcap == SR_HWCAP_TIMEBASE) {
300 /* Supported time bases */
301 printf(" %s", hwo->shortname);
302 if (sr_dev_info_get(dev, SR_DI_TIMEBASES,
303 (const void **)&rationals) != SR_OK) {
307 printf(" - supported time bases:\n");
308 for (i = 0; rationals[i].p && rationals[i].q; i++)
309 printf(" %s\n", sr_period_string(
310 rationals[i].p * rationals[i].q));
312 } else if (hwo->hwcap == SR_HWCAP_TRIGGER_SOURCE) {
313 /* Supported trigger sources */
314 printf(" %s", hwo->shortname);
315 if (sr_dev_info_get(dev, SR_DI_TRIGGER_SOURCES,
316 (const void **)&stropts) != SR_OK) {
320 printf(" - supported trigger sources:\n");
321 for (i = 0; stropts[i]; i++)
322 printf(" %s\n", stropts[i]);
324 } else if (hwo->hwcap == SR_HWCAP_FILTER) {
325 /* Supported trigger sources */
326 printf(" %s", hwo->shortname);
327 if (sr_dev_info_get(dev, SR_DI_FILTERS,
328 (const void **)&stropts) != SR_OK) {
332 printf(" - supported filter targets:\n");
333 for (i = 0; stropts[i]; i++)
334 printf(" %s\n", stropts[i]);
336 } else if (hwo->hwcap == SR_HWCAP_VDIV) {
337 /* Supported volts/div values */
338 printf(" %s", hwo->shortname);
339 if (sr_dev_info_get(dev, SR_DI_VDIVS,
340 (const void **)&rationals) != SR_OK) {
344 printf(" - supported volts/div:\n");
345 for (i = 0; rationals[i].p && rationals[i].q; i++)
346 printf(" %s\n", sr_voltage_string( &rationals[i]));
348 } else if (hwo->hwcap == SR_HWCAP_COUPLING) {
349 /* Supported coupling settings */
350 printf(" %s", hwo->shortname);
351 if (sr_dev_info_get(dev, SR_DI_COUPLING,
352 (const void **)&stropts) != SR_OK) {
356 printf(" - supported coupling options:\n");
357 for (i = 0; stropts[i]; i++)
358 printf(" %s\n", stropts[i]);
361 /* Everything else */
362 printf(" %s\n", hwo->shortname);
367 static void show_pd_detail(void)
370 struct srd_decoder *dec;
371 char **pdtokens, **pdtok, **ann, *doc;
374 pdtokens = g_strsplit(opt_pds, ",", -1);
375 for (pdtok = pdtokens; *pdtok; pdtok++) {
376 if (!(dec = srd_decoder_get_by_id(*pdtok))) {
377 printf("Protocol decoder %s not found.\n", *pdtok);
380 printf("ID: %s\nName: %s\nLong name: %s\nDescription: %s\n",
381 dec->id, dec->name, dec->longname, dec->desc);
382 printf("License: %s\n", dec->license);
383 printf("Annotations:\n");
384 if (dec->annotations) {
385 for (l = dec->annotations; l; l = l->next) {
387 printf("- %s\n %s\n", ann[0], ann[1]);
392 /* TODO: Print supported decoder options. */
393 printf("Required probes:\n");
395 for (l = dec->probes; l; l = l->next) {
397 printf("- %s (%s): %s\n",
398 p->name, p->id, p->desc);
403 printf("Optional probes:\n");
404 if (dec->opt_probes) {
405 for (l = dec->opt_probes; l; l = l->next) {
407 printf("- %s (%s): %s\n",
408 p->name, p->id, p->desc);
413 if ((doc = srd_decoder_doc_get(dec))) {
414 printf("Documentation:\n%s\n",
415 doc[0] == '\n' ? doc + 1 : doc);
420 g_strfreev(pdtokens);
423 static void datafeed_in(struct sr_dev *dev, struct sr_datafeed_packet *packet)
425 static struct sr_output *o = NULL;
426 static int logic_probelist[SR_MAX_NUM_PROBES] = { 0 };
427 static struct sr_probe *analog_probelist[SR_MAX_NUM_PROBES];
428 static uint64_t received_samples = 0;
429 static int unitsize = 0;
430 static int triggered = 0;
431 static FILE *outfile = NULL;
432 static int num_analog_probes = 0;
433 struct sr_probe *probe;
434 struct sr_datafeed_logic *logic;
435 struct sr_datafeed_meta_logic *meta_logic;
436 struct sr_datafeed_analog *analog;
437 struct sr_datafeed_meta_analog *meta_analog;
438 static int num_enabled_analog_probes = 0;
439 int num_enabled_probes, sample_size, data_offset, ret, i, j;
440 uint64_t output_len, filter_out_len;
441 uint8_t *output_buf, *filter_out;
444 /* If the first packet to come in isn't a header, don't even try. */
445 if (packet->type != SR_DF_HEADER && o == NULL)
449 switch (packet->type) {
451 g_debug("cli: Received SR_DF_HEADER");
452 /* Initialize the output module. */
453 if (!(o = g_try_malloc(sizeof(struct sr_output)))) {
454 g_critical("Output module malloc failed.");
457 o->format = output_format;
459 o->param = output_format_param;
460 if (o->format->init) {
461 if (o->format->init(o) != SR_OK) {
462 g_critical("Output format initialization failed.");
469 g_debug("cli: Received SR_DF_END");
471 g_debug("cli: double end!");
474 if (o->format->event) {
475 o->format->event(o, SR_DF_END, &output_buf, &output_len);
478 fwrite(output_buf, 1, output_len, outfile);
483 if (limit_samples && received_samples < limit_samples)
484 g_warning("Device only sent %" PRIu64 " samples.",
487 g_warning("Device stopped after %" PRIu64 " samples.",
490 if (outfile && outfile != stdout)
497 g_debug("cli: received SR_DF_TRIGGER");
498 if (o->format->event)
499 o->format->event(o, SR_DF_TRIGGER, &output_buf,
504 case SR_DF_META_LOGIC:
505 g_message("cli: Received SR_DF_META_LOGIC");
506 meta_logic = packet->payload;
507 num_enabled_probes = 0;
508 for (i = 0; i < meta_logic->num_probes; i++) {
509 probe = g_slist_nth_data(dev->probes, i);
511 logic_probelist[num_enabled_probes++] = probe->index;
513 /* How many bytes we need to store num_enabled_probes bits */
514 unitsize = (num_enabled_probes + 7) / 8;
517 if (opt_output_file) {
518 if (default_output_format) {
519 /* output file is in session format, which means we'll
520 * dump everything in the datastore as it comes in,
521 * and save from there after the session. */
523 ret = sr_datastore_new(unitsize, &(dev->datastore));
525 printf("Failed to create datastore.\n");
529 /* saving to a file in whatever format was set
530 * with --format, so all we need is a filehandle */
531 outfile = g_fopen(opt_output_file, "wb");
535 srd_session_start(num_enabled_probes, unitsize,
536 meta_logic->samplerate);
540 logic = packet->payload;
541 g_message("cli: received SR_DF_LOGIC, %"PRIu64" bytes", logic->length);
542 sample_size = logic->unitsize;
543 if (logic->length == 0)
546 /* Don't store any samples until triggered. */
547 if (opt_wait_trigger && !triggered)
550 if (limit_samples && received_samples >= limit_samples)
553 ret = sr_filter_probes(sample_size, unitsize, logic_probelist,
554 logic->data, logic->length,
555 &filter_out, &filter_out_len);
559 /* what comes out of the filter is guaranteed to be packed into the
560 * minimum size needed to support the number of samples at this sample
561 * size. however, the driver may have submitted too much -- cut off
562 * the buffer of the last packet according to the sample limit.
564 if (limit_samples && (received_samples + logic->length / sample_size >
565 limit_samples * sample_size))
566 filter_out_len = limit_samples * sample_size - received_samples;
569 sr_datastore_put(dev->datastore, filter_out,
570 filter_out_len, sample_size, logic_probelist);
572 if (opt_output_file && default_output_format)
573 /* saving to a session file, don't need to do anything else
574 * to this data for now. */
578 if (srd_session_send(received_samples, (uint8_t*)filter_out,
579 filter_out_len) != SRD_OK)
583 if (o->format->data && packet->type == o->format->df_type)
584 o->format->data(o, filter_out, filter_out_len, &output_buf, &output_len);
586 fwrite(output_buf, 1, output_len, outfile);
593 received_samples += logic->length / sample_size;
596 case SR_DF_META_ANALOG:
597 g_message("cli: Received SR_DF_META_ANALOG");
598 meta_analog = packet->payload;
599 num_analog_probes = meta_analog->num_probes;
600 num_enabled_analog_probes = 0;
601 for (i = 0; i < num_analog_probes; i++) {
602 probe = g_slist_nth_data(dev->probes, i);
604 analog_probelist[num_enabled_analog_probes++] = probe;
608 if (opt_output_file) {
609 if (default_output_format) {
610 /* output file is in session format, which means we'll
611 * dump everything in the datastore as it comes in,
612 * and save from there after the session. */
614 ret = sr_datastore_new(unitsize, &(dev->datastore));
616 printf("Failed to create datastore.\n");
620 /* saving to a file in whatever format was set
621 * with --format, so all we need is a filehandle */
622 outfile = g_fopen(opt_output_file, "wb");
626 // srd_session_start(num_enabled_probes, unitsize,
627 // meta_logic->samplerate);
631 analog = packet->payload;
632 g_message("cli: received SR_DF_ANALOG, %d samples", analog->num_samples);
633 if (analog->num_samples == 0)
636 if (limit_samples && received_samples >= limit_samples)
640 for (i = 0; i < analog->num_samples; i++) {
641 for (j = 0; j < num_enabled_analog_probes; j++) {
642 asample = analog->data[data_offset++];
643 printf("%s: %f\n", analog_probelist[j]->name, asample);
645 // asample1 = asample2 = 0.0;
646 // asample1 = analog->data[data_offset++];
647 // asample2 = analog->data[i * num_analog_probes + 1];
648 // printf("%d\t%f\t%f\n", received_samples+i+1, asample1, asample2);
652 // if (o->format->data && packet->type == o->format->df_type)
653 // o->format->data(o, filter_out, filter_out_len, &output_buf, &output_len);
655 received_samples += analog->num_samples;
658 case SR_DF_FRAME_BEGIN:
663 case SR_DF_FRAME_END:
669 g_message("received unknown packet type %d", packet->type);
674 /* Register the given PDs for this session.
675 * Accepts a string of the form: "spi:sck=3:sdata=4,spi:sck=3:sdata=5"
676 * That will instantiate two SPI decoders on the clock but different data
679 static int register_pds(struct sr_dev *dev, const char *pdstring)
681 GHashTable *pd_opthash;
682 struct srd_decoder_inst *di;
684 char **pdtokens, **pdtok, *pd_name;
686 /* Avoid compiler warnings. */
690 pd_ann_visible = g_hash_table_new_full(g_str_hash, g_int_equal,
694 pdtokens = g_strsplit(pdstring, ",", 0);
695 for (pdtok = pdtokens; *pdtok; pdtok++) {
696 if (!(pd_opthash = parse_generic_arg(*pdtok))) {
697 g_critical("Invalid protocol decoder option '%s'.", *pdtok);
701 pd_name = g_strdup(g_hash_table_lookup(pd_opthash, "sigrok_key"));
702 g_hash_table_remove(pd_opthash, "sigrok_key");
703 if (srd_decoder_load(pd_name) != SRD_OK) {
704 g_critical("Failed to load protocol decoder %s.", pd_name);
708 if (!(di = srd_inst_new(pd_name, pd_opthash))) {
709 g_critical("Failed to instantiate protocol decoder %s.", pd_name);
714 /* If no annotation list was specified, add them all in now.
715 * This will be pared down later to leave only the last PD
718 if (!opt_pd_annotations)
719 g_hash_table_insert(pd_ann_visible,
720 g_strdup(di->inst_id), NULL);
722 /* Any keys left in the options hash are probes, where the key
723 * is the probe name as specified in the decoder class, and the
724 * value is the probe number i.e. the order in which the PD's
725 * incoming samples are arranged. */
726 if (srd_inst_probe_set_all(di, pd_opthash) != SRD_OK) {
730 g_hash_table_destroy(pd_opthash);
735 g_strfreev(pdtokens);
737 g_hash_table_destroy(pd_opthash);
744 int setup_pd_stack(void)
746 struct srd_decoder_inst *di_from, *di_to;
750 /* Set up the protocol decoder stack. */
751 pds = g_strsplit(opt_pds, ",", 0);
752 if (g_strv_length(pds) > 1) {
754 /* A stack setup was specified, use that. */
756 pds = g_strsplit(opt_pd_stack, ",", 0);
757 if (g_strv_length(pds) < 2) {
759 g_critical("Specify at least two protocol decoders to stack.");
764 /* First PD goes at the bottom of the stack. */
765 ids = g_strsplit(pds[0], ":", 0);
766 if (!(di_from = srd_inst_find_by_id(ids[0]))) {
768 g_critical("Cannot stack protocol decoder '%s': "
769 "instance not found.", pds[0]);
774 /* Every subsequent PD goes on top. */
775 for (i = 1; pds[i]; i++) {
776 ids = g_strsplit(pds[i], ":", 0);
777 if (!(di_to = srd_inst_find_by_id(ids[0]))) {
779 g_critical("Cannot stack protocol decoder '%s': "
780 "instance not found.", pds[i]);
784 if ((ret = srd_inst_stack(di_from, di_to)) != SRD_OK)
787 /* Don't show annotation from this PD. Only the last PD in
788 * the stack will be left on the annotation list (unless
789 * the annotation list was specifically provided).
791 if (!opt_pd_annotations)
792 g_hash_table_remove(pd_ann_visible,
803 int setup_pd_annotations(void)
806 struct srd_decoder *dec;
808 char **pds, **pdtok, **keyval, **ann_descr;
810 /* Set up custom list of PDs and annotations to show. */
811 if (opt_pd_annotations) {
812 pds = g_strsplit(opt_pd_annotations, ",", 0);
813 for (pdtok = pds; *pdtok && **pdtok; pdtok++) {
815 keyval = g_strsplit(*pdtok, "=", 0);
816 if (!(dec = srd_decoder_get_by_id(keyval[0]))) {
817 g_critical("Protocol decoder '%s' not found.", keyval[0]);
820 if (!dec->annotations) {
821 g_critical("Protocol decoder '%s' has no annotations.", keyval[0]);
824 if (g_strv_length(keyval) == 2) {
825 for (l = dec->annotations; l; l = l->next, ann++) {
827 if (!canon_cmp(ann_descr[0], keyval[1]))
832 g_critical("Annotation '%s' not found "
833 "for protocol decoder '%s'.", keyval[1], keyval[0]);
837 g_debug("cli: showing protocol decoder annotation %d from '%s'", ann, keyval[0]);
838 g_hash_table_insert(pd_ann_visible, g_strdup(keyval[0]), GINT_TO_POINTER(ann));
847 int setup_output_format(void)
852 struct sr_output_format **outputs;
856 if (!opt_output_format) {
857 opt_output_format = DEFAULT_OUTPUT_FORMAT;
858 /* we'll need to remember this so when saving to a file
859 * later, sigrok session format will be used.
861 default_output_format = TRUE;
863 fmtargs = parse_generic_arg(opt_output_format);
864 fmtspec = g_hash_table_lookup(fmtargs, "sigrok_key");
866 g_critical("Invalid output format.");
869 outputs = sr_output_list();
870 for (i = 0; outputs[i]; i++) {
871 if (strcmp(outputs[i]->id, fmtspec))
873 g_hash_table_remove(fmtargs, "sigrok_key");
874 output_format = outputs[i];
875 g_hash_table_iter_init(&iter, fmtargs);
876 while (g_hash_table_iter_next(&iter, &key, &value)) {
877 /* only supporting one parameter per output module
878 * for now, and only its value */
879 output_format_param = g_strdup(value);
884 if (!output_format) {
885 g_critical("Invalid output format %s.", opt_output_format);
888 g_hash_table_destroy(fmtargs);
893 void show_pd_annotations(struct srd_proto_data *pdata, void *cb_data)
899 /* 'cb_data' is not used in this specific callback. */
905 if (!g_hash_table_lookup_extended(pd_ann_visible, pdata->pdo->di->inst_id,
907 /* Not in the list of PDs whose annotations we're showing. */
910 if (pdata->ann_format != GPOINTER_TO_INT(ann_format))
911 /* We don't want this particular format from the PD. */
914 annotations = pdata->data;
915 if (opt_loglevel > SR_LOG_WARN)
916 printf("%"PRIu64"-%"PRIu64" ", pdata->start_sample, pdata->end_sample);
917 printf("%s: ", pdata->pdo->proto_id);
918 for (i = 0; annotations[i]; i++)
919 printf("\"%s\" ", annotations[i]);
923 static int select_probes(struct sr_dev *dev)
925 struct sr_probe *probe;
933 * This only works because a device by default initializes
934 * and enables all its probes.
936 max_probes = g_slist_length(dev->probes);
937 probelist = parse_probestring(max_probes, opt_probes);
942 for (i = 0; i < max_probes; i++) {
944 sr_dev_probe_name_set(dev, i + 1, probelist[i]);
945 g_free(probelist[i]);
947 probe = sr_dev_probe_find(dev, i + 1);
948 probe->enabled = FALSE;
957 * Return the input file format which the CLI tool should use.
959 * If the user specified -I / --input-format, use that one. Otherwise, try to
960 * autodetect the format as good as possible. Failing that, return NULL.
962 * @param filename The filename of the input file. Must not be NULL.
963 * @param opt The -I / --input-file option the user specified (or NULL).
965 * @return A pointer to the 'struct sr_input_format' that should be used,
966 * or NULL if no input format was selected or auto-detected.
968 static struct sr_input_format *determine_input_file_format(
969 const char *filename, const char *opt)
972 struct sr_input_format **inputs;
974 /* If there are no input formats, return NULL right away. */
975 inputs = sr_input_list();
977 g_critical("No supported input formats available.");
981 /* If the user specified -I / --input-format, use that one. */
983 for (i = 0; inputs[i]; i++) {
984 if (strcasecmp(inputs[i]->id, opt_input_format))
986 g_debug("Using user-specified input file format '%s'.",
991 /* The user specified an unknown input format, return NULL. */
992 g_critical("Error: specified input file format '%s' is "
993 "unknown.", opt_input_format);
997 /* Otherwise, try to find an input module that can handle this file. */
998 for (i = 0; inputs[i]; i++) {
999 if (inputs[i]->format_match(filename))
1003 /* Return NULL if no input module wanted to touch this. */
1005 g_critical("Error: no matching input module found.");
1009 g_debug("cli: Autodetected '%s' input format for file '%s'.",
1010 inputs[i]->id, filename);
1015 static void load_input_file_format(void)
1018 struct sr_input *in;
1019 struct sr_input_format *input_format;
1021 if (!(input_format = determine_input_file_format(opt_input_file,
1023 /* The exact cause was already logged. */
1026 if (stat(opt_input_file, &st) == -1) {
1027 g_critical("Failed to load %s: %s", opt_input_file,
1032 /* Initialize the input module. */
1033 if (!(in = g_try_malloc(sizeof(struct sr_input)))) {
1034 g_critical("Failed to allocate input module.");
1037 in->format = input_format;
1038 in->param = input_format_param;
1039 if (in->format->init) {
1040 if (in->format->init(in) != SR_OK) {
1041 g_critical("Input format init failed.");
1046 if (select_probes(in->vdev) > 0)
1050 sr_session_datafeed_callback_add(datafeed_in);
1051 if (sr_session_dev_add(in->vdev) != SR_OK) {
1052 g_critical("Failed to use device.");
1053 sr_session_destroy();
1057 input_format->loadfile(in, opt_input_file);
1058 if (opt_output_file && default_output_format) {
1059 if (sr_session_save(opt_output_file) != SR_OK)
1060 g_critical("Failed to save session.");
1062 sr_session_destroy();
1065 static void load_input_file(void)
1068 if (sr_session_load(opt_input_file) == SR_OK) {
1069 /* sigrok session file */
1070 sr_session_datafeed_callback_add(datafeed_in);
1076 /* fall back on input modules */
1077 load_input_file_format();
1081 int num_real_devs(void)
1088 devs = sr_dev_list();
1089 for (l = devs; l; l = l->next) {
1091 if (!sr_dev_has_hwcap(dev, SR_HWCAP_DEMO_DEV))
1098 static int set_dev_options(struct sr_dev *dev, GHashTable *args)
1100 GHashTableIter iter;
1101 gpointer key, value;
1105 struct sr_rational tmp_rat;
1109 g_hash_table_iter_init(&iter, args);
1110 while (g_hash_table_iter_next(&iter, &key, &value)) {
1112 for (i = 0; sr_hwcap_options[i].hwcap; i++) {
1113 if (strcmp(sr_hwcap_options[i].shortname, key))
1115 if ((value == NULL) &&
1116 (sr_hwcap_options[i].type != SR_T_BOOL)) {
1117 g_critical("Option '%s' needs a value.", (char *)key);
1121 switch (sr_hwcap_options[i].type) {
1123 ret = sr_parse_sizestring(value, &tmp_u64);
1126 ret = dev->driver->dev_config_set(dev->driver_index,
1127 sr_hwcap_options[i].hwcap, &tmp_u64);
1130 ret = dev->driver->dev_config_set(dev->driver_index,
1131 sr_hwcap_options[i].hwcap, value);
1137 tmp_bool = sr_parse_boolstring(value);
1138 ret = dev->driver->dev_config_set(dev->driver_index,
1139 sr_hwcap_options[i].hwcap,
1140 GINT_TO_POINTER(tmp_bool));
1143 tmp_float = strtof(value, NULL);
1144 ret = dev->driver->dev_config_set(dev->driver_index,
1145 sr_hwcap_options[i].hwcap, &tmp_float);
1147 case SR_T_RATIONAL_PERIOD:
1148 if ((ret = sr_parse_period(value, &tmp_rat)) != SR_OK)
1150 ret = dev->driver->dev_config_set(dev->driver_index,
1151 sr_hwcap_options[i].hwcap, &tmp_rat);
1153 case SR_T_RATIONAL_VOLT:
1154 if ((ret = sr_parse_voltage(value, &tmp_rat)) != SR_OK)
1156 ret = dev->driver->dev_config_set(dev->driver_index,
1157 sr_hwcap_options[i].hwcap, &tmp_rat);
1164 g_critical("Failed to set device option '%s'.", (char *)key);
1171 g_critical("Unknown device option '%s'.", (char *) key);
1179 static void run_session(void)
1182 GHashTable *devargs;
1183 int num_devs, max_probes, i;
1185 char **probelist, *devspec;
1189 devargs = parse_generic_arg(opt_dev);
1190 devspec = g_hash_table_lookup(devargs, "sigrok_key");
1191 dev = parse_devstring(devspec);
1193 g_critical("Device not found.");
1196 g_hash_table_remove(devargs, "sigrok_key");
1198 num_devs = num_real_devs();
1199 if (num_devs == 1) {
1200 /* No device specified, but there is only one. */
1202 dev = parse_devstring("0");
1203 } else if (num_devs == 0) {
1204 g_critical("No devices found.");
1207 g_critical("%d devices found, please select one.", num_devs);
1213 sr_session_datafeed_callback_add(datafeed_in);
1215 if (sr_session_dev_add(dev) != SR_OK) {
1216 g_critical("Failed to use device.");
1217 sr_session_destroy();
1222 if (set_dev_options(dev, devargs) != SR_OK) {
1223 sr_session_destroy();
1226 g_hash_table_destroy(devargs);
1229 if (select_probes(dev) != SR_OK)
1232 if (opt_continuous) {
1233 if (!sr_driver_hwcap_exists(dev->driver, SR_HWCAP_CONTINUOUS)) {
1234 g_critical("This device does not support continuous sampling.");
1235 sr_session_destroy();
1241 probelist = sr_parse_triggerstring(dev, opt_triggers);
1243 sr_session_destroy();
1247 max_probes = g_slist_length(dev->probes);
1248 for (i = 0; i < max_probes; i++) {
1250 sr_dev_trigger_set(dev, i + 1, probelist[i]);
1251 g_free(probelist[i]);
1258 time_msec = sr_parse_timestring(opt_time);
1259 if (time_msec == 0) {
1260 g_critical("Invalid time '%s'", opt_time);
1261 sr_session_destroy();
1265 if (sr_driver_hwcap_exists(dev->driver, SR_HWCAP_LIMIT_MSEC)) {
1266 if (dev->driver->dev_config_set(dev->driver_index,
1267 SR_HWCAP_LIMIT_MSEC, &time_msec) != SR_OK) {
1268 g_critical("Failed to configure time limit.");
1269 sr_session_destroy();
1274 /* time limit set, but device doesn't support this...
1275 * convert to samples based on the samplerate.
1278 if (sr_dev_has_hwcap(dev, SR_HWCAP_SAMPLERATE)) {
1279 const uint64_t *samplerate;
1281 sr_dev_info_get(dev, SR_DI_CUR_SAMPLERATE,
1282 (const void **)&samplerate);
1283 limit_samples = (*samplerate) * time_msec / (uint64_t)1000;
1285 if (limit_samples == 0) {
1286 g_critical("Not enough time at this samplerate.");
1287 sr_session_destroy();
1291 if (dev->driver->dev_config_set(dev->driver_index,
1292 SR_HWCAP_LIMIT_SAMPLES, &limit_samples) != SR_OK) {
1293 g_critical("Failed to configure time-based sample limit.");
1294 sr_session_destroy();
1301 if ((sr_parse_sizestring(opt_samples, &limit_samples) != SR_OK)
1302 || (dev->driver->dev_config_set(dev->driver_index,
1303 SR_HWCAP_LIMIT_SAMPLES, &limit_samples) != SR_OK)) {
1304 g_critical("Failed to configure sample limit.");
1305 sr_session_destroy();
1311 if ((sr_parse_sizestring(opt_frames, &limit_frames) != SR_OK)
1312 || (dev->driver->dev_config_set(dev->driver_index,
1313 SR_HWCAP_LIMIT_FRAMES, &limit_frames) != SR_OK)) {
1314 printf("Failed to configure frame limit.\n");
1315 sr_session_destroy();
1320 if (dev->driver->dev_config_set(dev->driver_index,
1321 SR_HWCAP_PROBECONFIG, (char *)dev->probes) != SR_OK) {
1322 g_critical("Failed to configure probes.");
1323 sr_session_destroy();
1327 if (sr_session_start() != SR_OK) {
1328 g_critical("Failed to start session.");
1329 sr_session_destroy();
1341 if (opt_output_file && default_output_format) {
1342 if (sr_session_save(opt_output_file) != SR_OK)
1343 g_critical("Failed to save session.");
1345 sr_session_destroy();
1348 static void logger(const gchar *log_domain, GLogLevelFlags log_level,
1349 const gchar *message, gpointer cb_data)
1351 /* Avoid compiler warnings. */
1356 * All messages, warnings, errors etc. go to stderr (not stdout) in
1357 * order to not mess up the CLI tool data output, e.g. VCD output.
1359 if (log_level & (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING)
1360 || opt_loglevel > SR_LOG_WARN) {
1361 fprintf(stderr, "%s\n", message);
1366 int main(int argc, char **argv)
1368 GOptionContext *context;
1371 g_log_set_default_handler(logger, NULL);
1374 context = g_option_context_new(NULL);
1375 g_option_context_add_main_entries(context, optargs, NULL);
1377 if (!g_option_context_parse(context, &argc, &argv, &error)) {
1378 g_critical("%s", error->message);
1382 /* Set the loglevel (amount of messages to output) for libsigrok. */
1383 if (sr_log_loglevel_set(opt_loglevel) != SR_OK)
1386 /* Set the loglevel (amount of messages to output) for libsigrokdecode. */
1387 if (srd_log_loglevel_set(opt_loglevel) != SRD_OK)
1390 if (sr_init() != SR_OK)
1394 if (srd_init(NULL) != SRD_OK)
1396 if (register_pds(NULL, opt_pds) != 0)
1398 if (srd_pd_output_callback_add(SRD_OUTPUT_ANN,
1399 show_pd_annotations, NULL) != SRD_OK)
1401 if (setup_pd_stack() != 0)
1403 if (setup_pd_annotations() != 0)
1407 if (setup_output_format() != 0)
1412 else if (opt_list_devs)
1414 else if (opt_input_file)
1416 else if (opt_samples || opt_time || opt_frames || opt_continuous)
1423 printf("%s", g_option_context_get_help(context, TRUE, NULL));
1428 g_option_context_free(context);