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