]> sigrok.org Git - sigrok-cli.git/blob - sigrok-cli.c
70d3a59ee6cc2c3517c21baa84469619a129e255
[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 struct sr_datastore *singleds = NULL;
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 void datafeed_in(const struct sr_dev_inst *sdi,
550                 const struct sr_datafeed_packet *packet)
551 {
552         static struct sr_output *o = NULL;
553         static int logic_probelist[SR_MAX_NUM_PROBES] = { -1 };
554         static uint64_t received_samples = 0;
555         static int unitsize = 0;
556         static int triggered = 0;
557         static FILE *outfile = NULL;
558         struct sr_probe *probe;
559         const struct sr_datafeed_logic *logic;
560         const struct sr_datafeed_meta_logic *meta_logic;
561         const struct sr_datafeed_analog *analog;
562         int num_enabled_probes, sample_size, ret, i;
563         uint64_t output_len, filter_out_len;
564         uint8_t *output_buf, *filter_out;
565         GString *out;
566
567         /* If the first packet to come in isn't a header, don't even try. */
568         if (packet->type != SR_DF_HEADER && o == NULL)
569                 return;
570
571         sample_size = -1;
572         switch (packet->type) {
573         case SR_DF_HEADER:
574                 g_debug("cli: Received SR_DF_HEADER");
575                 /* Initialize the output module. */
576                 if (!(o = g_try_malloc(sizeof(struct sr_output)))) {
577                         g_critical("Output module malloc failed.");
578                         exit(1);
579                 }
580                 o->format = output_format;
581                 o->sdi = (struct sr_dev_inst *)sdi;
582                 o->param = output_format_param;
583                 if (o->format->init) {
584                         if (o->format->init(o) != SR_OK) {
585                                 g_critical("Output format initialization failed.");
586                                 exit(1);
587                         }
588                 }
589                 break;
590
591         case SR_DF_END:
592                 g_debug("cli: Received SR_DF_END");
593                 if (!o) {
594                         g_debug("cli: double end!");
595                         break;
596                 }
597                 if (o->format->event) {
598                         o->format->event(o, SR_DF_END, &output_buf, &output_len);
599                         if (output_buf) {
600                                 if (outfile)
601                                         fwrite(output_buf, 1, output_len, outfile);
602                                 g_free(output_buf);
603                                 output_len = 0;
604                         }
605                 }
606                 if (limit_samples && received_samples < limit_samples)
607                         g_warning("Device only sent %" PRIu64 " samples.",
608                                received_samples);
609                 if (opt_continuous)
610                         g_warning("Device stopped after %" PRIu64 " samples.",
611                                received_samples);
612                 if (outfile && outfile != stdout)
613                         fclose(outfile);
614
615                 if (o->format->cleanup)
616                         o->format->cleanup(o);
617                 g_free(o);
618                 o = NULL;
619                 break;
620
621         case SR_DF_TRIGGER:
622                 g_debug("cli: received SR_DF_TRIGGER");
623                 if (o->format->event)
624                         o->format->event(o, SR_DF_TRIGGER, &output_buf,
625                                          &output_len);
626                 triggered = 1;
627                 break;
628
629         case SR_DF_META_LOGIC:
630                 g_message("cli: Received SR_DF_META_LOGIC");
631                 meta_logic = packet->payload;
632                 num_enabled_probes = 0;
633                 for (i = 0; i < meta_logic->num_probes; i++) {
634                         probe = g_slist_nth_data(sdi->probes, i);
635                         if (probe->enabled)
636                                 logic_probelist[num_enabled_probes++] = probe->index;
637                 }
638                 logic_probelist[num_enabled_probes] = -1;
639                 /* How many bytes we need to store num_enabled_probes bits */
640                 unitsize = (num_enabled_probes + 7) / 8;
641
642                 outfile = stdout;
643                 if (opt_output_file) {
644                         if (default_output_format) {
645                                 /* output file is in session format, which means we'll
646                                  * dump everything in the datastore as it comes in,
647                                  * and save from there after the session. */
648                                 outfile = NULL;
649                                 ret = sr_datastore_new(unitsize, &singleds);
650                                 if (ret != SR_OK) {
651                                         g_critical("Failed to create datastore.");
652                                         exit(1);
653                                 }
654                         } else {
655                                 /* saving to a file in whatever format was set
656                                  * with --format, so all we need is a filehandle */
657                                 outfile = g_fopen(opt_output_file, "wb");
658                         }
659                 }
660                 if (opt_pds)
661                         srd_session_start(num_enabled_probes, unitsize,
662                                         meta_logic->samplerate);
663                 break;
664
665         case SR_DF_LOGIC:
666                 logic = packet->payload;
667                 g_message("cli: received SR_DF_LOGIC, %"PRIu64" bytes", logic->length);
668                 sample_size = logic->unitsize;
669                 if (logic->length == 0)
670                         break;
671
672                 /* Don't store any samples until triggered. */
673                 if (opt_wait_trigger && !triggered)
674                         break;
675
676                 if (limit_samples && received_samples >= limit_samples)
677                         break;
678
679                 ret = sr_filter_probes(sample_size, unitsize, logic_probelist,
680                                 logic->data, logic->length,
681                                 &filter_out, &filter_out_len);
682                 if (ret != SR_OK)
683                         break;
684
685                 /* what comes out of the filter is guaranteed to be packed into the
686                  * minimum size needed to support the number of samples at this sample
687                  * size. however, the driver may have submitted too much -- cut off
688                  * the buffer of the last packet according to the sample limit.
689                  */
690                 if (limit_samples && (received_samples + logic->length / sample_size >
691                                 limit_samples * sample_size))
692                         filter_out_len = limit_samples * sample_size - received_samples;
693
694                 if (singleds)
695                         sr_datastore_put(singleds, filter_out,
696                                         filter_out_len, sample_size, logic_probelist);
697
698                 if (opt_output_file && default_output_format)
699                         /* saving to a session file, don't need to do anything else
700                          * to this data for now. */
701                         goto cleanup;
702
703                 if (opt_pds) {
704                         if (srd_session_send(received_samples, (uint8_t*)filter_out,
705                                         filter_out_len) != SRD_OK)
706                                 sr_session_stop();
707                 } else {
708                         output_len = 0;
709                         if (o->format->data && packet->type == o->format->df_type)
710                                 o->format->data(o, filter_out, filter_out_len, &output_buf, &output_len);
711                         if (output_buf) {
712                                 fwrite(output_buf, 1, output_len, outfile);
713                                 fflush(outfile);
714                                 g_free(output_buf);
715                         }
716                 }
717
718                 cleanup:
719                 g_free(filter_out);
720                 received_samples += logic->length / sample_size;
721                 break;
722
723         case SR_DF_META_ANALOG:
724                 g_message("cli: Received SR_DF_META_ANALOG");
725
726                 outfile = stdout;
727                 if (opt_output_file) {
728                         if (default_output_format) {
729                                 /* output file is in session format, which means we'll
730                                  * dump everything in the datastore as it comes in,
731                                  * and save from there after the session. */
732                                 outfile = NULL;
733                                 ret = sr_datastore_new(unitsize, &singleds);
734                                 if (ret != SR_OK) {
735                                         g_critical("Failed to create datastore.");
736                                         exit(1);
737                                 }
738                         } else {
739                                 /* saving to a file in whatever format was set
740                                  * with --format, so all we need is a filehandle */
741                                 outfile = g_fopen(opt_output_file, "wb");
742                         }
743                 }
744                 break;
745
746         case SR_DF_ANALOG:
747                 analog = packet->payload;
748                 g_message("cli: received SR_DF_ANALOG, %d samples", analog->num_samples);
749                 if (analog->num_samples == 0)
750                         break;
751
752                 if (limit_samples && received_samples >= limit_samples)
753                         break;
754
755                 if (o->format->data && packet->type == o->format->df_type) {
756                         o->format->data(o, (const uint8_t *)analog->data,
757                                         analog->num_samples * sizeof(float),
758                                         &output_buf, &output_len);
759                         if (output_buf) {
760                                 fwrite(output_buf, 1, output_len, outfile);
761                                 fflush(outfile);
762                                 g_free(output_buf);
763                         }
764                 }
765
766                 received_samples += analog->num_samples;
767                 break;
768
769         case SR_DF_FRAME_BEGIN:
770                 g_debug("cli: received SR_DF_FRAME_BEGIN");
771                 if (o->format->event) {
772                         o->format->event(o, SR_DF_FRAME_BEGIN, &output_buf,
773                                          &output_len);
774                         if (output_buf) {
775                                 fwrite(output_buf, 1, output_len, outfile);
776                                 fflush(outfile);
777                                 g_free(output_buf);
778                         }
779                 }
780                 break;
781
782         case SR_DF_FRAME_END:
783                 g_debug("cli: received SR_DF_FRAME_END");
784                 if (o->format->event) {
785                         o->format->event(o, SR_DF_FRAME_END, &output_buf,
786                                          &output_len);
787                         if (output_buf) {
788                                 fwrite(output_buf, 1, output_len, outfile);
789                                 fflush(outfile);
790                                 g_free(output_buf);
791                         }
792                 }
793                 break;
794
795         default:
796                 g_message("received unknown packet type %d", packet->type);
797         }
798
799         if (o && o->format->recv) {
800                 out = o->format->recv(o, sdi, packet);
801                 if (out && out->len) {
802                         fwrite(out->str, 1, out->len, outfile);
803                         fflush(outfile);
804                 }
805         }
806
807 }
808
809 /* Register the given PDs for this session.
810  * Accepts a string of the form: "spi:sck=3:sdata=4,spi:sck=3:sdata=5"
811  * That will instantiate two SPI decoders on the clock but different data
812  * lines.
813  */
814 static int register_pds(struct sr_dev *dev, const char *pdstring)
815 {
816         GHashTable *pd_opthash;
817         struct srd_decoder_inst *di;
818         int ret;
819         char **pdtokens, **pdtok, *pd_name;
820
821         (void)dev;
822
823         ret = 0;
824         pd_ann_visible = g_hash_table_new_full(g_str_hash, g_int_equal,
825                         g_free, NULL);
826         pd_name = NULL;
827         pd_opthash = NULL;
828         pdtokens = g_strsplit(pdstring, ",", 0);
829         for (pdtok = pdtokens; *pdtok; pdtok++) {
830                 if (!(pd_opthash = parse_generic_arg(*pdtok, TRUE))) {
831                         g_critical("Invalid protocol decoder option '%s'.", *pdtok);
832                         goto err_out;
833                 }
834
835                 pd_name = g_strdup(g_hash_table_lookup(pd_opthash, "sigrok_key"));
836                 g_hash_table_remove(pd_opthash, "sigrok_key");
837                 if (srd_decoder_load(pd_name) != SRD_OK) {
838                         g_critical("Failed to load protocol decoder %s.", pd_name);
839                         ret = 1;
840                         goto err_out;
841                 }
842                 if (!(di = srd_inst_new(pd_name, pd_opthash))) {
843                         g_critical("Failed to instantiate protocol decoder %s.", pd_name);
844                         ret = 1;
845                         goto err_out;
846                 }
847
848                 /* If no annotation list was specified, add them all in now.
849                  * This will be pared down later to leave only the last PD
850                  * in the stack.
851                  */
852                 if (!opt_pd_annotations)
853                         g_hash_table_insert(pd_ann_visible,
854                                             g_strdup(di->inst_id), NULL);
855
856                 /* Any keys left in the options hash are probes, where the key
857                  * is the probe name as specified in the decoder class, and the
858                  * value is the probe number i.e. the order in which the PD's
859                  * incoming samples are arranged. */
860                 if (srd_inst_probe_set_all(di, pd_opthash) != SRD_OK) {
861                         ret = 1;
862                         goto err_out;
863                 }
864                 g_hash_table_destroy(pd_opthash);
865                 pd_opthash = NULL;
866         }
867
868 err_out:
869         g_strfreev(pdtokens);
870         if (pd_opthash)
871                 g_hash_table_destroy(pd_opthash);
872         if (pd_name)
873                 g_free(pd_name);
874
875         return ret;
876 }
877
878 int setup_pd_stack(void)
879 {
880         struct srd_decoder_inst *di_from, *di_to;
881         int ret, i;
882         char **pds, **ids;
883
884         /* Set up the protocol decoder stack. */
885         pds = g_strsplit(opt_pds, ",", 0);
886         if (g_strv_length(pds) > 1) {
887                 if (opt_pd_stack) {
888                         /* A stack setup was specified, use that. */
889                         g_strfreev(pds);
890                         pds = g_strsplit(opt_pd_stack, ",", 0);
891                         if (g_strv_length(pds) < 2) {
892                                 g_strfreev(pds);
893                                 g_critical("Specify at least two protocol decoders to stack.");
894                                 return 1;
895                         }
896                 }
897
898                 /* First PD goes at the bottom of the stack. */
899                 ids = g_strsplit(pds[0], ":", 0);
900                 if (!(di_from = srd_inst_find_by_id(ids[0]))) {
901                         g_strfreev(ids);
902                         g_critical("Cannot stack protocol decoder '%s': "
903                                         "instance not found.", pds[0]);
904                         return 1;
905                 }
906                 g_strfreev(ids);
907
908                 /* Every subsequent PD goes on top. */
909                 for (i = 1; pds[i]; i++) {
910                         ids = g_strsplit(pds[i], ":", 0);
911                         if (!(di_to = srd_inst_find_by_id(ids[0]))) {
912                                 g_strfreev(ids);
913                                 g_critical("Cannot stack protocol decoder '%s': "
914                                                 "instance not found.", pds[i]);
915                                 return 1;
916                         }
917                         g_strfreev(ids);
918                         if ((ret = srd_inst_stack(di_from, di_to)) != SRD_OK)
919                                 return 1;
920
921                         /* Don't show annotation from this PD. Only the last PD in
922                          * the stack will be left on the annotation list (unless
923                          * the annotation list was specifically provided).
924                          */
925                         if (!opt_pd_annotations)
926                                 g_hash_table_remove(pd_ann_visible,
927                                                     di_from->inst_id);
928
929                         di_from = di_to;
930                 }
931         }
932         g_strfreev(pds);
933
934         return 0;
935 }
936
937 int setup_pd_annotations(void)
938 {
939         GSList *l;
940         struct srd_decoder *dec;
941         int ann;
942         char **pds, **pdtok, **keyval, **ann_descr;
943
944         /* Set up custom list of PDs and annotations to show. */
945         if (opt_pd_annotations) {
946                 pds = g_strsplit(opt_pd_annotations, ",", 0);
947                 for (pdtok = pds; *pdtok && **pdtok; pdtok++) {
948                         ann = 0;
949                         keyval = g_strsplit(*pdtok, "=", 0);
950                         if (!(dec = srd_decoder_get_by_id(keyval[0]))) {
951                                 g_critical("Protocol decoder '%s' not found.", keyval[0]);
952                                 return 1;
953                         }
954                         if (!dec->annotations) {
955                                 g_critical("Protocol decoder '%s' has no annotations.", keyval[0]);
956                                 return 1;
957                         }
958                         if (g_strv_length(keyval) == 2) {
959                                 for (l = dec->annotations; l; l = l->next, ann++) {
960                                         ann_descr = l->data;
961                                         if (!canon_cmp(ann_descr[0], keyval[1]))
962                                                 /* Found it. */
963                                                 break;
964                                 }
965                                 if (!l) {
966                                         g_critical("Annotation '%s' not found "
967                                                         "for protocol decoder '%s'.", keyval[1], keyval[0]);
968                                         return 1;
969                                 }
970                         }
971                         g_debug("cli: showing protocol decoder annotation %d from '%s'", ann, keyval[0]);
972                         g_hash_table_insert(pd_ann_visible, g_strdup(keyval[0]), GINT_TO_POINTER(ann));
973                         g_strfreev(keyval);
974                 }
975                 g_strfreev(pds);
976         }
977
978         return 0;
979 }
980
981 int setup_output_format(void)
982 {
983         GHashTable *fmtargs;
984         GHashTableIter iter;
985         gpointer key, value;
986         struct sr_output_format **outputs;
987         int i;
988         char *fmtspec;
989
990         if (!opt_output_format) {
991                 opt_output_format = DEFAULT_OUTPUT_FORMAT;
992                 /* we'll need to remember this so when saving to a file
993                  * later, sigrok session format will be used.
994                  */
995                 default_output_format = TRUE;
996         }
997
998         fmtargs = parse_generic_arg(opt_output_format, TRUE);
999         fmtspec = g_hash_table_lookup(fmtargs, "sigrok_key");
1000         if (!fmtspec) {
1001                 g_critical("Invalid output format.");
1002                 return 1;
1003         }
1004         outputs = sr_output_list();
1005         for (i = 0; outputs[i]; i++) {
1006                 if (strcmp(outputs[i]->id, fmtspec))
1007                         continue;
1008                 g_hash_table_remove(fmtargs, "sigrok_key");
1009                 output_format = outputs[i];
1010                 g_hash_table_iter_init(&iter, fmtargs);
1011                 while (g_hash_table_iter_next(&iter, &key, &value)) {
1012                         /* only supporting one parameter per output module
1013                          * for now, and only its value */
1014                         output_format_param = g_strdup(value);
1015                         break;
1016                 }
1017                 break;
1018         }
1019         if (!output_format) {
1020                 g_critical("Invalid output format %s.", opt_output_format);
1021                 return 1;
1022         }
1023         g_hash_table_destroy(fmtargs);
1024
1025         return 0;
1026 }
1027
1028 void show_pd_annotations(struct srd_proto_data *pdata, void *cb_data)
1029 {
1030         int i;
1031         char **annotations;
1032         gpointer ann_format;
1033
1034         /* 'cb_data' is not used in this specific callback. */
1035         (void)cb_data;
1036
1037         if (!pd_ann_visible)
1038                 return;
1039
1040         if (!g_hash_table_lookup_extended(pd_ann_visible, pdata->pdo->di->inst_id,
1041                         NULL, &ann_format))
1042                 /* Not in the list of PDs whose annotations we're showing. */
1043                 return;
1044
1045         if (pdata->ann_format != GPOINTER_TO_INT(ann_format))
1046                 /* We don't want this particular format from the PD. */
1047                 return;
1048
1049         annotations = pdata->data;
1050         if (opt_loglevel > SR_LOG_WARN)
1051                 printf("%"PRIu64"-%"PRIu64" ", pdata->start_sample, pdata->end_sample);
1052         printf("%s: ", pdata->pdo->proto_id);
1053         for (i = 0; annotations[i]; i++)
1054                 printf("\"%s\" ", annotations[i]);
1055         printf("\n");
1056         fflush(stdout);
1057 }
1058
1059 static int select_probes(struct sr_dev_inst *sdi)
1060 {
1061         struct sr_probe *probe;
1062         GSList *selected_probes, *l;
1063
1064         if (!opt_probes)
1065                 return SR_OK;
1066
1067         if (!(selected_probes = parse_probestring(sdi, opt_probes)))
1068                 return SR_ERR;
1069
1070         for (l = sdi->probes; l; l = l->next) {
1071                 probe = l->data;
1072                 if (g_slist_find(selected_probes, probe))
1073                         probe->enabled = TRUE;
1074                 else
1075                         probe->enabled = FALSE;
1076         }
1077         g_slist_free(selected_probes);
1078
1079         return SR_OK;
1080 }
1081
1082 /**
1083  * Return the input file format which the CLI tool should use.
1084  *
1085  * If the user specified -I / --input-format, use that one. Otherwise, try to
1086  * autodetect the format as good as possible. Failing that, return NULL.
1087  *
1088  * @param filename The filename of the input file. Must not be NULL.
1089  * @param opt The -I / --input-file option the user specified (or NULL).
1090  *
1091  * @return A pointer to the 'struct sr_input_format' that should be used,
1092  *         or NULL if no input format was selected or auto-detected.
1093  */
1094 static struct sr_input_format *determine_input_file_format(
1095                         const char *filename, const char *opt)
1096 {
1097         int i;
1098         struct sr_input_format **inputs;
1099
1100         /* If there are no input formats, return NULL right away. */
1101         inputs = sr_input_list();
1102         if (!inputs) {
1103                 g_critical("No supported input formats available.");
1104                 return NULL;
1105         }
1106
1107         /* If the user specified -I / --input-format, use that one. */
1108         if (opt) {
1109                 for (i = 0; inputs[i]; i++) {
1110                         if (strcasecmp(inputs[i]->id, opt))
1111                                 continue;
1112                         g_debug("Using user-specified input file format '%s'.",
1113                                         inputs[i]->id);
1114                         return inputs[i];
1115                 }
1116
1117                 /* The user specified an unknown input format, return NULL. */
1118                 g_critical("Error: specified input file format '%s' is "
1119                         "unknown.", opt);
1120                 return NULL;
1121         }
1122
1123         /* Otherwise, try to find an input module that can handle this file. */
1124         for (i = 0; inputs[i]; i++) {
1125                 if (inputs[i]->format_match(filename))
1126                         break;
1127         }
1128
1129         /* Return NULL if no input module wanted to touch this. */
1130         if (!inputs[i]) {
1131                 g_critical("Error: no matching input module found.");
1132                 return NULL;
1133         }
1134
1135         g_debug("cli: Autodetected '%s' input format for file '%s'.",
1136                 inputs[i]->id, filename);
1137                 
1138         return inputs[i];
1139 }
1140
1141 static void load_input_file_format(void)
1142 {
1143         GHashTable *fmtargs = NULL;
1144         struct stat st;
1145         struct sr_input *in;
1146         struct sr_input_format *input_format;
1147         char *fmtspec = NULL;
1148
1149         if (opt_input_format) {
1150                 fmtargs = parse_generic_arg(opt_input_format, TRUE);
1151                 fmtspec = g_hash_table_lookup(fmtargs, "sigrok_key");
1152         }
1153
1154         if (!(input_format = determine_input_file_format(opt_input_file,
1155                                                    fmtspec))) {
1156                 /* The exact cause was already logged. */
1157                 return;
1158         }
1159
1160         if (fmtargs)
1161                 g_hash_table_remove(fmtargs, "sigrok_key");
1162
1163         if (stat(opt_input_file, &st) == -1) {
1164                 g_critical("Failed to load %s: %s", opt_input_file,
1165                         strerror(errno));
1166                 exit(1);
1167         }
1168
1169         /* Initialize the input module. */
1170         if (!(in = g_try_malloc(sizeof(struct sr_input)))) {
1171                 g_critical("Failed to allocate input module.");
1172                 exit(1);
1173         }
1174         in->format = input_format;
1175         in->param = fmtargs;
1176         if (in->format->init) {
1177                 if (in->format->init(in) != SR_OK) {
1178                         g_critical("Input format init failed.");
1179                         exit(1);
1180                 }
1181         }
1182
1183         if (select_probes(in->sdi) > 0)
1184             return;
1185
1186         sr_session_new();
1187         sr_session_datafeed_callback_add(datafeed_in);
1188         if (sr_session_dev_add(in->sdi) != SR_OK) {
1189                 g_critical("Failed to use device.");
1190                 sr_session_destroy();
1191                 return;
1192         }
1193
1194         input_format->loadfile(in, opt_input_file);
1195         if (opt_output_file && default_output_format) {
1196                 if (sr_session_save(opt_output_file, in->sdi, singleds) != SR_OK)
1197                         g_critical("Failed to save session.");
1198         }
1199         sr_session_destroy();
1200
1201         if (fmtargs)
1202                 g_hash_table_destroy(fmtargs);
1203 }
1204
1205 static void load_input_file(void)
1206 {
1207
1208         if (sr_session_load(opt_input_file) == SR_OK) {
1209                 /* sigrok session file */
1210                 sr_session_datafeed_callback_add(datafeed_in);
1211                 sr_session_start();
1212                 sr_session_run();
1213                 sr_session_stop();
1214         }
1215         else {
1216                 /* fall back on input modules */
1217                 load_input_file_format();
1218         }
1219 }
1220
1221 static int set_dev_options(struct sr_dev_inst *sdi, GHashTable *args)
1222 {
1223         const struct sr_hwcap_option *hwo;
1224         GHashTableIter iter;
1225         gpointer key, value;
1226         int ret;
1227         float tmp_float;
1228         uint64_t tmp_u64;
1229         struct sr_rational tmp_rat;
1230         gboolean tmp_bool;
1231         void *val;
1232
1233         g_hash_table_iter_init(&iter, args);
1234         while (g_hash_table_iter_next(&iter, &key, &value)) {
1235                 if (!(hwo = sr_devopt_name_get(key))) {
1236                         g_critical("Unknown device option '%s'.", (char *) key);
1237                         return SR_ERR;
1238                 }
1239
1240                 if ((value == NULL) &&
1241                         (hwo->type != SR_T_BOOL)) {
1242                         g_critical("Option '%s' needs a value.", (char *)key);
1243                         return SR_ERR;
1244                 }
1245                 val = NULL;
1246                 switch (hwo->type) {
1247                 case SR_T_UINT64:
1248                         ret = sr_parse_sizestring(value, &tmp_u64);
1249                         if (ret != SR_OK)
1250                                 break;
1251                         val = &tmp_u64;
1252                         break;
1253                 case SR_T_CHAR:
1254                         val = value;
1255                         break;
1256                 case SR_T_BOOL:
1257                         if (!value)
1258                                 tmp_bool = TRUE;
1259                         else
1260                                 tmp_bool = sr_parse_boolstring(value);
1261                         val = &tmp_bool;
1262                         break;
1263                 case SR_T_FLOAT:
1264                         tmp_float = strtof(value, NULL);
1265                         val = &tmp_float;
1266                         break;
1267                 case SR_T_RATIONAL_PERIOD:
1268                         if ((ret = sr_parse_period(value, &tmp_rat)) != SR_OK)
1269                                 break;
1270                         val = &tmp_rat;
1271                         break;
1272                 case SR_T_RATIONAL_VOLT:
1273                         if ((ret = sr_parse_voltage(value, &tmp_rat)) != SR_OK)
1274                                 break;
1275                         val = &tmp_rat;
1276                         break;
1277                 default:
1278                         ret = SR_ERR;
1279                 }
1280                 if (val)
1281                         ret = sr_dev_config_set(sdi, hwo->hwcap, val);
1282                 if (ret != SR_OK) {
1283                         g_critical("Failed to set device option '%s'.", (char *)key);
1284                         return ret;
1285                 }
1286         }
1287
1288         return SR_OK;
1289 }
1290
1291 static int set_limit_time(const struct sr_dev_inst *sdi)
1292 {
1293         uint64_t time_msec;
1294         uint64_t *samplerate;
1295
1296         time_msec = sr_parse_timestring(opt_time);
1297         if (time_msec == 0) {
1298                 g_critical("Invalid time '%s'", opt_time);
1299                 sr_session_destroy();
1300                 return SR_ERR;
1301         }
1302
1303         if (sr_driver_hwcap_exists(sdi->driver, SR_HWCAP_LIMIT_MSEC)) {
1304                 if (sr_dev_config_set(sdi, SR_HWCAP_LIMIT_MSEC, &time_msec) != SR_OK) {
1305                         g_critical("Failed to configure time limit.");
1306                         sr_session_destroy();
1307                         return SR_ERR;
1308                 }
1309         }
1310         else {
1311                 /* time limit set, but device doesn't support this...
1312                  * convert to samples based on the samplerate.
1313                  */
1314                 limit_samples = 0;
1315                 if (sr_dev_has_hwcap(sdi, SR_HWCAP_SAMPLERATE)) {
1316                         sr_info_get(sdi->driver, SR_DI_CUR_SAMPLERATE,
1317                                         (const void **)&samplerate, sdi);
1318                         limit_samples = (*samplerate) * time_msec / (uint64_t)1000;
1319                 }
1320                 if (limit_samples == 0) {
1321                         g_critical("Not enough time at this samplerate.");
1322                         sr_session_destroy();
1323                         return SR_ERR;
1324                 }
1325
1326                 if (sr_dev_config_set(sdi, SR_HWCAP_LIMIT_SAMPLES,
1327                                         &limit_samples) != SR_OK) {
1328                         g_critical("Failed to configure time-based sample limit.");
1329                         sr_session_destroy();
1330                         return SR_ERR;
1331                 }
1332         }
1333
1334         return SR_OK;
1335 }
1336
1337 static void run_session(void)
1338 {
1339         GSList *devices;
1340         GHashTable *devargs;
1341         struct sr_dev_inst *sdi;
1342         int max_probes, i;
1343         char **triggerlist;
1344
1345         devices = device_scan();
1346         if (!devices) {
1347                 g_critical("No devices found.");
1348                 return;
1349         }
1350         if (g_slist_length(devices) > 1) {
1351                 g_critical("sigrok-cli only supports one device for capturing.");
1352                 return;
1353         }
1354         sdi = devices->data;
1355
1356         sr_session_new();
1357         sr_session_datafeed_callback_add(datafeed_in);
1358
1359         if (sr_session_dev_add(sdi) != SR_OK) {
1360                 g_critical("Failed to use device.");
1361                 sr_session_destroy();
1362                 return;
1363         }
1364
1365         if (opt_dev) {
1366                 if ((devargs = parse_generic_arg(opt_dev, FALSE))) {
1367                         if (set_dev_options(sdi, devargs) != SR_OK)
1368                                 return;
1369                         g_hash_table_destroy(devargs);
1370                 }
1371         }
1372
1373         if (select_probes(sdi) != SR_OK) {
1374                 g_critical("Failed to set probes.");
1375                 sr_session_destroy();
1376                 return;
1377         }
1378
1379         if (opt_triggers) {
1380                 if (!(triggerlist = sr_parse_triggerstring(sdi, opt_triggers))) {
1381                         sr_session_destroy();
1382                         return;
1383                 }
1384                 max_probes = g_slist_length(sdi->probes);
1385                 for (i = 0; i < max_probes; i++) {
1386                         if (triggerlist[i]) {
1387                                 sr_dev_trigger_set(sdi, i, triggerlist[i]);
1388                                 g_free(triggerlist[i]);
1389                         }
1390                 }
1391                 g_free(triggerlist);
1392         }
1393
1394         if (opt_continuous) {
1395                 if (!sr_driver_hwcap_exists(sdi->driver, SR_HWCAP_CONTINUOUS)) {
1396                         g_critical("This device does not support continuous sampling.");
1397                         sr_session_destroy();
1398                         return;
1399                 }
1400         }
1401
1402         if (opt_time) {
1403                 if (set_limit_time(sdi) != SR_OK) {
1404                         sr_session_destroy();
1405                         return;
1406                 }
1407         }
1408
1409         if (opt_samples) {
1410                 if ((sr_parse_sizestring(opt_samples, &limit_samples) != SR_OK)
1411                                 || (sr_dev_config_set(sdi, SR_HWCAP_LIMIT_SAMPLES,
1412                                                 &limit_samples) != SR_OK)) {
1413                         g_critical("Failed to configure sample limit.");
1414                         sr_session_destroy();
1415                         return;
1416                 }
1417         }
1418
1419         if (opt_frames) {
1420                 if ((sr_parse_sizestring(opt_frames, &limit_frames) != SR_OK)
1421                                 || (sr_dev_config_set(sdi, SR_HWCAP_LIMIT_FRAMES,
1422                                                 &limit_frames) != SR_OK)) {
1423                         g_critical("Failed to configure frame limit.");
1424                         sr_session_destroy();
1425                         return;
1426                 }
1427         }
1428
1429         if (sr_session_start() != SR_OK) {
1430                 g_critical("Failed to start session.");
1431                 sr_session_destroy();
1432                 return;
1433         }
1434
1435         if (opt_continuous)
1436                 add_anykey();
1437
1438         sr_session_run();
1439
1440         if (opt_continuous)
1441                 clear_anykey();
1442
1443         if (opt_output_file && default_output_format) {
1444                 if (sr_session_save(opt_output_file, sdi, singleds) != SR_OK)
1445                         g_critical("Failed to save session.");
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 }