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