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