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