cli: Add a few more static keywords.
[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[65] = { 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(device->plugin->name, unitsize, 
326                                           time(NULL), 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                                 srd_instance_set_probe(di, probe, num);
466                                 /* TODO: else fail somehow */
467                 }
468                 g_strfreev(optokens);
469
470                 /* TODO: Handle errors. */
471         }
472
473         g_strfreev(pdtokens);
474
475         return 0;
476 }
477
478 static int select_probes(struct sr_device *device)
479 {
480         struct sr_probe *probe;
481         char **probelist;
482         int max_probes, i;
483
484         if (!opt_probes)
485                 return SR_OK;
486
487         /*
488          * This only works because a device by default initializes
489          * and enables all its probes.
490          */
491         max_probes = g_slist_length(device->probes);
492         probelist = parse_probestring(max_probes, opt_probes);
493         if (!probelist) {
494                 return SR_ERR;
495         }
496
497         for (i = 0; i < max_probes; i++) {
498                 if (probelist[i]) {
499                         sr_device_probe_name(device, i + 1, probelist[i]);
500                         g_free(probelist[i]);
501                 } else {
502                         probe = sr_device_probe_find(device, i + 1);
503                         probe->enabled = FALSE;
504                 }
505         }
506         g_free(probelist);
507
508         return SR_OK;
509 }
510
511 /**
512  * Return the input file format which the CLI tool should use.
513  *
514  * If the user specified -I / --input-format, use that one. Otherwise, try to
515  * autodetect the format as good as possible. Failing that, return NULL.
516  *
517  * @param filename The filename of the input file. Must not be NULL.
518  * @param opt The -I / --input-file option the user specified (or NULL).
519  *
520  * @return A pointer to the 'struct sr_input_format' that should be used,
521  *         or NULL if no input format was selected or auto-detected.
522  */
523 static struct sr_input_format *determine_input_file_format(
524                         const char *filename, const char *opt)
525 {
526         int i;
527         struct sr_input_format **inputs;
528
529         /* If there are no input formats, return NULL right away. */
530         inputs = sr_input_list();
531         if (!inputs) {
532                 fprintf(stderr, "cli: %s: no supported input formats "
533                         "available", __func__);
534                 return NULL;
535         }
536
537         /* If the user specified -I / --input-format, use that one. */
538         if (opt) {
539                 for (i = 0; inputs[i]; i++) {
540                         if (strcasecmp(inputs[i]->id, opt_input_format))
541                                 continue;
542                         printf("Using user-specified input file format"
543                                " '%s'.\n", inputs[i]->id);
544                         return inputs[i];
545                 }
546
547                 /* The user specified an unknown input format, return NULL. */
548                 fprintf(stderr, "Error: Specified input file format '%s' is "
549                         "unknown.\n", opt_input_format);
550                 return NULL;
551         }
552
553         /* Otherwise, try to find an input module that can handle this file. */
554         for (i = 0; inputs[i]; i++) {
555                 if (inputs[i]->format_match(filename))
556                         break;
557         }
558
559         /* Return NULL if no input module wanted to touch this. */
560         if (!inputs[i]) {
561                 fprintf(stderr, "Error: No matching input module found.\n");
562                 return NULL;
563         }
564                 
565         printf("Using input file format '%s'.\n", inputs[i]->id);
566         return inputs[i];
567 }
568
569 static void load_input_file_format(void)
570 {
571         struct stat st;
572         struct sr_input *in;
573         struct sr_input_format *input_format;
574
575         input_format = determine_input_file_format(opt_input_file,
576                                                    opt_input_format);
577         if (!input_format) {
578                 fprintf(stderr, "Error: Couldn't detect input file format.\n");
579                 return;
580         }
581
582         if (stat(opt_input_file, &st) == -1) {
583                 printf("Failed to load %s: %s\n", opt_input_file,
584                         strerror(errno));
585                 exit(1);
586         }
587
588         /* Initialize the input module. */
589         if (!(in = malloc(sizeof(struct sr_input)))) {
590                 printf("Failed to allocate input module.\n");
591                 exit(1);
592         }
593         in->format = input_format;
594         in->param = input_format_param;
595         if (in->format->init) {
596                 if (in->format->init(in) != SR_OK) {
597                         printf("Input format init failed.\n");
598                         exit(1);
599                 }
600         }
601
602         if (select_probes(in->vdevice) > 0)
603             return;
604
605         sr_session_new();
606         sr_session_datafeed_callback_add(datafeed_in);
607         if (sr_session_device_add(in->vdevice) != SR_OK) {
608                 printf("Failed to use device.\n");
609                 sr_session_destroy();
610                 return;
611         }
612
613         input_format->loadfile(in, opt_input_file);
614         if (opt_output_file && default_output_format) {
615                 if (sr_session_save(opt_output_file) != SR_OK)
616                         printf("Failed to save session.\n");
617         }
618         sr_session_destroy();
619
620 }
621
622 static void load_input_file(void)
623 {
624
625         if (sr_session_load(opt_input_file) == SR_OK) {
626                 /* sigrok session file */
627                 sr_session_datafeed_callback_add(datafeed_in);
628                 sr_session_start();
629                 sr_session_run();
630                 sr_session_stop();
631         }
632         else {
633                 /* fall back on input modules */
634                 load_input_file_format();
635         }
636
637 }
638
639 int num_real_devices(void)
640 {
641         struct sr_device *device;
642         GSList *devices, *l;
643         int num_devices;
644
645         num_devices = 0;
646         devices = sr_device_list();
647         for (l = devices; l; l = l->next) {
648                 device = l->data;
649                 if (!strstr(device->plugin->name, "demo"))
650                         num_devices++;
651         }
652
653         return num_devices;
654 }
655
656 static int set_device_options(struct sr_device *device, GHashTable *args)
657 {
658         GHashTableIter iter;
659         gpointer key, value;
660         int ret, i;
661         uint64_t tmp_u64;
662         gboolean found;
663         gboolean tmp_bool;
664
665         g_hash_table_iter_init(&iter, args);
666         while (g_hash_table_iter_next(&iter, &key, &value)) {
667                 found = FALSE;
668                 for (i = 0; sr_hwcap_options[i].capability; i++) {
669                         if (strcmp(sr_hwcap_options[i].shortname, key))
670                                 continue;
671                         if ((value == NULL) && 
672                             (sr_hwcap_options[i].type != SR_T_BOOL)) {
673                                 printf("Option '%s' needs a value.\n", (char *)key);
674                                 return SR_ERR;
675                         }
676                         found = TRUE;
677                         switch (sr_hwcap_options[i].type) {
678                         case SR_T_UINT64:
679                                 ret = sr_parse_sizestring(value, &tmp_u64);
680                                 if (ret != SR_OK)
681                                         break;
682                                 ret = device->plugin-> set_configuration(device-> plugin_index,
683                                                 sr_hwcap_options[i]. capability, &tmp_u64);
684                                 break;
685                         case SR_T_CHAR:
686                                 ret = device->plugin-> set_configuration(device-> plugin_index,
687                                                 sr_hwcap_options[i]. capability, value);
688                                 break;
689                         case SR_T_BOOL:
690                                 if (!value)
691                                         tmp_bool = TRUE;
692                                 else 
693                                         tmp_bool = sr_parse_boolstring(value);
694                                 ret = device->plugin-> set_configuration(device-> plugin_index,
695                                                 sr_hwcap_options[i]. capability, 
696                                                 GINT_TO_POINTER(tmp_bool));
697                                 break;
698                         default:
699                                 ret = SR_ERR;
700                         }
701
702                         if (ret != SR_OK) {
703                                 printf("Failed to set device option '%s'.\n", (char *)key);
704                                 return ret;
705                         }
706                         else
707                                 break;
708                 }
709                 if (!found) {
710                         printf("Unknown device option '%s'.\n", (char *) key);
711                         return SR_ERR;
712                 }
713         }
714
715         return SR_OK;
716 }
717
718 static void run_session(void)
719 {
720         struct sr_device *device;
721         GHashTable *devargs;
722         int num_devices, max_probes, *capabilities, i;
723         uint64_t tmp_u64, time_msec;
724         char **probelist, *devspec;
725
726         devargs = NULL;
727         if (opt_device) {
728                 devargs = parse_generic_arg(opt_device);
729                 devspec = g_hash_table_lookup(devargs, "sigrok_key");
730                 device = parse_devicestring(devspec);
731                 if (!device) {
732                         g_warning("Device not found.");
733                         return;
734                 }
735                 g_hash_table_remove(devargs, "sigrok_key");
736         } else {
737                 num_devices = num_real_devices();
738                 if (num_devices == 1) {
739                         /* No device specified, but there is only one. */
740                         devargs = NULL;
741                         device = parse_devicestring("0");
742                 } else if (num_devices == 0) {
743                         printf("No devices found.\n");
744                         return;
745                 } else {
746                         printf("%d devices found, please select one.\n", num_devices);
747                         return;
748                 }
749         }
750
751         sr_session_new();
752         sr_session_datafeed_callback_add(datafeed_in);
753
754         if (sr_session_device_add(device) != SR_OK) {
755                 printf("Failed to use device.\n");
756                 sr_session_destroy();
757                 return;
758         }
759
760         if (devargs) {
761                 if (set_device_options(device, devargs) != SR_OK) {
762                         sr_session_destroy();
763                         return;
764                 }
765                 g_hash_table_destroy(devargs);
766         }
767
768         if (select_probes(device) != SR_OK)
769             return;
770
771         if (opt_continuous) {
772                 capabilities = device->plugin->get_capabilities();
773                 if (!sr_find_hwcap(capabilities, SR_HWCAP_CONTINUOUS)) {
774                         printf("This device does not support continuous sampling.");
775                         sr_session_destroy();
776                         return;
777                 }
778         }
779
780         if (opt_triggers) {
781                 probelist = sr_parse_triggerstring(device, opt_triggers);
782                 if (!probelist) {
783                         sr_session_destroy();
784                         return;
785                 }
786
787                 max_probes = g_slist_length(device->probes);
788                 for (i = 0; i < max_probes; i++) {
789                         if (probelist[i]) {
790                                 sr_device_trigger_set(device, i + 1, probelist[i]);
791                                 g_free(probelist[i]);
792                         }
793                 }
794                 g_free(probelist);
795         }
796
797         if (opt_time) {
798                 time_msec = sr_parse_timestring(opt_time);
799                 if (time_msec == 0) {
800                         printf("Invalid time '%s'\n", opt_time);
801                         sr_session_destroy();
802                         return;
803                 }
804
805                 capabilities = device->plugin->get_capabilities();
806                 if (sr_find_hwcap(capabilities, SR_HWCAP_LIMIT_MSEC)) {
807                         if (device->plugin->set_configuration(device->plugin_index,
808                                                           SR_HWCAP_LIMIT_MSEC, &time_msec) != SR_OK) {
809                                 printf("Failed to configure time limit.\n");
810                                 sr_session_destroy();
811                                 return;
812                         }
813                 }
814                 else {
815                         /* time limit set, but device doesn't support this...
816                          * convert to samples based on the samplerate.
817                          */
818                         limit_samples = 0;
819                         if (sr_device_has_hwcap(device, SR_HWCAP_SAMPLERATE)) {
820                                 tmp_u64 = *((uint64_t *) device->plugin->get_device_info(
821                                                 device->plugin_index, SR_DI_CUR_SAMPLERATE));
822                                 limit_samples = tmp_u64 * time_msec / (uint64_t) 1000;
823                         }
824                         if (limit_samples == 0) {
825                                 printf("Not enough time at this samplerate.\n");
826                                 sr_session_destroy();
827                                 return;
828                         }
829
830                         if (device->plugin->set_configuration(device->plugin_index,
831                                                   SR_HWCAP_LIMIT_SAMPLES, &limit_samples) != SR_OK) {
832                                 printf("Failed to configure time-based sample limit.\n");
833                                 sr_session_destroy();
834                                 return;
835                         }
836                 }
837         }
838
839         if (opt_samples) {
840                 if ((sr_parse_sizestring(opt_samples, &limit_samples) != SR_OK)
841                         || (device->plugin->set_configuration(device->plugin_index,
842                                         SR_HWCAP_LIMIT_SAMPLES, &limit_samples) != SR_OK)) {
843                         printf("Failed to configure sample limit.\n");
844                         sr_session_destroy();
845                         return;
846                 }
847         }
848
849         if (device->plugin->set_configuration(device->plugin_index,
850                   SR_HWCAP_PROBECONFIG, (char *)device->probes) != SR_OK) {
851                 printf("Failed to configure probes.\n");
852                 sr_session_destroy();
853                 return;
854         }
855
856         if (sr_session_start() != SR_OK) {
857                 printf("Failed to start session.\n");
858                 sr_session_destroy();
859                 return;
860         }
861
862         if (opt_continuous)
863                 add_anykey();
864
865         sr_session_run();
866
867         if (opt_continuous)
868                 clear_anykey();
869
870         if (opt_output_file && default_output_format) {
871                 if (sr_session_save(opt_output_file) != SR_OK)
872                         printf("Failed to save session.\n");
873         }
874         sr_session_destroy();
875
876 }
877
878 static void logger(const gchar *log_domain, GLogLevelFlags log_level,
879                    const gchar *message, gpointer user_data)
880 {
881         /* Avoid compiler warnings. */
882         (void)log_domain;
883         (void)user_data;
884
885         /*
886          * All messages, warnings, errors etc. go to stderr (not stdout) in
887          * order to not mess up the CLI tool data output, e.g. VCD output.
888          */
889         if (log_level & (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_WARNING)) {
890                 fprintf(stderr, "%s\n", message);
891                 fflush(stderr);
892         } else {
893                 if ((log_level & G_LOG_LEVEL_MESSAGE && debug == 1)
894                     || debug == 2) {
895                         printf("%s\n", message);
896                         fflush(stderr);
897                 }
898         }
899 }
900
901 int main(int argc, char **argv)
902 {
903         struct sr_output_format **outputs;
904         GOptionContext *context;
905         GError *error;
906         GHashTable *fmtargs;
907         GHashTableIter iter;
908         gpointer key, value;
909         int i;
910         char *fmtspec;
911
912         g_log_set_default_handler(logger, NULL);
913         if (getenv("SIGROK_DEBUG"))
914                 debug = strtol(getenv("SIGROK_DEBUG"), NULL, 10);
915
916         error = NULL;
917         context = g_option_context_new(NULL);
918         g_option_context_add_main_entries(context, optargs, NULL);
919
920         if (!g_option_context_parse(context, &argc, &argv, &error)) {
921                 g_warning("%s", error->message);
922                 return 1;
923         }
924
925         /* Set the loglevel (amount of messages to output) for libsigrok. */
926         if (sr_set_loglevel(opt_loglevel) != SR_OK) {
927                 fprintf(stderr, "cli: %s: sr_set_loglevel(%d) failed\n",
928                         __func__, opt_loglevel);
929                 return 1;
930         }
931
932         if (sr_init() != SR_OK)
933                 return 1;
934
935         if (opt_pds) {
936                 /* TODO: Error handling. */
937                 srd_init();
938                 register_pds(NULL, opt_pds);
939         }
940
941         if (!opt_format) {
942                 opt_format = DEFAULT_OUTPUT_FORMAT;
943                 /* we'll need to remember this, so when saving to an file
944                  * later, sigrok session format will be used.
945                  */
946                 default_output_format = TRUE;
947         }
948         fmtargs = parse_generic_arg(opt_format);
949         fmtspec = g_hash_table_lookup(fmtargs, "sigrok_key");
950         if (!fmtspec) {
951                 printf("Invalid output format.\n");
952                 return 1;
953         }
954         outputs = sr_output_list();
955         for (i = 0; outputs[i]; i++) {
956                 if (strcmp(outputs[i]->id, fmtspec))
957                         continue;
958                 g_hash_table_remove(fmtargs, "sigrok_key");
959                 output_format = outputs[i];
960                 g_hash_table_iter_init(&iter, fmtargs);
961                 while (g_hash_table_iter_next(&iter, &key, &value)) {
962                         /* only supporting one parameter per output module
963                          * for now, and only its value */
964                         output_format_param = g_strdup(value);
965                         break;
966                 }
967                 break;
968         }
969         if (!output_format) {
970                 printf("invalid output format %s\n", opt_format);
971                 return 1;
972         }
973
974         if (opt_version)
975                 show_version();
976         else if (opt_list_devices)
977                 show_device_list();
978         else if (opt_input_file)
979                 load_input_file();
980         else if (opt_samples || opt_time || opt_continuous)
981                 run_session();
982         else if (opt_device)
983                 show_device_detail();
984         else
985                 printf("%s", g_option_context_get_help(context, TRUE, NULL));
986
987         if (opt_pds)
988                 srd_exit();
989
990         g_option_context_free(context);
991         g_hash_table_destroy(fmtargs);
992         sr_exit();
993
994         return 0;
995 }