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