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