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