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