]> sigrok.org Git - sigrok-cli.git/blame_incremental - sigrok-cli.c
cli: support for new output module API
[sigrok-cli.git] / sigrok-cli.c
... / ...
CommitLineData
1/*
2 * This file is part of the sigrok project.
3 *
4 * Copyright (C) 2012 Bert Vermeulen <bert@biot.com>
5 *
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.
10 *
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.
15 *
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/>.
18 */
19
20#include <sigrokdecode.h> /* First, so we avoid a _POSIX_C_SOURCE warning. */
21#include <stdio.h>
22#include <stdlib.h>
23#include <unistd.h>
24#include <string.h>
25#include <time.h>
26#include <sys/time.h>
27#include <inttypes.h>
28#include <sys/types.h>
29#include <sys/stat.h>
30#include <errno.h>
31#include <glib.h>
32#include <glib/gstdio.h>
33#include <libsigrok/libsigrok.h>
34#include "sigrok-cli.h"
35#include "config.h"
36
37#define DEFAULT_OUTPUT_FORMAT "bits:width=64"
38
39static uint64_t limit_samples = 0;
40static uint64_t limit_frames = 0;
41static struct sr_output_format *output_format = NULL;
42static int default_output_format = FALSE;
43static char *output_format_param = NULL;
44static GHashTable *pd_ann_visible = NULL;
45static struct sr_datastore *singleds = NULL;
46
47static gboolean opt_version = FALSE;
48static gint opt_loglevel = SR_LOG_WARN; /* Show errors+warnings per default. */
49static gboolean opt_list_devs = FALSE;
50static gboolean opt_wait_trigger = FALSE;
51static gchar *opt_input_file = NULL;
52static gchar *opt_output_file = NULL;
53static gchar *opt_drv = NULL;
54static gchar *opt_dev = NULL;
55static gchar *opt_probes = NULL;
56static gchar *opt_triggers = NULL;
57static gchar *opt_pds = NULL;
58static gchar *opt_pd_stack = NULL;
59static gchar *opt_pd_annotations = NULL;
60static gchar *opt_input_format = NULL;
61static gchar *opt_output_format = NULL;
62static gchar *opt_show = NULL;
63static gchar *opt_time = NULL;
64static gchar *opt_samples = NULL;
65static gchar *opt_frames = NULL;
66static gchar *opt_continuous = NULL;
67
68static 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 {"driver", 0, 0, G_OPTION_ARG_STRING, &opt_drv,
76 "Use only this driver", NULL},
77 {"device", 'd', 0, G_OPTION_ARG_STRING, &opt_dev,
78 "Use specified device", NULL},
79 {"input-file", 'i', 0, G_OPTION_ARG_FILENAME, &opt_input_file,
80 "Load input from file", NULL},
81 {"input-format", 'I', 0, G_OPTION_ARG_STRING, &opt_input_format,
82 "Input format", NULL},
83 {"output-file", 'o', 0, G_OPTION_ARG_FILENAME, &opt_output_file,
84 "Save output to file", NULL},
85 {"output-format", 'O', 0, G_OPTION_ARG_STRING, &opt_output_format,
86 "Output format", NULL},
87 {"probes", 'p', 0, G_OPTION_ARG_STRING, &opt_probes,
88 "Probes to use", NULL},
89 {"triggers", 't', 0, G_OPTION_ARG_STRING, &opt_triggers,
90 "Trigger configuration", NULL},
91 {"wait-trigger", 'w', 0, G_OPTION_ARG_NONE, &opt_wait_trigger,
92 "Wait for trigger", NULL},
93 {"protocol-decoders", 'a', 0, G_OPTION_ARG_STRING, &opt_pds,
94 "Protocol decoders to run", NULL},
95 {"protocol-decoder-stack", 's', 0, G_OPTION_ARG_STRING, &opt_pd_stack,
96 "Protocol decoder stack", NULL},
97 {"protocol-decoder-annotations", 'A', 0, G_OPTION_ARG_STRING, &opt_pd_annotations,
98 "Protocol decoder annotation(s) to show", NULL},
99 {"show", 0, 0, G_OPTION_ARG_NONE, &opt_show,
100 "Show device detail", NULL},
101 {"time", 0, 0, G_OPTION_ARG_STRING, &opt_time,
102 "How long to sample (ms)", NULL},
103 {"samples", 0, 0, G_OPTION_ARG_STRING, &opt_samples,
104 "Number of samples to acquire", NULL},
105 {"frames", 0, 0, G_OPTION_ARG_STRING, &opt_frames,
106 "Number of frames to acquire", NULL},
107 {"continuous", 0, 0, G_OPTION_ARG_NONE, &opt_continuous,
108 "Sample continuously", NULL},
109 {NULL, 0, 0, 0, NULL, NULL, NULL}
110};
111
112
113/* Convert driver options hash to GSList of struct sr_hwopt. */
114static GSList *hash_to_hwopt(GHashTable *hash)
115{
116 const struct sr_hwcap_option *hwo;
117 struct sr_hwopt *hwopt;
118 GList *gl, *keys;
119 GSList *opts;
120 char *key, *value;
121
122 keys = g_hash_table_get_keys(hash);
123 opts = NULL;
124 for (gl = keys; gl; gl = gl->next) {
125 key = gl->data;
126 if (!(hwo = sr_drvopt_name_get(key))) {
127 g_critical("Unknown option %s", key);
128 return NULL;
129 }
130 hwopt = g_try_malloc(sizeof(struct sr_hwopt));
131 hwopt->hwopt = hwo->hwcap;
132 value = g_hash_table_lookup(hash, key);
133 hwopt->value = g_strdup(value);
134 opts = g_slist_append(opts, hwopt);
135 }
136 g_list_free(keys);
137
138 return opts;
139}
140
141static GSList *device_scan(void)
142{
143 struct sr_dev_driver **drivers, *driver;
144 GHashTable *drvargs;
145 GSList *drvopts, *devices, *tmpdevs, *l;
146 int i;
147 char *drvname;
148
149 if (opt_drv) {
150 drvargs = parse_generic_arg(opt_drv, TRUE);
151 drvname = g_strdup(g_hash_table_lookup(drvargs, "sigrok_key"));
152 g_hash_table_remove(drvargs, "sigrok_key");
153 driver = NULL;
154 drivers = sr_driver_list();
155 for (i = 0; drivers[i]; i++) {
156 if (strcmp(drivers[i]->name, drvname))
157 continue;
158 driver = drivers[i];
159 }
160 if (!driver) {
161 g_critical("Driver %s not found.", drvname);
162 return NULL;
163 }
164 g_free(drvname);
165 if (sr_driver_init(driver) != SR_OK) {
166 g_critical("Failed to initialize driver.");
167 return NULL;
168 }
169 drvopts = NULL;
170 if (g_hash_table_size(drvargs) > 0)
171 if (!(drvopts = hash_to_hwopt(drvargs)))
172 /* Unknown options, already logged. */
173 return NULL;
174 devices = sr_driver_scan(driver, drvopts);
175 } else {
176 /* No driver specified, let them all scan on their own. */
177 devices = NULL;
178 drivers = sr_driver_list();
179 for (i = 0; drivers[i]; i++) {
180 driver = drivers[i];
181 if (sr_driver_init(driver) != SR_OK) {
182 g_critical("Failed to initialize driver.");
183 return NULL;
184 }
185 tmpdevs = sr_driver_scan(driver, NULL);
186 for (l = tmpdevs; l; l = l->next)
187 devices = g_slist_append(devices, l->data);
188 g_slist_free(tmpdevs);
189 }
190 }
191
192 return devices;
193}
194
195static void show_version(void)
196{
197 GSList *l;
198 struct sr_dev_driver **drivers;
199 struct sr_input_format **inputs;
200 struct sr_output_format **outputs;
201 struct srd_decoder *dec;
202 int i;
203
204 printf("sigrok-cli %s\n\n", VERSION);
205
206 printf("Using libsigrok %s (lib version %s).\n",
207 sr_package_version_string_get(), sr_lib_version_string_get());
208 printf("Using libsigrokdecode %s (lib version %s).\n\n",
209 srd_package_version_string_get(), srd_lib_version_string_get());
210
211 printf("Supported hardware drivers:\n");
212 drivers = sr_driver_list();
213 for (i = 0; drivers[i]; i++) {
214 printf(" %-20s %s\n", drivers[i]->name, drivers[i]->longname);
215 }
216 printf("\n");
217
218 printf("Supported input formats:\n");
219 inputs = sr_input_list();
220 for (i = 0; inputs[i]; i++)
221 printf(" %-20s %s\n", inputs[i]->id, inputs[i]->description);
222 printf("\n");
223
224 printf("Supported output formats:\n");
225 outputs = sr_output_list();
226 for (i = 0; outputs[i]; i++)
227 printf(" %-20s %s\n", outputs[i]->id, outputs[i]->description);
228 printf("\n");
229
230 if (srd_init(NULL) == SRD_OK) {
231 printf("Supported protocol decoders:\n");
232 srd_decoder_load_all();
233 for (l = srd_decoder_list(); l; l = l->next) {
234 dec = l->data;
235 printf(" %-20s %s\n", dec->id, dec->longname);
236 /* Print protocol description upon "-l 3" or higher. */
237 if (opt_loglevel >= SR_LOG_INFO)
238 printf(" %-20s %s\n", "", dec->desc);
239 }
240 srd_exit();
241 }
242 printf("\n");
243}
244
245static void print_dev_line(const struct sr_dev_inst *sdi)
246{
247
248 if (sdi->vendor && sdi->vendor[0])
249 printf("%s ", sdi->vendor);
250 if (sdi->model && sdi->model[0])
251 printf("%s ", sdi->model);
252 if (sdi->version && sdi->version[0])
253 printf("%s ", sdi->version);
254 if (sdi->probes)
255 printf("with %d probes", g_slist_length(sdi->probes));
256 printf("\n");
257}
258
259static void show_dev_list(void)
260{
261 struct sr_dev_inst *sdi;
262 GSList *devices, *l;
263
264 if (!(devices = device_scan()))
265 return;
266
267 printf("The following devices were found:\n");
268 for (l = devices; l; l = l->next) {
269 sdi = l->data;
270 print_dev_line(sdi);
271 }
272 g_slist_free(devices);
273
274}
275
276static void show_dev_detail(void)
277{
278 struct sr_dev_inst *sdi;
279 const struct sr_hwcap_option *hwo;
280 const struct sr_samplerates *samplerates;
281 struct sr_rational *rationals;
282 GSList *devices;
283 uint64_t *integers;
284 const int *hwopts, *hwcaps;
285 int cap, num_devices, n, i;
286 char *s, *title;
287 const char *charopts, **stropts;
288
289 if (!(devices = device_scan())) {
290 g_critical("No devices found.");
291 return;
292 }
293
294 num_devices = g_slist_length(devices);
295 if (num_devices > 1) {
296 if (!opt_dev) {
297 g_critical("%d devices found. Use --list-devices to show them, "
298 "and --device to select one.", num_devices);
299 return;
300 }
301 /* opt_dev is NULL if not specified, which is fine. */
302 n = strtol(opt_dev, NULL, 10);
303 if (n >= num_devices) {
304 g_critical("%d devices found, numbered starting from 0.",
305 num_devices);
306 return;
307 }
308 sdi = g_slist_nth_data(devices, n);
309 } else
310 sdi = g_slist_nth_data(devices, 0);
311
312 print_dev_line(sdi);
313
314 if (sr_info_get(sdi->driver, SR_DI_TRIGGER_TYPES, (const void **)&charopts,
315 sdi) == SR_OK && charopts) {
316 printf("Supported triggers: ");
317 while (*charopts) {
318 printf("%c ", *charopts);
319 charopts++;
320 }
321 printf("\n");
322 }
323
324 if ((sr_info_get(sdi->driver, SR_DI_HWOPTS, (const void **)&hwopts,
325 NULL) == SR_OK) && hwopts) {
326 printf("Supported driver options:\n");
327 for (i = 0; hwopts[i]; i++) {
328 if (!(hwo = sr_drvopt_get(hwopts[i])))
329 continue;
330 printf(" %s\n", hwo->shortname);
331 }
332 }
333
334 title = "Supported device options:\n";
335 if ((sr_info_get(sdi->driver, SR_DI_HWCAPS, (const void **)&hwcaps,
336 NULL) != SR_OK) || !hwcaps)
337 /* Driver supports no device instance options. */
338 return;
339
340 for (cap = 0; hwcaps[cap]; cap++) {
341 if (!(hwo = sr_devopt_get(hwcaps[cap])))
342 continue;
343
344 if (title) {
345 printf("%s", title);
346 title = NULL;
347 }
348
349 if (hwo->hwcap == SR_HWCAP_PATTERN_MODE) {
350 /* Pattern generator modes */
351 printf(" %s", hwo->shortname);
352 if (sr_info_get(sdi->driver, SR_DI_PATTERNS,
353 (const void **)&stropts, sdi) == SR_OK) {
354 printf(" - supported patterns:\n");
355 for (i = 0; stropts[i]; i++)
356 printf(" %s\n", stropts[i]);
357 } else {
358 printf("\n");
359 }
360
361 } else if (hwo->hwcap == SR_HWCAP_SAMPLERATE) {
362 /* Supported samplerates */
363 printf(" %s", hwo->shortname);
364 if (sr_info_get(sdi->driver, SR_DI_SAMPLERATES,
365 (const void **)&samplerates, sdi) != SR_OK) {
366 printf("\n");
367 continue;
368 }
369 if (samplerates->step) {
370 /* low */
371 if (!(s = sr_samplerate_string(samplerates->low)))
372 continue;
373 printf(" (%s", s);
374 g_free(s);
375 /* high */
376 if (!(s = sr_samplerate_string(samplerates->high)))
377 continue;
378 printf(" - %s", s);
379 g_free(s);
380 /* step */
381 if (!(s = sr_samplerate_string(samplerates->step)))
382 continue;
383 printf(" in steps of %s)\n", s);
384 g_free(s);
385 } else {
386 printf(" - supported samplerates:\n");
387 for (i = 0; samplerates->list[i]; i++)
388 printf(" %s\n", sr_samplerate_string(samplerates->list[i]));
389 }
390
391 } else if (hwo->hwcap == SR_HWCAP_BUFFERSIZE) {
392 /* Supported buffer sizes */
393 printf(" %s", hwo->shortname);
394 if (sr_info_get(sdi->driver, SR_DI_BUFFERSIZES,
395 (const void **)&integers, sdi) != SR_OK) {
396 printf("\n");
397 continue;
398 }
399 printf(" - supported buffer sizes:\n");
400 for (i = 0; integers[i]; i++)
401 printf(" %"PRIu64"\n", integers[i]);
402
403 } else if (hwo->hwcap == SR_HWCAP_TIMEBASE) {
404 /* Supported time bases */
405 printf(" %s", hwo->shortname);
406 if (sr_info_get(sdi->driver, SR_DI_TIMEBASES,
407 (const void **)&rationals, sdi) != SR_OK) {
408 printf("\n");
409 continue;
410 }
411 printf(" - supported time bases:\n");
412 for (i = 0; rationals[i].p && rationals[i].q; i++)
413 printf(" %s\n", sr_period_string(
414 rationals[i].p * rationals[i].q));
415
416 } else if (hwo->hwcap == SR_HWCAP_TRIGGER_SOURCE) {
417 /* Supported trigger sources */
418 printf(" %s", hwo->shortname);
419 if (sr_info_get(sdi->driver, SR_DI_TRIGGER_SOURCES,
420 (const void **)&stropts, sdi) != SR_OK) {
421 printf("\n");
422 continue;
423 }
424 printf(" - supported trigger sources:\n");
425 for (i = 0; stropts[i]; i++)
426 printf(" %s\n", stropts[i]);
427
428 } else if (hwo->hwcap == SR_HWCAP_FILTER) {
429 /* Supported trigger sources */
430 printf(" %s", hwo->shortname);
431 if (sr_info_get(sdi->driver, SR_DI_FILTERS,
432 (const void **)&stropts, sdi) != SR_OK) {
433 printf("\n");
434 continue;
435 }
436 printf(" - supported filter targets:\n");
437 for (i = 0; stropts[i]; i++)
438 printf(" %s\n", stropts[i]);
439
440 } else if (hwo->hwcap == SR_HWCAP_VDIV) {
441 /* Supported volts/div values */
442 printf(" %s", hwo->shortname);
443 if (sr_info_get(sdi->driver, SR_DI_VDIVS,
444 (const void **)&rationals, sdi) != SR_OK) {
445 printf("\n");
446 continue;
447 }
448 printf(" - supported volts/div:\n");
449 for (i = 0; rationals[i].p && rationals[i].q; i++)
450 printf(" %s\n", sr_voltage_string( &rationals[i]));
451
452 } else if (hwo->hwcap == SR_HWCAP_COUPLING) {
453 /* Supported coupling settings */
454 printf(" %s", hwo->shortname);
455 if (sr_info_get(sdi->driver, SR_DI_COUPLING,
456 (const void **)&stropts, sdi) != SR_OK) {
457 printf("\n");
458 continue;
459 }
460 printf(" - supported coupling options:\n");
461 for (i = 0; stropts[i]; i++)
462 printf(" %s\n", stropts[i]);
463
464 } else {
465 /* Everything else */
466 printf(" %s\n", hwo->shortname);
467 }
468 }
469
470}
471
472static void show_pd_detail(void)
473{
474 GSList *l;
475 struct srd_decoder *dec;
476 char **pdtokens, **pdtok, **ann, *doc;
477 struct srd_probe *p;
478
479 pdtokens = g_strsplit(opt_pds, ",", -1);
480 for (pdtok = pdtokens; *pdtok; pdtok++) {
481 if (!(dec = srd_decoder_get_by_id(*pdtok))) {
482 g_critical("Protocol decoder %s not found.", *pdtok);
483 return;
484 }
485 printf("ID: %s\nName: %s\nLong name: %s\nDescription: %s\n",
486 dec->id, dec->name, dec->longname, dec->desc);
487 printf("License: %s\n", dec->license);
488 printf("Annotations:\n");
489 if (dec->annotations) {
490 for (l = dec->annotations; l; l = l->next) {
491 ann = l->data;
492 printf("- %s\n %s\n", ann[0], ann[1]);
493 }
494 } else {
495 printf("None.\n");
496 }
497 /* TODO: Print supported decoder options. */
498 printf("Required probes:\n");
499 if (dec->probes) {
500 for (l = dec->probes; l; l = l->next) {
501 p = l->data;
502 printf("- %s (%s): %s\n",
503 p->name, p->id, p->desc);
504 }
505 } else {
506 printf("None.\n");
507 }
508 printf("Optional probes:\n");
509 if (dec->opt_probes) {
510 for (l = dec->opt_probes; l; l = l->next) {
511 p = l->data;
512 printf("- %s (%s): %s\n",
513 p->name, p->id, p->desc);
514 }
515 } else {
516 printf("None.\n");
517 }
518 if ((doc = srd_decoder_doc_get(dec))) {
519 printf("Documentation:\n%s\n",
520 doc[0] == '\n' ? doc + 1 : doc);
521 g_free(doc);
522 }
523 }
524
525 g_strfreev(pdtokens);
526}
527
528static void datafeed_in(const struct sr_dev_inst *sdi,
529 struct sr_datafeed_packet *packet)
530{
531 static struct sr_output *o = NULL;
532 static int logic_probelist[SR_MAX_NUM_PROBES] = { -1 };
533 static struct sr_probe *analog_probelist[SR_MAX_NUM_PROBES];
534 static uint64_t received_samples = 0;
535 static int unitsize = 0;
536 static int triggered = 0;
537 static FILE *outfile = NULL;
538 static int num_analog_probes = 0;
539 struct sr_probe *probe;
540 struct sr_datafeed_logic *logic;
541 struct sr_datafeed_meta_logic *meta_logic;
542 struct sr_datafeed_analog *analog;
543 struct sr_datafeed_meta_analog *meta_analog;
544 static int num_enabled_analog_probes = 0;
545 int num_enabled_probes, sample_size, ret, i;
546 uint64_t output_len, filter_out_len;
547 uint8_t *output_buf, *filter_out;
548 GString *out;
549
550 /* If the first packet to come in isn't a header, don't even try. */
551 if (packet->type != SR_DF_HEADER && o == NULL)
552 return;
553
554 sample_size = -1;
555 switch (packet->type) {
556 case SR_DF_HEADER:
557 g_debug("cli: Received SR_DF_HEADER");
558 /* Initialize the output module. */
559 if (!(o = g_try_malloc(sizeof(struct sr_output)))) {
560 g_critical("Output module malloc failed.");
561 exit(1);
562 }
563 o->format = output_format;
564 o->sdi = (struct sr_dev_inst *)sdi;
565 o->param = output_format_param;
566 if (o->format->init) {
567 if (o->format->init(o) != SR_OK) {
568 g_critical("Output format initialization failed.");
569 exit(1);
570 }
571 }
572 break;
573
574 case SR_DF_END:
575 g_debug("cli: Received SR_DF_END");
576 if (!o) {
577 g_debug("cli: double end!");
578 break;
579 }
580 if (o->format->event) {
581 o->format->event(o, SR_DF_END, &output_buf, &output_len);
582 if (output_buf) {
583 if (outfile)
584 fwrite(output_buf, 1, output_len, outfile);
585 g_free(output_buf);
586 output_len = 0;
587 }
588 }
589 if (limit_samples && received_samples < limit_samples)
590 g_warning("Device only sent %" PRIu64 " samples.",
591 received_samples);
592 if (opt_continuous)
593 g_warning("Device stopped after %" PRIu64 " samples.",
594 received_samples);
595 if (outfile && outfile != stdout)
596 fclose(outfile);
597
598 if (o->format->cleanup)
599 o->format->cleanup(o);
600 g_free(o);
601 o = NULL;
602 break;
603
604 case SR_DF_TRIGGER:
605 g_debug("cli: received SR_DF_TRIGGER");
606 if (o->format->event)
607 o->format->event(o, SR_DF_TRIGGER, &output_buf,
608 &output_len);
609 triggered = 1;
610 break;
611
612 case SR_DF_META_LOGIC:
613 g_message("cli: Received SR_DF_META_LOGIC");
614 meta_logic = packet->payload;
615 num_enabled_probes = 0;
616 for (i = 0; i < meta_logic->num_probes; i++) {
617 probe = g_slist_nth_data(sdi->probes, i);
618 if (probe->enabled)
619 logic_probelist[num_enabled_probes++] = probe->index;
620 }
621 logic_probelist[num_enabled_probes] = -1;
622 /* How many bytes we need to store num_enabled_probes bits */
623 unitsize = (num_enabled_probes + 7) / 8;
624
625 outfile = stdout;
626 if (opt_output_file) {
627 if (default_output_format) {
628 /* output file is in session format, which means we'll
629 * dump everything in the datastore as it comes in,
630 * and save from there after the session. */
631 outfile = NULL;
632 ret = sr_datastore_new(unitsize, &singleds);
633 if (ret != SR_OK) {
634 g_critical("Failed to create datastore.");
635 exit(1);
636 }
637 } else {
638 /* saving to a file in whatever format was set
639 * with --format, so all we need is a filehandle */
640 outfile = g_fopen(opt_output_file, "wb");
641 }
642 }
643 if (opt_pds)
644 srd_session_start(num_enabled_probes, unitsize,
645 meta_logic->samplerate);
646 break;
647
648 case SR_DF_LOGIC:
649 logic = packet->payload;
650 g_message("cli: received SR_DF_LOGIC, %"PRIu64" bytes", logic->length);
651 sample_size = logic->unitsize;
652 if (logic->length == 0)
653 break;
654
655 /* Don't store any samples until triggered. */
656 if (opt_wait_trigger && !triggered)
657 break;
658
659 if (limit_samples && received_samples >= limit_samples)
660 break;
661
662 ret = sr_filter_probes(sample_size, unitsize, logic_probelist,
663 logic->data, logic->length,
664 &filter_out, &filter_out_len);
665 if (ret != SR_OK)
666 break;
667
668 /* what comes out of the filter is guaranteed to be packed into the
669 * minimum size needed to support the number of samples at this sample
670 * size. however, the driver may have submitted too much -- cut off
671 * the buffer of the last packet according to the sample limit.
672 */
673 if (limit_samples && (received_samples + logic->length / sample_size >
674 limit_samples * sample_size))
675 filter_out_len = limit_samples * sample_size - received_samples;
676
677 if (singleds)
678 sr_datastore_put(singleds, filter_out,
679 filter_out_len, sample_size, logic_probelist);
680
681 if (opt_output_file && default_output_format)
682 /* saving to a session file, don't need to do anything else
683 * to this data for now. */
684 goto cleanup;
685
686 if (opt_pds) {
687 if (srd_session_send(received_samples, (uint8_t*)filter_out,
688 filter_out_len) != SRD_OK)
689 sr_session_stop();
690 } else {
691 output_len = 0;
692 if (o->format->data && packet->type == o->format->df_type)
693 o->format->data(o, filter_out, filter_out_len, &output_buf, &output_len);
694 if (output_buf) {
695 fwrite(output_buf, 1, output_len, outfile);
696 fflush(outfile);
697 g_free(output_buf);
698 }
699 }
700
701 cleanup:
702 g_free(filter_out);
703 received_samples += logic->length / sample_size;
704 break;
705
706 case SR_DF_META_ANALOG:
707 g_message("cli: Received SR_DF_META_ANALOG");
708 meta_analog = packet->payload;
709 num_analog_probes = meta_analog->num_probes;
710 num_enabled_analog_probes = 0;
711 for (i = 0; i < num_analog_probes; i++) {
712 probe = g_slist_nth_data(sdi->probes, i);
713 if (probe->enabled)
714 analog_probelist[num_enabled_analog_probes++] = probe;
715 }
716
717 outfile = stdout;
718 if (opt_output_file) {
719 if (default_output_format) {
720 /* output file is in session format, which means we'll
721 * dump everything in the datastore as it comes in,
722 * and save from there after the session. */
723 outfile = NULL;
724 ret = sr_datastore_new(unitsize, &singleds);
725 if (ret != SR_OK) {
726 g_critical("Failed to create datastore.");
727 exit(1);
728 }
729 } else {
730 /* saving to a file in whatever format was set
731 * with --format, so all we need is a filehandle */
732 outfile = g_fopen(opt_output_file, "wb");
733 }
734 }
735 break;
736
737 case SR_DF_ANALOG:
738 analog = packet->payload;
739 g_message("cli: received SR_DF_ANALOG, %d samples", analog->num_samples);
740 if (analog->num_samples == 0)
741 break;
742
743 if (limit_samples && received_samples >= limit_samples)
744 break;
745
746 if (o->format->data && packet->type == o->format->df_type) {
747 o->format->data(o, (const uint8_t *)analog->data,
748 analog->num_samples * sizeof(float),
749 &output_buf, &output_len);
750 if (output_buf) {
751 fwrite(output_buf, 1, output_len, outfile);
752 fflush(outfile);
753 g_free(output_buf);
754 }
755 }
756
757 received_samples += analog->num_samples;
758 break;
759
760 case SR_DF_FRAME_BEGIN:
761 g_debug("cli: received SR_DF_FRAME_BEGIN");
762 if (o->format->event) {
763 o->format->event(o, SR_DF_FRAME_BEGIN, &output_buf,
764 &output_len);
765 if (output_buf) {
766 fwrite(output_buf, 1, output_len, outfile);
767 fflush(outfile);
768 g_free(output_buf);
769 }
770 }
771 break;
772
773 case SR_DF_FRAME_END:
774 g_debug("cli: received SR_DF_FRAME_END");
775 if (o->format->event) {
776 o->format->event(o, SR_DF_FRAME_END, &output_buf,
777 &output_len);
778 if (output_buf) {
779 fwrite(output_buf, 1, output_len, outfile);
780 fflush(outfile);
781 g_free(output_buf);
782 }
783 }
784 break;
785
786 default:
787 g_message("received unknown packet type %d", packet->type);
788 }
789
790 if (o && o->format->recv) {
791 out = o->format->recv(o, sdi, packet);
792 if (out && out->len) {
793 fwrite(out->str, 1, out->len, outfile);
794 fflush(outfile);
795 }
796 }
797
798}
799
800/* Register the given PDs for this session.
801 * Accepts a string of the form: "spi:sck=3:sdata=4,spi:sck=3:sdata=5"
802 * That will instantiate two SPI decoders on the clock but different data
803 * lines.
804 */
805static int register_pds(struct sr_dev *dev, const char *pdstring)
806{
807 GHashTable *pd_opthash;
808 struct srd_decoder_inst *di;
809 int ret;
810 char **pdtokens, **pdtok, *pd_name;
811
812 /* Avoid compiler warnings. */
813 (void)dev;
814
815 ret = 0;
816 pd_ann_visible = g_hash_table_new_full(g_str_hash, g_int_equal,
817 g_free, NULL);
818 pd_name = NULL;
819 pd_opthash = NULL;
820 pdtokens = g_strsplit(pdstring, ",", 0);
821 for (pdtok = pdtokens; *pdtok; pdtok++) {
822 if (!(pd_opthash = parse_generic_arg(*pdtok, TRUE))) {
823 g_critical("Invalid protocol decoder option '%s'.", *pdtok);
824 goto err_out;
825 }
826
827 pd_name = g_strdup(g_hash_table_lookup(pd_opthash, "sigrok_key"));
828 g_hash_table_remove(pd_opthash, "sigrok_key");
829 if (srd_decoder_load(pd_name) != SRD_OK) {
830 g_critical("Failed to load protocol decoder %s.", pd_name);
831 ret = 1;
832 goto err_out;
833 }
834 if (!(di = srd_inst_new(pd_name, pd_opthash))) {
835 g_critical("Failed to instantiate protocol decoder %s.", pd_name);
836 ret = 1;
837 goto err_out;
838 }
839
840 /* If no annotation list was specified, add them all in now.
841 * This will be pared down later to leave only the last PD
842 * in the stack.
843 */
844 if (!opt_pd_annotations)
845 g_hash_table_insert(pd_ann_visible,
846 g_strdup(di->inst_id), NULL);
847
848 /* Any keys left in the options hash are probes, where the key
849 * is the probe name as specified in the decoder class, and the
850 * value is the probe number i.e. the order in which the PD's
851 * incoming samples are arranged. */
852 if (srd_inst_probe_set_all(di, pd_opthash) != SRD_OK) {
853 ret = 1;
854 goto err_out;
855 }
856 g_hash_table_destroy(pd_opthash);
857 pd_opthash = NULL;
858 }
859
860err_out:
861 g_strfreev(pdtokens);
862 if (pd_opthash)
863 g_hash_table_destroy(pd_opthash);
864 if (pd_name)
865 g_free(pd_name);
866
867 return ret;
868}
869
870int setup_pd_stack(void)
871{
872 struct srd_decoder_inst *di_from, *di_to;
873 int ret, i;
874 char **pds, **ids;
875
876 /* Set up the protocol decoder stack. */
877 pds = g_strsplit(opt_pds, ",", 0);
878 if (g_strv_length(pds) > 1) {
879 if (opt_pd_stack) {
880 /* A stack setup was specified, use that. */
881 g_strfreev(pds);
882 pds = g_strsplit(opt_pd_stack, ",", 0);
883 if (g_strv_length(pds) < 2) {
884 g_strfreev(pds);
885 g_critical("Specify at least two protocol decoders to stack.");
886 return 1;
887 }
888 }
889
890 /* First PD goes at the bottom of the stack. */
891 ids = g_strsplit(pds[0], ":", 0);
892 if (!(di_from = srd_inst_find_by_id(ids[0]))) {
893 g_strfreev(ids);
894 g_critical("Cannot stack protocol decoder '%s': "
895 "instance not found.", pds[0]);
896 return 1;
897 }
898 g_strfreev(ids);
899
900 /* Every subsequent PD goes on top. */
901 for (i = 1; pds[i]; i++) {
902 ids = g_strsplit(pds[i], ":", 0);
903 if (!(di_to = srd_inst_find_by_id(ids[0]))) {
904 g_strfreev(ids);
905 g_critical("Cannot stack protocol decoder '%s': "
906 "instance not found.", pds[i]);
907 return 1;
908 }
909 g_strfreev(ids);
910 if ((ret = srd_inst_stack(di_from, di_to)) != SRD_OK)
911 return 1;
912
913 /* Don't show annotation from this PD. Only the last PD in
914 * the stack will be left on the annotation list (unless
915 * the annotation list was specifically provided).
916 */
917 if (!opt_pd_annotations)
918 g_hash_table_remove(pd_ann_visible,
919 di_from->inst_id);
920
921 di_from = di_to;
922 }
923 }
924 g_strfreev(pds);
925
926 return 0;
927}
928
929int setup_pd_annotations(void)
930{
931 GSList *l;
932 struct srd_decoder *dec;
933 int ann;
934 char **pds, **pdtok, **keyval, **ann_descr;
935
936 /* Set up custom list of PDs and annotations to show. */
937 if (opt_pd_annotations) {
938 pds = g_strsplit(opt_pd_annotations, ",", 0);
939 for (pdtok = pds; *pdtok && **pdtok; pdtok++) {
940 ann = 0;
941 keyval = g_strsplit(*pdtok, "=", 0);
942 if (!(dec = srd_decoder_get_by_id(keyval[0]))) {
943 g_critical("Protocol decoder '%s' not found.", keyval[0]);
944 return 1;
945 }
946 if (!dec->annotations) {
947 g_critical("Protocol decoder '%s' has no annotations.", keyval[0]);
948 return 1;
949 }
950 if (g_strv_length(keyval) == 2) {
951 for (l = dec->annotations; l; l = l->next, ann++) {
952 ann_descr = l->data;
953 if (!canon_cmp(ann_descr[0], keyval[1]))
954 /* Found it. */
955 break;
956 }
957 if (!l) {
958 g_critical("Annotation '%s' not found "
959 "for protocol decoder '%s'.", keyval[1], keyval[0]);
960 return 1;
961 }
962 }
963 g_debug("cli: showing protocol decoder annotation %d from '%s'", ann, keyval[0]);
964 g_hash_table_insert(pd_ann_visible, g_strdup(keyval[0]), GINT_TO_POINTER(ann));
965 g_strfreev(keyval);
966 }
967 g_strfreev(pds);
968 }
969
970 return 0;
971}
972
973int setup_output_format(void)
974{
975 GHashTable *fmtargs;
976 GHashTableIter iter;
977 gpointer key, value;
978 struct sr_output_format **outputs;
979 int i;
980 char *fmtspec;
981
982 if (!opt_output_format) {
983 opt_output_format = DEFAULT_OUTPUT_FORMAT;
984 /* we'll need to remember this so when saving to a file
985 * later, sigrok session format will be used.
986 */
987 default_output_format = TRUE;
988 }
989
990 fmtargs = parse_generic_arg(opt_output_format, TRUE);
991 fmtspec = g_hash_table_lookup(fmtargs, "sigrok_key");
992 if (!fmtspec) {
993 g_critical("Invalid output format.");
994 return 1;
995 }
996 outputs = sr_output_list();
997 for (i = 0; outputs[i]; i++) {
998 if (strcmp(outputs[i]->id, fmtspec))
999 continue;
1000 g_hash_table_remove(fmtargs, "sigrok_key");
1001 output_format = outputs[i];
1002 g_hash_table_iter_init(&iter, fmtargs);
1003 while (g_hash_table_iter_next(&iter, &key, &value)) {
1004 /* only supporting one parameter per output module
1005 * for now, and only its value */
1006 output_format_param = g_strdup(value);
1007 break;
1008 }
1009 break;
1010 }
1011 if (!output_format) {
1012 g_critical("Invalid output format %s.", opt_output_format);
1013 return 1;
1014 }
1015 g_hash_table_destroy(fmtargs);
1016
1017 return 0;
1018}
1019
1020void show_pd_annotations(struct srd_proto_data *pdata, void *cb_data)
1021{
1022 int i;
1023 char **annotations;
1024 gpointer ann_format;
1025
1026 /* 'cb_data' is not used in this specific callback. */
1027 (void)cb_data;
1028
1029 if (!pd_ann_visible)
1030 return;
1031
1032 if (!g_hash_table_lookup_extended(pd_ann_visible, pdata->pdo->di->inst_id,
1033 NULL, &ann_format))
1034 /* Not in the list of PDs whose annotations we're showing. */
1035 return;
1036
1037 if (pdata->ann_format != GPOINTER_TO_INT(ann_format))
1038 /* We don't want this particular format from the PD. */
1039 return;
1040
1041 annotations = pdata->data;
1042 if (opt_loglevel > SR_LOG_WARN)
1043 printf("%"PRIu64"-%"PRIu64" ", pdata->start_sample, pdata->end_sample);
1044 printf("%s: ", pdata->pdo->proto_id);
1045 for (i = 0; annotations[i]; i++)
1046 printf("\"%s\" ", annotations[i]);
1047 printf("\n");
1048 fflush(stdout);
1049}
1050
1051static int select_probes(struct sr_dev_inst *sdi)
1052{
1053 char **probelist;
1054 int max_probes, i;
1055
1056 if (!opt_probes)
1057 return SR_OK;
1058
1059 /*
1060 * This only works because a device by default initializes
1061 * and enables all its probes.
1062 */
1063 max_probes = g_slist_length(sdi->probes);
1064 probelist = parse_probestring(max_probes, opt_probes);
1065 if (!probelist) {
1066 return SR_ERR;
1067 }
1068
1069 for (i = 0; i < max_probes; i++) {
1070 if (probelist[i]) {
1071 sr_dev_probe_name_set(sdi, i, probelist[i]);
1072 g_free(probelist[i]);
1073 } else {
1074 sr_dev_probe_enable(sdi, i, FALSE);
1075 }
1076 }
1077 g_free(probelist);
1078
1079 return SR_OK;
1080}
1081
1082/**
1083 * Return the input file format which the CLI tool should use.
1084 *
1085 * If the user specified -I / --input-format, use that one. Otherwise, try to
1086 * autodetect the format as good as possible. Failing that, return NULL.
1087 *
1088 * @param filename The filename of the input file. Must not be NULL.
1089 * @param opt The -I / --input-file option the user specified (or NULL).
1090 *
1091 * @return A pointer to the 'struct sr_input_format' that should be used,
1092 * or NULL if no input format was selected or auto-detected.
1093 */
1094static struct sr_input_format *determine_input_file_format(
1095 const char *filename, const char *opt)
1096{
1097 int i;
1098 struct sr_input_format **inputs;
1099
1100 /* If there are no input formats, return NULL right away. */
1101 inputs = sr_input_list();
1102 if (!inputs) {
1103 g_critical("No supported input formats available.");
1104 return NULL;
1105 }
1106
1107 /* If the user specified -I / --input-format, use that one. */
1108 if (opt) {
1109 for (i = 0; inputs[i]; i++) {
1110 if (strcasecmp(inputs[i]->id, opt))
1111 continue;
1112 g_debug("Using user-specified input file format '%s'.",
1113 inputs[i]->id);
1114 return inputs[i];
1115 }
1116
1117 /* The user specified an unknown input format, return NULL. */
1118 g_critical("Error: specified input file format '%s' is "
1119 "unknown.", opt);
1120 return NULL;
1121 }
1122
1123 /* Otherwise, try to find an input module that can handle this file. */
1124 for (i = 0; inputs[i]; i++) {
1125 if (inputs[i]->format_match(filename))
1126 break;
1127 }
1128
1129 /* Return NULL if no input module wanted to touch this. */
1130 if (!inputs[i]) {
1131 g_critical("Error: no matching input module found.");
1132 return NULL;
1133 }
1134
1135 g_debug("cli: Autodetected '%s' input format for file '%s'.",
1136 inputs[i]->id, filename);
1137
1138 return inputs[i];
1139}
1140
1141static void load_input_file_format(void)
1142{
1143 GHashTable *fmtargs = NULL;
1144 struct stat st;
1145 struct sr_input *in;
1146 struct sr_input_format *input_format;
1147 char *fmtspec = NULL;
1148
1149 if (opt_input_format) {
1150 fmtargs = parse_generic_arg(opt_input_format, TRUE);
1151 fmtspec = g_hash_table_lookup(fmtargs, "sigrok_key");
1152 }
1153
1154 if (!(input_format = determine_input_file_format(opt_input_file,
1155 fmtspec))) {
1156 /* The exact cause was already logged. */
1157 return;
1158 }
1159
1160 if (fmtargs)
1161 g_hash_table_remove(fmtargs, "sigrok_key");
1162
1163 if (stat(opt_input_file, &st) == -1) {
1164 g_critical("Failed to load %s: %s", opt_input_file,
1165 strerror(errno));
1166 exit(1);
1167 }
1168
1169 /* Initialize the input module. */
1170 if (!(in = g_try_malloc(sizeof(struct sr_input)))) {
1171 g_critical("Failed to allocate input module.");
1172 exit(1);
1173 }
1174 in->format = input_format;
1175 in->param = fmtargs;
1176 if (in->format->init) {
1177 if (in->format->init(in) != SR_OK) {
1178 g_critical("Input format init failed.");
1179 exit(1);
1180 }
1181 }
1182
1183 if (select_probes(in->sdi) > 0)
1184 return;
1185
1186 sr_session_new();
1187 sr_session_datafeed_callback_add(datafeed_in);
1188 if (sr_session_dev_add(in->sdi) != SR_OK) {
1189 g_critical("Failed to use device.");
1190 sr_session_destroy();
1191 return;
1192 }
1193
1194 input_format->loadfile(in, opt_input_file);
1195 if (opt_output_file && default_output_format) {
1196 if (sr_session_save(opt_output_file, in->sdi, singleds) != SR_OK)
1197 g_critical("Failed to save session.");
1198 }
1199 sr_session_destroy();
1200
1201 if (fmtargs)
1202 g_hash_table_destroy(fmtargs);
1203}
1204
1205static void load_input_file(void)
1206{
1207
1208 if (sr_session_load(opt_input_file) == SR_OK) {
1209 /* sigrok session file */
1210 sr_session_datafeed_callback_add(datafeed_in);
1211 sr_session_start();
1212 sr_session_run();
1213 sr_session_stop();
1214 }
1215 else {
1216 /* fall back on input modules */
1217 load_input_file_format();
1218 }
1219}
1220
1221static int set_dev_options(struct sr_dev_inst *sdi, GHashTable *args)
1222{
1223 const struct sr_hwcap_option *hwo;
1224 GHashTableIter iter;
1225 gpointer key, value;
1226 int ret;
1227 float tmp_float;
1228 uint64_t tmp_u64;
1229 struct sr_rational tmp_rat;
1230 gboolean tmp_bool;
1231 void *val;
1232
1233 g_hash_table_iter_init(&iter, args);
1234 while (g_hash_table_iter_next(&iter, &key, &value)) {
1235 if (!(hwo = sr_devopt_name_get(key))) {
1236 g_critical("Unknown device option '%s'.", (char *) key);
1237 return SR_ERR;
1238 }
1239
1240 if ((value == NULL) &&
1241 (hwo->type != SR_T_BOOL)) {
1242 g_critical("Option '%s' needs a value.", (char *)key);
1243 return SR_ERR;
1244 }
1245 val = NULL;
1246 switch (hwo->type) {
1247 case SR_T_UINT64:
1248 ret = sr_parse_sizestring(value, &tmp_u64);
1249 if (ret != SR_OK)
1250 break;
1251 val = &tmp_u64;
1252 break;
1253 case SR_T_CHAR:
1254 val = value;
1255 break;
1256 case SR_T_BOOL:
1257 if (!value)
1258 tmp_bool = TRUE;
1259 else
1260 tmp_bool = sr_parse_boolstring(value);
1261 val = &tmp_bool;
1262 break;
1263 case SR_T_FLOAT:
1264 tmp_float = strtof(value, NULL);
1265 val = &tmp_float;
1266 break;
1267 case SR_T_RATIONAL_PERIOD:
1268 if ((ret = sr_parse_period(value, &tmp_rat)) != SR_OK)
1269 break;
1270 val = &tmp_rat;
1271 break;
1272 case SR_T_RATIONAL_VOLT:
1273 if ((ret = sr_parse_voltage(value, &tmp_rat)) != SR_OK)
1274 break;
1275 val = &tmp_rat;
1276 break;
1277 default:
1278 ret = SR_ERR;
1279 }
1280 if (val)
1281 ret = sr_dev_config_set(sdi, hwo->hwcap, val);
1282 if (ret != SR_OK) {
1283 g_critical("Failed to set device option '%s'.", (char *)key);
1284 return ret;
1285 }
1286 else
1287 break;
1288 }
1289
1290 return SR_OK;
1291}
1292
1293static int set_limit_time(const struct sr_dev_inst *sdi)
1294{
1295 uint64_t time_msec;
1296 uint64_t *samplerate;
1297
1298 time_msec = sr_parse_timestring(opt_time);
1299 if (time_msec == 0) {
1300 g_critical("Invalid time '%s'", opt_time);
1301 sr_session_destroy();
1302 return SR_ERR;
1303 }
1304
1305 if (sr_driver_hwcap_exists(sdi->driver, SR_HWCAP_LIMIT_MSEC)) {
1306 if (sr_dev_config_set(sdi, SR_HWCAP_LIMIT_MSEC, &time_msec) != SR_OK) {
1307 g_critical("Failed to configure time limit.");
1308 sr_session_destroy();
1309 return SR_ERR;
1310 }
1311 }
1312 else {
1313 /* time limit set, but device doesn't support this...
1314 * convert to samples based on the samplerate.
1315 */
1316 limit_samples = 0;
1317 if (sr_dev_has_hwcap(sdi, SR_HWCAP_SAMPLERATE)) {
1318 sr_info_get(sdi->driver, SR_DI_CUR_SAMPLERATE,
1319 (const void **)&samplerate, sdi);
1320 limit_samples = (*samplerate) * time_msec / (uint64_t)1000;
1321 }
1322 if (limit_samples == 0) {
1323 g_critical("Not enough time at this samplerate.");
1324 sr_session_destroy();
1325 return SR_ERR;
1326 }
1327
1328 if (sr_dev_config_set(sdi, SR_HWCAP_LIMIT_SAMPLES,
1329 &limit_samples) != SR_OK) {
1330 g_critical("Failed to configure time-based sample limit.");
1331 sr_session_destroy();
1332 return SR_ERR;
1333 }
1334 }
1335
1336 return SR_OK;
1337}
1338
1339static void run_session(void)
1340{
1341 GSList *devices;
1342 GHashTable *devargs;
1343 struct sr_dev_inst *sdi;
1344 int max_probes, i;
1345 char **triggerlist;
1346
1347 devices = device_scan();
1348 if (!devices) {
1349 g_critical("No devices found.");
1350 return;
1351 }
1352 if (g_slist_length(devices) > 1) {
1353 g_critical("sigrok-cli only supports one device for capturing.");
1354 return;
1355 }
1356 sdi = devices->data;
1357
1358 sr_session_new();
1359 sr_session_datafeed_callback_add(datafeed_in);
1360
1361 if (sr_session_dev_add(sdi) != SR_OK) {
1362 g_critical("Failed to use device.");
1363 sr_session_destroy();
1364 return;
1365 }
1366
1367 if (opt_dev) {
1368 if ((devargs = parse_generic_arg(opt_dev, FALSE))) {
1369 if (set_dev_options(sdi, devargs) != SR_OK)
1370 return;
1371 g_hash_table_destroy(devargs);
1372 }
1373 }
1374
1375 if (select_probes(sdi) != SR_OK) {
1376 g_critical("Failed to set probes.");
1377 sr_session_destroy();
1378 return;
1379 }
1380
1381 if (opt_triggers) {
1382 if (!(triggerlist = sr_parse_triggerstring(sdi, opt_triggers))) {
1383 sr_session_destroy();
1384 return;
1385 }
1386 max_probes = g_slist_length(sdi->probes);
1387 for (i = 0; i < max_probes; i++) {
1388 if (triggerlist[i]) {
1389 sr_dev_trigger_set(sdi, i, triggerlist[i]);
1390 g_free(triggerlist[i]);
1391 }
1392 }
1393 g_free(triggerlist);
1394 }
1395
1396 if (opt_continuous) {
1397 if (!sr_driver_hwcap_exists(sdi->driver, SR_HWCAP_CONTINUOUS)) {
1398 g_critical("This device does not support continuous sampling.");
1399 sr_session_destroy();
1400 return;
1401 }
1402 }
1403
1404 if (opt_time) {
1405 if (set_limit_time(sdi) != SR_OK) {
1406 sr_session_destroy();
1407 return;
1408 }
1409 }
1410
1411 if (opt_samples) {
1412 if ((sr_parse_sizestring(opt_samples, &limit_samples) != SR_OK)
1413 || (sr_dev_config_set(sdi, SR_HWCAP_LIMIT_SAMPLES,
1414 &limit_samples) != SR_OK)) {
1415 g_critical("Failed to configure sample limit.");
1416 sr_session_destroy();
1417 return;
1418 }
1419 }
1420
1421 if (opt_frames) {
1422 if ((sr_parse_sizestring(opt_frames, &limit_frames) != SR_OK)
1423 || (sr_dev_config_set(sdi, SR_HWCAP_LIMIT_FRAMES,
1424 &limit_frames) != SR_OK)) {
1425 g_critical("Failed to configure frame limit.");
1426 sr_session_destroy();
1427 return;
1428 }
1429 }
1430
1431 if (sr_session_start() != SR_OK) {
1432 g_critical("Failed to start session.");
1433 sr_session_destroy();
1434 return;
1435 }
1436
1437 if (opt_continuous)
1438 add_anykey();
1439
1440 sr_session_run();
1441
1442 if (opt_continuous)
1443 clear_anykey();
1444
1445 if (opt_output_file && default_output_format) {
1446 if (sr_session_save(opt_output_file, sdi, singleds) != SR_OK)
1447 g_critical("Failed to save session.");
1448 }
1449 sr_session_destroy();
1450 g_slist_free(devices);
1451
1452}
1453
1454static void logger(const gchar *log_domain, GLogLevelFlags log_level,
1455 const gchar *message, gpointer cb_data)
1456{
1457 /* Avoid compiler warnings. */
1458 (void)log_domain;
1459 (void)cb_data;
1460
1461 /*
1462 * All messages, warnings, errors etc. go to stderr (not stdout) in
1463 * order to not mess up the CLI tool data output, e.g. VCD output.
1464 */
1465 if (log_level & (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING)
1466 || opt_loglevel > SR_LOG_WARN) {
1467 fprintf(stderr, "%s\n", message);
1468 fflush(stderr);
1469 }
1470}
1471
1472int main(int argc, char **argv)
1473{
1474 GOptionContext *context;
1475 GError *error;
1476
1477 g_log_set_default_handler(logger, NULL);
1478
1479 error = NULL;
1480 context = g_option_context_new(NULL);
1481 g_option_context_add_main_entries(context, optargs, NULL);
1482
1483 if (!g_option_context_parse(context, &argc, &argv, &error)) {
1484 g_critical("%s", error->message);
1485 return 1;
1486 }
1487
1488 /* Set the loglevel (amount of messages to output) for libsigrok. */
1489 if (sr_log_loglevel_set(opt_loglevel) != SR_OK)
1490 return 1;
1491
1492 /* Set the loglevel (amount of messages to output) for libsigrokdecode. */
1493 if (srd_log_loglevel_set(opt_loglevel) != SRD_OK)
1494 return 1;
1495
1496 if (sr_init() != SR_OK)
1497 return 1;
1498
1499 if (opt_pds) {
1500 if (srd_init(NULL) != SRD_OK)
1501 return 1;
1502 if (register_pds(NULL, opt_pds) != 0)
1503 return 1;
1504 if (srd_pd_output_callback_add(SRD_OUTPUT_ANN,
1505 show_pd_annotations, NULL) != SRD_OK)
1506 return 1;
1507 if (setup_pd_stack() != 0)
1508 return 1;
1509 if (setup_pd_annotations() != 0)
1510 return 1;
1511 }
1512
1513 if (setup_output_format() != 0)
1514 return 1;
1515
1516 if (opt_version)
1517 show_version();
1518 else if (opt_list_devs)
1519 show_dev_list();
1520 else if (opt_pds && opt_show)
1521 show_pd_detail();
1522 else if (opt_show)
1523 show_dev_detail();
1524 else if (opt_input_file)
1525 load_input_file();
1526 else if (opt_samples || opt_time || opt_frames || opt_continuous)
1527 run_session();
1528 else
1529 printf("%s", g_option_context_get_help(context, TRUE, NULL));
1530
1531 if (opt_pds)
1532 srd_exit();
1533
1534 g_option_context_free(context);
1535 sr_exit();
1536
1537 return 0;
1538}