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