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