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