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