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