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