b02312042e9da03ff2ba617efc31088b8c9f18be
[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 <sigrok.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 struct sr_output_format *output_format = NULL;
43 static int default_output_format = FALSE;
44 static char *output_format_param = NULL;
45 static char *input_format_param = NULL;
46 static GData *pd_ann_visible = NULL;
47
48 static gboolean opt_version = FALSE;
49 static gint opt_loglevel = SR_LOG_WARN; /* Show errors+warnings per default. */
50 static gboolean opt_list_devs = FALSE;
51 static gboolean opt_wait_trigger = FALSE;
52 static gchar *opt_input_file = NULL;
53 static gchar *opt_output_file = NULL;
54 static gchar *opt_dev = NULL;
55 static gchar *opt_probes = NULL;
56 static gchar *opt_triggers = NULL;
57 static gchar *opt_pds = NULL;
58 static gchar *opt_pd_stack = NULL;
59 static gchar *opt_input_format = NULL;
60 static gchar *opt_output_format = NULL;
61 static gchar *opt_time = NULL;
62 static gchar *opt_samples = NULL;
63 static gchar *opt_continuous = NULL;
64
65 static GOptionEntry optargs[] = {
66         {"version", 'V', 0, G_OPTION_ARG_NONE, &opt_version, "Show version and support list", NULL},
67         {"loglevel", 'l', 0, G_OPTION_ARG_INT, &opt_loglevel, "Select libsigrok/libsigrokdecode loglevel", NULL},
68         {"list-devices", 'D', 0, G_OPTION_ARG_NONE, &opt_list_devs, "Scan for devices", NULL},
69         {"device", 'd', 0, G_OPTION_ARG_STRING, &opt_dev, "Use specified device", NULL},
70         {"input-file", 'i', 0, G_OPTION_ARG_FILENAME, &opt_input_file, "Load input from file", NULL},
71         {"input-format", 'I', 0, G_OPTION_ARG_STRING, &opt_input_format, "Input format", NULL},
72         {"output-file", 'o', 0, G_OPTION_ARG_FILENAME, &opt_output_file, "Save output to file", NULL},
73         {"output-format", 'O', 0, G_OPTION_ARG_STRING, &opt_output_format, "Output format", NULL},
74         {"probes", 'p', 0, G_OPTION_ARG_STRING, &opt_probes, "Probes to use", NULL},
75         {"triggers", 't', 0, G_OPTION_ARG_STRING, &opt_triggers, "Trigger configuration", NULL},
76         {"wait-trigger", 'w', 0, G_OPTION_ARG_NONE, &opt_wait_trigger, "Wait for trigger", NULL},
77         {"protocol-decoders", 'a', 0, G_OPTION_ARG_STRING, &opt_pds, "Protocol decoders to run", NULL},
78         {"protocol-decoder-stack", 's', 0, G_OPTION_ARG_STRING, &opt_pd_stack, "Protocol decoder stack", NULL},
79         {"time", 0, 0, G_OPTION_ARG_STRING, &opt_time, "How long to sample (ms)", NULL},
80         {"samples", 0, 0, G_OPTION_ARG_STRING, &opt_samples, "Number of samples to acquire", NULL},
81         {"continuous", 0, 0, G_OPTION_ARG_NONE, &opt_continuous, "Sample continuously", NULL},
82         {NULL, 0, 0, 0, NULL, NULL, NULL}
83 };
84
85 static void show_version(void)
86 {
87         GSList *l;
88         struct sr_dev_driver **drivers;
89         struct sr_input_format **inputs;
90         struct sr_output_format **outputs;
91         struct srd_decoder *dec;
92         int i;
93
94         printf("sigrok-cli %s\n\n", VERSION);
95
96         printf("Using libsigrok %s (lib version %s).\n",
97                sr_package_version_string_get(), sr_lib_version_string_get());
98         printf("Using libsigrokdecode %s (lib version %s).\n\n",
99                srd_package_version_string_get(), srd_lib_version_string_get());
100
101         printf("Supported hardware drivers:\n");
102         drivers = sr_driver_list();
103         for (i = 0; drivers[i]; i++) {
104                 printf("  %-20s %s\n", drivers[i]->name, drivers[i]->longname);
105         }
106         printf("\n");
107
108         printf("Supported input formats:\n");
109         inputs = sr_input_list();
110         for (i = 0; inputs[i]; i++)
111                 printf("  %-20s %s\n", inputs[i]->id, inputs[i]->description);
112         printf("\n");
113
114         printf("Supported output formats:\n");
115         outputs = sr_output_list();
116         for (i = 0; outputs[i]; i++)
117                 printf("  %-20s %s\n", outputs[i]->id, outputs[i]->description);
118         printf("\n");
119
120         if (srd_init(NULL) == SRD_OK) {
121                 printf("Supported protocol decoders:\n");
122                 srd_decoder_load_all();
123                 for (l = srd_decoder_list(); l; l = l->next) {
124                         dec = l->data;
125                         printf("  %-20s %s\n", dec->id, dec->longname);
126                         /* Print protocol description upon "-l 3" or higher. */
127                         if (opt_loglevel >= SR_LOG_INFO)
128                                 printf("  %-20s %s\n", "", dec->desc);
129                 }
130                 srd_exit();
131         }
132         printf("\n");
133 }
134
135 static void print_dev_line(const struct sr_dev *dev)
136 {
137         const struct sr_dev_inst *sdi;
138
139         sr_dev_info_get(dev, SR_DI_INST, (const void **)&sdi);
140
141         if (sdi->vendor && sdi->vendor[0])
142                 printf("%s ", sdi->vendor);
143         if (sdi->model && sdi->model[0])
144                 printf("%s ", sdi->model);
145         if (sdi->version && sdi->version[0])
146                 printf("%s ", sdi->version);
147         if (dev->probes)
148                 printf("with %d probes", g_slist_length(dev->probes));
149         printf("\n");
150 }
151
152 static void show_dev_list(void)
153 {
154         struct sr_dev *dev, *demo_dev;
155         GSList *devs, *l;
156         int devcnt;
157
158         devcnt = 0;
159         devs = sr_dev_list();
160
161         if (g_slist_length(devs) == 0)
162                 return;
163
164         printf("The following devices were found:\nID    Device\n");
165         demo_dev = NULL;
166         for (l = devs; l; l = l->next) {
167                 dev = l->data;
168                 if (sr_dev_has_hwcap(dev, SR_HWCAP_DEMO_DEV)) {
169                         demo_dev = dev;
170                         continue;
171                 }
172                 printf("%-3d   ", devcnt++);
173                 print_dev_line(dev);
174         }
175         if (demo_dev) {
176                 printf("demo  ");
177                 print_dev_line(demo_dev);
178         }
179 }
180
181 static void show_dev_detail(void)
182 {
183         struct sr_dev *dev;
184         struct sr_hwcap_option *hwo;
185         const struct sr_samplerates *samplerates;
186         int cap, *hwcaps, i;
187         char *s, *title;
188         const char *charopts, **stropts;
189
190         dev = parse_devstring(opt_dev);
191         if (!dev) {
192                 printf("No such device. Use -D to list all devices.\n");
193                 return;
194         }
195
196         print_dev_line(dev);
197
198         if (sr_dev_info_get(dev, SR_DI_TRIGGER_TYPES,
199                                         (const void **)&charopts) == SR_OK) {
200                 printf("Supported triggers: ");
201                 while (*charopts) {
202                         printf("%c ", *charopts);
203                         charopts++;
204                 }
205                 printf("\n");
206         }
207
208         title = "Supported options:\n";
209         hwcaps = dev->driver->hwcap_get_all();
210         for (cap = 0; hwcaps[cap]; cap++) {
211                 if (!(hwo = sr_hw_hwcap_get(hwcaps[cap])))
212                         continue;
213
214                 if (title) {
215                         printf("%s", title);
216                         title = NULL;
217                 }
218
219                 if (hwo->hwcap == SR_HWCAP_PATTERN_MODE) {
220                         printf("    %s", hwo->shortname);
221                         if (sr_dev_info_get(dev, SR_DI_PATTERNS,
222                                         (const void **)&stropts) == SR_OK) {
223                                 printf(" - supported patterns:\n");
224                                 for (i = 0; stropts[i]; i++)
225                                         printf("      %s\n", stropts[i]);
226                         } else {
227                                 printf("\n");
228                         }
229                 } else if (hwo->hwcap == SR_HWCAP_SAMPLERATE) {
230                         printf("    %s", hwo->shortname);
231                         /* Supported samplerates */
232                         if (sr_dev_info_get(dev, SR_DI_SAMPLERATES,
233                                         (const void **)&samplerates) != SR_OK) {
234                                 printf("\n");
235                                 continue;
236                         }
237
238                         if (samplerates->step) {
239                                 /* low */
240                                 if (!(s = sr_samplerate_string(samplerates->low)))
241                                         continue;
242                                 printf(" (%s", s);
243                                 g_free(s);
244                                 /* high */
245                                 if (!(s = sr_samplerate_string(samplerates->high)))
246                                         continue;
247                                 printf(" - %s", s);
248                                 g_free(s);
249                                 /* step */
250                                 if (!(s = sr_samplerate_string(samplerates->step)))
251                                         continue;
252                                 printf(" in steps of %s)\n", s);
253                                 g_free(s);
254                         } else {
255                                 printf(" - supported samplerates:\n");
256                                 for (i = 0; samplerates->list[i]; i++) {
257                                         printf("      %s\n", sr_samplerate_string(samplerates->list[i]));
258                                 }
259                         }
260                 } else {
261                         printf("    %s\n", hwo->shortname);
262                 }
263         }
264 }
265
266 static void show_pd_detail(void)
267 {
268         GSList *l;
269         struct srd_decoder *dec;
270         char **pdtokens, **pdtok, **ann, *doc;
271         struct srd_probe *p;
272
273         pdtokens = g_strsplit(opt_pds, ",", -1);
274         for (pdtok = pdtokens; *pdtok; pdtok++) {
275                 if (!(dec = srd_decoder_get_by_id(*pdtok))) {
276                         printf("Protocol decoder %s not found.", *pdtok);
277                         return;
278                 }
279                 printf("ID: %s\nName: %s\nLong name: %s\nDescription: %s\n",
280                                 dec->id, dec->name, dec->longname, dec->desc);
281                 printf("License: %s\n", dec->license);
282                 printf("Annotations:\n");
283                 if (dec->annotations) {
284                         for (l = dec->annotations; l; l = l->next) {
285                                 ann = l->data;
286                                 printf("- %s\n  %s\n", ann[0], ann[1]);
287                         }
288                 } else {
289                         printf("None.\n");
290                 }
291                 /* TODO: Print supported decoder options. */
292                 printf("Required probes:\n");
293                 if (dec->probes) {
294                         for (l = dec->probes; l; l = l->next) {
295                                 p = l->data;
296                                 printf("- %s (%s): %s\n",
297                                        p->name, p->id, p->desc);
298                         }
299                 } else {
300                         printf("None.\n");
301                 }
302                 printf("Optional probes:\n");
303                 if (dec->opt_probes) {
304                         for (l = dec->opt_probes; l; l = l->next) {
305                                 p = l->data;
306                                 printf("- %s (%s): %s\n",
307                                        p->name, p->id, p->desc);
308                         }
309                 } else {
310                         printf("None.\n");
311                 }
312                 if ((doc = srd_decoder_doc_get(dec))) {
313                         printf("Documentation:\n%s\n",
314                                doc[0] == '\n' ? doc + 1 : doc);
315                         g_free(doc);
316                 }
317         }
318
319         g_strfreev(pdtokens);
320 }
321
322 static void datafeed_in(struct sr_dev *dev, struct sr_datafeed_packet *packet)
323 {
324         static struct sr_output *o = NULL;
325         static int probelist[SR_MAX_NUM_PROBES + 1] = { 0 };
326         static uint64_t received_samples = 0;
327         static int unitsize = 0;
328         static int triggered = 0;
329         static FILE *outfile = NULL;
330         struct sr_probe *probe;
331         struct sr_datafeed_header *header;
332         struct sr_datafeed_logic *logic;
333         int num_enabled_probes, sample_size, ret, i;
334         uint64_t output_len, filter_out_len;
335         uint8_t *output_buf, *filter_out;
336
337         /* If the first packet to come in isn't a header, don't even try. */
338         if (packet->type != SR_DF_HEADER && o == NULL)
339                 return;
340
341         sample_size = -1;
342         switch (packet->type) {
343         case SR_DF_HEADER:
344                 g_message("cli: Received SR_DF_HEADER");
345                 /* Initialize the output module. */
346                 if (!(o = g_try_malloc(sizeof(struct sr_output)))) {
347                         printf("Output module malloc failed.\n");
348                         exit(1);
349                 }
350                 o->format = output_format;
351                 o->dev = dev;
352                 o->param = output_format_param;
353                 if (o->format->init) {
354                         if (o->format->init(o) != SR_OK) {
355                                 printf("Output format initialization failed.\n");
356                                 exit(1);
357                         }
358                 }
359
360                 header = packet->payload;
361                 num_enabled_probes = 0;
362                 for (i = 0; i < header->num_logic_probes; i++) {
363                         probe = g_slist_nth_data(dev->probes, i);
364                         if (probe->enabled)
365                                 probelist[num_enabled_probes++] = probe->index;
366                 }
367                 /* How many bytes we need to store num_enabled_probes bits */
368                 unitsize = (num_enabled_probes + 7) / 8;
369
370                 outfile = stdout;
371                 if (opt_output_file) {
372                         if (default_output_format) {
373                                 /* output file is in session format, which means we'll
374                                  * dump everything in the datastore as it comes in,
375                                  * and save from there after the session. */
376                                 outfile = NULL;
377                                 ret = sr_datastore_new(unitsize, &(dev->datastore));
378                                 if (ret != SR_OK) {
379                                         printf("Failed to create datastore.\n");
380                                         exit(1);
381                                 }
382                         } else {
383                                 /* saving to a file in whatever format was set
384                                  * with -O, so all we need is a filehandle */
385                                 outfile = g_fopen(opt_output_file, "wb");
386                         }
387                 }
388                 if (opt_pds)
389                         srd_session_start(num_enabled_probes, unitsize,
390                                         header->samplerate);
391                 break;
392         case SR_DF_END:
393                 g_message("cli: Received SR_DF_END");
394                 if (!o) {
395                         g_message("cli: double end!");
396                         break;
397                 }
398                 if (o->format->event) {
399                         o->format->event(o, SR_DF_END, &output_buf, &output_len);
400                         if (output_len) {
401                                 if (outfile)
402                                         fwrite(output_buf, 1, output_len, outfile);
403                                 g_free(output_buf);
404                                 output_len = 0;
405                         }
406                 }
407                 if (limit_samples && received_samples < limit_samples)
408                         printf("Device only sent %" PRIu64 " samples.\n",
409                                received_samples);
410                 if (opt_continuous)
411                         printf("Device stopped after %" PRIu64 " samples.\n",
412                                received_samples);
413                 sr_session_halt();
414                 if (outfile && outfile != stdout)
415                         fclose(outfile);
416                 g_free(o);
417                 o = NULL;
418                 break;
419         case SR_DF_TRIGGER:
420                 g_message("cli: received SR_DF_TRIGGER");
421                 if (o->format->event)
422                         o->format->event(o, SR_DF_TRIGGER, &output_buf,
423                                          &output_len);
424                 triggered = 1;
425                 break;
426         case SR_DF_LOGIC:
427                 logic = packet->payload;
428                 sample_size = logic->unitsize;
429                 g_message("cli: received SR_DF_LOGIC, %"PRIu64" bytes", logic->length);
430                 break;
431         }
432
433         /* not supporting anything but SR_DF_LOGIC for now */
434
435         if (sample_size == -1 || logic->length == 0)
436                 return;
437
438         /* Don't store any samples until triggered. */
439         if (opt_wait_trigger && !triggered)
440                 return;
441
442         if (limit_samples && received_samples >= limit_samples)
443                 return;
444
445         /* TODO: filters only support SR_DF_LOGIC */
446         ret = sr_filter_probes(sample_size, unitsize, probelist,
447                                    logic->data, logic->length,
448                                    &filter_out, &filter_out_len);
449         if (ret != SR_OK)
450                 return;
451
452         /* what comes out of the filter is guaranteed to be packed into the
453          * minimum size needed to support the number of samples at this sample
454          * size. however, the driver may have submitted too much -- cut off
455          * the buffer of the last packet according to the sample limit.
456          */
457         if (limit_samples && (received_samples + logic->length / sample_size >
458                         limit_samples * sample_size))
459                 filter_out_len = limit_samples * sample_size - received_samples;
460
461         if (dev->datastore)
462                 sr_datastore_put(dev->datastore, filter_out,
463                                  filter_out_len, sample_size, probelist);
464
465         if (opt_output_file && default_output_format)
466                 /* saving to a session file, don't need to do anything else
467                  * to this data for now. */
468                 goto cleanup;
469
470         if (opt_pds) {
471                 if (srd_session_send(received_samples, (uint8_t*)filter_out,
472                                 filter_out_len) != SRD_OK)
473                         sr_session_halt();
474         } else {
475                 output_len = 0;
476                 if (o->format->data && packet->type == o->format->df_type)
477                         o->format->data(o, filter_out, filter_out_len, &output_buf, &output_len);
478                 if (output_len) {
479                         fwrite(output_buf, 1, output_len, outfile);
480                         g_free(output_buf);
481                 }
482         }
483
484 cleanup:
485         g_free(filter_out);
486         received_samples += logic->length / sample_size;
487 }
488
489 /* Register the given PDs for this session.
490  * Accepts a string of the form: "spi:sck=3:sdata=4,spi:sck=3:sdata=5"
491  * That will instantiate two SPI decoders on the clock but different data
492  * lines.
493  */
494 static int register_pds(struct sr_dev *dev, const char *pdstring)
495 {
496         GHashTable *pd_opthash;
497         struct srd_decoder_inst *di;
498         char **pdtokens, **pdtok, *pd_name;
499
500         /* Avoid compiler warnings. */
501         (void)dev;
502
503         g_datalist_init(&pd_ann_visible);
504         pdtokens = g_strsplit(pdstring, ",", -1);
505         pd_opthash = NULL;
506         pd_name = NULL;
507
508         for (pdtok = pdtokens; *pdtok; pdtok++) {
509                 if (!(pd_opthash = parse_generic_arg(*pdtok))) {
510                         fprintf(stderr, "Invalid protocol decoder option '%s'.\n", *pdtok);
511                         goto err_out;
512                 }
513
514                 pd_name = g_strdup(g_hash_table_lookup(pd_opthash, "sigrok_key"));
515                 g_hash_table_remove(pd_opthash, "sigrok_key");
516                 if (srd_decoder_load(pd_name) != SRD_OK) {
517                         fprintf(stderr, "Failed to load protocol decoder %s\n", pd_name);
518                         goto err_out;
519                 }
520                 if (!(di = srd_inst_new(pd_name, pd_opthash))) {
521                         fprintf(stderr, "Failed to instantiate protocol decoder %s\n", pd_name);
522                         goto err_out;
523                 }
524                 g_datalist_set_data(&pd_ann_visible, di->inst_id, pd_name);
525
526                 /* Any keys left in the options hash are probes, where the key
527                  * is the probe name as specified in the decoder class, and the
528                  * value is the probe number i.e. the order in which the PD's
529                  * incoming samples are arranged. */
530                 if (srd_inst_probe_set_all(di, pd_opthash) != SRD_OK)
531                         goto err_out;
532                 g_hash_table_destroy(pd_opthash);
533                 pd_opthash = NULL;
534         }
535
536 err_out:
537         g_strfreev(pdtokens);
538         if (pd_opthash)
539                 g_hash_table_destroy(pd_opthash);
540         if (pd_name)
541                 g_free(pd_name);
542
543         return 0;
544 }
545
546 void show_pd_annotation(struct srd_proto_data *pdata, void *cb_data)
547 {
548         int i;
549         char **annotations;
550
551         /* 'cb_data' is not used in this specific callback. */
552         (void)cb_data;
553
554         if (pdata->ann_format != 0) {
555                 /* CLI only shows the default annotation format. */
556                 return;
557         }
558
559         if (!g_datalist_get_data(&pd_ann_visible, pdata->pdo->di->inst_id)) {
560                 /* Not in the list of PDs whose annotations we're showing. */
561                 return;
562         }
563
564         annotations = pdata->data;
565         if (opt_loglevel > SR_LOG_WARN)
566                 printf("%"PRIu64"-%"PRIu64" ", pdata->start_sample, pdata->end_sample);
567         printf("%s: ", pdata->pdo->proto_id);
568         for (i = 0; annotations[i]; i++)
569                 printf("\"%s\" ", annotations[i]);
570         printf("\n");
571 }
572
573 static int select_probes(struct sr_dev *dev)
574 {
575         struct sr_probe *probe;
576         char **probelist;
577         int max_probes, i;
578
579         if (!opt_probes)
580                 return SR_OK;
581
582         /*
583          * This only works because a device by default initializes
584          * and enables all its probes.
585          */
586         max_probes = g_slist_length(dev->probes);
587         probelist = parse_probestring(max_probes, opt_probes);
588         if (!probelist) {
589                 return SR_ERR;
590         }
591
592         for (i = 0; i < max_probes; i++) {
593                 if (probelist[i]) {
594                         sr_dev_probe_name_set(dev, i + 1, probelist[i]);
595                         g_free(probelist[i]);
596                 } else {
597                         probe = sr_dev_probe_find(dev, i + 1);
598                         probe->enabled = FALSE;
599                 }
600         }
601         g_free(probelist);
602
603         return SR_OK;
604 }
605
606 /**
607  * Return the input file format which the CLI tool should use.
608  *
609  * If the user specified -I / --input-format, use that one. Otherwise, try to
610  * autodetect the format as good as possible. Failing that, return NULL.
611  *
612  * @param filename The filename of the input file. Must not be NULL.
613  * @param opt The -I / --input-file option the user specified (or NULL).
614  *
615  * @return A pointer to the 'struct sr_input_format' that should be used,
616  *         or NULL if no input format was selected or auto-detected.
617  */
618 static struct sr_input_format *determine_input_file_format(
619                         const char *filename, const char *opt)
620 {
621         int i;
622         struct sr_input_format **inputs;
623
624         /* If there are no input formats, return NULL right away. */
625         inputs = sr_input_list();
626         if (!inputs) {
627                 fprintf(stderr, "cli: %s: no supported input formats "
628                         "available", __func__);
629                 return NULL;
630         }
631
632         /* If the user specified -I / --input-format, use that one. */
633         if (opt) {
634                 for (i = 0; inputs[i]; i++) {
635                         if (strcasecmp(inputs[i]->id, opt_input_format))
636                                 continue;
637                         printf("Using user-specified input file format"
638                                " '%s'.\n", inputs[i]->id);
639                         return inputs[i];
640                 }
641
642                 /* The user specified an unknown input format, return NULL. */
643                 fprintf(stderr, "Error: Specified input file format '%s' is "
644                         "unknown.\n", opt_input_format);
645                 return NULL;
646         }
647
648         /* Otherwise, try to find an input module that can handle this file. */
649         for (i = 0; inputs[i]; i++) {
650                 if (inputs[i]->format_match(filename))
651                         break;
652         }
653
654         /* Return NULL if no input module wanted to touch this. */
655         if (!inputs[i]) {
656                 fprintf(stderr, "Error: No matching input module found.\n");
657                 return NULL;
658         }
659                 
660         printf("Using input file format '%s'.\n", inputs[i]->id);
661         return inputs[i];
662 }
663
664 static void load_input_file_format(void)
665 {
666         struct stat st;
667         struct sr_input *in;
668         struct sr_input_format *input_format;
669
670         input_format = determine_input_file_format(opt_input_file,
671                                                    opt_input_format);
672         if (!input_format) {
673                 fprintf(stderr, "Error: Couldn't detect input file format.\n");
674                 return;
675         }
676
677         if (stat(opt_input_file, &st) == -1) {
678                 printf("Failed to load %s: %s\n", opt_input_file,
679                         strerror(errno));
680                 exit(1);
681         }
682
683         /* Initialize the input module. */
684         if (!(in = g_try_malloc(sizeof(struct sr_input)))) {
685                 printf("Failed to allocate input module.\n");
686                 exit(1);
687         }
688         in->format = input_format;
689         in->param = input_format_param;
690         if (in->format->init) {
691                 if (in->format->init(in) != SR_OK) {
692                         printf("Input format init failed.\n");
693                         exit(1);
694                 }
695         }
696
697         if (select_probes(in->vdev) > 0)
698             return;
699
700         sr_session_new();
701         sr_session_datafeed_callback_add(datafeed_in);
702         if (sr_session_dev_add(in->vdev) != SR_OK) {
703                 printf("Failed to use device.\n");
704                 sr_session_destroy();
705                 return;
706         }
707
708         input_format->loadfile(in, opt_input_file);
709         if (opt_output_file && default_output_format) {
710                 if (sr_session_save(opt_output_file) != SR_OK)
711                         printf("Failed to save session.\n");
712         }
713         sr_session_destroy();
714 }
715
716 static void load_input_file(void)
717 {
718
719         if (sr_session_load(opt_input_file) == SR_OK) {
720                 /* sigrok session file */
721                 sr_session_datafeed_callback_add(datafeed_in);
722                 sr_session_start();
723                 sr_session_run();
724                 sr_session_stop();
725         }
726         else {
727                 /* fall back on input modules */
728                 load_input_file_format();
729         }
730 }
731
732 int num_real_devs(void)
733 {
734         struct sr_dev *dev;
735         GSList *devs, *l;
736         int num_devs;
737
738         num_devs = 0;
739         devs = sr_dev_list();
740         for (l = devs; l; l = l->next) {
741                 dev = l->data;
742                 if (!sr_dev_has_hwcap(dev, SR_HWCAP_DEMO_DEV))
743                         num_devs++;
744         }
745
746         return num_devs;
747 }
748
749 static int set_dev_options(struct sr_dev *dev, GHashTable *args)
750 {
751         GHashTableIter iter;
752         gpointer key, value;
753         int ret, i;
754         uint64_t tmp_u64;
755         gboolean found;
756         gboolean tmp_bool;
757
758         g_hash_table_iter_init(&iter, args);
759         while (g_hash_table_iter_next(&iter, &key, &value)) {
760                 found = FALSE;
761                 for (i = 0; sr_hwcap_options[i].hwcap; i++) {
762                         if (strcmp(sr_hwcap_options[i].shortname, key))
763                                 continue;
764                         if ((value == NULL) && 
765                             (sr_hwcap_options[i].type != SR_T_BOOL)) {
766                                 printf("Option '%s' needs a value.\n", (char *)key);
767                                 return SR_ERR;
768                         }
769                         found = TRUE;
770                         switch (sr_hwcap_options[i].type) {
771                         case SR_T_UINT64:
772                                 ret = sr_parse_sizestring(value, &tmp_u64);
773                                 if (ret != SR_OK)
774                                         break;
775                                 ret = dev->driver->dev_config_set(dev->driver_index,
776                                         sr_hwcap_options[i].hwcap, &tmp_u64);
777                                 break;
778                         case SR_T_CHAR:
779                                 ret = dev->driver->dev_config_set(dev->driver_index,
780                                         sr_hwcap_options[i].hwcap, value);
781                                 break;
782                         case SR_T_BOOL:
783                                 if (!value)
784                                         tmp_bool = TRUE;
785                                 else 
786                                         tmp_bool = sr_parse_boolstring(value);
787                                 ret = dev->driver->dev_config_set(dev->driver_index,
788                                                 sr_hwcap_options[i].hwcap, 
789                                                 GINT_TO_POINTER(tmp_bool));
790                                 break;
791                         default:
792                                 ret = SR_ERR;
793                         }
794
795                         if (ret != SR_OK) {
796                                 printf("Failed to set device option '%s'.\n", (char *)key);
797                                 return ret;
798                         }
799                         else
800                                 break;
801                 }
802                 if (!found) {
803                         printf("Unknown device option '%s'.\n", (char *) key);
804                         return SR_ERR;
805                 }
806         }
807
808         return SR_OK;
809 }
810
811 static void run_session(void)
812 {
813         struct sr_dev *dev;
814         GHashTable *devargs;
815         int num_devs, max_probes, i;
816         uint64_t time_msec;
817         char **probelist, *devspec;
818
819         devargs = NULL;
820         if (opt_dev) {
821                 devargs = parse_generic_arg(opt_dev);
822                 devspec = g_hash_table_lookup(devargs, "sigrok_key");
823                 dev = parse_devstring(devspec);
824                 if (!dev) {
825                         g_warning("Device not found.");
826                         return;
827                 }
828                 g_hash_table_remove(devargs, "sigrok_key");
829         } else {
830                 num_devs = num_real_devs();
831                 if (num_devs == 1) {
832                         /* No device specified, but there is only one. */
833                         devargs = NULL;
834                         dev = parse_devstring("0");
835                 } else if (num_devs == 0) {
836                         printf("No devices found.\n");
837                         return;
838                 } else {
839                         printf("%d devices found, please select one.\n", num_devs);
840                         return;
841                 }
842         }
843
844         sr_session_new();
845         sr_session_datafeed_callback_add(datafeed_in);
846
847         if (sr_session_dev_add(dev) != SR_OK) {
848                 printf("Failed to use device.\n");
849                 sr_session_destroy();
850                 return;
851         }
852
853         if (devargs) {
854                 if (set_dev_options(dev, devargs) != SR_OK) {
855                         sr_session_destroy();
856                         return;
857                 }
858                 g_hash_table_destroy(devargs);
859         }
860
861         if (select_probes(dev) != SR_OK)
862             return;
863
864         if (opt_continuous) {
865                 if (!sr_driver_hwcap_exists(dev->driver, SR_HWCAP_CONTINUOUS)) {
866                         printf("This device does not support continuous sampling.");
867                         sr_session_destroy();
868                         return;
869                 }
870         }
871
872         if (opt_triggers) {
873                 probelist = sr_parse_triggerstring(dev, opt_triggers);
874                 if (!probelist) {
875                         sr_session_destroy();
876                         return;
877                 }
878
879                 max_probes = g_slist_length(dev->probes);
880                 for (i = 0; i < max_probes; i++) {
881                         if (probelist[i]) {
882                                 sr_dev_trigger_set(dev, i + 1, probelist[i]);
883                                 g_free(probelist[i]);
884                         }
885                 }
886                 g_free(probelist);
887         }
888
889         if (opt_time) {
890                 time_msec = sr_parse_timestring(opt_time);
891                 if (time_msec == 0) {
892                         printf("Invalid time '%s'\n", opt_time);
893                         sr_session_destroy();
894                         return;
895                 }
896
897                 if (sr_driver_hwcap_exists(dev->driver, SR_HWCAP_LIMIT_MSEC)) {
898                         if (dev->driver->dev_config_set(dev->driver_index,
899                             SR_HWCAP_LIMIT_MSEC, &time_msec) != SR_OK) {
900                                 printf("Failed to configure time limit.\n");
901                                 sr_session_destroy();
902                                 return;
903                         }
904                 }
905                 else {
906                         /* time limit set, but device doesn't support this...
907                          * convert to samples based on the samplerate.
908                          */
909                         limit_samples = 0;
910                         if (sr_dev_has_hwcap(dev, SR_HWCAP_SAMPLERATE)) {
911                                 const uint64_t *samplerate;
912
913                                 sr_dev_info_get(dev, SR_DI_CUR_SAMPLERATE,
914                                                 (const void **)&samplerate);
915                                 limit_samples = (*samplerate) * time_msec / (uint64_t)1000;
916                         }
917                         if (limit_samples == 0) {
918                                 printf("Not enough time at this samplerate.\n");
919                                 sr_session_destroy();
920                                 return;
921                         }
922
923                         if (dev->driver->dev_config_set(dev->driver_index,
924                             SR_HWCAP_LIMIT_SAMPLES, &limit_samples) != SR_OK) {
925                                 printf("Failed to configure time-based sample limit.\n");
926                                 sr_session_destroy();
927                                 return;
928                         }
929                 }
930         }
931
932         if (opt_samples) {
933                 if ((sr_parse_sizestring(opt_samples, &limit_samples) != SR_OK)
934                         || (dev->driver->dev_config_set(dev->driver_index,
935                             SR_HWCAP_LIMIT_SAMPLES, &limit_samples) != SR_OK)) {
936                         printf("Failed to configure sample limit.\n");
937                         sr_session_destroy();
938                         return;
939                 }
940         }
941
942         if (dev->driver->dev_config_set(dev->driver_index,
943                   SR_HWCAP_PROBECONFIG, (char *)dev->probes) != SR_OK) {
944                 printf("Failed to configure probes.\n");
945                 sr_session_destroy();
946                 return;
947         }
948
949         if (sr_session_start() != SR_OK) {
950                 printf("Failed to start session.\n");
951                 sr_session_destroy();
952                 return;
953         }
954
955         if (opt_continuous)
956                 add_anykey();
957
958         sr_session_run();
959
960         if (opt_continuous)
961                 clear_anykey();
962
963         if (opt_output_file && default_output_format) {
964                 if (sr_session_save(opt_output_file) != SR_OK)
965                         printf("Failed to save session.\n");
966         }
967         sr_session_destroy();
968 }
969
970 static void logger(const gchar *log_domain, GLogLevelFlags log_level,
971                    const gchar *message, gpointer cb_data)
972 {
973         /* Avoid compiler warnings. */
974         (void)log_domain;
975         (void)cb_data;
976
977         /*
978          * All messages, warnings, errors etc. go to stderr (not stdout) in
979          * order to not mess up the CLI tool data output, e.g. VCD output.
980          */
981         if (log_level & (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_WARNING)
982                         || opt_loglevel > SR_LOG_WARN) {
983                 fprintf(stderr, "%s\n", message);
984                 fflush(stderr);
985         }
986 }
987
988 int main(int argc, char **argv)
989 {
990         GOptionContext *context;
991         GError *error;
992         GHashTable *fmtargs;
993         GHashTableIter iter;
994         gpointer key, value;
995         struct sr_output_format **outputs;
996         struct srd_decoder_inst *di_from, *di_to;
997         int i, ret;
998         char *fmtspec, **pds;
999
1000         g_log_set_default_handler(logger, NULL);
1001
1002         error = NULL;
1003         context = g_option_context_new(NULL);
1004         g_option_context_add_main_entries(context, optargs, NULL);
1005
1006         if (!g_option_context_parse(context, &argc, &argv, &error)) {
1007                 g_warning("%s", error->message);
1008                 return 1;
1009         }
1010
1011         /* Set the loglevel (amount of messages to output) for libsigrok. */
1012         if (sr_log_loglevel_set(opt_loglevel) != SR_OK) {
1013                 fprintf(stderr, "cli: %s: sr_log_loglevel_set(%d) failed\n",
1014                         __func__, opt_loglevel);
1015                 return 1;
1016         }
1017
1018         /* Set the loglevel (amount of messages to output) for libsigrokdecode. */
1019         if (srd_log_loglevel_set(opt_loglevel) != SRD_OK) {
1020                 fprintf(stderr, "cli: %s: srd_log_loglevel_set(%d) failed\n",
1021                         __func__, opt_loglevel);
1022                 return 1;
1023         }
1024
1025         if (sr_init() != SR_OK)
1026                 return 1;
1027
1028         if (opt_pds) {
1029                 if (srd_init(NULL) != SRD_OK) {
1030                         printf("Failed to initialize sigrokdecode\n");
1031                         return 1;
1032                 }
1033                 if (register_pds(NULL, opt_pds) != 0) {
1034                         printf("Failed to register protocol decoders\n");
1035                         return 1;
1036                 }
1037                 if (srd_pd_output_callback_add(SRD_OUTPUT_ANN,
1038                                 show_pd_annotation, NULL) != SRD_OK) {
1039                         printf("Failed to register protocol decoder callback\n");
1040                         return 1;
1041                 }
1042
1043                 pds = g_strsplit(opt_pds, ",", 0);
1044                 if (g_strv_length(pds) > 1) {
1045                         if (opt_pd_stack) {
1046                                 /* A stack setup was specified, use that. */
1047                                 g_strfreev(pds);
1048                                 pds = g_strsplit(opt_pd_stack, ",", 0);
1049                                 if (g_strv_length(pds) < 2) {
1050                                         g_strfreev(pds);
1051                                         printf("Specify at least two protocol decoders to stack.\n");
1052                                         return 1;
1053                                 }
1054                         }
1055
1056                         if (!(di_from = srd_inst_find_by_id(pds[0]))) {
1057                                 printf("Cannot stack protocol decoder '%s': instance not found.\n", pds[0]);
1058                                 return 1;
1059                         }
1060                         for (i = 1; pds[i]; i++) {
1061                                 if (!(di_to = srd_inst_find_by_id(pds[i]))) {
1062                                         printf("Cannot stack protocol decoder '%s': instance not found.\n", pds[i]);
1063                                         return 1;
1064                                 }
1065                                 if ((ret = srd_inst_stack(di_from, di_to)) != SRD_OK)
1066                                         return ret;
1067
1068                                 /* Don't show annotation from this PD. Only the last PD in
1069                                  * the stack will be left on the annotation list.
1070                                  */
1071                                 g_datalist_remove_data(&pd_ann_visible, di_from->inst_id);
1072
1073                                 di_from = di_to;
1074                         }
1075                 }
1076                 g_strfreev(pds);
1077         }
1078
1079         if (!opt_output_format) {
1080                 opt_output_format = DEFAULT_OUTPUT_FORMAT;
1081                 /* we'll need to remember this so when saving to a file
1082                  * later, sigrok session format will be used.
1083                  */
1084                 default_output_format = TRUE;
1085         }
1086         fmtargs = parse_generic_arg(opt_output_format);
1087         fmtspec = g_hash_table_lookup(fmtargs, "sigrok_key");
1088         if (!fmtspec) {
1089                 printf("Invalid output format.\n");
1090                 return 1;
1091         }
1092         outputs = sr_output_list();
1093         for (i = 0; outputs[i]; i++) {
1094                 if (strcmp(outputs[i]->id, fmtspec))
1095                         continue;
1096                 g_hash_table_remove(fmtargs, "sigrok_key");
1097                 output_format = outputs[i];
1098                 g_hash_table_iter_init(&iter, fmtargs);
1099                 while (g_hash_table_iter_next(&iter, &key, &value)) {
1100                         /* only supporting one parameter per output module
1101                          * for now, and only its value */
1102                         output_format_param = g_strdup(value);
1103                         break;
1104                 }
1105                 break;
1106         }
1107         if (!output_format) {
1108                 printf("invalid output format %s\n", opt_output_format);
1109                 return 1;
1110         }
1111
1112         if (opt_version)
1113                 show_version();
1114         else if (opt_list_devs)
1115                 show_dev_list();
1116         else if (opt_input_file)
1117                 load_input_file();
1118         else if (opt_samples || opt_time || opt_continuous)
1119                 run_session();
1120         else if (opt_dev)
1121                 show_dev_detail();
1122         else if (opt_pds)
1123                 show_pd_detail();
1124         else
1125                 printf("%s", g_option_context_get_help(context, TRUE, NULL));
1126
1127         if (opt_pds)
1128                 srd_exit();
1129
1130         g_option_context_free(context);
1131         g_hash_table_destroy(fmtargs);
1132         sr_exit();
1133
1134         return 0;
1135 }