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