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