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