]> sigrok.org Git - sigrok-cli.git/blame_incremental - sigrok-cli.c
Use annotation-specific struct
[sigrok-cli.git] / sigrok-cli.c
... / ...
CommitLineData
1/*
2 * This file is part of the sigrok-cli 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 "config.h"
21#ifdef HAVE_SRD
22#include <libsigrokdecode/libsigrokdecode.h> /* First, so we avoid a _POSIX_C_SOURCE warning. */
23#endif
24#include <stdio.h>
25#include <stdlib.h>
26#include <unistd.h>
27#include <string.h>
28#include <time.h>
29#include <sys/time.h>
30#include <inttypes.h>
31#include <sys/types.h>
32#include <sys/stat.h>
33#include <errno.h>
34#include <glib.h>
35#include <glib/gstdio.h>
36#include <libsigrok/libsigrok.h>
37#include "sigrok-cli.h"
38
39#define DEFAULT_OUTPUT_FORMAT "bits:width=64"
40
41static struct sr_context *sr_ctx = NULL;
42
43static uint64_t limit_samples = 0;
44static uint64_t limit_frames = 0;
45static struct sr_output_format *output_format = NULL;
46static int default_output_format = FALSE;
47static char *output_format_param = NULL;
48#ifdef HAVE_SRD
49static struct srd_session *srd_sess = NULL;
50static GHashTable *pd_ann_visible = NULL;
51#endif
52static GByteArray *savebuf;
53
54static gboolean opt_version = FALSE;
55static gint opt_loglevel = SR_LOG_WARN; /* Show errors+warnings per default. */
56static gboolean opt_scan_devs = FALSE;
57static gboolean opt_wait_trigger = FALSE;
58static gchar *opt_input_file = NULL;
59static gchar *opt_output_file = NULL;
60static gchar *opt_drv = NULL;
61static gchar *opt_config = NULL;
62static gchar *opt_probes = NULL;
63static gchar *opt_probe_group = NULL;
64static gchar *opt_triggers = NULL;
65static gchar *opt_pds = NULL;
66#ifdef HAVE_SRD
67static gchar *opt_pd_stack = NULL;
68static gchar *opt_pd_annotations = NULL;
69#endif
70static gchar *opt_input_format = NULL;
71static gchar *opt_output_format = NULL;
72static gchar *opt_show = NULL;
73static gchar *opt_time = NULL;
74static gchar *opt_samples = NULL;
75static gchar *opt_frames = NULL;
76static gchar *opt_continuous = NULL;
77static gchar *opt_set = NULL;
78
79static GOptionEntry optargs[] = {
80 {"version", 'V', 0, G_OPTION_ARG_NONE, &opt_version,
81 "Show version and support list", NULL},
82 {"loglevel", 'l', 0, G_OPTION_ARG_INT, &opt_loglevel,
83 "Set loglevel (5 is most verbose)", NULL},
84 {"driver", 'd', 0, G_OPTION_ARG_STRING, &opt_drv,
85 "The driver to use", NULL},
86 {"config", 'c', 0, G_OPTION_ARG_STRING, &opt_config,
87 "Specify device configuration options", NULL},
88 {"input-file", 'i', 0, G_OPTION_ARG_FILENAME, &opt_input_file,
89 "Load input from file", NULL},
90 {"input-format", 'I', 0, G_OPTION_ARG_STRING, &opt_input_format,
91 "Input format", NULL},
92 {"output-file", 'o', 0, G_OPTION_ARG_FILENAME, &opt_output_file,
93 "Save output to file", NULL},
94 {"output-format", 'O', 0, G_OPTION_ARG_STRING, &opt_output_format,
95 "Output format", NULL},
96 {"probes", 'p', 0, G_OPTION_ARG_STRING, &opt_probes,
97 "Probes to use", NULL},
98 {"probe-group", 'g', 0, G_OPTION_ARG_STRING, &opt_probe_group,
99 "Probe groups", NULL},
100 {"triggers", 't', 0, G_OPTION_ARG_STRING, &opt_triggers,
101 "Trigger configuration", NULL},
102 {"wait-trigger", 'w', 0, G_OPTION_ARG_NONE, &opt_wait_trigger,
103 "Wait for trigger", NULL},
104#ifdef HAVE_SRD
105 {"protocol-decoders", 'P', 0, G_OPTION_ARG_STRING, &opt_pds,
106 "Protocol decoders to run", NULL},
107 {"protocol-decoder-stack", 'S', 0, G_OPTION_ARG_STRING, &opt_pd_stack,
108 "Protocol decoder stack", NULL},
109 {"protocol-decoder-annotations", 'A', 0, G_OPTION_ARG_STRING, &opt_pd_annotations,
110 "Protocol decoder annotation(s) to show", NULL},
111#endif
112 {"scan", 0, 0, G_OPTION_ARG_NONE, &opt_scan_devs,
113 "Scan for devices", NULL},
114 {"show", 0, 0, G_OPTION_ARG_NONE, &opt_show,
115 "Show device detail", NULL},
116 {"time", 0, 0, G_OPTION_ARG_STRING, &opt_time,
117 "How long to sample (ms)", NULL},
118 {"samples", 0, 0, G_OPTION_ARG_STRING, &opt_samples,
119 "Number of samples to acquire", NULL},
120 {"frames", 0, 0, G_OPTION_ARG_STRING, &opt_frames,
121 "Number of frames to acquire", NULL},
122 {"continuous", 0, 0, G_OPTION_ARG_NONE, &opt_continuous,
123 "Sample continuously", NULL},
124 {"set", 0, 0, G_OPTION_ARG_NONE, &opt_set, "Set device options only", NULL},
125 {NULL, 0, 0, 0, NULL, NULL, NULL}
126};
127
128
129/* Convert driver options hash to GSList of struct sr_config. */
130static GSList *hash_to_hwopt(GHashTable *hash)
131{
132 const struct sr_config_info *srci;
133 struct sr_config *src;
134 GList *gl, *keys;
135 GSList *opts;
136 char *key, *value;
137
138 keys = g_hash_table_get_keys(hash);
139 opts = NULL;
140 for (gl = keys; gl; gl = gl->next) {
141 key = gl->data;
142 if (!(srci = sr_config_info_name_get(key))) {
143 g_critical("Unknown option %s", key);
144 return NULL;
145 }
146 src = g_try_malloc(sizeof(struct sr_config));
147 src->key = srci->key;
148 value = g_hash_table_lookup(hash, key);
149 src->data = g_variant_new_string(value);
150 opts = g_slist_append(opts, src);
151 }
152 g_list_free(keys);
153
154 return opts;
155}
156
157static struct sr_probe_group *select_probe_group(struct sr_dev_inst *sdi)
158{
159 struct sr_probe_group *pg;
160 GSList *l;
161
162 if (!opt_probe_group)
163 return NULL;
164
165 if (!sdi->probe_groups) {
166 g_critical("This device does not have any probe groups.");
167 return NULL;
168 }
169
170 for (l = sdi->probe_groups; l; l = l->next) {
171 pg = l->data;
172 if (!strcasecmp(opt_probe_group, pg->name)) {
173 return pg;
174 }
175 }
176
177 return NULL;
178}
179
180static void free_drvopts(struct sr_config *src)
181{
182 g_variant_unref(src->data);
183 g_free(src);
184}
185
186static GSList *device_scan(void)
187{
188 struct sr_dev_driver **drivers, *driver;
189 GHashTable *drvargs;
190 GSList *drvopts, *devices, *tmpdevs, *l;
191 int i;
192 char *drvname;
193
194 if (opt_drv) {
195 drvargs = parse_generic_arg(opt_drv, TRUE);
196 drvname = g_strdup(g_hash_table_lookup(drvargs, "sigrok_key"));
197 g_hash_table_remove(drvargs, "sigrok_key");
198 driver = NULL;
199 drivers = sr_driver_list();
200 for (i = 0; drivers[i]; i++) {
201 if (strcmp(drivers[i]->name, drvname))
202 continue;
203 driver = drivers[i];
204 }
205 if (!driver) {
206 g_critical("Driver %s not found.", drvname);
207 g_hash_table_destroy(drvargs);
208 g_free(drvname);
209 return NULL;
210 }
211 g_free(drvname);
212 if (sr_driver_init(sr_ctx, driver) != SR_OK) {
213 g_critical("Failed to initialize driver.");
214 g_hash_table_destroy(drvargs);
215 return NULL;
216 }
217 drvopts = NULL;
218 if (g_hash_table_size(drvargs) > 0) {
219 if (!(drvopts = hash_to_hwopt(drvargs))) {
220 /* Unknown options, already logged. */
221 g_hash_table_destroy(drvargs);
222 return NULL;
223 }
224 }
225 g_hash_table_destroy(drvargs);
226 devices = sr_driver_scan(driver, drvopts);
227 g_slist_free_full(drvopts, (GDestroyNotify)free_drvopts);
228 } else {
229 /* No driver specified, let them all scan on their own. */
230 devices = NULL;
231 drivers = sr_driver_list();
232 for (i = 0; drivers[i]; i++) {
233 driver = drivers[i];
234 if (sr_driver_init(sr_ctx, driver) != SR_OK) {
235 g_critical("Failed to initialize driver.");
236 return NULL;
237 }
238 tmpdevs = sr_driver_scan(driver, NULL);
239 for (l = tmpdevs; l; l = l->next)
240 devices = g_slist_append(devices, l->data);
241 g_slist_free(tmpdevs);
242 }
243 }
244
245 return devices;
246}
247
248static void show_version(void)
249{
250 struct sr_dev_driver **drivers;
251 struct sr_input_format **inputs;
252 struct sr_output_format **outputs;
253 int i;
254#ifdef HAVE_SRD
255 struct srd_decoder *dec;
256 const GSList *l;
257#endif
258
259 printf("sigrok-cli %s\n\n", VERSION);
260
261 printf("Using libsigrok %s (lib version %s).\n",
262 sr_package_version_string_get(), sr_lib_version_string_get());
263#ifdef HAVE_SRD
264 printf("Using libsigrokdecode %s (lib version %s).\n\n",
265 srd_package_version_string_get(), srd_lib_version_string_get());
266#endif
267
268 printf("Supported hardware drivers:\n");
269 drivers = sr_driver_list();
270 for (i = 0; drivers[i]; i++) {
271 printf(" %-20s %s\n", drivers[i]->name, drivers[i]->longname);
272 }
273 printf("\n");
274
275 printf("Supported input formats:\n");
276 inputs = sr_input_list();
277 for (i = 0; inputs[i]; i++)
278 printf(" %-20s %s\n", inputs[i]->id, inputs[i]->description);
279 printf("\n");
280
281 printf("Supported output formats:\n");
282 outputs = sr_output_list();
283 for (i = 0; outputs[i]; i++)
284 printf(" %-20s %s\n", outputs[i]->id, outputs[i]->description);
285 printf(" %-20s %s\n", "sigrok", "Default file output format");
286 printf("\n");
287
288#ifdef HAVE_SRD
289 if (srd_init(NULL) == SRD_OK) {
290 printf("Supported protocol decoders:\n");
291 srd_decoder_load_all();
292 for (l = srd_decoder_list(); l; l = l->next) {
293 dec = l->data;
294 printf(" %-20s %s\n", dec->id, dec->longname);
295 /* Print protocol description upon "-l 3" or higher. */
296 if (opt_loglevel >= SR_LOG_INFO)
297 printf(" %-20s %s\n", "", dec->desc);
298 }
299 srd_exit();
300 }
301 printf("\n");
302#endif
303}
304
305static void print_dev_line(const struct sr_dev_inst *sdi)
306{
307 struct sr_probe *probe;
308 GSList *l;
309 GString *s;
310 GVariant *gvar;
311
312 s = g_string_sized_new(128);
313 g_string_assign(s, sdi->driver->name);
314 if (sr_config_get(sdi->driver, sdi, NULL, SR_CONF_CONN, &gvar) == SR_OK) {
315 g_string_append(s, ":conn=");
316 g_string_append(s, g_variant_get_string(gvar, NULL));
317 g_variant_unref(gvar);
318 }
319 g_string_append(s, " - ");
320 if (sdi->vendor && sdi->vendor[0])
321 g_string_append_printf(s, "%s ", sdi->vendor);
322 if (sdi->model && sdi->model[0])
323 g_string_append_printf(s, "%s ", sdi->model);
324 if (sdi->version && sdi->version[0])
325 g_string_append_printf(s, "%s ", sdi->version);
326 if (sdi->probes) {
327 if (g_slist_length(sdi->probes) == 1) {
328 probe = sdi->probes->data;
329 g_string_append_printf(s, "with 1 probe: %s", probe->name);
330 } else {
331 g_string_append_printf(s, "with %d probes:", g_slist_length(sdi->probes));
332 for (l = sdi->probes; l; l = l->next) {
333 probe = l->data;
334 g_string_append_printf(s, " %s", probe->name);
335 }
336 }
337 }
338 g_string_append_printf(s, "\n");
339 printf("%s", s->str);
340 g_string_free(s, TRUE);
341
342}
343
344static void show_dev_list(void)
345{
346 struct sr_dev_inst *sdi;
347 GSList *devices, *l;
348
349 if (!(devices = device_scan()))
350 return;
351
352 printf("The following devices were found:\n");
353 for (l = devices; l; l = l->next) {
354 sdi = l->data;
355 print_dev_line(sdi);
356 }
357 g_slist_free(devices);
358
359}
360
361static void show_dev_detail(void)
362{
363 struct sr_dev_inst *sdi;
364 const struct sr_config_info *srci;
365 struct sr_probe *probe;
366 struct sr_probe_group *probe_group, *pg;
367 GSList *devices, *pgl, *prl;
368 GVariant *gvar_opts, *gvar_dict, *gvar_list, *gvar;
369 gsize num_opts, num_elements;
370 const uint64_t *uint64, p, q, low, high;
371 uint64_t cur_low, cur_high;
372 const int32_t *opts;
373 unsigned int num_devices, o, i;
374 char *tmp_str;
375 char *s;
376 const char *charopts, **stropts;
377
378 if (!(devices = device_scan())) {
379 g_critical("No devices found.");
380 return;
381 }
382
383 num_devices = g_slist_length(devices);
384 if (num_devices > 1) {
385 g_critical("%d devices found. Use --scan to show them, "
386 "and select one to show.", num_devices);
387 return;
388 }
389
390 sdi = devices->data;
391 print_dev_line(sdi);
392
393 if (sr_dev_open(sdi) != SR_OK) {
394 g_critical("Failed to open device.");
395 return;
396 }
397
398 if ((sr_config_list(sdi->driver, NULL, NULL, SR_CONF_SCAN_OPTIONS,
399 &gvar_opts) == SR_OK)) {
400 opts = g_variant_get_fixed_array(gvar_opts, &num_elements,
401 sizeof(int32_t));
402 printf("Supported driver options:\n");
403 for (i = 0; i < num_elements; i++) {
404 if (!(srci = sr_config_info_get(opts[i])))
405 continue;
406 printf(" %s\n", srci->id);
407 }
408 g_variant_unref(gvar_opts);
409 }
410
411 probe_group = select_probe_group(sdi);
412 if ((sr_config_list(sdi->driver, sdi, probe_group, SR_CONF_DEVICE_OPTIONS,
413 &gvar_opts)) != SR_OK)
414 /* Driver supports no device instance options. */
415 return;
416
417 if (sdi->probe_groups) {
418 printf("Probe groups:\n");
419 for (pgl = sdi->probe_groups; pgl; pgl = pgl->next) {
420 pg = pgl->data;
421 printf(" %s: channel%s", pg->name,
422 g_slist_length(pg->probes) > 1 ? "s" : "");
423 for (prl = pg->probes; prl; prl = prl->next) {
424 probe = prl->data;
425 printf(" %s", probe->name);
426 }
427 printf("\n");
428 }
429 }
430
431 printf("Supported configuration options");
432 if (sdi->probe_groups) {
433 if (!probe_group)
434 printf(" across all probe groups");
435 else
436 printf(" on probe group %s", probe_group->name);
437 }
438 printf(":\n");
439 opts = g_variant_get_fixed_array(gvar_opts, &num_opts, sizeof(int32_t));
440 for (o = 0; o < num_opts; o++) {
441 if (!(srci = sr_config_info_get(opts[o])))
442 continue;
443
444 if (srci->key == SR_CONF_TRIGGER_TYPE) {
445 if (sr_config_list(sdi->driver, sdi, probe_group, srci->key,
446 &gvar) != SR_OK) {
447 printf("\n");
448 continue;
449 }
450 charopts = g_variant_get_string(gvar, NULL);
451 printf(" Supported triggers: ");
452 while (*charopts) {
453 printf("%c ", *charopts);
454 charopts++;
455 }
456 printf("\n");
457 g_variant_unref(gvar);
458
459 } else if (srci->key == SR_CONF_PATTERN_MODE) {
460 /* Pattern generator modes */
461 printf(" %s", srci->id);
462 if (sr_config_list(sdi->driver, sdi, probe_group, srci->key,
463 &gvar) == SR_OK) {
464 printf(" - supported patterns:\n");
465 stropts = g_variant_get_strv(gvar, &num_elements);
466 for (i = 0; i < num_elements; i++)
467 printf(" %s\n", stropts[i]);
468 g_variant_unref(gvar);
469 } else {
470 printf("\n");
471 }
472
473 } else if (srci->key == SR_CONF_SAMPLERATE) {
474 /* Supported samplerates */
475 printf(" %s", srci->id);
476 if (sr_config_list(sdi->driver, sdi, probe_group, SR_CONF_SAMPLERATE,
477 &gvar_dict) != SR_OK) {
478 printf("\n");
479 continue;
480 }
481 if ((gvar_list = g_variant_lookup_value(gvar_dict,
482 "samplerates", G_VARIANT_TYPE("at")))) {
483 uint64 = g_variant_get_fixed_array(gvar_list,
484 &num_elements, sizeof(uint64_t));
485 printf(" - supported samplerates:\n");
486 for (i = 0; i < num_elements; i++) {
487 if (!(s = sr_samplerate_string(uint64[i])))
488 continue;
489 printf(" %s\n", s);
490 g_free(s);
491 }
492 g_variant_unref(gvar_list);
493 } else if ((gvar_list = g_variant_lookup_value(gvar_dict,
494 "samplerate-steps", G_VARIANT_TYPE("at")))) {
495 uint64 = g_variant_get_fixed_array(gvar_list,
496 &num_elements, sizeof(uint64_t));
497 /* low */
498 if (!(s = sr_samplerate_string(uint64[0])))
499 continue;
500 printf(" (%s", s);
501 g_free(s);
502 /* high */
503 if (!(s = sr_samplerate_string(uint64[1])))
504 continue;
505 printf(" - %s", s);
506 g_free(s);
507 /* step */
508 if (!(s = sr_samplerate_string(uint64[2])))
509 continue;
510 printf(" in steps of %s)\n", s);
511 g_free(s);
512 g_variant_unref(gvar_list);
513 }
514 g_variant_unref(gvar_dict);
515
516 } else if (srci->key == SR_CONF_BUFFERSIZE) {
517 /* Supported buffer sizes */
518 printf(" %s", srci->id);
519 if (sr_config_list(sdi->driver, sdi, probe_group,
520 SR_CONF_BUFFERSIZE, &gvar_list) != SR_OK) {
521 printf("\n");
522 continue;
523 }
524 uint64 = g_variant_get_fixed_array(gvar_list,
525 &num_elements, sizeof(uint64_t));
526 printf(" - supported buffer sizes:\n");
527 for (i = 0; i < num_elements; i++)
528 printf(" %"PRIu64"\n", uint64[i]);
529 g_variant_unref(gvar_list);
530
531 } else if (srci->key == SR_CONF_TIMEBASE) {
532 /* Supported time bases */
533 printf(" %s", srci->id);
534 if (sr_config_list(sdi->driver, sdi, probe_group,
535 SR_CONF_TIMEBASE, &gvar_list) != SR_OK) {
536 printf("\n");
537 continue;
538 }
539 printf(" - supported time bases:\n");
540 num_elements = g_variant_n_children(gvar_list);
541 for (i = 0; i < num_elements; i++) {
542 gvar = g_variant_get_child_value(gvar_list, i);
543 g_variant_get(gvar, "(tt)", &p, &q);
544 s = sr_period_string(p * q);
545 printf(" %s\n", s);
546 g_free(s);
547 }
548 g_variant_unref(gvar_list);
549
550 } else if (srci->key == SR_CONF_VDIV) {
551 /* Supported volts/div values */
552 printf(" %s", srci->id);
553 if (sr_config_list(sdi->driver, sdi, probe_group,
554 SR_CONF_VDIV, &gvar_list) != SR_OK) {
555 printf("\n");
556 continue;
557 }
558 printf(" - supported volts/div:\n");
559 num_elements = g_variant_n_children(gvar_list);
560 for (i = 0; i < num_elements; i++) {
561 gvar = g_variant_get_child_value(gvar_list, i);
562 g_variant_get(gvar, "(tt)", &p, &q);
563 s = sr_voltage_string(p, q);
564 printf(" %s\n", s);
565 g_free(s);
566 }
567 g_variant_unref(gvar_list);
568
569 } else if (srci->datatype == SR_T_CHAR) {
570 printf(" %s: ", srci->id);
571 if (sr_config_get(sdi->driver, sdi, probe_group, srci->key,
572 &gvar) == SR_OK) {
573 tmp_str = g_strdup(g_variant_get_string(gvar, NULL));
574 g_variant_unref(gvar);
575 } else
576 tmp_str = NULL;
577
578 if (sr_config_list(sdi->driver, sdi, probe_group, srci->key,
579 &gvar) != SR_OK) {
580 printf("\n");
581 continue;
582 }
583
584 stropts = g_variant_get_strv(gvar, &num_elements);
585 for (i = 0; i < num_elements; i++) {
586 if (i)
587 printf(", ");
588 printf("%s", stropts[i]);
589 if (tmp_str && !strcmp(tmp_str, stropts[i]))
590 printf(" (current)");
591 }
592 printf("\n");
593 g_free(stropts);
594 g_free(tmp_str);
595 g_variant_unref(gvar);
596
597 } else if (srci->datatype == SR_T_UINT64_RANGE) {
598 printf(" %s: ", srci->id);
599 if (sr_config_list(sdi->driver, sdi, probe_group, srci->key,
600 &gvar_list) != SR_OK) {
601 printf("\n");
602 continue;
603 }
604
605 if (sr_config_get(sdi->driver, sdi, NULL, srci->key, &gvar) == SR_OK) {
606 g_variant_get(gvar, "(tt)", &cur_low, &cur_high);
607 g_variant_unref(gvar);
608 } else {
609 cur_low = 0;
610 cur_high = 0;
611 }
612
613 num_elements = g_variant_n_children(gvar_list);
614 for (i = 0; i < num_elements; i++) {
615 gvar = g_variant_get_child_value(gvar_list, i);
616 g_variant_get(gvar, "(tt)", &low, &high);
617 g_variant_unref(gvar);
618 if (i)
619 printf(", ");
620 printf("%"PRIu64"-%"PRIu64, low, high);
621 if (low == cur_low && high == cur_high)
622 printf(" (current)");
623 }
624 printf("\n");
625 g_variant_unref(gvar_list);
626
627 } else if (srci->datatype == SR_T_BOOL) {
628 printf(" %s: ", srci->id);
629 if (sr_config_get(sdi->driver, sdi, NULL, srci->key,
630 &gvar) == SR_OK) {
631 if (g_variant_get_boolean(gvar))
632 printf("on (current), off\n");
633 else
634 printf("on, off (current)\n");
635 g_variant_unref(gvar);
636 } else
637 printf("on, off\n");
638
639 } else {
640
641 /* Everything else */
642 printf(" %s\n", srci->id);
643 }
644 }
645 g_variant_unref(gvar_opts);
646
647 sr_dev_close(sdi);
648 g_slist_free(devices);
649
650}
651
652#ifdef HAVE_SRD
653static void show_pd_detail(void)
654{
655 GSList *l;
656 struct srd_decoder *dec;
657 struct srd_decoder_option *o;
658 char **pdtokens, **pdtok, *optsep, **ann, *val, *doc;
659 struct srd_probe *p;
660
661 pdtokens = g_strsplit(opt_pds, ",", -1);
662 for (pdtok = pdtokens; *pdtok; pdtok++) {
663 /* Strip options. */
664 if ((optsep = strchr(*pdtok, ':')))
665 *optsep = '\0';
666 if (!(dec = srd_decoder_get_by_id(*pdtok))) {
667 g_critical("Protocol decoder %s not found.", *pdtok);
668 return;
669 }
670 printf("ID: %s\nName: %s\nLong name: %s\nDescription: %s\n",
671 dec->id, dec->name, dec->longname, dec->desc);
672 printf("License: %s\n", dec->license);
673 printf("Annotations:\n");
674 if (dec->annotations) {
675 for (l = dec->annotations; l; l = l->next) {
676 ann = l->data;
677 printf("- %s\n %s\n", ann[0], ann[1]);
678 }
679 } else {
680 printf("None.\n");
681 }
682 printf("Required probes:\n");
683 if (dec->probes) {
684 for (l = dec->probes; l; l = l->next) {
685 p = l->data;
686 printf("- %s (%s): %s\n",
687 p->name, p->id, p->desc);
688 }
689 } else {
690 printf("None.\n");
691 }
692 printf("Optional probes:\n");
693 if (dec->opt_probes) {
694 for (l = dec->opt_probes; l; l = l->next) {
695 p = l->data;
696 printf("- %s (%s): %s\n",
697 p->name, p->id, p->desc);
698 }
699 } else {
700 printf("None.\n");
701 }
702 if (dec->options) {
703 printf("Options:\n");
704 for (l = dec->options; l; l = l->next) {
705 o = l->data;
706 val = g_variant_print(o->def, FALSE);
707 printf("- %s: %s (default %s)\n", o->id, o->desc, val);
708 g_free(val);
709 }
710 }
711 if ((doc = srd_decoder_doc_get(dec))) {
712 printf("Documentation:\n%s\n",
713 doc[0] == '\n' ? doc + 1 : doc);
714 g_free(doc);
715 }
716 }
717
718 g_strfreev(pdtokens);
719}
720#endif
721
722static GArray *get_enabled_logic_probes(const struct sr_dev_inst *sdi)
723{
724 struct sr_probe *probe;
725 GArray *probes;
726 GSList *l;
727
728 probes = g_array_new(FALSE, FALSE, sizeof(int));
729 for (l = sdi->probes; l; l = l->next) {
730 probe = l->data;
731 if (probe->type != SR_PROBE_LOGIC)
732 continue;
733 if (probe->enabled != TRUE)
734 continue;
735 g_array_append_val(probes, probe->index);
736 }
737
738 return probes;
739}
740
741static void datafeed_in(const struct sr_dev_inst *sdi,
742 const struct sr_datafeed_packet *packet, void *cb_data)
743{
744 const struct sr_datafeed_meta *meta;
745 const struct sr_datafeed_logic *logic;
746 const struct sr_datafeed_analog *analog;
747 struct sr_config *src;
748 static struct sr_output *o = NULL;
749 static GArray *logic_probelist = NULL;
750 static uint64_t received_samples = 0;
751 static int unitsize = 0;
752 static int triggered = 0;
753 static FILE *outfile = NULL;
754 GSList *l;
755 GString *out;
756 int sample_size, ret;
757 uint64_t samplerate, output_len, filter_out_len, end_sample;
758 uint8_t *output_buf, *filter_out;
759
760 (void) cb_data;
761
762 /* If the first packet to come in isn't a header, don't even try. */
763 if (packet->type != SR_DF_HEADER && o == NULL)
764 return;
765
766 sample_size = -1;
767 switch (packet->type) {
768 case SR_DF_HEADER:
769 g_debug("cli: Received SR_DF_HEADER");
770 /* Initialize the output module. */
771 if (!(o = g_try_malloc(sizeof(struct sr_output)))) {
772 g_critical("Output module malloc failed.");
773 exit(1);
774 }
775 o->format = output_format;
776 o->sdi = (struct sr_dev_inst *)sdi;
777 o->param = output_format_param;
778 if (o->format->init) {
779 if (o->format->init(o) != SR_OK) {
780 g_critical("Output format initialization failed.");
781 exit(1);
782 }
783 }
784
785 /* Prepare non-stdout output. */
786 outfile = stdout;
787 if (opt_output_file) {
788 if (default_output_format) {
789 /* output file is in session format, so we'll
790 * keep a copy of everything as it comes in
791 * and save from there after the session. */
792 outfile = NULL;
793 savebuf = g_byte_array_new();
794 } else {
795 /* saving to a file in whatever format was set
796 * with --format, so all we need is a filehandle */
797 outfile = g_fopen(opt_output_file, "wb");
798 }
799 }
800
801 /* Prepare for logic data. */
802 logic_probelist = get_enabled_logic_probes(sdi);
803 /* How many bytes we need to store the packed samples. */
804 unitsize = (logic_probelist->len + 7) / 8;
805
806#ifdef HAVE_SRD
807 GVariant *gvar;
808 if (opt_pds && logic_probelist->len) {
809 if (sr_config_get(sdi->driver, sdi, NULL, SR_CONF_SAMPLERATE,
810 &gvar) == SR_OK) {
811 samplerate = g_variant_get_uint64(gvar);
812 g_variant_unref(gvar);
813 if (srd_session_metadata_set(srd_sess, SRD_CONF_SAMPLERATE,
814 g_variant_new_uint64(samplerate)) != SRD_OK) {
815 g_critical("Failed to configure decode session.");
816 break;
817 }
818 }
819 if (srd_session_start(srd_sess) != SRD_OK) {
820 g_critical("Failed to start decode session.");
821 break;
822 }
823 }
824#endif
825 break;
826
827 case SR_DF_META:
828 g_debug("cli: received SR_DF_META");
829 meta = packet->payload;
830 for (l = meta->config; l; l = l->next) {
831 src = l->data;
832 switch (src->key) {
833 case SR_CONF_SAMPLERATE:
834 samplerate = g_variant_get_uint64(src->data);
835 g_debug("cli: got samplerate %"PRIu64" Hz", samplerate);
836#ifdef HAVE_SRD
837 if (opt_pds) {
838 if (srd_session_metadata_set(srd_sess, SRD_CONF_SAMPLERATE,
839 g_variant_new_uint64(samplerate)) != SRD_OK) {
840 g_critical("Failed to pass samplerate to decoder.");
841 }
842 }
843#endif
844 break;
845 case SR_CONF_SAMPLE_INTERVAL:
846 samplerate = g_variant_get_uint64(src->data);
847 g_debug("cli: got sample interval %"PRIu64" ms", samplerate);
848 break;
849 default:
850 /* Unknown metadata is not an error. */
851 break;
852 }
853 }
854 break;
855
856 case SR_DF_TRIGGER:
857 g_debug("cli: received SR_DF_TRIGGER");
858 if (o->format->event)
859 o->format->event(o, SR_DF_TRIGGER, &output_buf,
860 &output_len);
861 triggered = 1;
862 break;
863
864 case SR_DF_LOGIC:
865 logic = packet->payload;
866 g_message("cli: received SR_DF_LOGIC, %"PRIu64" bytes", logic->length);
867 sample_size = logic->unitsize;
868 if (logic->length == 0)
869 break;
870
871 /* Don't store any samples until triggered. */
872 if (opt_wait_trigger && !triggered)
873 break;
874
875 if (limit_samples && received_samples >= limit_samples)
876 break;
877
878 ret = sr_filter_probes(sample_size, unitsize, logic_probelist,
879 logic->data, logic->length,
880 &filter_out, &filter_out_len);
881 if (ret != SR_OK)
882 break;
883
884 /*
885 * What comes out of the filter is guaranteed to be packed into the
886 * minimum size needed to support the number of samples at this sample
887 * size. however, the driver may have submitted too much. Cut off
888 * the buffer of the last packet according to the sample limit.
889 */
890 if (limit_samples && (received_samples + logic->length / sample_size >
891 limit_samples * sample_size))
892 filter_out_len = limit_samples * sample_size - received_samples;
893
894 if (opt_output_file && default_output_format) {
895 /* Saving to a session file. */
896 g_byte_array_append(savebuf, filter_out, filter_out_len);
897 } else {
898 if (opt_pds) {
899#ifdef HAVE_SRD
900 end_sample = received_samples + filter_out_len / unitsize;
901 if (srd_session_send(srd_sess, received_samples, end_sample,
902 (uint8_t*)filter_out, filter_out_len) != SRD_OK)
903 sr_session_stop();
904#endif
905 } else {
906 output_len = 0;
907 if (o->format->data && packet->type == o->format->df_type)
908 o->format->data(o, filter_out, filter_out_len,
909 &output_buf, &output_len);
910 if (output_len) {
911 fwrite(output_buf, 1, output_len, outfile);
912 fflush(outfile);
913 g_free(output_buf);
914 }
915 }
916 }
917 g_free(filter_out);
918
919 received_samples += logic->length / sample_size;
920 break;
921
922 case SR_DF_ANALOG:
923 analog = packet->payload;
924 g_message("cli: received SR_DF_ANALOG, %d samples", analog->num_samples);
925 if (analog->num_samples == 0)
926 break;
927
928 if (limit_samples && received_samples >= limit_samples)
929 break;
930
931 if (o->format->data && packet->type == o->format->df_type) {
932 o->format->data(o, (const uint8_t *)analog->data,
933 analog->num_samples * sizeof(float),
934 &output_buf, &output_len);
935 if (output_buf) {
936 fwrite(output_buf, 1, output_len, outfile);
937 fflush(outfile);
938 g_free(output_buf);
939 }
940 }
941
942 received_samples += analog->num_samples;
943 break;
944
945 case SR_DF_FRAME_BEGIN:
946 g_debug("cli: received SR_DF_FRAME_BEGIN");
947 if (o->format->event) {
948 o->format->event(o, SR_DF_FRAME_BEGIN, &output_buf,
949 &output_len);
950 if (output_buf) {
951 fwrite(output_buf, 1, output_len, outfile);
952 fflush(outfile);
953 g_free(output_buf);
954 }
955 }
956 break;
957
958 case SR_DF_FRAME_END:
959 g_debug("cli: received SR_DF_FRAME_END");
960 if (o->format->event) {
961 o->format->event(o, SR_DF_FRAME_END, &output_buf,
962 &output_len);
963 if (output_buf) {
964 fwrite(output_buf, 1, output_len, outfile);
965 fflush(outfile);
966 g_free(output_buf);
967 }
968 }
969 break;
970
971 default:
972 break;
973 }
974
975 if (o && o->format->receive) {
976 if (o->format->receive(o, sdi, packet, &out) == SR_OK && out) {
977 fwrite(out->str, 1, out->len, outfile);
978 fflush(outfile);
979 g_string_free(out, TRUE);
980 }
981 }
982
983 /* SR_DF_END needs to be handled after the output module's receive()
984 * is called, so it can properly clean up that module etc. */
985 if (packet->type == SR_DF_END) {
986 g_debug("cli: Received SR_DF_END");
987
988 if (o->format->event) {
989 o->format->event(o, SR_DF_END, &output_buf, &output_len);
990 if (output_buf) {
991 if (outfile)
992 fwrite(output_buf, 1, output_len, outfile);
993 g_free(output_buf);
994 output_len = 0;
995 }
996 }
997
998 if (limit_samples && received_samples < limit_samples)
999 g_warning("Device only sent %" PRIu64 " samples.",
1000 received_samples);
1001
1002 if (opt_continuous)
1003 g_warning("Device stopped after %" PRIu64 " samples.",
1004 received_samples);
1005
1006 g_array_free(logic_probelist, TRUE);
1007
1008 if (o->format->cleanup)
1009 o->format->cleanup(o);
1010 g_free(o);
1011 o = NULL;
1012
1013 if (outfile && outfile != stdout)
1014 fclose(outfile);
1015
1016 if (opt_output_file && default_output_format && savebuf->len) {
1017 if (sr_session_save(opt_output_file, sdi, savebuf->data,
1018 unitsize, savebuf->len / unitsize) != SR_OK)
1019 g_critical("Failed to save session.");
1020 g_byte_array_free(savebuf, FALSE);
1021 }
1022 }
1023
1024}
1025
1026#ifdef HAVE_SRD
1027static int opts_to_gvar(struct srd_decoder *dec, GHashTable *hash,
1028 GHashTable **options)
1029{
1030 struct srd_decoder_option *o;
1031 GSList *optl;
1032 GVariant *gvar;
1033 gint64 val_int;
1034 int ret;
1035 char *val_str, *conv;
1036
1037 ret = TRUE;
1038 *options = g_hash_table_new_full(g_str_hash, g_str_equal, g_free,
1039 (GDestroyNotify)g_variant_unref);
1040
1041 for (optl = dec->options; optl; optl = optl->next) {
1042 o = optl->data;
1043 if (!(val_str = g_hash_table_lookup(hash, o->id)))
1044 /* Not specified. */
1045 continue;
1046 if (g_variant_is_of_type(o->def, G_VARIANT_TYPE_STRING)) {
1047 gvar = g_variant_new_string(val_str);
1048 } else if (g_variant_is_of_type(o->def, G_VARIANT_TYPE_INT64)) {
1049 val_int = strtoll(val_str, &conv, 0);
1050 if (!conv || conv == val_str) {
1051 g_critical("Protocol decoder '%s' option '%s' "
1052 "requires a number.", dec->name, o->id);
1053 ret = FALSE;
1054 break;
1055 }
1056 gvar = g_variant_new_int64(val_int);
1057 } else {
1058 g_critical("Unsupported type for option '%s' (%s)",
1059 o->id, g_variant_get_type_string(o->def));
1060 ret = FALSE;
1061 break;
1062 }
1063 g_variant_ref_sink(gvar);
1064 g_hash_table_insert(*options, g_strdup(o->id), gvar);
1065 g_hash_table_remove(hash, o->id);
1066 }
1067
1068 return ret;
1069}
1070
1071static int probes_to_gvar(struct srd_decoder *dec, GHashTable *hash,
1072 GHashTable **probes)
1073{
1074 struct srd_probe *p;
1075 GSList *all_probes, *l;
1076 GVariant *gvar;
1077 gint32 val_int;
1078 int ret;
1079 char *val_str, *conv;
1080
1081 ret = TRUE;
1082 *probes = g_hash_table_new_full(g_str_hash, g_str_equal, g_free,
1083 (GDestroyNotify)g_variant_unref);
1084
1085 all_probes = g_slist_copy(dec->probes);
1086 all_probes = g_slist_concat(all_probes, g_slist_copy(dec->opt_probes));
1087 for (l = all_probes; l; l = l->next) {
1088 p = l->data;
1089 if (!(val_str = g_hash_table_lookup(hash, p->id)))
1090 /* Not specified. */
1091 continue;
1092 val_int = strtoll(val_str, &conv, 10);
1093 if (!conv || conv == val_str) {
1094 g_critical("Protocol decoder '%s' probes '%s' "
1095 "is not a number.", dec->name, p->id);
1096 ret = FALSE;
1097 break;
1098 }
1099 gvar = g_variant_new_int32(val_int);
1100 g_variant_ref_sink(gvar);
1101 g_hash_table_insert(*probes, g_strdup(p->id), gvar);
1102 g_hash_table_remove(hash, p->id);
1103 }
1104 g_slist_free(all_probes);
1105
1106 return ret;
1107}
1108
1109/* Register the given PDs for this session.
1110 * Accepts a string of the form: "spi:sck=3:sdata=4,spi:sck=3:sdata=5"
1111 * That will instantiate two SPI decoders on the clock but different data
1112 * lines.
1113 */
1114static int register_pds(struct sr_dev *dev, const char *pdstring)
1115{
1116 struct srd_decoder *dec;
1117 GHashTable *pd_opthash, *options, *probes;
1118 GList *leftover, *l;
1119 struct srd_decoder_inst *di;
1120 int ret;
1121 char **pdtokens, **pdtok, *pd_name;
1122
1123 (void)dev;
1124
1125 ret = 0;
1126 pd_ann_visible = g_hash_table_new_full(g_str_hash, g_int_equal,
1127 g_free, NULL);
1128 pd_name = NULL;
1129 pd_opthash = options = probes = NULL;
1130 pdtokens = g_strsplit(pdstring, ",", 0);
1131 for (pdtok = pdtokens; *pdtok; pdtok++) {
1132 if (!(pd_opthash = parse_generic_arg(*pdtok, TRUE))) {
1133 g_critical("Invalid protocol decoder option '%s'.", *pdtok);
1134 break;
1135 }
1136
1137 pd_name = g_strdup(g_hash_table_lookup(pd_opthash, "sigrok_key"));
1138 g_hash_table_remove(pd_opthash, "sigrok_key");
1139 if (srd_decoder_load(pd_name) != SRD_OK) {
1140 g_critical("Failed to load protocol decoder %s.", pd_name);
1141 ret = 1;
1142 break;
1143 }
1144 dec = srd_decoder_get_by_id(pd_name);
1145
1146 /* Convert decoder option and probe values to GVariant. */
1147 if (!opts_to_gvar(dec, pd_opthash, &options)) {
1148 ret = 1;
1149 break;
1150 }
1151 if (!probes_to_gvar(dec, pd_opthash, &probes)) {
1152 ret = 1;
1153 break;
1154 }
1155 if (g_hash_table_size(pd_opthash) > 0) {
1156 leftover = g_hash_table_get_keys(pd_opthash);
1157 for (l = leftover; l; l = l->next)
1158 g_critical("Unknown option or probe '%s'", (char *)l->data);
1159 g_list_free(leftover);
1160 break;
1161 }
1162
1163 if (!(di = srd_inst_new(srd_sess, pd_name, options))) {
1164 g_critical("Failed to instantiate protocol decoder %s.", pd_name);
1165 ret = 1;
1166 break;
1167 }
1168
1169 /* If no annotation list was specified, add them all in now.
1170 * This will be pared down later to leave only the last PD
1171 * in the stack.
1172 */
1173 if (!opt_pd_annotations)
1174 g_hash_table_insert(pd_ann_visible,
1175 g_strdup(di->inst_id), NULL);
1176
1177 /* Remap the probes if needed. */
1178 if (srd_inst_probe_set_all(di, probes) != SRD_OK) {
1179 ret = 1;
1180 break;
1181 }
1182 }
1183
1184 g_strfreev(pdtokens);
1185 if (pd_opthash)
1186 g_hash_table_destroy(pd_opthash);
1187 if (options)
1188 g_hash_table_destroy(options);
1189 if (probes)
1190 g_hash_table_destroy(probes);
1191 if (pd_name)
1192 g_free(pd_name);
1193
1194 return ret;
1195}
1196
1197int setup_pd_stack(void)
1198{
1199 struct srd_decoder_inst *di_from, *di_to;
1200 int ret, i;
1201 char **pds, **ids;
1202
1203 /* Set up the protocol decoder stack. */
1204 pds = g_strsplit(opt_pds, ",", 0);
1205 if (g_strv_length(pds) > 1) {
1206 if (opt_pd_stack) {
1207 /* A stack setup was specified, use that. */
1208 g_strfreev(pds);
1209 pds = g_strsplit(opt_pd_stack, ",", 0);
1210 if (g_strv_length(pds) < 2) {
1211 g_strfreev(pds);
1212 g_critical("Specify at least two protocol decoders to stack.");
1213 return 1;
1214 }
1215 }
1216
1217 /* First PD goes at the bottom of the stack. */
1218 ids = g_strsplit(pds[0], ":", 0);
1219 if (!(di_from = srd_inst_find_by_id(srd_sess, ids[0]))) {
1220 g_strfreev(ids);
1221 g_critical("Cannot stack protocol decoder '%s': "
1222 "instance not found.", pds[0]);
1223 return 1;
1224 }
1225 g_strfreev(ids);
1226
1227 /* Every subsequent PD goes on top. */
1228 for (i = 1; pds[i]; i++) {
1229 ids = g_strsplit(pds[i], ":", 0);
1230 if (!(di_to = srd_inst_find_by_id(srd_sess, ids[0]))) {
1231 g_strfreev(ids);
1232 g_critical("Cannot stack protocol decoder '%s': "
1233 "instance not found.", pds[i]);
1234 return 1;
1235 }
1236 g_strfreev(ids);
1237 if ((ret = srd_inst_stack(srd_sess, di_from, di_to)) != SRD_OK)
1238 return 1;
1239
1240 /* Don't show annotation from this PD. Only the last PD in
1241 * the stack will be left on the annotation list (unless
1242 * the annotation list was specifically provided).
1243 */
1244 if (!opt_pd_annotations)
1245 g_hash_table_remove(pd_ann_visible,
1246 di_from->inst_id);
1247
1248 di_from = di_to;
1249 }
1250 }
1251 g_strfreev(pds);
1252
1253 return 0;
1254}
1255
1256int setup_pd_annotations(void)
1257{
1258 GSList *l;
1259 struct srd_decoder *dec;
1260 int ann;
1261 char **pds, **pdtok, **keyval, **ann_descr;
1262
1263 /* Set up custom list of PDs and annotations to show. */
1264 if (opt_pd_annotations) {
1265 pds = g_strsplit(opt_pd_annotations, ",", 0);
1266 for (pdtok = pds; *pdtok && **pdtok; pdtok++) {
1267 ann = 0;
1268 keyval = g_strsplit(*pdtok, "=", 0);
1269 if (!(dec = srd_decoder_get_by_id(keyval[0]))) {
1270 g_critical("Protocol decoder '%s' not found.", keyval[0]);
1271 return 1;
1272 }
1273 if (!dec->annotations) {
1274 g_critical("Protocol decoder '%s' has no annotations.", keyval[0]);
1275 return 1;
1276 }
1277 if (g_strv_length(keyval) == 2) {
1278 for (l = dec->annotations; l; l = l->next, ann++) {
1279 ann_descr = l->data;
1280 if (!canon_cmp(ann_descr[0], keyval[1]))
1281 /* Found it. */
1282 break;
1283 }
1284 if (!l) {
1285 g_critical("Annotation '%s' not found "
1286 "for protocol decoder '%s'.", keyval[1], keyval[0]);
1287 return 1;
1288 }
1289 }
1290 g_debug("cli: showing protocol decoder annotation %d from '%s'", ann, keyval[0]);
1291 g_hash_table_insert(pd_ann_visible, g_strdup(keyval[0]), GINT_TO_POINTER(ann));
1292 g_strfreev(keyval);
1293 }
1294 g_strfreev(pds);
1295 }
1296
1297 return 0;
1298}
1299
1300void show_pd_annotations(struct srd_proto_data *pdata, void *cb_data)
1301{
1302 struct srd_proto_data_annotation *pda;
1303 gpointer ann_format;
1304 int i;
1305
1306 /* 'cb_data' is not used in this specific callback. */
1307 (void)cb_data;
1308
1309 if (!pd_ann_visible)
1310 return;
1311
1312 if (!g_hash_table_lookup_extended(pd_ann_visible, pdata->pdo->di->inst_id,
1313 NULL, &ann_format))
1314 /* Not in the list of PDs whose annotations we're showing. */
1315 return;
1316
1317 pda = pdata->data;
1318 if (pda->ann_format != GPOINTER_TO_INT(ann_format))
1319 /* We don't want this particular format from the PD. */
1320 return;
1321
1322 if (opt_loglevel > SR_LOG_WARN)
1323 printf("%"PRIu64"-%"PRIu64" ", pdata->start_sample, pdata->end_sample);
1324 printf("%s: ", pdata->pdo->proto_id);
1325 for (i = 0; pda->ann_text[i]; i++)
1326 printf("\"%s\" ", pda->ann_text[i]);
1327 printf("\n");
1328 fflush(stdout);
1329}
1330#endif
1331
1332int setup_output_format(void)
1333{
1334 GHashTable *fmtargs;
1335 GHashTableIter iter;
1336 gpointer key, value;
1337 struct sr_output_format **outputs;
1338 int i;
1339 char *fmtspec;
1340
1341 if (opt_output_format && !strcmp(opt_output_format, "sigrok")) {
1342 /* Doesn't really exist as an output module - this is
1343 * the session save mode. */
1344 g_free(opt_output_format);
1345 opt_output_format = NULL;
1346 }
1347
1348 if (!opt_output_format) {
1349 opt_output_format = DEFAULT_OUTPUT_FORMAT;
1350 /* we'll need to remember this so when saving to a file
1351 * later, sigrok session format will be used.
1352 */
1353 default_output_format = TRUE;
1354 }
1355
1356 fmtargs = parse_generic_arg(opt_output_format, TRUE);
1357 fmtspec = g_hash_table_lookup(fmtargs, "sigrok_key");
1358 if (!fmtspec) {
1359 g_critical("Invalid output format.");
1360 return 1;
1361 }
1362 outputs = sr_output_list();
1363 for (i = 0; outputs[i]; i++) {
1364 if (strcmp(outputs[i]->id, fmtspec))
1365 continue;
1366 g_hash_table_remove(fmtargs, "sigrok_key");
1367 output_format = outputs[i];
1368 g_hash_table_iter_init(&iter, fmtargs);
1369 while (g_hash_table_iter_next(&iter, &key, &value)) {
1370 /* only supporting one parameter per output module
1371 * for now, and only its value */
1372 output_format_param = g_strdup(value);
1373 break;
1374 }
1375 break;
1376 }
1377 if (!output_format) {
1378 g_critical("Invalid output format %s.", opt_output_format);
1379 return 1;
1380 }
1381 g_hash_table_destroy(fmtargs);
1382
1383 return 0;
1384}
1385
1386static int select_probes(struct sr_dev_inst *sdi)
1387{
1388 struct sr_probe *probe;
1389 GSList *selected_probes, *l;
1390
1391 if (!opt_probes)
1392 return SR_OK;
1393
1394 if (!(selected_probes = parse_probestring(sdi, opt_probes)))
1395 return SR_ERR;
1396
1397 for (l = sdi->probes; l; l = l->next) {
1398 probe = l->data;
1399 if (g_slist_find(selected_probes, probe))
1400 probe->enabled = TRUE;
1401 else
1402 probe->enabled = FALSE;
1403 }
1404 g_slist_free(selected_probes);
1405
1406 return SR_OK;
1407}
1408
1409/**
1410 * Return the input file format which the CLI tool should use.
1411 *
1412 * If the user specified -I / --input-format, use that one. Otherwise, try to
1413 * autodetect the format as good as possible. Failing that, return NULL.
1414 *
1415 * @param filename The filename of the input file. Must not be NULL.
1416 * @param opt The -I / --input-file option the user specified (or NULL).
1417 *
1418 * @return A pointer to the 'struct sr_input_format' that should be used,
1419 * or NULL if no input format was selected or auto-detected.
1420 */
1421static struct sr_input_format *determine_input_file_format(
1422 const char *filename, const char *opt)
1423{
1424 int i;
1425 struct sr_input_format **inputs;
1426
1427 /* If there are no input formats, return NULL right away. */
1428 inputs = sr_input_list();
1429 if (!inputs) {
1430 g_critical("No supported input formats available.");
1431 return NULL;
1432 }
1433
1434 /* If the user specified -I / --input-format, use that one. */
1435 if (opt) {
1436 for (i = 0; inputs[i]; i++) {
1437 if (strcasecmp(inputs[i]->id, opt))
1438 continue;
1439 g_debug("Using user-specified input file format '%s'.",
1440 inputs[i]->id);
1441 return inputs[i];
1442 }
1443
1444 /* The user specified an unknown input format, return NULL. */
1445 g_critical("Error: specified input file format '%s' is "
1446 "unknown.", opt);
1447 return NULL;
1448 }
1449
1450 /* Otherwise, try to find an input module that can handle this file. */
1451 for (i = 0; inputs[i]; i++) {
1452 if (inputs[i]->format_match(filename))
1453 break;
1454 }
1455
1456 /* Return NULL if no input module wanted to touch this. */
1457 if (!inputs[i]) {
1458 g_critical("Error: no matching input module found.");
1459 return NULL;
1460 }
1461
1462 g_debug("cli: Autodetected '%s' input format for file '%s'.",
1463 inputs[i]->id, filename);
1464
1465 return inputs[i];
1466}
1467
1468static void load_input_file_format(void)
1469{
1470 GHashTable *fmtargs = NULL;
1471 struct stat st;
1472 struct sr_input *in;
1473 struct sr_input_format *input_format;
1474 char *fmtspec = NULL;
1475
1476 if (opt_input_format) {
1477 fmtargs = parse_generic_arg(opt_input_format, TRUE);
1478 fmtspec = g_hash_table_lookup(fmtargs, "sigrok_key");
1479 }
1480
1481 if (!(input_format = determine_input_file_format(opt_input_file,
1482 fmtspec))) {
1483 /* The exact cause was already logged. */
1484 return;
1485 }
1486
1487 if (fmtargs)
1488 g_hash_table_remove(fmtargs, "sigrok_key");
1489
1490 if (stat(opt_input_file, &st) == -1) {
1491 g_critical("Failed to load %s: %s", opt_input_file,
1492 strerror(errno));
1493 exit(1);
1494 }
1495
1496 /* Initialize the input module. */
1497 if (!(in = g_try_malloc(sizeof(struct sr_input)))) {
1498 g_critical("Failed to allocate input module.");
1499 exit(1);
1500 }
1501 in->format = input_format;
1502 in->param = fmtargs;
1503 if (in->format->init) {
1504 if (in->format->init(in, opt_input_file) != SR_OK) {
1505 g_critical("Input format init failed.");
1506 exit(1);
1507 }
1508 }
1509
1510 if (select_probes(in->sdi) > 0)
1511 return;
1512
1513 sr_session_new();
1514 sr_session_datafeed_callback_add(datafeed_in, NULL);
1515 if (sr_session_dev_add(in->sdi) != SR_OK) {
1516 g_critical("Failed to use device.");
1517 sr_session_destroy();
1518 return;
1519 }
1520
1521 input_format->loadfile(in, opt_input_file);
1522
1523 sr_session_destroy();
1524
1525 if (fmtargs)
1526 g_hash_table_destroy(fmtargs);
1527}
1528
1529static void load_input_file(void)
1530{
1531
1532 if (sr_session_load(opt_input_file) == SR_OK) {
1533 /* sigrok session file */
1534 sr_session_datafeed_callback_add(datafeed_in, NULL);
1535 sr_session_start();
1536 sr_session_run();
1537 sr_session_stop();
1538 }
1539 else {
1540 /* fall back on input modules */
1541 load_input_file_format();
1542 }
1543}
1544
1545static int set_dev_options(struct sr_dev_inst *sdi, GHashTable *args)
1546{
1547 const struct sr_config_info *srci;
1548 struct sr_probe_group *pg;
1549 GHashTableIter iter;
1550 gpointer key, value;
1551 int ret;
1552 double tmp_double;
1553 uint64_t tmp_u64, p, q, low, high;
1554 gboolean tmp_bool;
1555 GVariant *val, *rational[2], *range[2];
1556
1557 g_hash_table_iter_init(&iter, args);
1558 while (g_hash_table_iter_next(&iter, &key, &value)) {
1559 if (!(srci = sr_config_info_name_get(key))) {
1560 g_critical("Unknown device option '%s'.", (char *) key);
1561 return SR_ERR;
1562 }
1563
1564 if ((value == NULL) &&
1565 (srci->datatype != SR_T_BOOL)) {
1566 g_critical("Option '%s' needs a value.", (char *)key);
1567 return SR_ERR;
1568 }
1569 val = NULL;
1570 switch (srci->datatype) {
1571 case SR_T_UINT64:
1572 ret = sr_parse_sizestring(value, &tmp_u64);
1573 if (ret != SR_OK)
1574 break;
1575 val = g_variant_new_uint64(tmp_u64);
1576 break;
1577 case SR_T_CHAR:
1578 val = g_variant_new_string(value);
1579 break;
1580 case SR_T_BOOL:
1581 if (!value)
1582 tmp_bool = TRUE;
1583 else
1584 tmp_bool = sr_parse_boolstring(value);
1585 val = g_variant_new_boolean(tmp_bool);
1586 break;
1587 case SR_T_FLOAT:
1588 tmp_double = strtof(value, NULL);
1589 val = g_variant_new_double(tmp_double);
1590 break;
1591 case SR_T_RATIONAL_PERIOD:
1592 if ((ret = sr_parse_period(value, &p, &q)) != SR_OK)
1593 break;
1594 rational[0] = g_variant_new_uint64(p);
1595 rational[1] = g_variant_new_uint64(q);
1596 val = g_variant_new_tuple(rational, 2);
1597 break;
1598 case SR_T_RATIONAL_VOLT:
1599 if ((ret = sr_parse_voltage(value, &p, &q)) != SR_OK)
1600 break;
1601 rational[0] = g_variant_new_uint64(p);
1602 rational[1] = g_variant_new_uint64(q);
1603 val = g_variant_new_tuple(rational, 2);
1604 break;
1605 case SR_T_UINT64_RANGE:
1606 if (sscanf(value, "%"PRIu64"-%"PRIu64, &low, &high) != 2) {
1607 ret = SR_ERR;
1608 break;
1609 } else {
1610 range[0] = g_variant_new_uint64(low);
1611 range[1] = g_variant_new_uint64(high);
1612 val = g_variant_new_tuple(range, 2);
1613 }
1614 break;
1615 default:
1616 ret = SR_ERR;
1617 }
1618 if (val) {
1619 pg = select_probe_group(sdi);
1620 ret = sr_config_set(sdi, pg, srci->key, val);
1621 }
1622 if (ret != SR_OK) {
1623 g_critical("Failed to set device option '%s'.", (char *)key);
1624 return ret;
1625 }
1626 }
1627
1628 return SR_OK;
1629}
1630
1631static void set_options(void)
1632{
1633 struct sr_dev_inst *sdi;
1634 GSList *devices;
1635 GHashTable *devargs;
1636
1637 if (!opt_config) {
1638 g_critical("No setting specified.");
1639 return;
1640 }
1641
1642 if (!(devargs = parse_generic_arg(opt_config, FALSE)))
1643 return;
1644
1645 if (!(devices = device_scan())) {
1646 g_critical("No devices found.");
1647 return;
1648 }
1649 sdi = devices->data;
1650
1651 if (sr_dev_open(sdi) != SR_OK) {
1652 g_critical("Failed to open device.");
1653 return;
1654 }
1655
1656 set_dev_options(sdi, devargs);
1657
1658 sr_dev_close(sdi);
1659 g_slist_free(devices);
1660 g_hash_table_destroy(devargs);
1661
1662}
1663
1664static int set_limit_time(const struct sr_dev_inst *sdi)
1665{
1666 GVariant *gvar;
1667 uint64_t time_msec;
1668 uint64_t samplerate;
1669
1670 if (!(time_msec = sr_parse_timestring(opt_time))) {
1671 g_critical("Invalid time '%s'", opt_time);
1672 return SR_ERR;
1673 }
1674
1675 if (sr_dev_has_option(sdi, SR_CONF_LIMIT_MSEC)) {
1676 gvar = g_variant_new_uint64(time_msec);
1677 if (sr_config_set(sdi, NULL, SR_CONF_LIMIT_MSEC, gvar) != SR_OK) {
1678 g_critical("Failed to configure time limit.");
1679 return SR_ERR;
1680 }
1681 } else if (sr_dev_has_option(sdi, SR_CONF_SAMPLERATE)) {
1682 /* Convert to samples based on the samplerate. */
1683 sr_config_get(sdi->driver, sdi, NULL, SR_CONF_SAMPLERATE, &gvar);
1684 samplerate = g_variant_get_uint64(gvar);
1685 g_variant_unref(gvar);
1686 limit_samples = (samplerate) * time_msec / (uint64_t)1000;
1687 if (limit_samples == 0) {
1688 g_critical("Not enough time at this samplerate.");
1689 return SR_ERR;
1690 }
1691 gvar = g_variant_new_uint64(limit_samples);
1692 if (sr_config_set(sdi, NULL, SR_CONF_LIMIT_SAMPLES, gvar) != SR_OK) {
1693 g_critical("Failed to configure time-based sample limit.");
1694 return SR_ERR;
1695 }
1696 } else {
1697 g_critical("This device does not support time limits.");
1698 return SR_ERR;
1699 }
1700
1701 return SR_OK;
1702}
1703
1704static void run_session(void)
1705{
1706 GSList *devices;
1707 GHashTable *devargs;
1708 GVariant *gvar;
1709 struct sr_dev_inst *sdi;
1710 int max_probes, i;
1711 char **triggerlist;
1712
1713 devices = device_scan();
1714 if (!devices) {
1715 g_critical("No devices found.");
1716 return;
1717 }
1718 if (g_slist_length(devices) > 1) {
1719 g_critical("sigrok-cli only supports one device for capturing.");
1720 return;
1721 }
1722 sdi = devices->data;
1723
1724 sr_session_new();
1725 sr_session_datafeed_callback_add(datafeed_in, NULL);
1726
1727 if (sr_dev_open(sdi) != SR_OK) {
1728 g_critical("Failed to open device.");
1729 return;
1730 }
1731
1732 if (sr_session_dev_add(sdi) != SR_OK) {
1733 g_critical("Failed to add device to session.");
1734 sr_session_destroy();
1735 return;
1736 }
1737
1738 if (opt_config) {
1739 if ((devargs = parse_generic_arg(opt_config, FALSE))) {
1740 if (set_dev_options(sdi, devargs) != SR_OK)
1741 return;
1742 g_hash_table_destroy(devargs);
1743 }
1744 }
1745
1746 if (select_probes(sdi) != SR_OK) {
1747 g_critical("Failed to set probes.");
1748 sr_session_destroy();
1749 return;
1750 }
1751
1752 if (opt_triggers) {
1753 if (!(triggerlist = sr_parse_triggerstring(sdi, opt_triggers))) {
1754 sr_session_destroy();
1755 return;
1756 }
1757 max_probes = g_slist_length(sdi->probes);
1758 for (i = 0; i < max_probes; i++) {
1759 if (triggerlist[i]) {
1760 sr_dev_trigger_set(sdi, i, triggerlist[i]);
1761 g_free(triggerlist[i]);
1762 }
1763 }
1764 g_free(triggerlist);
1765 }
1766
1767 if (opt_continuous) {
1768 if (!sr_dev_has_option(sdi, SR_CONF_CONTINUOUS)) {
1769 g_critical("This device does not support continuous sampling.");
1770 sr_session_destroy();
1771 return;
1772 }
1773 }
1774
1775 if (opt_time) {
1776 if (set_limit_time(sdi) != SR_OK) {
1777 sr_session_destroy();
1778 return;
1779 }
1780 }
1781
1782 if (opt_samples) {
1783 if ((sr_parse_sizestring(opt_samples, &limit_samples) != SR_OK)) {
1784 g_critical("Invalid sample limit '%s'.", opt_samples);
1785 sr_session_destroy();
1786 return;
1787 }
1788 gvar = g_variant_new_uint64(limit_samples);
1789 if (sr_config_set(sdi, NULL, SR_CONF_LIMIT_SAMPLES, gvar) != SR_OK) {
1790 g_critical("Failed to configure sample limit.");
1791 sr_session_destroy();
1792 return;
1793 }
1794 }
1795
1796 if (opt_frames) {
1797 if ((sr_parse_sizestring(opt_frames, &limit_frames) != SR_OK)) {
1798 g_critical("Invalid sample limit '%s'.", opt_samples);
1799 sr_session_destroy();
1800 return;
1801 }
1802 gvar = g_variant_new_uint64(limit_frames);
1803 if (sr_config_set(sdi, NULL, SR_CONF_LIMIT_FRAMES, gvar) != SR_OK) {
1804 g_critical("Failed to configure frame limit.");
1805 sr_session_destroy();
1806 return;
1807 }
1808 }
1809
1810 if (sr_session_start() != SR_OK) {
1811 g_critical("Failed to start session.");
1812 sr_session_destroy();
1813 return;
1814 }
1815
1816 if (opt_continuous)
1817 add_anykey();
1818
1819 sr_session_run();
1820
1821 if (opt_continuous)
1822 clear_anykey();
1823
1824 sr_session_datafeed_callback_remove_all();
1825 sr_session_destroy();
1826 g_slist_free(devices);
1827
1828}
1829
1830static void logger(const gchar *log_domain, GLogLevelFlags log_level,
1831 const gchar *message, gpointer cb_data)
1832{
1833 (void)log_domain;
1834 (void)cb_data;
1835
1836 /*
1837 * All messages, warnings, errors etc. go to stderr (not stdout) in
1838 * order to not mess up the CLI tool data output, e.g. VCD output.
1839 */
1840 if (log_level & (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING)
1841 || opt_loglevel > SR_LOG_WARN) {
1842 fprintf(stderr, "%s\n", message);
1843 fflush(stderr);
1844 }
1845
1846 if (log_level & (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL))
1847 exit(1);
1848
1849}
1850
1851int main(int argc, char **argv)
1852{
1853 GOptionContext *context;
1854 GError *error;
1855 int ret;
1856 char *help;
1857
1858 g_log_set_default_handler(logger, NULL);
1859
1860 context = g_option_context_new(NULL);
1861 g_option_context_add_main_entries(context, optargs, NULL);
1862
1863 ret = 1;
1864 error = NULL;
1865 if (!g_option_context_parse(context, &argc, &argv, &error)) {
1866 g_critical("%s", error->message);
1867 goto done;
1868 }
1869
1870 /* Set the loglevel (amount of messages to output) for libsigrok. */
1871 if (sr_log_loglevel_set(opt_loglevel) != SR_OK)
1872 goto done;
1873
1874 if (sr_init(&sr_ctx) != SR_OK)
1875 goto done;
1876
1877#ifdef HAVE_SRD
1878 /* Set the loglevel (amount of messages to output) for libsigrokdecode. */
1879 if (srd_log_loglevel_set(opt_loglevel) != SRD_OK)
1880 goto done;
1881
1882 if (opt_pds) {
1883 if (srd_init(NULL) != SRD_OK)
1884 goto done;
1885 if (srd_session_new(&srd_sess) != SRD_OK) {
1886 g_critical("Failed to create new decode session.");
1887 goto done;
1888 }
1889 if (register_pds(NULL, opt_pds) != 0)
1890 goto done;
1891 if (srd_pd_output_callback_add(srd_sess, SRD_OUTPUT_ANN,
1892 show_pd_annotations, NULL) != SRD_OK)
1893 goto done;
1894 if (setup_pd_stack() != 0)
1895 goto done;
1896 if (setup_pd_annotations() != 0)
1897 goto done;
1898 }
1899#endif
1900
1901 if (setup_output_format() != 0)
1902 goto done;
1903
1904 if (opt_version)
1905 show_version();
1906 else if (opt_scan_devs)
1907 show_dev_list();
1908#ifdef HAVE_SRD
1909 else if (opt_pds && opt_show)
1910 show_pd_detail();
1911#endif
1912 else if (opt_show)
1913 show_dev_detail();
1914 else if (opt_input_file)
1915 load_input_file();
1916 else if (opt_set)
1917 set_options();
1918 else if (opt_samples || opt_time || opt_frames || opt_continuous)
1919 run_session();
1920 else {
1921 help = g_option_context_get_help(context, TRUE, NULL);
1922 printf("%s", help);
1923 g_free(help);
1924 }
1925
1926#ifdef HAVE_SRD
1927 if (opt_pds)
1928 srd_exit();
1929#endif
1930
1931 ret = 0;
1932
1933done:
1934 if (sr_ctx)
1935 sr_exit(sr_ctx);
1936
1937 g_option_context_free(context);
1938
1939 return ret;
1940}