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