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