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