2 * This file is part of the sigrok project.
4 * Copyright (C) 2012 Bert Vermeulen <bert@biot.com>
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 #include <sigrokdecode.h> /* First, so we avoid a _POSIX_C_SOURCE warning. */
28 #include <sys/types.h>
32 #include <glib/gstdio.h>
33 #include <libsigrok/libsigrok.h>
34 #include "sigrok-cli.h"
37 #define DEFAULT_OUTPUT_FORMAT "bits:width=64"
39 static struct sr_context
*sr_ctx
= NULL
;
41 static uint64_t limit_samples
= 0;
42 static uint64_t limit_frames
= 0;
43 static struct sr_output_format
*output_format
= NULL
;
44 static int default_output_format
= FALSE
;
45 static char *output_format_param
= NULL
;
46 static GHashTable
*pd_ann_visible
= NULL
;
47 static struct sr_datastore
*singleds
= 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_drv
= NULL
;
56 static gchar
*opt_dev
= NULL
;
57 static gchar
*opt_probes
= NULL
;
58 static gchar
*opt_triggers
= NULL
;
59 static gchar
*opt_pds
= NULL
;
60 static gchar
*opt_pd_stack
= NULL
;
61 static gchar
*opt_pd_annotations
= NULL
;
62 static gchar
*opt_input_format
= NULL
;
63 static gchar
*opt_output_format
= NULL
;
64 static gchar
*opt_show
= NULL
;
65 static gchar
*opt_time
= NULL
;
66 static gchar
*opt_samples
= NULL
;
67 static gchar
*opt_frames
= NULL
;
68 static gchar
*opt_continuous
= NULL
;
70 static GOptionEntry optargs
[] = {
71 {"version", 'V', 0, G_OPTION_ARG_NONE
, &opt_version
,
72 "Show version and support list", NULL
},
73 {"loglevel", 'l', 0, G_OPTION_ARG_INT
, &opt_loglevel
,
74 "Set libsigrok/libsigrokdecode loglevel", NULL
},
75 {"list-devices", 'D', 0, G_OPTION_ARG_NONE
, &opt_list_devs
,
76 "Scan for devices", NULL
},
77 {"driver", 0, 0, G_OPTION_ARG_STRING
, &opt_drv
,
78 "Use only this driver", NULL
},
79 {"device", 'd', 0, G_OPTION_ARG_STRING
, &opt_dev
,
80 "Use specified device", NULL
},
81 {"input-file", 'i', 0, G_OPTION_ARG_FILENAME
, &opt_input_file
,
82 "Load input from file", NULL
},
83 {"input-format", 'I', 0, G_OPTION_ARG_STRING
, &opt_input_format
,
84 "Input format", NULL
},
85 {"output-file", 'o', 0, G_OPTION_ARG_FILENAME
, &opt_output_file
,
86 "Save output to file", NULL
},
87 {"output-format", 'O', 0, G_OPTION_ARG_STRING
, &opt_output_format
,
88 "Output format", NULL
},
89 {"probes", 'p', 0, G_OPTION_ARG_STRING
, &opt_probes
,
90 "Probes to use", NULL
},
91 {"triggers", 't', 0, G_OPTION_ARG_STRING
, &opt_triggers
,
92 "Trigger configuration", NULL
},
93 {"wait-trigger", 'w', 0, G_OPTION_ARG_NONE
, &opt_wait_trigger
,
94 "Wait for trigger", NULL
},
95 {"protocol-decoders", 'a', 0, G_OPTION_ARG_STRING
, &opt_pds
,
96 "Protocol decoders to run", NULL
},
97 {"protocol-decoder-stack", 's', 0, G_OPTION_ARG_STRING
, &opt_pd_stack
,
98 "Protocol decoder stack", NULL
},
99 {"protocol-decoder-annotations", 'A', 0, G_OPTION_ARG_STRING
, &opt_pd_annotations
,
100 "Protocol decoder annotation(s) to show", NULL
},
101 {"show", 0, 0, G_OPTION_ARG_NONE
, &opt_show
,
102 "Show device detail", NULL
},
103 {"time", 0, 0, G_OPTION_ARG_STRING
, &opt_time
,
104 "How long to sample (ms)", NULL
},
105 {"samples", 0, 0, G_OPTION_ARG_STRING
, &opt_samples
,
106 "Number of samples to acquire", NULL
},
107 {"frames", 0, 0, G_OPTION_ARG_STRING
, &opt_frames
,
108 "Number of frames to acquire", NULL
},
109 {"continuous", 0, 0, G_OPTION_ARG_NONE
, &opt_continuous
,
110 "Sample continuously", NULL
},
111 {NULL
, 0, 0, 0, NULL
, NULL
, NULL
}
115 /* Convert driver options hash to GSList of struct sr_hwopt. */
116 static GSList
*hash_to_hwopt(GHashTable
*hash
)
118 const struct sr_hwcap_option
*hwo
;
119 struct sr_hwopt
*hwopt
;
124 keys
= g_hash_table_get_keys(hash
);
126 for (gl
= keys
; gl
; gl
= gl
->next
) {
128 if (!(hwo
= sr_drvopt_name_get(key
))) {
129 g_critical("Unknown option %s", key
);
132 hwopt
= g_try_malloc(sizeof(struct sr_hwopt
));
133 hwopt
->hwopt
= hwo
->hwcap
;
134 value
= g_hash_table_lookup(hash
, key
);
135 hwopt
->value
= g_strdup(value
);
136 opts
= g_slist_append(opts
, hwopt
);
143 static GSList
*device_scan(void)
145 struct sr_dev_driver
**drivers
, *driver
;
147 GSList
*drvopts
, *devices
, *tmpdevs
, *l
;
152 drvargs
= parse_generic_arg(opt_drv
, TRUE
);
153 drvname
= g_strdup(g_hash_table_lookup(drvargs
, "sigrok_key"));
154 g_hash_table_remove(drvargs
, "sigrok_key");
156 drivers
= sr_driver_list();
157 for (i
= 0; drivers
[i
]; i
++) {
158 if (strcmp(drivers
[i
]->name
, drvname
))
163 g_critical("Driver %s not found.", drvname
);
167 if (sr_driver_init(sr_ctx
, driver
) != SR_OK
) {
168 g_critical("Failed to initialize driver.");
172 if (g_hash_table_size(drvargs
) > 0)
173 if (!(drvopts
= hash_to_hwopt(drvargs
)))
174 /* Unknown options, already logged. */
176 devices
= sr_driver_scan(driver
, drvopts
);
178 /* No driver specified, let them all scan on their own. */
180 drivers
= sr_driver_list();
181 for (i
= 0; drivers
[i
]; i
++) {
183 if (sr_driver_init(sr_ctx
, driver
) != SR_OK
) {
184 g_critical("Failed to initialize driver.");
187 tmpdevs
= sr_driver_scan(driver
, NULL
);
188 for (l
= tmpdevs
; l
; l
= l
->next
)
189 devices
= g_slist_append(devices
, l
->data
);
190 g_slist_free(tmpdevs
);
197 static void show_version(void)
200 struct sr_dev_driver
**drivers
;
201 struct sr_input_format
**inputs
;
202 struct sr_output_format
**outputs
;
203 struct srd_decoder
*dec
;
206 printf("sigrok-cli %s\n\n", VERSION
);
208 printf("Using libsigrok %s (lib version %s).\n",
209 sr_package_version_string_get(), sr_lib_version_string_get());
210 printf("Using libsigrokdecode %s (lib version %s).\n\n",
211 srd_package_version_string_get(), srd_lib_version_string_get());
213 printf("Supported hardware drivers:\n");
214 drivers
= sr_driver_list();
215 for (i
= 0; drivers
[i
]; i
++) {
216 printf(" %-20s %s\n", drivers
[i
]->name
, drivers
[i
]->longname
);
220 printf("Supported input formats:\n");
221 inputs
= sr_input_list();
222 for (i
= 0; inputs
[i
]; i
++)
223 printf(" %-20s %s\n", inputs
[i
]->id
, inputs
[i
]->description
);
226 printf("Supported output formats:\n");
227 outputs
= sr_output_list();
228 for (i
= 0; outputs
[i
]; i
++)
229 printf(" %-20s %s\n", outputs
[i
]->id
, outputs
[i
]->description
);
232 if (srd_init(NULL
) == SRD_OK
) {
233 printf("Supported protocol decoders:\n");
234 srd_decoder_load_all();
235 for (l
= srd_decoder_list(); l
; l
= l
->next
) {
237 printf(" %-20s %s\n", dec
->id
, dec
->longname
);
238 /* Print protocol description upon "-l 3" or higher. */
239 if (opt_loglevel
>= SR_LOG_INFO
)
240 printf(" %-20s %s\n", "", dec
->desc
);
247 static void print_dev_line(const struct sr_dev_inst
*sdi
)
249 struct sr_probe
*probe
;
252 if (sdi
->vendor
&& sdi
->vendor
[0])
253 printf("%s ", sdi
->vendor
);
254 if (sdi
->model
&& sdi
->model
[0])
255 printf("%s ", sdi
->model
);
256 if (sdi
->version
&& sdi
->version
[0])
257 printf("%s ", sdi
->version
);
259 if (g_slist_length(sdi
->probes
) == 1) {
260 probe
= sdi
->probes
->data
;
261 printf("with 1 probe: %s", probe
->name
);
263 printf("with %d probes:", g_slist_length(sdi
->probes
));
264 for (l
= sdi
->probes
; l
; l
= l
->next
) {
266 printf(" %s", probe
->name
);
273 static void show_dev_list(void)
275 struct sr_dev_inst
*sdi
;
278 if (!(devices
= device_scan()))
281 printf("The following devices were found:\n");
282 for (l
= devices
; l
; l
= l
->next
) {
286 g_slist_free(devices
);
290 static void show_dev_detail(void)
292 struct sr_dev_inst
*sdi
;
293 const struct sr_hwcap_option
*hwo
;
294 const struct sr_samplerates
*samplerates
;
295 struct sr_rational
*rationals
;
298 const int *hwopts
, *hwcaps
;
299 int cap
, num_devices
, n
, i
;
301 const char *charopts
, **stropts
;
303 if (!(devices
= device_scan())) {
304 g_critical("No devices found.");
308 num_devices
= g_slist_length(devices
);
309 if (num_devices
> 1) {
311 g_critical("%d devices found. Use --list-devices to show them, "
312 "and --device to select one.", num_devices
);
315 /* opt_dev is NULL if not specified, which is fine. */
316 n
= strtol(opt_dev
, NULL
, 10);
317 if (n
>= num_devices
) {
318 g_critical("%d devices found, numbered starting from 0.",
322 sdi
= g_slist_nth_data(devices
, n
);
324 sdi
= g_slist_nth_data(devices
, 0);
328 if (sr_info_get(sdi
->driver
, SR_DI_TRIGGER_TYPES
, (const void **)&charopts
,
329 sdi
) == SR_OK
&& charopts
) {
330 printf("Supported triggers: ");
332 printf("%c ", *charopts
);
338 if ((sr_info_get(sdi
->driver
, SR_DI_HWOPTS
, (const void **)&hwopts
,
339 NULL
) == SR_OK
) && hwopts
) {
340 printf("Supported driver options:\n");
341 for (i
= 0; hwopts
[i
]; i
++) {
342 if (!(hwo
= sr_drvopt_get(hwopts
[i
])))
344 printf(" %s\n", hwo
->shortname
);
348 title
= "Supported device options:\n";
349 if ((sr_info_get(sdi
->driver
, SR_DI_HWCAPS
, (const void **)&hwcaps
,
350 NULL
) != SR_OK
) || !hwcaps
)
351 /* Driver supports no device instance options. */
354 for (cap
= 0; hwcaps
[cap
]; cap
++) {
355 if (!(hwo
= sr_devopt_get(hwcaps
[cap
])))
363 if (hwo
->hwcap
== SR_HWCAP_PATTERN_MODE
) {
364 /* Pattern generator modes */
365 printf(" %s", hwo
->shortname
);
366 if (sr_info_get(sdi
->driver
, SR_DI_PATTERNS
,
367 (const void **)&stropts
, sdi
) == SR_OK
) {
368 printf(" - supported patterns:\n");
369 for (i
= 0; stropts
[i
]; i
++)
370 printf(" %s\n", stropts
[i
]);
375 } else if (hwo
->hwcap
== SR_HWCAP_SAMPLERATE
) {
376 /* Supported samplerates */
377 printf(" %s", hwo
->shortname
);
378 if (sr_info_get(sdi
->driver
, SR_DI_SAMPLERATES
,
379 (const void **)&samplerates
, sdi
) != SR_OK
) {
383 if (samplerates
->step
) {
385 if (!(s
= sr_samplerate_string(samplerates
->low
)))
390 if (!(s
= sr_samplerate_string(samplerates
->high
)))
395 if (!(s
= sr_samplerate_string(samplerates
->step
)))
397 printf(" in steps of %s)\n", s
);
400 printf(" - supported samplerates:\n");
401 for (i
= 0; samplerates
->list
[i
]; i
++)
402 printf(" %s\n", sr_samplerate_string(samplerates
->list
[i
]));
405 } else if (hwo
->hwcap
== SR_HWCAP_BUFFERSIZE
) {
406 /* Supported buffer sizes */
407 printf(" %s", hwo
->shortname
);
408 if (sr_info_get(sdi
->driver
, SR_DI_BUFFERSIZES
,
409 (const void **)&integers
, sdi
) != SR_OK
) {
413 printf(" - supported buffer sizes:\n");
414 for (i
= 0; integers
[i
]; i
++)
415 printf(" %"PRIu64
"\n", integers
[i
]);
417 } else if (hwo
->hwcap
== SR_HWCAP_TIMEBASE
) {
418 /* Supported time bases */
419 printf(" %s", hwo
->shortname
);
420 if (sr_info_get(sdi
->driver
, SR_DI_TIMEBASES
,
421 (const void **)&rationals
, sdi
) != SR_OK
) {
425 printf(" - supported time bases:\n");
426 for (i
= 0; rationals
[i
].p
&& rationals
[i
].q
; i
++)
427 printf(" %s\n", sr_period_string(
428 rationals
[i
].p
* rationals
[i
].q
));
430 } else if (hwo
->hwcap
== SR_HWCAP_TRIGGER_SOURCE
) {
431 /* Supported trigger sources */
432 printf(" %s", hwo
->shortname
);
433 if (sr_info_get(sdi
->driver
, SR_DI_TRIGGER_SOURCES
,
434 (const void **)&stropts
, sdi
) != SR_OK
) {
438 printf(" - supported trigger sources:\n");
439 for (i
= 0; stropts
[i
]; i
++)
440 printf(" %s\n", stropts
[i
]);
442 } else if (hwo
->hwcap
== SR_HWCAP_FILTER
) {
443 /* Supported trigger sources */
444 printf(" %s", hwo
->shortname
);
445 if (sr_info_get(sdi
->driver
, SR_DI_FILTERS
,
446 (const void **)&stropts
, sdi
) != SR_OK
) {
450 printf(" - supported filter targets:\n");
451 for (i
= 0; stropts
[i
]; i
++)
452 printf(" %s\n", stropts
[i
]);
454 } else if (hwo
->hwcap
== SR_HWCAP_VDIV
) {
455 /* Supported volts/div values */
456 printf(" %s", hwo
->shortname
);
457 if (sr_info_get(sdi
->driver
, SR_DI_VDIVS
,
458 (const void **)&rationals
, sdi
) != SR_OK
) {
462 printf(" - supported volts/div:\n");
463 for (i
= 0; rationals
[i
].p
&& rationals
[i
].q
; i
++)
464 printf(" %s\n", sr_voltage_string( &rationals
[i
]));
466 } else if (hwo
->hwcap
== SR_HWCAP_COUPLING
) {
467 /* Supported coupling settings */
468 printf(" %s", hwo
->shortname
);
469 if (sr_info_get(sdi
->driver
, SR_DI_COUPLING
,
470 (const void **)&stropts
, sdi
) != SR_OK
) {
474 printf(" - supported coupling options:\n");
475 for (i
= 0; stropts
[i
]; i
++)
476 printf(" %s\n", stropts
[i
]);
479 /* Everything else */
480 printf(" %s\n", hwo
->shortname
);
486 static void show_pd_detail(void)
489 struct srd_decoder
*dec
;
490 char **pdtokens
, **pdtok
, **ann
, *doc
;
493 pdtokens
= g_strsplit(opt_pds
, ",", -1);
494 for (pdtok
= pdtokens
; *pdtok
; pdtok
++) {
495 if (!(dec
= srd_decoder_get_by_id(*pdtok
))) {
496 g_critical("Protocol decoder %s not found.", *pdtok
);
499 printf("ID: %s\nName: %s\nLong name: %s\nDescription: %s\n",
500 dec
->id
, dec
->name
, dec
->longname
, dec
->desc
);
501 printf("License: %s\n", dec
->license
);
502 printf("Annotations:\n");
503 if (dec
->annotations
) {
504 for (l
= dec
->annotations
; l
; l
= l
->next
) {
506 printf("- %s\n %s\n", ann
[0], ann
[1]);
511 /* TODO: Print supported decoder options. */
512 printf("Required probes:\n");
514 for (l
= dec
->probes
; l
; l
= l
->next
) {
516 printf("- %s (%s): %s\n",
517 p
->name
, p
->id
, p
->desc
);
522 printf("Optional probes:\n");
523 if (dec
->opt_probes
) {
524 for (l
= dec
->opt_probes
; l
; l
= l
->next
) {
526 printf("- %s (%s): %s\n",
527 p
->name
, p
->id
, p
->desc
);
532 if ((doc
= srd_decoder_doc_get(dec
))) {
533 printf("Documentation:\n%s\n",
534 doc
[0] == '\n' ? doc
+ 1 : doc
);
539 g_strfreev(pdtokens
);
542 static void datafeed_in(const struct sr_dev_inst
*sdi
,
543 const struct sr_datafeed_packet
*packet
)
545 static struct sr_output
*o
= NULL
;
546 static int logic_probelist
[SR_MAX_NUM_PROBES
] = { -1 };
547 static struct sr_probe
*analog_probelist
[SR_MAX_NUM_PROBES
];
548 static uint64_t received_samples
= 0;
549 static int unitsize
= 0;
550 static int triggered
= 0;
551 static FILE *outfile
= NULL
;
552 static int num_analog_probes
= 0;
553 struct sr_probe
*probe
;
554 const struct sr_datafeed_logic
*logic
;
555 const struct sr_datafeed_meta_logic
*meta_logic
;
556 const struct sr_datafeed_analog
*analog
;
557 const struct sr_datafeed_meta_analog
*meta_analog
;
558 static int num_enabled_analog_probes
= 0;
559 int num_enabled_probes
, sample_size
, ret
, i
;
560 uint64_t output_len
, filter_out_len
;
561 uint8_t *output_buf
, *filter_out
;
564 /* If the first packet to come in isn't a header, don't even try. */
565 if (packet
->type
!= SR_DF_HEADER
&& o
== NULL
)
569 switch (packet
->type
) {
571 g_debug("cli: Received SR_DF_HEADER");
572 /* Initialize the output module. */
573 if (!(o
= g_try_malloc(sizeof(struct sr_output
)))) {
574 g_critical("Output module malloc failed.");
577 o
->format
= output_format
;
578 o
->sdi
= (struct sr_dev_inst
*)sdi
;
579 o
->param
= output_format_param
;
580 if (o
->format
->init
) {
581 if (o
->format
->init(o
) != SR_OK
) {
582 g_critical("Output format initialization failed.");
589 g_debug("cli: Received SR_DF_END");
591 g_debug("cli: double end!");
594 if (o
->format
->event
) {
595 o
->format
->event(o
, SR_DF_END
, &output_buf
, &output_len
);
598 fwrite(output_buf
, 1, output_len
, outfile
);
603 if (limit_samples
&& received_samples
< limit_samples
)
604 g_warning("Device only sent %" PRIu64
" samples.",
607 g_warning("Device stopped after %" PRIu64
" samples.",
609 if (outfile
&& outfile
!= stdout
)
612 if (o
->format
->cleanup
)
613 o
->format
->cleanup(o
);
619 g_debug("cli: received SR_DF_TRIGGER");
620 if (o
->format
->event
)
621 o
->format
->event(o
, SR_DF_TRIGGER
, &output_buf
,
626 case SR_DF_META_LOGIC
:
627 g_message("cli: Received SR_DF_META_LOGIC");
628 meta_logic
= packet
->payload
;
629 num_enabled_probes
= 0;
630 for (i
= 0; i
< meta_logic
->num_probes
; i
++) {
631 probe
= g_slist_nth_data(sdi
->probes
, i
);
633 logic_probelist
[num_enabled_probes
++] = probe
->index
;
635 logic_probelist
[num_enabled_probes
] = -1;
636 /* How many bytes we need to store num_enabled_probes bits */
637 unitsize
= (num_enabled_probes
+ 7) / 8;
640 if (opt_output_file
) {
641 if (default_output_format
) {
642 /* output file is in session format, which means we'll
643 * dump everything in the datastore as it comes in,
644 * and save from there after the session. */
646 ret
= sr_datastore_new(unitsize
, &singleds
);
648 g_critical("Failed to create datastore.");
652 /* saving to a file in whatever format was set
653 * with --format, so all we need is a filehandle */
654 outfile
= g_fopen(opt_output_file
, "wb");
658 srd_session_start(num_enabled_probes
, unitsize
,
659 meta_logic
->samplerate
);
663 logic
= packet
->payload
;
664 g_message("cli: received SR_DF_LOGIC, %"PRIu64
" bytes", logic
->length
);
665 sample_size
= logic
->unitsize
;
666 if (logic
->length
== 0)
669 /* Don't store any samples until triggered. */
670 if (opt_wait_trigger
&& !triggered
)
673 if (limit_samples
&& received_samples
>= limit_samples
)
676 ret
= sr_filter_probes(sample_size
, unitsize
, logic_probelist
,
677 logic
->data
, logic
->length
,
678 &filter_out
, &filter_out_len
);
682 /* what comes out of the filter is guaranteed to be packed into the
683 * minimum size needed to support the number of samples at this sample
684 * size. however, the driver may have submitted too much -- cut off
685 * the buffer of the last packet according to the sample limit.
687 if (limit_samples
&& (received_samples
+ logic
->length
/ sample_size
>
688 limit_samples
* sample_size
))
689 filter_out_len
= limit_samples
* sample_size
- received_samples
;
692 sr_datastore_put(singleds
, filter_out
,
693 filter_out_len
, sample_size
, logic_probelist
);
695 if (opt_output_file
&& default_output_format
)
696 /* saving to a session file, don't need to do anything else
697 * to this data for now. */
701 if (srd_session_send(received_samples
, (uint8_t*)filter_out
,
702 filter_out_len
) != SRD_OK
)
706 if (o
->format
->data
&& packet
->type
== o
->format
->df_type
)
707 o
->format
->data(o
, filter_out
, filter_out_len
, &output_buf
, &output_len
);
709 fwrite(output_buf
, 1, output_len
, outfile
);
717 received_samples
+= logic
->length
/ sample_size
;
720 case SR_DF_META_ANALOG
:
721 g_message("cli: Received SR_DF_META_ANALOG");
722 meta_analog
= packet
->payload
;
723 num_analog_probes
= meta_analog
->num_probes
;
724 num_enabled_analog_probes
= 0;
725 for (i
= 0; i
< num_analog_probes
; i
++) {
726 probe
= g_slist_nth_data(sdi
->probes
, i
);
728 analog_probelist
[num_enabled_analog_probes
++] = probe
;
732 if (opt_output_file
) {
733 if (default_output_format
) {
734 /* output file is in session format, which means we'll
735 * dump everything in the datastore as it comes in,
736 * and save from there after the session. */
738 ret
= sr_datastore_new(unitsize
, &singleds
);
740 g_critical("Failed to create datastore.");
744 /* saving to a file in whatever format was set
745 * with --format, so all we need is a filehandle */
746 outfile
= g_fopen(opt_output_file
, "wb");
752 analog
= packet
->payload
;
753 g_message("cli: received SR_DF_ANALOG, %d samples", analog
->num_samples
);
754 if (analog
->num_samples
== 0)
757 if (limit_samples
&& received_samples
>= limit_samples
)
760 if (o
->format
->data
&& packet
->type
== o
->format
->df_type
) {
761 o
->format
->data(o
, (const uint8_t *)analog
->data
,
762 analog
->num_samples
* sizeof(float),
763 &output_buf
, &output_len
);
765 fwrite(output_buf
, 1, output_len
, outfile
);
771 received_samples
+= analog
->num_samples
;
774 case SR_DF_FRAME_BEGIN
:
775 g_debug("cli: received SR_DF_FRAME_BEGIN");
776 if (o
->format
->event
) {
777 o
->format
->event(o
, SR_DF_FRAME_BEGIN
, &output_buf
,
780 fwrite(output_buf
, 1, output_len
, outfile
);
787 case SR_DF_FRAME_END
:
788 g_debug("cli: received SR_DF_FRAME_END");
789 if (o
->format
->event
) {
790 o
->format
->event(o
, SR_DF_FRAME_END
, &output_buf
,
793 fwrite(output_buf
, 1, output_len
, outfile
);
801 g_message("received unknown packet type %d", packet
->type
);
804 if (o
&& o
->format
->recv
) {
805 out
= o
->format
->recv(o
, sdi
, packet
);
806 if (out
&& out
->len
) {
807 fwrite(out
->str
, 1, out
->len
, outfile
);
814 /* Register the given PDs for this session.
815 * Accepts a string of the form: "spi:sck=3:sdata=4,spi:sck=3:sdata=5"
816 * That will instantiate two SPI decoders on the clock but different data
819 static int register_pds(struct sr_dev
*dev
, const char *pdstring
)
821 GHashTable
*pd_opthash
;
822 struct srd_decoder_inst
*di
;
824 char **pdtokens
, **pdtok
, *pd_name
;
829 pd_ann_visible
= g_hash_table_new_full(g_str_hash
, g_int_equal
,
833 pdtokens
= g_strsplit(pdstring
, ",", 0);
834 for (pdtok
= pdtokens
; *pdtok
; pdtok
++) {
835 if (!(pd_opthash
= parse_generic_arg(*pdtok
, TRUE
))) {
836 g_critical("Invalid protocol decoder option '%s'.", *pdtok
);
840 pd_name
= g_strdup(g_hash_table_lookup(pd_opthash
, "sigrok_key"));
841 g_hash_table_remove(pd_opthash
, "sigrok_key");
842 if (srd_decoder_load(pd_name
) != SRD_OK
) {
843 g_critical("Failed to load protocol decoder %s.", pd_name
);
847 if (!(di
= srd_inst_new(pd_name
, pd_opthash
))) {
848 g_critical("Failed to instantiate protocol decoder %s.", pd_name
);
853 /* If no annotation list was specified, add them all in now.
854 * This will be pared down later to leave only the last PD
857 if (!opt_pd_annotations
)
858 g_hash_table_insert(pd_ann_visible
,
859 g_strdup(di
->inst_id
), NULL
);
861 /* Any keys left in the options hash are probes, where the key
862 * is the probe name as specified in the decoder class, and the
863 * value is the probe number i.e. the order in which the PD's
864 * incoming samples are arranged. */
865 if (srd_inst_probe_set_all(di
, pd_opthash
) != SRD_OK
) {
869 g_hash_table_destroy(pd_opthash
);
874 g_strfreev(pdtokens
);
876 g_hash_table_destroy(pd_opthash
);
883 int setup_pd_stack(void)
885 struct srd_decoder_inst
*di_from
, *di_to
;
889 /* Set up the protocol decoder stack. */
890 pds
= g_strsplit(opt_pds
, ",", 0);
891 if (g_strv_length(pds
) > 1) {
893 /* A stack setup was specified, use that. */
895 pds
= g_strsplit(opt_pd_stack
, ",", 0);
896 if (g_strv_length(pds
) < 2) {
898 g_critical("Specify at least two protocol decoders to stack.");
903 /* First PD goes at the bottom of the stack. */
904 ids
= g_strsplit(pds
[0], ":", 0);
905 if (!(di_from
= srd_inst_find_by_id(ids
[0]))) {
907 g_critical("Cannot stack protocol decoder '%s': "
908 "instance not found.", pds
[0]);
913 /* Every subsequent PD goes on top. */
914 for (i
= 1; pds
[i
]; i
++) {
915 ids
= g_strsplit(pds
[i
], ":", 0);
916 if (!(di_to
= srd_inst_find_by_id(ids
[0]))) {
918 g_critical("Cannot stack protocol decoder '%s': "
919 "instance not found.", pds
[i
]);
923 if ((ret
= srd_inst_stack(di_from
, di_to
)) != SRD_OK
)
926 /* Don't show annotation from this PD. Only the last PD in
927 * the stack will be left on the annotation list (unless
928 * the annotation list was specifically provided).
930 if (!opt_pd_annotations
)
931 g_hash_table_remove(pd_ann_visible
,
942 int setup_pd_annotations(void)
945 struct srd_decoder
*dec
;
947 char **pds
, **pdtok
, **keyval
, **ann_descr
;
949 /* Set up custom list of PDs and annotations to show. */
950 if (opt_pd_annotations
) {
951 pds
= g_strsplit(opt_pd_annotations
, ",", 0);
952 for (pdtok
= pds
; *pdtok
&& **pdtok
; pdtok
++) {
954 keyval
= g_strsplit(*pdtok
, "=", 0);
955 if (!(dec
= srd_decoder_get_by_id(keyval
[0]))) {
956 g_critical("Protocol decoder '%s' not found.", keyval
[0]);
959 if (!dec
->annotations
) {
960 g_critical("Protocol decoder '%s' has no annotations.", keyval
[0]);
963 if (g_strv_length(keyval
) == 2) {
964 for (l
= dec
->annotations
; l
; l
= l
->next
, ann
++) {
966 if (!canon_cmp(ann_descr
[0], keyval
[1]))
971 g_critical("Annotation '%s' not found "
972 "for protocol decoder '%s'.", keyval
[1], keyval
[0]);
976 g_debug("cli: showing protocol decoder annotation %d from '%s'", ann
, keyval
[0]);
977 g_hash_table_insert(pd_ann_visible
, g_strdup(keyval
[0]), GINT_TO_POINTER(ann
));
986 int setup_output_format(void)
991 struct sr_output_format
**outputs
;
995 if (!opt_output_format
) {
996 opt_output_format
= DEFAULT_OUTPUT_FORMAT
;
997 /* we'll need to remember this so when saving to a file
998 * later, sigrok session format will be used.
1000 default_output_format
= TRUE
;
1003 fmtargs
= parse_generic_arg(opt_output_format
, TRUE
);
1004 fmtspec
= g_hash_table_lookup(fmtargs
, "sigrok_key");
1006 g_critical("Invalid output format.");
1009 outputs
= sr_output_list();
1010 for (i
= 0; outputs
[i
]; i
++) {
1011 if (strcmp(outputs
[i
]->id
, fmtspec
))
1013 g_hash_table_remove(fmtargs
, "sigrok_key");
1014 output_format
= outputs
[i
];
1015 g_hash_table_iter_init(&iter
, fmtargs
);
1016 while (g_hash_table_iter_next(&iter
, &key
, &value
)) {
1017 /* only supporting one parameter per output module
1018 * for now, and only its value */
1019 output_format_param
= g_strdup(value
);
1024 if (!output_format
) {
1025 g_critical("Invalid output format %s.", opt_output_format
);
1028 g_hash_table_destroy(fmtargs
);
1033 void show_pd_annotations(struct srd_proto_data
*pdata
, void *cb_data
)
1037 gpointer ann_format
;
1039 /* 'cb_data' is not used in this specific callback. */
1042 if (!pd_ann_visible
)
1045 if (!g_hash_table_lookup_extended(pd_ann_visible
, pdata
->pdo
->di
->inst_id
,
1047 /* Not in the list of PDs whose annotations we're showing. */
1050 if (pdata
->ann_format
!= GPOINTER_TO_INT(ann_format
))
1051 /* We don't want this particular format from the PD. */
1054 annotations
= pdata
->data
;
1055 if (opt_loglevel
> SR_LOG_WARN
)
1056 printf("%"PRIu64
"-%"PRIu64
" ", pdata
->start_sample
, pdata
->end_sample
);
1057 printf("%s: ", pdata
->pdo
->proto_id
);
1058 for (i
= 0; annotations
[i
]; i
++)
1059 printf("\"%s\" ", annotations
[i
]);
1064 static int select_probes(struct sr_dev_inst
*sdi
)
1066 struct sr_probe
*probe
;
1067 GSList
*selected_probes
, *l
;
1072 if (!(selected_probes
= parse_probestring(sdi
, opt_probes
)))
1075 for (l
= sdi
->probes
; l
; l
= l
->next
) {
1077 if (g_slist_find(selected_probes
, probe
))
1078 probe
->enabled
= TRUE
;
1080 probe
->enabled
= FALSE
;
1082 g_slist_free(selected_probes
);
1088 * Return the input file format which the CLI tool should use.
1090 * If the user specified -I / --input-format, use that one. Otherwise, try to
1091 * autodetect the format as good as possible. Failing that, return NULL.
1093 * @param filename The filename of the input file. Must not be NULL.
1094 * @param opt The -I / --input-file option the user specified (or NULL).
1096 * @return A pointer to the 'struct sr_input_format' that should be used,
1097 * or NULL if no input format was selected or auto-detected.
1099 static struct sr_input_format
*determine_input_file_format(
1100 const char *filename
, const char *opt
)
1103 struct sr_input_format
**inputs
;
1105 /* If there are no input formats, return NULL right away. */
1106 inputs
= sr_input_list();
1108 g_critical("No supported input formats available.");
1112 /* If the user specified -I / --input-format, use that one. */
1114 for (i
= 0; inputs
[i
]; i
++) {
1115 if (strcasecmp(inputs
[i
]->id
, opt
))
1117 g_debug("Using user-specified input file format '%s'.",
1122 /* The user specified an unknown input format, return NULL. */
1123 g_critical("Error: specified input file format '%s' is "
1128 /* Otherwise, try to find an input module that can handle this file. */
1129 for (i
= 0; inputs
[i
]; i
++) {
1130 if (inputs
[i
]->format_match(filename
))
1134 /* Return NULL if no input module wanted to touch this. */
1136 g_critical("Error: no matching input module found.");
1140 g_debug("cli: Autodetected '%s' input format for file '%s'.",
1141 inputs
[i
]->id
, filename
);
1146 static void load_input_file_format(void)
1148 GHashTable
*fmtargs
= NULL
;
1150 struct sr_input
*in
;
1151 struct sr_input_format
*input_format
;
1152 char *fmtspec
= NULL
;
1154 if (opt_input_format
) {
1155 fmtargs
= parse_generic_arg(opt_input_format
, TRUE
);
1156 fmtspec
= g_hash_table_lookup(fmtargs
, "sigrok_key");
1159 if (!(input_format
= determine_input_file_format(opt_input_file
,
1161 /* The exact cause was already logged. */
1166 g_hash_table_remove(fmtargs
, "sigrok_key");
1168 if (stat(opt_input_file
, &st
) == -1) {
1169 g_critical("Failed to load %s: %s", opt_input_file
,
1174 /* Initialize the input module. */
1175 if (!(in
= g_try_malloc(sizeof(struct sr_input
)))) {
1176 g_critical("Failed to allocate input module.");
1179 in
->format
= input_format
;
1180 in
->param
= fmtargs
;
1181 if (in
->format
->init
) {
1182 if (in
->format
->init(in
) != SR_OK
) {
1183 g_critical("Input format init failed.");
1188 if (select_probes(in
->sdi
) > 0)
1192 sr_session_datafeed_callback_add(datafeed_in
);
1193 if (sr_session_dev_add(in
->sdi
) != SR_OK
) {
1194 g_critical("Failed to use device.");
1195 sr_session_destroy();
1199 input_format
->loadfile(in
, opt_input_file
);
1200 if (opt_output_file
&& default_output_format
) {
1201 if (sr_session_save(opt_output_file
, in
->sdi
, singleds
) != SR_OK
)
1202 g_critical("Failed to save session.");
1204 sr_session_destroy();
1207 g_hash_table_destroy(fmtargs
);
1210 static void load_input_file(void)
1213 if (sr_session_load(opt_input_file
) == SR_OK
) {
1214 /* sigrok session file */
1215 sr_session_datafeed_callback_add(datafeed_in
);
1221 /* fall back on input modules */
1222 load_input_file_format();
1226 static int set_dev_options(struct sr_dev_inst
*sdi
, GHashTable
*args
)
1228 const struct sr_hwcap_option
*hwo
;
1229 GHashTableIter iter
;
1230 gpointer key
, value
;
1234 struct sr_rational tmp_rat
;
1238 g_hash_table_iter_init(&iter
, args
);
1239 while (g_hash_table_iter_next(&iter
, &key
, &value
)) {
1240 if (!(hwo
= sr_devopt_name_get(key
))) {
1241 g_critical("Unknown device option '%s'.", (char *) key
);
1245 if ((value
== NULL
) &&
1246 (hwo
->type
!= SR_T_BOOL
)) {
1247 g_critical("Option '%s' needs a value.", (char *)key
);
1251 switch (hwo
->type
) {
1253 ret
= sr_parse_sizestring(value
, &tmp_u64
);
1265 tmp_bool
= sr_parse_boolstring(value
);
1269 tmp_float
= strtof(value
, NULL
);
1272 case SR_T_RATIONAL_PERIOD
:
1273 if ((ret
= sr_parse_period(value
, &tmp_rat
)) != SR_OK
)
1277 case SR_T_RATIONAL_VOLT
:
1278 if ((ret
= sr_parse_voltage(value
, &tmp_rat
)) != SR_OK
)
1286 ret
= sr_dev_config_set(sdi
, hwo
->hwcap
, val
);
1288 g_critical("Failed to set device option '%s'.", (char *)key
);
1298 static int set_limit_time(const struct sr_dev_inst
*sdi
)
1301 uint64_t *samplerate
;
1303 time_msec
= sr_parse_timestring(opt_time
);
1304 if (time_msec
== 0) {
1305 g_critical("Invalid time '%s'", opt_time
);
1306 sr_session_destroy();
1310 if (sr_driver_hwcap_exists(sdi
->driver
, SR_HWCAP_LIMIT_MSEC
)) {
1311 if (sr_dev_config_set(sdi
, SR_HWCAP_LIMIT_MSEC
, &time_msec
) != SR_OK
) {
1312 g_critical("Failed to configure time limit.");
1313 sr_session_destroy();
1318 /* time limit set, but device doesn't support this...
1319 * convert to samples based on the samplerate.
1322 if (sr_dev_has_hwcap(sdi
, SR_HWCAP_SAMPLERATE
)) {
1323 sr_info_get(sdi
->driver
, SR_DI_CUR_SAMPLERATE
,
1324 (const void **)&samplerate
, sdi
);
1325 limit_samples
= (*samplerate
) * time_msec
/ (uint64_t)1000;
1327 if (limit_samples
== 0) {
1328 g_critical("Not enough time at this samplerate.");
1329 sr_session_destroy();
1333 if (sr_dev_config_set(sdi
, SR_HWCAP_LIMIT_SAMPLES
,
1334 &limit_samples
) != SR_OK
) {
1335 g_critical("Failed to configure time-based sample limit.");
1336 sr_session_destroy();
1344 static void run_session(void)
1347 GHashTable
*devargs
;
1348 struct sr_dev_inst
*sdi
;
1352 devices
= device_scan();
1354 g_critical("No devices found.");
1357 if (g_slist_length(devices
) > 1) {
1358 g_critical("sigrok-cli only supports one device for capturing.");
1361 sdi
= devices
->data
;
1364 sr_session_datafeed_callback_add(datafeed_in
);
1366 if (sr_session_dev_add(sdi
) != SR_OK
) {
1367 g_critical("Failed to use device.");
1368 sr_session_destroy();
1373 if ((devargs
= parse_generic_arg(opt_dev
, FALSE
))) {
1374 if (set_dev_options(sdi
, devargs
) != SR_OK
)
1376 g_hash_table_destroy(devargs
);
1380 if (select_probes(sdi
) != SR_OK
) {
1381 g_critical("Failed to set probes.");
1382 sr_session_destroy();
1387 if (!(triggerlist
= sr_parse_triggerstring(sdi
, opt_triggers
))) {
1388 sr_session_destroy();
1391 max_probes
= g_slist_length(sdi
->probes
);
1392 for (i
= 0; i
< max_probes
; i
++) {
1393 if (triggerlist
[i
]) {
1394 sr_dev_trigger_set(sdi
, i
, triggerlist
[i
]);
1395 g_free(triggerlist
[i
]);
1398 g_free(triggerlist
);
1401 if (opt_continuous
) {
1402 if (!sr_driver_hwcap_exists(sdi
->driver
, SR_HWCAP_CONTINUOUS
)) {
1403 g_critical("This device does not support continuous sampling.");
1404 sr_session_destroy();
1410 if (set_limit_time(sdi
) != SR_OK
) {
1411 sr_session_destroy();
1417 if ((sr_parse_sizestring(opt_samples
, &limit_samples
) != SR_OK
)
1418 || (sr_dev_config_set(sdi
, SR_HWCAP_LIMIT_SAMPLES
,
1419 &limit_samples
) != SR_OK
)) {
1420 g_critical("Failed to configure sample limit.");
1421 sr_session_destroy();
1427 if ((sr_parse_sizestring(opt_frames
, &limit_frames
) != SR_OK
)
1428 || (sr_dev_config_set(sdi
, SR_HWCAP_LIMIT_FRAMES
,
1429 &limit_frames
) != SR_OK
)) {
1430 g_critical("Failed to configure frame limit.");
1431 sr_session_destroy();
1436 if (sr_session_start() != SR_OK
) {
1437 g_critical("Failed to start session.");
1438 sr_session_destroy();
1450 if (opt_output_file
&& default_output_format
) {
1451 if (sr_session_save(opt_output_file
, sdi
, singleds
) != SR_OK
)
1452 g_critical("Failed to save session.");
1454 sr_session_destroy();
1455 g_slist_free(devices
);
1459 static void logger(const gchar
*log_domain
, GLogLevelFlags log_level
,
1460 const gchar
*message
, gpointer cb_data
)
1466 * All messages, warnings, errors etc. go to stderr (not stdout) in
1467 * order to not mess up the CLI tool data output, e.g. VCD output.
1469 if (log_level
& (G_LOG_LEVEL_ERROR
| G_LOG_LEVEL_CRITICAL
| G_LOG_LEVEL_WARNING
)
1470 || opt_loglevel
> SR_LOG_WARN
) {
1471 fprintf(stderr
, "%s\n", message
);
1476 int main(int argc
, char **argv
)
1479 GOptionContext
*context
;
1482 g_log_set_default_handler(logger
, NULL
);
1485 context
= g_option_context_new(NULL
);
1486 g_option_context_add_main_entries(context
, optargs
, NULL
);
1488 if (!g_option_context_parse(context
, &argc
, &argv
, &error
)) {
1489 g_critical("%s", error
->message
);
1493 /* Set the loglevel (amount of messages to output) for libsigrok. */
1494 if (sr_log_loglevel_set(opt_loglevel
) != SR_OK
)
1497 /* Set the loglevel (amount of messages to output) for libsigrokdecode. */
1498 if (srd_log_loglevel_set(opt_loglevel
) != SRD_OK
)
1501 if (sr_init(&sr_ctx
) != SR_OK
)
1505 if (srd_init(NULL
) != SRD_OK
)
1507 if (register_pds(NULL
, opt_pds
) != 0)
1509 if (srd_pd_output_callback_add(SRD_OUTPUT_ANN
,
1510 show_pd_annotations
, NULL
) != SRD_OK
)
1512 if (setup_pd_stack() != 0)
1514 if (setup_pd_annotations() != 0)
1518 if (setup_output_format() != 0)
1523 else if (opt_list_devs
)
1525 else if (opt_pds
&& opt_show
)
1529 else if (opt_input_file
)
1531 else if (opt_samples
|| opt_time
|| opt_frames
|| opt_continuous
)
1534 printf("%s", g_option_context_get_help(context
, TRUE
, NULL
));
1545 g_option_context_free(context
);