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