cli: obsolete SR_HWCAP_PROBECONFIG
[sigrok:sigrok.git] / sigrok-cli / 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 <sigrokdecode.h> /* First, so we avoid a _POSIX_C_SOURCE warning. */
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <unistd.h>
24 #include <string.h>
25 #include <time.h>
26 #include <sys/time.h>
27 #include <inttypes.h>
28 #include <sys/types.h>
29 #include <sys/stat.h>
30 #include <errno.h>
31 #include <glib.h>
32 #include <glib/gstdio.h>
33 #include <libsigrok/libsigrok.h>
34 #include "sigrok-cli.h"
35 #include "config.h"
36
37 #define DEFAULT_OUTPUT_FORMAT "bits:width=64"
38
39 static uint64_t limit_samples = 0;
40 static uint64_t limit_frames = 0;
41 static struct sr_output_format *output_format = NULL;
42 static int default_output_format = FALSE;
43 static char *output_format_param = NULL;
44 static GHashTable *pd_ann_visible = NULL;
45 static struct sr_datastore *singleds = NULL;
46
47 static gboolean opt_version = FALSE;
48 static gint opt_loglevel = SR_LOG_WARN; /* Show errors+warnings per default. */
49 static gboolean opt_list_devs = FALSE;
50 static gboolean opt_wait_trigger = FALSE;
51 static gchar *opt_input_file = NULL;
52 static gchar *opt_output_file = NULL;
53 static gchar *opt_drv = NULL;
54 static gchar *opt_dev = NULL;
55 static gchar *opt_probes = NULL;
56 static gchar *opt_triggers = NULL;
57 static gchar *opt_pds = NULL;
58 static gchar *opt_pd_stack = NULL;
59 static gchar *opt_pd_annotations = NULL;
60 static gchar *opt_input_format = NULL;
61 static gchar *opt_output_format = NULL;
62 static gchar *opt_show = NULL;
63 static gchar *opt_time = NULL;
64 static gchar *opt_samples = NULL;
65 static gchar *opt_frames = NULL;
66 static gchar *opt_continuous = NULL;
67
68 static GOptionEntry optargs[] = {
69         {"version", 'V', 0, G_OPTION_ARG_NONE, &opt_version,
70                         "Show version and support list", NULL},
71         {"loglevel", 'l', 0, G_OPTION_ARG_INT, &opt_loglevel,
72                         "Set libsigrok/libsigrokdecode loglevel", NULL},
73         {"list-devices", 'D', 0, G_OPTION_ARG_NONE, &opt_list_devs,
74                         "Scan for devices", NULL},
75         {"driver", 0, 0, G_OPTION_ARG_STRING, &opt_drv,
76                         "Use only this driver", NULL},
77         {"device", 'd', 0, G_OPTION_ARG_STRING, &opt_dev,
78                         "Use specified device", NULL},
79         {"input-file", 'i', 0, G_OPTION_ARG_FILENAME, &opt_input_file,
80                         "Load input from file", NULL},
81         {"input-format", 'I', 0, G_OPTION_ARG_STRING, &opt_input_format,
82                         "Input format", NULL},
83         {"output-file", 'o', 0, G_OPTION_ARG_FILENAME, &opt_output_file,
84                         "Save output to file", NULL},
85         {"output-format", 'O', 0, G_OPTION_ARG_STRING, &opt_output_format,
86                         "Output format", NULL},
87         {"probes", 'p', 0, G_OPTION_ARG_STRING, &opt_probes,
88                         "Probes to use", NULL},
89         {"triggers", 't', 0, G_OPTION_ARG_STRING, &opt_triggers,
90                         "Trigger configuration", NULL},
91         {"wait-trigger", 'w', 0, G_OPTION_ARG_NONE, &opt_wait_trigger,
92                         "Wait for trigger", NULL},
93         {"protocol-decoders", 'a', 0, G_OPTION_ARG_STRING, &opt_pds,
94                         "Protocol decoders to run", NULL},
95         {"protocol-decoder-stack", 's', 0, G_OPTION_ARG_STRING, &opt_pd_stack,
96                         "Protocol decoder stack", NULL},
97         {"protocol-decoder-annotations", 'A', 0, G_OPTION_ARG_STRING, &opt_pd_annotations,
98                         "Protocol decoder annotation(s) to show", NULL},
99         {"show", 0, 0, G_OPTION_ARG_NONE, &opt_show,
100                         "Show device detail", NULL},
101         {"time", 0, 0, G_OPTION_ARG_STRING, &opt_time,
102                         "How long to sample (ms)", NULL},
103         {"samples", 0, 0, G_OPTION_ARG_STRING, &opt_samples,
104                         "Number of samples to acquire", NULL},
105         {"frames", 0, 0, G_OPTION_ARG_STRING, &opt_frames,
106                         "Number of frames to acquire", NULL},
107         {"continuous", 0, 0, G_OPTION_ARG_NONE, &opt_continuous,
108                         "Sample continuously", NULL},
109         {NULL, 0, 0, 0, NULL, NULL, NULL}
110 };
111
112
113 /* Convert driver options hash to GSList of struct sr_hwopt. */
114 static GSList *hash_to_hwopt(GHashTable *hash)
115 {
116         const struct sr_hwcap_option *hwo;
117         struct sr_hwopt *hwopt;
118         GList *gl, *keys;
119         GSList *opts;
120         char *key, *value;
121
122         keys = g_hash_table_get_keys(hash);
123         opts = NULL;
124         for (gl = keys; gl; gl = gl->next) {
125                 key = gl->data;
126                 if (!(hwo = sr_drvopt_name_get(key))) {
127                         g_critical("Unknown option %s", key);
128                         return NULL;
129                 }
130                 hwopt = g_try_malloc(sizeof(struct sr_hwopt));
131                 hwopt->hwopt = hwo->hwcap;
132                 value = g_hash_table_lookup(hash, key);
133                 hwopt->value = g_strdup(value);
134                 opts = g_slist_append(opts, hwopt);
135                 break;
136         }
137         g_list_free(keys);
138
139         return opts;
140 }
141
142 static GSList *device_scan(void)
143 {
144         struct sr_dev_driver **drivers, *driver;
145         GHashTable *drvargs;
146         GSList *drvopts, *devices, *tmpdevs, *l;
147         int i;
148         char *drvname;
149
150         if (opt_drv) {
151                 drvargs = parse_generic_arg(opt_drv, TRUE);
152                 drvname = g_strdup(g_hash_table_lookup(drvargs, "sigrok_key"));
153                 g_hash_table_remove(drvargs, "sigrok_key");
154                 driver = NULL;
155                 drivers = sr_driver_list();
156                 for (i = 0; drivers[i]; i++) {
157                         if (strcmp(drivers[i]->name, drvname))
158                                 continue;
159                         driver = drivers[i];
160                 }
161                 if (!driver) {
162                         g_critical("Driver %s not found.", drvname);
163                         return NULL;
164                 }
165                 g_free(drvname);
166                 if (sr_driver_init(driver) != SR_OK) {
167                         g_critical("Failed to initialize driver.");
168                         return NULL;
169                 }
170                 drvopts = NULL;
171                 if (g_hash_table_size(drvargs) > 0)
172                         if (!(drvopts = hash_to_hwopt(drvargs)))
173                                 /* Unknown options, already logged. */
174                                 return NULL;
175                 devices = sr_driver_scan(driver, drvopts);
176         } else {
177                 /* No driver specified, let them all scan on their own. */
178                 devices = NULL;
179                 drivers = sr_driver_list();
180                 for (i = 0; drivers[i]; i++) {
181                         driver = drivers[i];
182                         if (sr_driver_init(driver) != SR_OK) {
183                                 g_critical("Failed to initialize driver.");
184                                 return NULL;
185                         }
186                         tmpdevs = sr_driver_scan(driver, NULL);
187                         for (l = tmpdevs; l; l = l->next)
188                                 devices = g_slist_append(devices, l->data);
189                         g_slist_free(tmpdevs);
190                 }
191         }
192
193         return devices;
194 }
195
196 static void show_version(void)
197 {
198         GSList *l;
199         struct sr_dev_driver **drivers;
200         struct sr_input_format **inputs;
201         struct sr_output_format **outputs;
202         struct srd_decoder *dec;
203         int i;
204
205         printf("sigrok-cli %s\n\n", VERSION);
206
207         printf("Using libsigrok %s (lib version %s).\n",
208                sr_package_version_string_get(), sr_lib_version_string_get());
209         printf("Using libsigrokdecode %s (lib version %s).\n\n",
210                srd_package_version_string_get(), srd_lib_version_string_get());
211
212         printf("Supported hardware drivers:\n");
213         drivers = sr_driver_list();
214         for (i = 0; drivers[i]; i++) {
215                 printf("  %-20s %s\n", drivers[i]->name, drivers[i]->longname);
216         }
217         printf("\n");
218
219         printf("Supported input formats:\n");
220         inputs = sr_input_list();
221         for (i = 0; inputs[i]; i++)
222                 printf("  %-20s %s\n", inputs[i]->id, inputs[i]->description);
223         printf("\n");
224
225         printf("Supported output formats:\n");
226         outputs = sr_output_list();
227         for (i = 0; outputs[i]; i++)
228                 printf("  %-20s %s\n", outputs[i]->id, outputs[i]->description);
229         printf("\n");
230
231         if (srd_init(NULL) == SRD_OK) {
232                 printf("Supported protocol decoders:\n");
233                 srd_decoder_load_all();
234                 for (l = srd_decoder_list(); l; l = l->next) {
235                         dec = l->data;
236                         printf("  %-20s %s\n", dec->id, dec->longname);
237                         /* Print protocol description upon "-l 3" or higher. */
238                         if (opt_loglevel >= SR_LOG_INFO)
239                                 printf("  %-20s %s\n", "", dec->desc);
240                 }
241                 srd_exit();
242         }
243         printf("\n");
244 }
245
246 static void print_dev_line(const struct sr_dev_inst *sdi)
247 {
248
249         if (sdi->vendor && sdi->vendor[0])
250                 printf("%s ", sdi->vendor);
251         if (sdi->model && sdi->model[0])
252                 printf("%s ", sdi->model);
253         if (sdi->version && sdi->version[0])
254                 printf("%s ", sdi->version);
255         if (sdi->probes)
256                 printf("with %d probes", g_slist_length(sdi->probes));
257         printf("\n");
258 }
259
260 static void show_dev_list(void)
261 {
262         struct sr_dev_inst *sdi;
263         GSList *devices, *l;
264
265         if (!(devices = device_scan()))
266                 return;
267
268         printf("The following devices were found:\n");
269         for (l = devices; l; l = l->next) {
270                 sdi = l->data;
271                 print_dev_line(sdi);
272         }
273         g_slist_free(devices);
274
275 }
276
277 static void show_dev_detail(void)
278 {
279         struct sr_dev_inst *sdi;
280         const struct sr_hwcap_option *hwo;
281         const struct sr_samplerates *samplerates;
282         struct sr_rational *rationals;
283         GSList *devices;
284         uint64_t *integers;
285         const int *hwopts, *hwcaps;
286         int cap, num_devices, n, i;
287         char *s, *title;
288         const char *charopts, **stropts;
289
290         if (!(devices = device_scan())) {
291                 g_critical("No devices found.");
292                 return;
293         }
294
295         num_devices = g_slist_length(devices);
296         if (num_devices > 1) {
297                 if (!opt_dev) {
298                         g_critical("%d devices found. Use --list-devices to show them, "
299                                         "and --device to select one.", num_devices);
300                         return;
301                 }
302                 /* opt_dev is NULL if not specified, which is fine. */
303                 n = strtol(opt_dev, NULL, 10);
304                 if (n >= num_devices) {
305                         g_critical("%d devices found, numbered starting from 0.",
306                                         num_devices);
307                         return;
308                 }
309                 sdi = g_slist_nth_data(devices, n);
310         } else
311                 sdi = g_slist_nth_data(devices, 0);
312
313         print_dev_line(sdi);
314
315         if (sr_info_get(sdi->driver, SR_DI_TRIGGER_TYPES, (const void **)&charopts,
316                         sdi) == SR_OK && charopts) {
317                 printf("Supported triggers: ");
318                 while (*charopts) {
319                         printf("%c ", *charopts);
320                         charopts++;
321                 }
322                 printf("\n");
323         }
324
325         if ((sr_info_get(sdi->driver, SR_DI_HWOPTS, (const void **)&hwopts,
326                         NULL) == SR_OK) && hwopts) {
327                 printf("Supported driver options:\n");
328                 for (i = 0; hwopts[i]; i++) {
329                         if (!(hwo = sr_drvopt_get(hwopts[i])))
330                                 continue;
331                         printf("    %s\n", hwo->shortname);
332                 }
333         }
334
335         title = "Supported device options:\n";
336         if ((sr_info_get(sdi->driver, SR_DI_HWCAPS, (const void **)&hwcaps,
337                         NULL) != SR_OK) || !hwcaps)
338                 /* Driver supports no device instance options. */
339                 return;
340
341         for (cap = 0; hwcaps[cap]; cap++) {
342                 if (!(hwo = sr_devopt_get(hwcaps[cap])))
343                         continue;
344
345                 if (title) {
346                         printf("%s", title);
347                         title = NULL;
348                 }
349
350                 if (hwo->hwcap == SR_HWCAP_PATTERN_MODE) {
351                         /* Pattern generator modes */
352                         printf("    %s", hwo->shortname);
353                         if (sr_info_get(sdi->driver, SR_DI_PATTERNS,
354                                         (const void **)&stropts, sdi) == SR_OK) {
355                                 printf(" - supported patterns:\n");
356                                 for (i = 0; stropts[i]; i++)
357                                         printf("      %s\n", stropts[i]);
358                         } else {
359                                 printf("\n");
360                         }
361
362                 } else if (hwo->hwcap == SR_HWCAP_SAMPLERATE) {
363                         /* Supported samplerates */
364                         printf("    %s", hwo->shortname);
365                         if (sr_info_get(sdi->driver, SR_DI_SAMPLERATES,
366                                         (const void **)&samplerates, sdi) != SR_OK) {
367                                 printf("\n");
368                                 continue;
369                         }
370                         if (samplerates->step) {
371                                 /* low */
372                                 if (!(s = sr_samplerate_string(samplerates->low)))
373                                         continue;
374                                 printf(" (%s", s);
375                                 g_free(s);
376                                 /* high */
377                                 if (!(s = sr_samplerate_string(samplerates->high)))
378                                         continue;
379                                 printf(" - %s", s);
380                                 g_free(s);
381                                 /* step */
382                                 if (!(s = sr_samplerate_string(samplerates->step)))
383                                         continue;
384                                 printf(" in steps of %s)\n", s);
385                                 g_free(s);
386                         } else {
387                                 printf(" - supported samplerates:\n");
388                                 for (i = 0; samplerates->list[i]; i++)
389                                         printf("      %s\n", sr_samplerate_string(samplerates->list[i]));
390                         }
391
392                 } else if (hwo->hwcap == SR_HWCAP_BUFFERSIZE) {
393                         /* Supported buffer sizes */
394                         printf("    %s", hwo->shortname);
395                         if (sr_info_get(sdi->driver, SR_DI_BUFFERSIZES,
396                                         (const void **)&integers, sdi) != SR_OK) {
397                                 printf("\n");
398                                 continue;
399                         }
400                         printf(" - supported buffer sizes:\n");
401                         for (i = 0; integers[i]; i++)
402                                 printf("      %"PRIu64"\n", integers[i]);
403
404                 } else if (hwo->hwcap == SR_HWCAP_TIMEBASE) {
405                         /* Supported time bases */
406                         printf("    %s", hwo->shortname);
407                         if (sr_info_get(sdi->driver, SR_DI_TIMEBASES,
408                                         (const void **)&rationals, sdi) != SR_OK) {
409                                 printf("\n");
410                                 continue;
411                         }
412                         printf(" - supported time bases:\n");
413                         for (i = 0; rationals[i].p && rationals[i].q; i++)
414                                 printf("      %s\n", sr_period_string(
415                                                 rationals[i].p * rationals[i].q));
416
417                 } else if (hwo->hwcap == SR_HWCAP_TRIGGER_SOURCE) {
418                         /* Supported trigger sources */
419                         printf("    %s", hwo->shortname);
420                         if (sr_info_get(sdi->driver, SR_DI_TRIGGER_SOURCES,
421                                         (const void **)&stropts, sdi) != SR_OK) {
422                                 printf("\n");
423                                 continue;
424                         }
425                         printf(" - supported trigger sources:\n");
426                         for (i = 0; stropts[i]; i++)
427                                 printf("      %s\n", stropts[i]);
428
429                 } else if (hwo->hwcap == SR_HWCAP_FILTER) {
430                         /* Supported trigger sources */
431                         printf("    %s", hwo->shortname);
432                         if (sr_info_get(sdi->driver, SR_DI_FILTERS,
433                                         (const void **)&stropts, sdi) != SR_OK) {
434                                 printf("\n");
435                                 continue;
436                         }
437                         printf(" - supported filter targets:\n");
438                         for (i = 0; stropts[i]; i++)
439                                 printf("      %s\n", stropts[i]);
440
441                 } else if (hwo->hwcap == SR_HWCAP_VDIV) {
442                         /* Supported volts/div values */
443                         printf("    %s", hwo->shortname);
444                         if (sr_info_get(sdi->driver, SR_DI_VDIVS,
445                                         (const void **)&rationals, sdi) != SR_OK) {
446                                 printf("\n");
447                                 continue;
448                         }
449                         printf(" - supported volts/div:\n");
450                         for (i = 0; rationals[i].p && rationals[i].q; i++)
451                                 printf("      %s\n", sr_voltage_string( &rationals[i]));
452
453                 } else if (hwo->hwcap == SR_HWCAP_COUPLING) {
454                         /* Supported coupling settings */
455                         printf("    %s", hwo->shortname);
456                         if (sr_info_get(sdi->driver, SR_DI_COUPLING,
457                                         (const void **)&stropts, sdi) != SR_OK) {
458                                 printf("\n");
459                                 continue;
460                         }
461                         printf(" - supported coupling options:\n");
462                         for (i = 0; stropts[i]; i++)
463                                 printf("      %s\n", stropts[i]);
464
465                 } else {
466                         /* Everything else */
467                         printf("    %s\n", hwo->shortname);
468                 }
469         }
470
471 }
472
473 static void show_pd_detail(void)
474 {
475         GSList *l;
476         struct srd_decoder *dec;
477         char **pdtokens, **pdtok, **ann, *doc;
478         struct srd_probe *p;
479
480         pdtokens = g_strsplit(opt_pds, ",", -1);
481         for (pdtok = pdtokens; *pdtok; pdtok++) {
482                 if (!(dec = srd_decoder_get_by_id(*pdtok))) {
483                         g_critical("Protocol decoder %s not found.", *pdtok);
484                         return;
485                 }
486                 printf("ID: %s\nName: %s\nLong name: %s\nDescription: %s\n",
487                                 dec->id, dec->name, dec->longname, dec->desc);
488                 printf("License: %s\n", dec->license);
489                 printf("Annotations:\n");
490                 if (dec->annotations) {
491                         for (l = dec->annotations; l; l = l->next) {
492                                 ann = l->data;
493                                 printf("- %s\n  %s\n", ann[0], ann[1]);
494                         }
495                 } else {
496                         printf("None.\n");
497                 }
498                 /* TODO: Print supported decoder options. */
499                 printf("Required probes:\n");
500                 if (dec->probes) {
501                         for (l = dec->probes; l; l = l->next) {
502                                 p = l->data;
503                                 printf("- %s (%s): %s\n",
504                                        p->name, p->id, p->desc);
505                         }
506                 } else {
507                         printf("None.\n");
508                 }
509                 printf("Optional probes:\n");
510                 if (dec->opt_probes) {
511                         for (l = dec->opt_probes; l; l = l->next) {
512                                 p = l->data;
513                                 printf("- %s (%s): %s\n",
514                                        p->name, p->id, p->desc);
515                         }
516                 } else {
517                         printf("None.\n");
518                 }
519                 if ((doc = srd_decoder_doc_get(dec))) {
520                         printf("Documentation:\n%s\n",
521                                doc[0] == '\n' ? doc + 1 : doc);
522                         g_free(doc);
523                 }
524         }
525
526         g_strfreev(pdtokens);
527 }
528
529 static void datafeed_in(const struct sr_dev_inst *sdi,
530                 struct sr_datafeed_packet *packet)
531 {
532         static struct sr_output *o = NULL;
533         static int logic_probelist[SR_MAX_NUM_PROBES] = { -1 };
534         static struct sr_probe *analog_probelist[SR_MAX_NUM_PROBES];
535         static uint64_t received_samples = 0;
536         static int unitsize = 0;
537         static int triggered = 0;
538         static FILE *outfile = NULL;
539         static int num_analog_probes = 0;
540         struct sr_probe *probe;
541         struct sr_datafeed_logic *logic;
542         struct sr_datafeed_meta_logic *meta_logic;
543         struct sr_datafeed_analog *analog;
544         struct sr_datafeed_meta_analog *meta_analog;
545         static int num_enabled_analog_probes = 0;
546         int num_enabled_probes, sample_size, ret, i;
547         uint64_t output_len, filter_out_len;
548         uint8_t *output_buf, *filter_out;
549
550         /* If the first packet to come in isn't a header, don't even try. */
551         if (packet->type != SR_DF_HEADER && o == NULL)
552                 return;
553
554         sample_size = -1;
555         switch (packet->type) {
556         case SR_DF_HEADER:
557                 g_debug("cli: Received SR_DF_HEADER");
558                 /* Initialize the output module. */
559                 if (!(o = g_try_malloc(sizeof(struct sr_output)))) {
560                         g_critical("Output module malloc failed.");
561                         exit(1);
562                 }
563                 o->format = output_format;
564                 o->sdi = (struct sr_dev_inst *)sdi;
565                 o->param = output_format_param;
566                 if (o->format->init) {
567                         if (o->format->init(o) != SR_OK) {
568                                 g_critical("Output format initialization failed.");
569                                 exit(1);
570                         }
571                 }
572                 break;
573
574         case SR_DF_END:
575                 g_debug("cli: Received SR_DF_END");
576                 if (!o) {
577                         g_debug("cli: double end!");
578                         break;
579                 }
580                 if (o->format->event) {
581                         o->format->event(o, SR_DF_END, &output_buf, &output_len);
582                         if (output_buf) {
583                                 if (outfile)
584                                         fwrite(output_buf, 1, output_len, outfile);
585                                 g_free(output_buf);
586                                 output_len = 0;
587                         }
588                 }
589                 if (limit_samples && received_samples < limit_samples)
590                         g_warning("Device only sent %" PRIu64 " samples.",
591                                received_samples);
592                 if (opt_continuous)
593                         g_warning("Device stopped after %" PRIu64 " samples.",
594                                received_samples);
595                 if (outfile && outfile != stdout)
596                         fclose(outfile);
597                 g_free(o);
598                 o = NULL;
599                 break;
600
601         case SR_DF_TRIGGER:
602                 g_debug("cli: received SR_DF_TRIGGER");
603                 if (o->format->event)
604                         o->format->event(o, SR_DF_TRIGGER, &output_buf,
605                                          &output_len);
606                 triggered = 1;
607                 break;
608
609         case SR_DF_META_LOGIC:
610                 g_message("cli: Received SR_DF_META_LOGIC");
611                 meta_logic = packet->payload;
612                 num_enabled_probes = 0;
613                 for (i = 0; i < meta_logic->num_probes; i++) {
614                         probe = g_slist_nth_data(sdi->probes, i);
615                         if (probe->enabled)
616                                 logic_probelist[num_enabled_probes++] = probe->index;
617                 }
618                 logic_probelist[num_enabled_probes] = -1;
619                 /* How many bytes we need to store num_enabled_probes bits */
620                 unitsize = (num_enabled_probes + 7) / 8;
621
622                 outfile = stdout;
623                 if (opt_output_file) {
624                         if (default_output_format) {
625                                 /* output file is in session format, which means we'll
626                                  * dump everything in the datastore as it comes in,
627                                  * and save from there after the session. */
628                                 outfile = NULL;
629                                 ret = sr_datastore_new(unitsize, &singleds);
630                                 if (ret != SR_OK) {
631                                         g_critical("Failed to create datastore.");
632                                         exit(1);
633                                 }
634                         } else {
635                                 /* saving to a file in whatever format was set
636                                  * with --format, so all we need is a filehandle */
637                                 outfile = g_fopen(opt_output_file, "wb");
638                         }
639                 }
640                 if (opt_pds)
641                         srd_session_start(num_enabled_probes, unitsize,
642                                         meta_logic->samplerate);
643                 break;
644
645         case SR_DF_LOGIC:
646                 logic = packet->payload;
647                 g_message("cli: received SR_DF_LOGIC, %"PRIu64" bytes", logic->length);
648                 sample_size = logic->unitsize;
649                 if (logic->length == 0)
650                         break;
651
652                 /* Don't store any samples until triggered. */
653                 if (opt_wait_trigger && !triggered)
654                         break;
655
656                 if (limit_samples && received_samples >= limit_samples)
657                         break;
658
659                 ret = sr_filter_probes(sample_size, unitsize, logic_probelist,
660                                 logic->data, logic->length,
661                                 &filter_out, &filter_out_len);
662                 if (ret != SR_OK)
663                         break;
664
665                 /* what comes out of the filter is guaranteed to be packed into the
666                  * minimum size needed to support the number of samples at this sample
667                  * size. however, the driver may have submitted too much -- cut off
668                  * the buffer of the last packet according to the sample limit.
669                  */
670                 if (limit_samples && (received_samples + logic->length / sample_size >
671                                 limit_samples * sample_size))
672                         filter_out_len = limit_samples * sample_size - received_samples;
673
674                 if (singleds)
675                         sr_datastore_put(singleds, filter_out,
676                                         filter_out_len, sample_size, logic_probelist);
677
678                 if (opt_output_file && default_output_format)
679                         /* saving to a session file, don't need to do anything else
680                          * to this data for now. */
681                         goto cleanup;
682
683                 if (opt_pds) {
684                         if (srd_session_send(received_samples, (uint8_t*)filter_out,
685                                         filter_out_len) != SRD_OK)
686                                 sr_session_stop();
687                 } else {
688                         output_len = 0;
689                         if (o->format->data && packet->type == o->format->df_type)
690                                 o->format->data(o, filter_out, filter_out_len, &output_buf, &output_len);
691                         if (output_buf) {
692                                 fwrite(output_buf, 1, output_len, outfile);
693                                 fflush(outfile);
694                                 g_free(output_buf);
695                         }
696                 }
697
698                 cleanup:
699                 g_free(filter_out);
700                 received_samples += logic->length / sample_size;
701                 break;
702
703         case SR_DF_META_ANALOG:
704                 g_message("cli: Received SR_DF_META_ANALOG");
705                 meta_analog = packet->payload;
706                 num_analog_probes = meta_analog->num_probes;
707                 num_enabled_analog_probes = 0;
708                 for (i = 0; i < num_analog_probes; i++) {
709                         probe = g_slist_nth_data(sdi->probes, i);
710                         if (probe->enabled)
711                                 analog_probelist[num_enabled_analog_probes++] = probe;
712                 }
713
714                 outfile = stdout;
715                 if (opt_output_file) {
716                         if (default_output_format) {
717                                 /* output file is in session format, which means we'll
718                                  * dump everything in the datastore as it comes in,
719                                  * and save from there after the session. */
720                                 outfile = NULL;
721                                 ret = sr_datastore_new(unitsize, &singleds);
722                                 if (ret != SR_OK) {
723                                         g_critical("Failed to create datastore.");
724                                         exit(1);
725                                 }
726                         } else {
727                                 /* saving to a file in whatever format was set
728                                  * with --format, so all we need is a filehandle */
729                                 outfile = g_fopen(opt_output_file, "wb");
730                         }
731                 }
732                 break;
733
734         case SR_DF_ANALOG:
735                 analog = packet->payload;
736                 g_message("cli: received SR_DF_ANALOG, %d samples", analog->num_samples);
737                 if (analog->num_samples == 0)
738                         break;
739
740                 if (limit_samples && received_samples >= limit_samples)
741                         break;
742
743                 if (o->format->data && packet->type == o->format->df_type) {
744                         o->format->data(o, (const uint8_t *)analog->data,
745                                         analog->num_samples * sizeof(float),
746                                         &output_buf, &output_len);
747                         if (output_buf) {
748                                 fwrite(output_buf, 1, output_len, outfile);
749                                 fflush(outfile);
750                                 g_free(output_buf);
751                         }
752                 }
753
754                 received_samples += analog->num_samples;
755                 break;
756
757         case SR_DF_FRAME_BEGIN:
758                 g_debug("cli: received SR_DF_FRAME_BEGIN");
759                 if (o->format->event) {
760                         o->format->event(o, SR_DF_FRAME_BEGIN, &output_buf,
761                                          &output_len);
762                         if (output_buf) {
763                                 fwrite(output_buf, 1, output_len, outfile);
764                                 fflush(outfile);
765                                 g_free(output_buf);
766                         }
767                 }
768                 break;
769
770         case SR_DF_FRAME_END:
771                 g_debug("cli: received SR_DF_FRAME_END");
772                 if (o->format->event) {
773                         o->format->event(o, SR_DF_FRAME_END, &output_buf,
774                                          &output_len);
775                         if (output_buf) {
776                                 fwrite(output_buf, 1, output_len, outfile);
777                                 fflush(outfile);
778                                 g_free(output_buf);
779                         }
780                 }
781                 break;
782
783         default:
784                 g_message("received unknown packet type %d", packet->type);
785         }
786
787 }
788
789 /* Register the given PDs for this session.
790  * Accepts a string of the form: "spi:sck=3:sdata=4,spi:sck=3:sdata=5"
791  * That will instantiate two SPI decoders on the clock but different data
792  * lines.
793  */
794 static int register_pds(struct sr_dev *dev, const char *pdstring)
795 {
796         GHashTable *pd_opthash;
797         struct srd_decoder_inst *di;
798         int ret;
799         char **pdtokens, **pdtok, *pd_name;
800
801         /* Avoid compiler warnings. */
802         (void)dev;
803
804         ret = 0;
805         pd_ann_visible = g_hash_table_new_full(g_str_hash, g_int_equal,
806                         g_free, NULL);
807         pd_name = NULL;
808         pd_opthash = NULL;
809         pdtokens = g_strsplit(pdstring, ",", 0);
810         for (pdtok = pdtokens; *pdtok; pdtok++) {
811                 if (!(pd_opthash = parse_generic_arg(*pdtok, TRUE))) {
812                         g_critical("Invalid protocol decoder option '%s'.", *pdtok);
813                         goto err_out;
814                 }
815
816                 pd_name = g_strdup(g_hash_table_lookup(pd_opthash, "sigrok_key"));
817                 g_hash_table_remove(pd_opthash, "sigrok_key");
818                 if (srd_decoder_load(pd_name) != SRD_OK) {
819                         g_critical("Failed to load protocol decoder %s.", pd_name);
820                         ret = 1;
821                         goto err_out;
822                 }
823                 if (!(di = srd_inst_new(pd_name, pd_opthash))) {
824                         g_critical("Failed to instantiate protocol decoder %s.", pd_name);
825                         ret = 1;
826                         goto err_out;
827                 }
828
829                 /* If no annotation list was specified, add them all in now.
830                  * This will be pared down later to leave only the last PD
831                  * in the stack.
832                  */
833                 if (!opt_pd_annotations)
834                         g_hash_table_insert(pd_ann_visible,
835                                             g_strdup(di->inst_id), NULL);
836
837                 /* Any keys left in the options hash are probes, where the key
838                  * is the probe name as specified in the decoder class, and the
839                  * value is the probe number i.e. the order in which the PD's
840                  * incoming samples are arranged. */
841                 if (srd_inst_probe_set_all(di, pd_opthash) != SRD_OK) {
842                         ret = 1;
843                         goto err_out;
844                 }
845                 g_hash_table_destroy(pd_opthash);
846                 pd_opthash = NULL;
847         }
848
849 err_out:
850         g_strfreev(pdtokens);
851         if (pd_opthash)
852                 g_hash_table_destroy(pd_opthash);
853         if (pd_name)
854                 g_free(pd_name);
855
856         return ret;
857 }
858
859 int setup_pd_stack(void)
860 {
861         struct srd_decoder_inst *di_from, *di_to;
862         int ret, i;
863         char **pds, **ids;
864
865         /* Set up the protocol decoder stack. */
866         pds = g_strsplit(opt_pds, ",", 0);
867         if (g_strv_length(pds) > 1) {
868                 if (opt_pd_stack) {
869                         /* A stack setup was specified, use that. */
870                         g_strfreev(pds);
871                         pds = g_strsplit(opt_pd_stack, ",", 0);
872                         if (g_strv_length(pds) < 2) {
873                                 g_strfreev(pds);
874                                 g_critical("Specify at least two protocol decoders to stack.");
875                                 return 1;
876                         }
877                 }
878
879                 /* First PD goes at the bottom of the stack. */
880                 ids = g_strsplit(pds[0], ":", 0);
881                 if (!(di_from = srd_inst_find_by_id(ids[0]))) {
882                         g_strfreev(ids);
883                         g_critical("Cannot stack protocol decoder '%s': "
884                                         "instance not found.", pds[0]);
885                         return 1;
886                 }
887                 g_strfreev(ids);
888
889                 /* Every subsequent PD goes on top. */
890                 for (i = 1; pds[i]; i++) {
891                         ids = g_strsplit(pds[i], ":", 0);
892                         if (!(di_to = srd_inst_find_by_id(ids[0]))) {
893                                 g_strfreev(ids);
894                                 g_critical("Cannot stack protocol decoder '%s': "
895                                                 "instance not found.", pds[i]);
896                                 return 1;
897                         }
898                         g_strfreev(ids);
899                         if ((ret = srd_inst_stack(di_from, di_to)) != SRD_OK)
900                                 return 1;
901
902                         /* Don't show annotation from this PD. Only the last PD in
903                          * the stack will be left on the annotation list (unless
904                          * the annotation list was specifically provided).
905                          */
906                         if (!opt_pd_annotations)
907                                 g_hash_table_remove(pd_ann_visible,
908                                                     di_from->inst_id);
909
910                         di_from = di_to;
911                 }
912         }
913         g_strfreev(pds);
914
915         return 0;
916 }
917
918 int setup_pd_annotations(void)
919 {
920         GSList *l;
921         struct srd_decoder *dec;
922         int ann;
923         char **pds, **pdtok, **keyval, **ann_descr;
924
925         /* Set up custom list of PDs and annotations to show. */
926         if (opt_pd_annotations) {
927                 pds = g_strsplit(opt_pd_annotations, ",", 0);
928                 for (pdtok = pds; *pdtok && **pdtok; pdtok++) {
929                         ann = 0;
930                         keyval = g_strsplit(*pdtok, "=", 0);
931                         if (!(dec = srd_decoder_get_by_id(keyval[0]))) {
932                                 g_critical("Protocol decoder '%s' not found.", keyval[0]);
933                                 return 1;
934                         }
935                         if (!dec->annotations) {
936                                 g_critical("Protocol decoder '%s' has no annotations.", keyval[0]);
937                                 return 1;
938                         }
939                         if (g_strv_length(keyval) == 2) {
940                                 for (l = dec->annotations; l; l = l->next, ann++) {
941                                         ann_descr = l->data;
942                                         if (!canon_cmp(ann_descr[0], keyval[1]))
943                                                 /* Found it. */
944                                                 break;
945                                 }
946                                 if (!l) {
947                                         g_critical("Annotation '%s' not found "
948                                                         "for protocol decoder '%s'.", keyval[1], keyval[0]);
949                                         return 1;
950                                 }
951                         }
952                         g_debug("cli: showing protocol decoder annotation %d from '%s'", ann, keyval[0]);
953                         g_hash_table_insert(pd_ann_visible, g_strdup(keyval[0]), GINT_TO_POINTER(ann));
954                         g_strfreev(keyval);
955                 }
956                 g_strfreev(pds);
957         }
958
959         return 0;
960 }
961
962 int setup_output_format(void)
963 {
964         GHashTable *fmtargs;
965         GHashTableIter iter;
966         gpointer key, value;
967         struct sr_output_format **outputs;
968         int i;
969         char *fmtspec;
970
971         if (!opt_output_format) {
972                 opt_output_format = DEFAULT_OUTPUT_FORMAT;
973                 /* we'll need to remember this so when saving to a file
974                  * later, sigrok session format will be used.
975                  */
976                 default_output_format = TRUE;
977         }
978
979         fmtargs = parse_generic_arg(opt_output_format, TRUE);
980         fmtspec = g_hash_table_lookup(fmtargs, "sigrok_key");
981         if (!fmtspec) {
982                 g_critical("Invalid output format.");
983                 return 1;
984         }
985         outputs = sr_output_list();
986         for (i = 0; outputs[i]; i++) {
987                 if (strcmp(outputs[i]->id, fmtspec))
988                         continue;
989                 g_hash_table_remove(fmtargs, "sigrok_key");
990                 output_format = outputs[i];
991                 g_hash_table_iter_init(&iter, fmtargs);
992                 while (g_hash_table_iter_next(&iter, &key, &value)) {
993                         /* only supporting one parameter per output module
994                          * for now, and only its value */
995                         output_format_param = g_strdup(value);
996                         break;
997                 }
998                 break;
999         }
1000         if (!output_format) {
1001                 g_critical("Invalid output format %s.", opt_output_format);
1002                 return 1;
1003         }
1004         g_hash_table_destroy(fmtargs);
1005
1006         return 0;
1007 }
1008
1009 void show_pd_annotations(struct srd_proto_data *pdata, void *cb_data)
1010 {
1011         int i;
1012         char **annotations;
1013         gpointer ann_format;
1014
1015         /* 'cb_data' is not used in this specific callback. */
1016         (void)cb_data;
1017
1018         if (!pd_ann_visible)
1019                 return;
1020
1021         if (!g_hash_table_lookup_extended(pd_ann_visible, pdata->pdo->di->inst_id,
1022                         NULL, &ann_format))
1023                 /* Not in the list of PDs whose annotations we're showing. */
1024                 return;
1025
1026         if (pdata->ann_format != GPOINTER_TO_INT(ann_format))
1027                 /* We don't want this particular format from the PD. */
1028                 return;
1029
1030         annotations = pdata->data;
1031         if (opt_loglevel > SR_LOG_WARN)
1032                 printf("%"PRIu64"-%"PRIu64" ", pdata->start_sample, pdata->end_sample);
1033         printf("%s: ", pdata->pdo->proto_id);
1034         for (i = 0; annotations[i]; i++)
1035                 printf("\"%s\" ", annotations[i]);
1036         printf("\n");
1037         fflush(stdout);
1038 }
1039
1040 static int select_probes(struct sr_dev_inst *sdi)
1041 {
1042         char **probelist;
1043         int max_probes, i;
1044
1045         if (!opt_probes)
1046                 return SR_OK;
1047
1048         /*
1049          * This only works because a device by default initializes
1050          * and enables all its probes.
1051          */
1052         max_probes = g_slist_length(sdi->probes);
1053         probelist = parse_probestring(max_probes, opt_probes);
1054         if (!probelist) {
1055                 return SR_ERR;
1056         }
1057
1058         for (i = 0; i < max_probes; i++) {
1059                 if (probelist[i]) {
1060                         sr_dev_probe_name_set(sdi, i, probelist[i]);
1061                         g_free(probelist[i]);
1062                 } else {
1063                         sr_dev_probe_enable(sdi, i, FALSE);
1064                 }
1065         }
1066         g_free(probelist);
1067
1068         return SR_OK;
1069 }
1070
1071 /**
1072  * Return the input file format which the CLI tool should use.
1073  *
1074  * If the user specified -I / --input-format, use that one. Otherwise, try to
1075  * autodetect the format as good as possible. Failing that, return NULL.
1076  *
1077  * @param filename The filename of the input file. Must not be NULL.
1078  * @param opt The -I / --input-file option the user specified (or NULL).
1079  *
1080  * @return A pointer to the 'struct sr_input_format' that should be used,
1081  *         or NULL if no input format was selected or auto-detected.
1082  */
1083 static struct sr_input_format *determine_input_file_format(
1084                         const char *filename, const char *opt)
1085 {
1086         int i;
1087         struct sr_input_format **inputs;
1088
1089         /* If there are no input formats, return NULL right away. */
1090         inputs = sr_input_list();
1091         if (!inputs) {
1092                 g_critical("No supported input formats available.");
1093                 return NULL;
1094         }
1095
1096         /* If the user specified -I / --input-format, use that one. */
1097         if (opt) {
1098                 for (i = 0; inputs[i]; i++) {
1099                         if (strcasecmp(inputs[i]->id, opt))
1100                                 continue;
1101                         g_debug("Using user-specified input file format '%s'.",
1102                                         inputs[i]->id);
1103                         return inputs[i];
1104                 }
1105
1106                 /* The user specified an unknown input format, return NULL. */
1107                 g_critical("Error: specified input file format '%s' is "
1108                         "unknown.", opt);
1109                 return NULL;
1110         }
1111
1112         /* Otherwise, try to find an input module that can handle this file. */
1113         for (i = 0; inputs[i]; i++) {
1114                 if (inputs[i]->format_match(filename))
1115                         break;
1116         }
1117
1118         /* Return NULL if no input module wanted to touch this. */
1119         if (!inputs[i]) {
1120                 g_critical("Error: no matching input module found.");
1121                 return NULL;
1122         }
1123
1124         g_debug("cli: Autodetected '%s' input format for file '%s'.",
1125                 inputs[i]->id, filename);
1126                 
1127         return inputs[i];
1128 }
1129
1130 static void load_input_file_format(void)
1131 {
1132         GHashTable *fmtargs = NULL;
1133         struct stat st;
1134         struct sr_input *in;
1135         struct sr_input_format *input_format;
1136         char *fmtspec = NULL;
1137
1138         if (opt_input_format) {
1139                 fmtargs = parse_generic_arg(opt_input_format, TRUE);
1140                 fmtspec = g_hash_table_lookup(fmtargs, "sigrok_key");
1141         }
1142
1143         if (!(input_format = determine_input_file_format(opt_input_file,
1144                                                    fmtspec))) {
1145                 /* The exact cause was already logged. */
1146                 return;
1147         }
1148
1149         if (fmtargs)
1150                 g_hash_table_remove(fmtargs, "sigrok_key");
1151
1152         if (stat(opt_input_file, &st) == -1) {
1153                 g_critical("Failed to load %s: %s", opt_input_file,
1154                         strerror(errno));
1155                 exit(1);
1156         }
1157
1158         /* Initialize the input module. */
1159         if (!(in = g_try_malloc(sizeof(struct sr_input)))) {
1160                 g_critical("Failed to allocate input module.");
1161                 exit(1);
1162         }
1163         in->format = input_format;
1164         in->param = fmtargs;
1165         if (in->format->init) {
1166                 if (in->format->init(in) != SR_OK) {
1167                         g_critical("Input format init failed.");
1168                         exit(1);
1169                 }
1170         }
1171
1172         if (select_probes(in->sdi) > 0)
1173             return;
1174
1175         sr_session_new();
1176         sr_session_datafeed_callback_add(datafeed_in);
1177         if (sr_session_dev_add(in->sdi) != SR_OK) {
1178                 g_critical("Failed to use device.");
1179                 sr_session_destroy();
1180                 return;
1181         }
1182
1183         input_format->loadfile(in, opt_input_file);
1184         if (opt_output_file && default_output_format) {
1185                 if (sr_session_save(opt_output_file, in->sdi, singleds) != SR_OK)
1186                         g_critical("Failed to save session.");
1187         }
1188         sr_session_destroy();
1189
1190         if (fmtargs)
1191                 g_hash_table_destroy(fmtargs);
1192 }
1193
1194 static void load_input_file(void)
1195 {
1196
1197         if (sr_session_load(opt_input_file) == SR_OK) {
1198                 /* sigrok session file */
1199                 sr_session_datafeed_callback_add(datafeed_in);
1200                 sr_session_start();
1201                 sr_session_run();
1202                 sr_session_stop();
1203         }
1204         else {
1205                 /* fall back on input modules */
1206                 load_input_file_format();
1207         }
1208 }
1209
1210 static int set_dev_options(struct sr_dev_inst *sdi, GHashTable *args)
1211 {
1212         const struct sr_hwcap_option *hwo;
1213         GHashTableIter iter;
1214         gpointer key, value;
1215         int ret;
1216         float tmp_float;
1217         uint64_t tmp_u64;
1218         struct sr_rational tmp_rat;
1219         gboolean tmp_bool;
1220         void *val;
1221
1222         g_hash_table_iter_init(&iter, args);
1223         while (g_hash_table_iter_next(&iter, &key, &value)) {
1224                 if (!(hwo = sr_devopt_name_get(key))) {
1225                         g_critical("Unknown device option '%s'.", (char *) key);
1226                         return SR_ERR;
1227                 }
1228
1229                 if ((value == NULL) &&
1230                         (hwo->type != SR_T_BOOL)) {
1231                         g_critical("Option '%s' needs a value.", (char *)key);
1232                         return SR_ERR;
1233                 }
1234                 val = NULL;
1235                 switch (hwo->type) {
1236                 case SR_T_UINT64:
1237                         ret = sr_parse_sizestring(value, &tmp_u64);
1238                         if (ret != SR_OK)
1239                                 break;
1240                         val = &tmp_u64;
1241                         break;
1242                 case SR_T_CHAR:
1243                         val = value;
1244                         break;
1245                 case SR_T_BOOL:
1246                         if (!value)
1247                                 tmp_bool = TRUE;
1248                         else
1249                                 tmp_bool = sr_parse_boolstring(value);
1250                         val = &tmp_bool;
1251                         break;
1252                 case SR_T_FLOAT:
1253                         tmp_float = strtof(value, NULL);
1254                         val = &tmp_float;
1255                         break;
1256                 case SR_T_RATIONAL_PERIOD:
1257                         if ((ret = sr_parse_period(value, &tmp_rat)) != SR_OK)
1258                                 break;
1259                         val = &tmp_rat;
1260                         break;
1261                 case SR_T_RATIONAL_VOLT:
1262                         if ((ret = sr_parse_voltage(value, &tmp_rat)) != SR_OK)
1263                                 break;
1264                         val = &tmp_rat;
1265                         break;
1266                 default:
1267                         ret = SR_ERR;
1268                 }
1269                 if (val)
1270                         ret = sr_dev_config_set(sdi, hwo->hwcap, val);
1271                 if (ret != SR_OK) {
1272                         g_critical("Failed to set device option '%s'.", (char *)key);
1273                         return ret;
1274                 }
1275                 else
1276                         break;
1277         }
1278
1279         return SR_OK;
1280 }
1281
1282 static int set_limit_time(const struct sr_dev_inst *sdi)
1283 {
1284         uint64_t time_msec;
1285         uint64_t *samplerate;
1286
1287         time_msec = sr_parse_timestring(opt_time);
1288         if (time_msec == 0) {
1289                 g_critical("Invalid time '%s'", opt_time);
1290                 sr_session_destroy();
1291                 return SR_ERR;
1292         }
1293
1294         if (sr_driver_hwcap_exists(sdi->driver, SR_HWCAP_LIMIT_MSEC)) {
1295                 if (sr_dev_config_set(sdi, SR_HWCAP_LIMIT_MSEC, &time_msec) != SR_OK) {
1296                         g_critical("Failed to configure time limit.");
1297                         sr_session_destroy();
1298                         return SR_ERR;
1299                 }
1300         }
1301         else {
1302                 /* time limit set, but device doesn't support this...
1303                  * convert to samples based on the samplerate.
1304                  */
1305                 limit_samples = 0;
1306                 if (sr_dev_has_hwcap(sdi, SR_HWCAP_SAMPLERATE)) {
1307                         sr_info_get(sdi->driver, SR_DI_CUR_SAMPLERATE,
1308                                         (const void **)&samplerate, sdi);
1309                         limit_samples = (*samplerate) * time_msec / (uint64_t)1000;
1310                 }
1311                 if (limit_samples == 0) {
1312                         g_critical("Not enough time at this samplerate.");
1313                         sr_session_destroy();
1314                         return SR_ERR;
1315                 }
1316
1317                 if (sr_dev_config_set(sdi, SR_HWCAP_LIMIT_SAMPLES,
1318                                         &limit_samples) != SR_OK) {
1319                         g_critical("Failed to configure time-based sample limit.");
1320                         sr_session_destroy();
1321                         return SR_ERR;
1322                 }
1323         }
1324
1325         return SR_OK;
1326 }
1327
1328 static void run_session(void)
1329 {
1330         GSList *devices;
1331         GHashTable *devargs;
1332         struct sr_dev_inst *sdi;
1333         int max_probes, i;
1334         char **triggerlist;
1335
1336         devices = device_scan();
1337         if (!devices) {
1338                 g_critical("No devices found.");
1339                 return;
1340         }
1341         if (g_slist_length(devices) > 1) {
1342                 g_critical("sigrok-cli only supports one device for capturing.");
1343                 return;
1344         }
1345         sdi = devices->data;
1346
1347         sr_session_new();
1348         sr_session_datafeed_callback_add(datafeed_in);
1349
1350         if (sr_session_dev_add(sdi) != SR_OK) {
1351                 g_critical("Failed to use device.");
1352                 sr_session_destroy();
1353                 return;
1354         }
1355
1356         if (opt_dev) {
1357                 if ((devargs = parse_generic_arg(opt_dev, FALSE))) {
1358                         if (set_dev_options(sdi, devargs) != SR_OK)
1359                                 return;
1360                         g_hash_table_destroy(devargs);
1361                 }
1362         }
1363
1364         if (select_probes(sdi) != SR_OK) {
1365                 g_critical("Failed to set probes.");
1366                 sr_session_destroy();
1367                 return;
1368         }
1369
1370         if (opt_triggers) {
1371                 if (!(triggerlist = sr_parse_triggerstring(sdi, opt_triggers))) {
1372                         sr_session_destroy();
1373                         return;
1374                 }
1375                 max_probes = g_slist_length(sdi->probes);
1376                 for (i = 0; i < max_probes; i++) {
1377                         if (triggerlist[i]) {
1378                                 sr_dev_trigger_set(sdi, i, triggerlist[i]);
1379                                 g_free(triggerlist[i]);
1380                         }
1381                 }
1382                 g_free(triggerlist);
1383         }
1384
1385         if (opt_continuous) {
1386                 if (!sr_driver_hwcap_exists(sdi->driver, SR_HWCAP_CONTINUOUS)) {
1387                         g_critical("This device does not support continuous sampling.");
1388                         sr_session_destroy();
1389                         return;
1390                 }
1391         }
1392
1393         if (opt_time) {
1394                 if (set_limit_time(sdi) != SR_OK) {
1395                         sr_session_destroy();
1396                         return;
1397                 }
1398         }
1399
1400         if (opt_samples) {
1401                 if ((sr_parse_sizestring(opt_samples, &limit_samples) != SR_OK)
1402                                 || (sr_dev_config_set(sdi, SR_HWCAP_LIMIT_SAMPLES,
1403                                                 &limit_samples) != SR_OK)) {
1404                         g_critical("Failed to configure sample limit.");
1405                         sr_session_destroy();
1406                         return;
1407                 }
1408         }
1409
1410         if (opt_frames) {
1411                 if ((sr_parse_sizestring(opt_frames, &limit_frames) != SR_OK)
1412                                 || (sr_dev_config_set(sdi, SR_HWCAP_LIMIT_FRAMES,
1413                                                 &limit_frames) != SR_OK)) {
1414                         g_critical("Failed to configure frame limit.");
1415                         sr_session_destroy();
1416                         return;
1417                 }
1418         }
1419
1420         if (sr_session_start() != SR_OK) {
1421                 g_critical("Failed to start session.");
1422                 sr_session_destroy();
1423                 return;
1424         }
1425
1426         if (opt_continuous)
1427                 add_anykey();
1428
1429         sr_session_run();
1430
1431         if (opt_continuous)
1432                 clear_anykey();
1433
1434         if (opt_output_file && default_output_format) {
1435                 if (sr_session_save(opt_output_file, sdi, singleds) != SR_OK)
1436                         g_critical("Failed to save session.");
1437         }
1438         sr_session_destroy();
1439         g_slist_free(devices);
1440
1441 }
1442
1443 static void logger(const gchar *log_domain, GLogLevelFlags log_level,
1444                    const gchar *message, gpointer cb_data)
1445 {
1446         /* Avoid compiler warnings. */
1447         (void)log_domain;
1448         (void)cb_data;
1449
1450         /*
1451          * All messages, warnings, errors etc. go to stderr (not stdout) in
1452          * order to not mess up the CLI tool data output, e.g. VCD output.
1453          */
1454         if (log_level & (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING)
1455                         || opt_loglevel > SR_LOG_WARN) {
1456                 fprintf(stderr, "%s\n", message);
1457                 fflush(stderr);
1458         }
1459 }
1460
1461 int main(int argc, char **argv)
1462 {
1463         GOptionContext *context;
1464         GError *error;
1465
1466         g_log_set_default_handler(logger, NULL);
1467
1468         error = NULL;
1469         context = g_option_context_new(NULL);
1470         g_option_context_add_main_entries(context, optargs, NULL);
1471
1472         if (!g_option_context_parse(context, &argc, &argv, &error)) {
1473                 g_critical("%s", error->message);
1474                 return 1;
1475         }
1476
1477         /* Set the loglevel (amount of messages to output) for libsigrok. */
1478         if (sr_log_loglevel_set(opt_loglevel) != SR_OK)
1479                 return 1;
1480
1481         /* Set the loglevel (amount of messages to output) for libsigrokdecode. */
1482         if (srd_log_loglevel_set(opt_loglevel) != SRD_OK)
1483                 return 1;
1484
1485         if (sr_init() != SR_OK)
1486                 return 1;
1487
1488         if (opt_pds) {
1489                 if (srd_init(NULL) != SRD_OK)
1490                         return 1;
1491                 if (register_pds(NULL, opt_pds) != 0)
1492                         return 1;
1493                 if (srd_pd_output_callback_add(SRD_OUTPUT_ANN,
1494                                 show_pd_annotations, NULL) != SRD_OK)
1495                         return 1;
1496                 if (setup_pd_stack() != 0)
1497                         return 1;
1498                 if (setup_pd_annotations() != 0)
1499                         return 1;
1500         }
1501
1502         if (setup_output_format() != 0)
1503                 return 1;
1504
1505         if (opt_version)
1506                 show_version();
1507         else if (opt_list_devs)
1508                 show_dev_list();
1509         else if (opt_show)
1510                 show_dev_detail();
1511         else if (opt_pds)
1512                 show_pd_detail();
1513         else if (opt_input_file)
1514                 load_input_file();
1515         else if (opt_samples || opt_time || opt_frames || opt_continuous)
1516                 run_session();
1517         else
1518                 printf("%s", g_option_context_get_help(context, TRUE, NULL));
1519
1520         if (opt_pds)
1521                 srd_exit();
1522
1523         g_option_context_free(context);
1524         sr_exit();
1525
1526         return 0;
1527 }