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