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