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