]> sigrok.org Git - sigrok-cli.git/blame - sigrok-cli.c
Show only the longest PD annotation.
[sigrok-cli.git] / sigrok-cli.c
CommitLineData
43e5747a 1/*
630293b4 2 * This file is part of the sigrok-cli project.
43e5747a 3 *
110aa72a 4 * Copyright (C) 2012 Bert Vermeulen <bert@biot.com>
43e5747a
UH
5 *
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 */
19
de0a066e
BV
20#include "config.h"
21#ifdef HAVE_SRD
efdb6a22 22#include <libsigrokdecode/libsigrokdecode.h> /* First, so we avoid a _POSIX_C_SOURCE warning. */
de0a066e 23#endif
43e5747a
UH
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>
60ea8937 36#include <libsigrok/libsigrok.h>
43e5747a 37#include "sigrok-cli.h"
43e5747a
UH
38
39#define DEFAULT_OUTPUT_FORMAT "bits:width=64"
40
e2fe62cc
PS
41static struct sr_context *sr_ctx = NULL;
42
1999ae06 43static uint64_t limit_samples = 0;
ce48d892 44static uint64_t limit_frames = 0;
1999ae06
UH
45static struct sr_output_format *output_format = NULL;
46static int default_output_format = FALSE;
47static char *output_format_param = NULL;
de0a066e 48#ifdef HAVE_SRD
a0e36511 49static struct srd_session *srd_sess = NULL;
120f9ee7 50static GHashTable *pd_ann_visible = NULL;
f1c146f0 51static GHashTable *pd_meta_visible = NULL;
de0a066e 52#endif
c27450ea 53static GByteArray *savebuf;
43e5747a
UH
54
55static gboolean opt_version = FALSE;
56static gint opt_loglevel = SR_LOG_WARN; /* Show errors+warnings per default. */
ea7741ee 57static gboolean opt_scan_devs = FALSE;
43e5747a
UH
58static gboolean opt_wait_trigger = FALSE;
59static gchar *opt_input_file = NULL;
60static gchar *opt_output_file = NULL;
9e2e414f 61static gchar *opt_drv = NULL;
ea7741ee 62static gchar *opt_config = NULL;
43e5747a 63static gchar *opt_probes = NULL;
dd671ce7 64static gchar *opt_probe_group = NULL;
43e5747a
UH
65static gchar *opt_triggers = NULL;
66static gchar *opt_pds = NULL;
de0a066e 67#ifdef HAVE_SRD
9f4a898e 68static gchar *opt_pd_stack = NULL;
b6bd032d 69static gchar *opt_pd_annotations = NULL;
f1c146f0 70static gchar *opt_pd_meta = NULL;
de0a066e 71#endif
43e5747a 72static gchar *opt_input_format = NULL;
76ae913d 73static gchar *opt_output_format = NULL;
22981b2c 74static gchar *opt_show = NULL;
43e5747a
UH
75static gchar *opt_time = NULL;
76static gchar *opt_samples = NULL;
ce48d892 77static gchar *opt_frames = NULL;
43e5747a 78static gchar *opt_continuous = NULL;
2d73284e 79static gchar *opt_set = NULL;
43e5747a
UH
80
81static GOptionEntry optargs[] = {
03996962
BV
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,
ea7741ee
BV
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},
03996962
BV
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},
dd671ce7
BV
100 {"probe-group", 'g', 0, G_OPTION_ARG_STRING, &opt_probe_group,
101 "Probe groups", NULL},
03996962
BV
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},
de0a066e 106#ifdef HAVE_SRD
ea7741ee 107 {"protocol-decoders", 'P', 0, G_OPTION_ARG_STRING, &opt_pds,
03996962 108 "Protocol decoders to run", NULL},
ea7741ee 109 {"protocol-decoder-stack", 'S', 0, G_OPTION_ARG_STRING, &opt_pd_stack,
03996962 110 "Protocol decoder stack", NULL},
b6bd032d
UH
111 {"protocol-decoder-annotations", 'A', 0, G_OPTION_ARG_STRING, &opt_pd_annotations,
112 "Protocol decoder annotation(s) to show", NULL},
f1c146f0
BV
113 {"protocol-decoder-meta", 'M', 0, G_OPTION_ARG_STRING, &opt_pd_meta,
114 "Protocol decoder meta output to show", NULL},
de0a066e 115#endif
ea7741ee
BV
116 {"scan", 0, 0, G_OPTION_ARG_NONE, &opt_scan_devs,
117 "Scan for devices", NULL},
22981b2c
BV
118 {"show", 0, 0, G_OPTION_ARG_NONE, &opt_show,
119 "Show device detail", NULL},
03996962
BV
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},
ce48d892
BV
124 {"frames", 0, 0, G_OPTION_ARG_STRING, &opt_frames,
125 "Number of frames to acquire", NULL},
03996962
BV
126 {"continuous", 0, 0, G_OPTION_ARG_NONE, &opt_continuous,
127 "Sample continuously", NULL},
2d73284e 128 {"set", 0, 0, G_OPTION_ARG_NONE, &opt_set, "Set device options only", NULL},
43e5747a
UH
129 {NULL, 0, 0, 0, NULL, NULL, NULL}
130};
131
9e2e414f 132
995713f4 133/* Convert driver options hash to GSList of struct sr_config. */
9e2e414f
BV
134static GSList *hash_to_hwopt(GHashTable *hash)
135{
995713f4
BV
136 const struct sr_config_info *srci;
137 struct sr_config *src;
9e2e414f
BV
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;
74b9bf0c 146 if (!(srci = sr_config_info_name_get(key))) {
9e2e414f
BV
147 g_critical("Unknown option %s", key);
148 return NULL;
149 }
995713f4
BV
150 src = g_try_malloc(sizeof(struct sr_config));
151 src->key = srci->key;
cfd3ec6e 152 value = g_hash_table_lookup(hash, key);
1616f663 153 src->data = g_variant_new_string(value);
995713f4 154 opts = g_slist_append(opts, src);
9e2e414f
BV
155 }
156 g_list_free(keys);
157
158 return opts;
159}
160
9d47bc56
BV
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
995713f4 184static void free_drvopts(struct sr_config *src)
a2853311 185{
1616f663 186 g_variant_unref(src->data);
995713f4 187 g_free(src);
a2853311
AG
188}
189
9e2e414f
BV
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);
49dbdb78
DJ
211 g_hash_table_destroy(drvargs);
212 g_free(drvname);
9e2e414f
BV
213 return NULL;
214 }
215 g_free(drvname);
e2fe62cc 216 if (sr_driver_init(sr_ctx, driver) != SR_OK) {
9e2e414f 217 g_critical("Failed to initialize driver.");
49dbdb78 218 g_hash_table_destroy(drvargs);
9e2e414f
BV
219 return NULL;
220 }
221 drvopts = NULL;
17982bc9
BV
222 if (g_hash_table_size(drvargs) > 0) {
223 if (!(drvopts = hash_to_hwopt(drvargs))) {
9e2e414f 224 /* Unknown options, already logged. */
17982bc9 225 g_hash_table_destroy(drvargs);
9e2e414f 226 return NULL;
17982bc9
BV
227 }
228 }
49dbdb78 229 g_hash_table_destroy(drvargs);
9e2e414f 230 devices = sr_driver_scan(driver, drvopts);
995713f4 231 g_slist_free_full(drvopts, (GDestroyNotify)free_drvopts);
9e2e414f
BV
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];
e2fe62cc 238 if (sr_driver_init(sr_ctx, driver) != SR_OK) {
9e2e414f
BV
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
43e5747a
UH
252static void show_version(void)
253{
a210c4cc 254 struct sr_dev_driver **drivers;
43e5747a
UH
255 struct sr_input_format **inputs;
256 struct sr_output_format **outputs;
43e5747a 257 int i;
de0a066e
BV
258#ifdef HAVE_SRD
259 struct srd_decoder *dec;
260 const GSList *l;
261#endif
43e5747a
UH
262
263 printf("sigrok-cli %s\n\n", VERSION);
15d920a9 264
4d167240
UH
265 printf("Using libsigrok %s (lib version %s).\n",
266 sr_package_version_string_get(), sr_lib_version_string_get());
de0a066e 267#ifdef HAVE_SRD
4d167240
UH
268 printf("Using libsigrokdecode %s (lib version %s).\n\n",
269 srd_package_version_string_get(), srd_lib_version_string_get());
de0a066e 270#endif
4d167240 271
43e5747a 272 printf("Supported hardware drivers:\n");
a214a2eb 273 drivers = sr_driver_list();
a210c4cc
UH
274 for (i = 0; drivers[i]; i++) {
275 printf(" %-20s %s\n", drivers[i]->name, drivers[i]->longname);
43e5747a
UH
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);
c25c8e45 289 printf(" %-20s %s\n", "sigrok", "Default file output format");
43e5747a
UH
290 printf("\n");
291
de0a066e 292#ifdef HAVE_SRD
15d920a9
BV
293 if (srd_init(NULL) == SRD_OK) {
294 printf("Supported protocol decoders:\n");
1b34803d
UH
295 srd_decoder_load_all();
296 for (l = srd_decoder_list(); l; l = l->next) {
15d920a9
BV
297 dec = l->data;
298 printf(" %-20s %s\n", dec->id, dec->longname);
20622036
UH
299 /* Print protocol description upon "-l 3" or higher. */
300 if (opt_loglevel >= SR_LOG_INFO)
301 printf(" %-20s %s\n", "", dec->desc);
15d920a9
BV
302 }
303 srd_exit();
43e5747a
UH
304 }
305 printf("\n");
de0a066e 306#endif
43e5747a
UH
307}
308
22981b2c 309static void print_dev_line(const struct sr_dev_inst *sdi)
43e5747a 310{
11b62b6f
BV
311 struct sr_probe *probe;
312 GSList *l;
fe6970ec
BV
313 GString *s;
314 GVariant *gvar;
43e5747a 315
fe6970ec
BV
316 s = g_string_sized_new(128);
317 g_string_assign(s, sdi->driver->name);
3f2d32a4 318 if (sr_config_get(sdi->driver, sdi, NULL, SR_CONF_CONN, &gvar) == SR_OK) {
fe6970ec
BV
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, " - ");
43e5747a 324 if (sdi->vendor && sdi->vendor[0])
fe6970ec 325 g_string_append_printf(s, "%s ", sdi->vendor);
43e5747a 326 if (sdi->model && sdi->model[0])
fe6970ec 327 g_string_append_printf(s, "%s ", sdi->model);
43e5747a 328 if (sdi->version && sdi->version[0])
fe6970ec 329 g_string_append_printf(s, "%s ", sdi->version);
11b62b6f
BV
330 if (sdi->probes) {
331 if (g_slist_length(sdi->probes) == 1) {
332 probe = sdi->probes->data;
fe6970ec 333 g_string_append_printf(s, "with 1 probe: %s", probe->name);
11b62b6f 334 } else {
fe6970ec 335 g_string_append_printf(s, "with %d probes:", g_slist_length(sdi->probes));
11b62b6f
BV
336 for (l = sdi->probes; l; l = l->next) {
337 probe = l->data;
fe6970ec 338 g_string_append_printf(s, " %s", probe->name);
11b62b6f
BV
339 }
340 }
4d326ca1 341 }
fe6970ec
BV
342 g_string_append_printf(s, "\n");
343 printf("%s", s->str);
344 g_string_free(s, TRUE);
345
43e5747a
UH
346}
347
1e0f9ed9 348static void show_dev_list(void)
43e5747a 349{
22981b2c
BV
350 struct sr_dev_inst *sdi;
351 GSList *devices, *l;
43e5747a 352
22981b2c 353 if (!(devices = device_scan()))
43e5747a
UH
354 return;
355
22981b2c
BV
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);
43e5747a 360 }
22981b2c
BV
361 g_slist_free(devices);
362
43e5747a
UH
363}
364
1e0f9ed9 365static void show_dev_detail(void)
43e5747a 366{
22981b2c 367 struct sr_dev_inst *sdi;
995713f4 368 const struct sr_config_info *srci;
96e0e450 369 struct sr_probe *probe;
9d47bc56 370 struct sr_probe_group *probe_group, *pg;
96e0e450 371 GSList *devices, *pgl, *prl;
1616f663
BV
372 GVariant *gvar_opts, *gvar_dict, *gvar_list, *gvar;
373 gsize num_opts, num_elements;
43d3d80b
BV
374 const uint64_t *uint64, p, q, low, high;
375 uint64_t cur_low, cur_high;
e07340ad 376 const int32_t *opts;
43d3d80b
BV
377 unsigned int num_devices, o, i;
378 char *tmp_str;
1616f663 379 char *s;
9c9c1080 380 const char *charopts, **stropts;
43e5747a 381
22981b2c
BV
382 if (!(devices = device_scan())) {
383 g_critical("No devices found.");
43e5747a
UH
384 return;
385 }
386
22981b2c
BV
387 num_devices = g_slist_length(devices);
388 if (num_devices > 1) {
7d559a46 389 g_critical("%d devices found. Use --scan to show them, "
d79d4806 390 "and select one to show.", num_devices);
41d7fb23
BV
391 return;
392 }
22981b2c 393
41d7fb23 394 sdi = devices->data;
22981b2c 395 print_dev_line(sdi);
43e5747a 396
0687f23d
BV
397 if (sr_dev_open(sdi) != SR_OK) {
398 g_critical("Failed to open device.");
8e8827f4
BV
399 return;
400 }
401
3f2d32a4
BV
402 if ((sr_config_list(sdi->driver, NULL, NULL, SR_CONF_SCAN_OPTIONS,
403 &gvar_opts) == SR_OK)) {
1616f663
BV
404 opts = g_variant_get_fixed_array(gvar_opts, &num_elements,
405 sizeof(int32_t));
22981b2c 406 printf("Supported driver options:\n");
1616f663
BV
407 for (i = 0; i < num_elements; i++) {
408 if (!(srci = sr_config_info_get(opts[i])))
22981b2c 409 continue;
995713f4 410 printf(" %s\n", srci->id);
22981b2c 411 }
1616f663 412 g_variant_unref(gvar_opts);
22981b2c
BV
413 }
414
9d47bc56
BV
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)
22981b2c
BV
418 /* Driver supports no device instance options. */
419 return;
420
96e0e450
BV
421 if (sdi->probe_groups) {
422 printf("Probe groups:\n");
423 for (pgl = sdi->probe_groups; pgl; pgl = pgl->next) {
9d47bc56
BV
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) {
96e0e450
BV
428 probe = prl->data;
429 printf(" %s", probe->name);
430 }
431 printf("\n");
432 }
433 }
434
9d47bc56
BV
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");
1616f663
BV
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])))
43e5747a
UH
446 continue;
447
1616f663 448 if (srci->key == SR_CONF_TRIGGER_TYPE) {
9d47bc56 449 if (sr_config_list(sdi->driver, sdi, probe_group, srci->key,
3f2d32a4 450 &gvar) != SR_OK) {
1616f663
BV
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);
43e5747a 462
1616f663 463 } else if (srci->key == SR_CONF_PATTERN_MODE) {
c8db7172 464 /* Pattern generator modes */
995713f4 465 printf(" %s", srci->id);
9d47bc56 466 if (sr_config_list(sdi->driver, sdi, probe_group, srci->key,
3f2d32a4 467 &gvar) == SR_OK) {
0a56f4ec 468 printf(" - supported patterns:\n");
1e1316b3
BV
469 stropts = g_variant_get_strv(gvar, &num_elements);
470 for (i = 0; i < num_elements; i++)
9c9c1080 471 printf(" %s\n", stropts[i]);
1616f663 472 g_variant_unref(gvar);
9c9c1080 473 } else {
43e5747a 474 printf("\n");
43e5747a 475 }
c8db7172 476
b5c63de9 477 } else if (srci->key == SR_CONF_SAMPLERATE) {
43e5747a 478 /* Supported samplerates */
995713f4 479 printf(" %s", srci->id);
9d47bc56 480 if (sr_config_list(sdi->driver, sdi, probe_group, SR_CONF_SAMPLERATE,
3f2d32a4 481 &gvar_dict) != SR_OK) {
43e5747a
UH
482 printf("\n");
483 continue;
484 }
1616f663
BV
485 if ((gvar_list = g_variant_lookup_value(gvar_dict,
486 "samplerates", G_VARIANT_TYPE("at")))) {
4e0db44d 487 uint64 = g_variant_get_fixed_array(gvar_list,
1616f663
BV
488 &num_elements, sizeof(uint64_t));
489 printf(" - supported samplerates:\n");
17982bc9
BV
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,
1616f663 498 "samplerate-steps", G_VARIANT_TYPE("at")))) {
4e0db44d 499 uint64 = g_variant_get_fixed_array(gvar_list,
1616f663 500 &num_elements, sizeof(uint64_t));
43e5747a 501 /* low */
4e0db44d 502 if (!(s = sr_samplerate_string(uint64[0])))
43e5747a
UH
503 continue;
504 printf(" (%s", s);
c2c4a0de 505 g_free(s);
43e5747a 506 /* high */
4e0db44d 507 if (!(s = sr_samplerate_string(uint64[1])))
43e5747a
UH
508 continue;
509 printf(" - %s", s);
c2c4a0de 510 g_free(s);
43e5747a 511 /* step */
4e0db44d 512 if (!(s = sr_samplerate_string(uint64[2])))
43e5747a
UH
513 continue;
514 printf(" in steps of %s)\n", s);
c2c4a0de 515 g_free(s);
1e1316b3 516 g_variant_unref(gvar_list);
43e5747a 517 }
1616f663 518 g_variant_unref(gvar_dict);
c8db7172 519
b5c63de9 520 } else if (srci->key == SR_CONF_BUFFERSIZE) {
c8db7172 521 /* Supported buffer sizes */
995713f4 522 printf(" %s", srci->id);
9d47bc56 523 if (sr_config_list(sdi->driver, sdi, probe_group,
3f2d32a4 524 SR_CONF_BUFFERSIZE, &gvar_list) != SR_OK) {
c8db7172
BV
525 printf("\n");
526 continue;
527 }
4e0db44d 528 uint64 = g_variant_get_fixed_array(gvar_list,
1e1316b3 529 &num_elements, sizeof(uint64_t));
c8db7172 530 printf(" - supported buffer sizes:\n");
1e1316b3 531 for (i = 0; i < num_elements; i++)
4e0db44d 532 printf(" %"PRIu64"\n", uint64[i]);
1e1316b3 533 g_variant_unref(gvar_list);
c8db7172 534
b5c63de9 535 } else if (srci->key == SR_CONF_TIMEBASE) {
c8db7172 536 /* Supported time bases */
995713f4 537 printf(" %s", srci->id);
9d47bc56 538 if (sr_config_list(sdi->driver, sdi, probe_group,
3f2d32a4 539 SR_CONF_TIMEBASE, &gvar_list) != SR_OK) {
c8db7172
BV
540 printf("\n");
541 continue;
542 }
543 printf(" - supported time bases:\n");
e07340ad
BV
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 }
1e1316b3 552 g_variant_unref(gvar_list);
c8db7172 553
b5c63de9 554 } else if (srci->key == SR_CONF_VDIV) {
8f3b8464 555 /* Supported volts/div values */
995713f4 556 printf(" %s", srci->id);
9d47bc56 557 if (sr_config_list(sdi->driver, sdi, probe_group,
3f2d32a4 558 SR_CONF_VDIV, &gvar_list) != SR_OK) {
8f3b8464
BV
559 printf("\n");
560 continue;
561 }
562 printf(" - supported volts/div:\n");
e07340ad
BV
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 }
1e1316b3 571 g_variant_unref(gvar_list);
8f3b8464 572
43d3d80b
BV
573 } else if (srci->datatype == SR_T_CHAR) {
574 printf(" %s: ", srci->id);
9d47bc56 575 if (sr_config_get(sdi->driver, sdi, probe_group, srci->key,
1c4eb5c6 576 &gvar) == SR_OK) {
43d3d80b
BV
577 tmp_str = g_strdup(g_variant_get_string(gvar, NULL));
578 g_variant_unref(gvar);
579 } else
580 tmp_str = NULL;
581
9d47bc56 582 if (sr_config_list(sdi->driver, sdi, probe_group, srci->key,
1c4eb5c6 583 &gvar) != SR_OK) {
498f9167
BV
584 printf("\n");
585 continue;
586 }
43d3d80b 587
1e1316b3 588 stropts = g_variant_get_strv(gvar, &num_elements);
43d3d80b
BV
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);
1e1316b3 599 g_variant_unref(gvar);
498f9167 600
43d3d80b
BV
601 } else if (srci->datatype == SR_T_UINT64_RANGE) {
602 printf(" %s: ", srci->id);
9d47bc56 603 if (sr_config_list(sdi->driver, sdi, probe_group, srci->key,
1c4eb5c6 604 &gvar_list) != SR_OK) {
43d3d80b
BV
605 printf("\n");
606 continue;
607 }
608
1c4eb5c6 609 if (sr_config_get(sdi->driver, sdi, NULL, srci->key, &gvar) == SR_OK) {
43d3d80b 610 g_variant_get(gvar, "(tt)", &cur_low, &cur_high);
1e1316b3 611 g_variant_unref(gvar);
43d3d80b
BV
612 } else {
613 cur_low = 0;
614 cur_high = 0;
8e8827f4 615 }
43d3d80b
BV
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);
1c4eb5c6
BV
633 if (sr_config_get(sdi->driver, sdi, NULL, srci->key,
634 &gvar) == SR_OK) {
43d3d80b
BV
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
43e5747a 643 } else {
43d3d80b 644
c8db7172 645 /* Everything else */
995713f4 646 printf(" %s\n", srci->id);
43e5747a
UH
647 }
648 }
1616f663 649 g_variant_unref(gvar_opts);
22981b2c 650
0687f23d 651 sr_dev_close(sdi);
17982bc9 652 g_slist_free(devices);
8e8827f4 653
43e5747a
UH
654}
655
de0a066e 656#ifdef HAVE_SRD
71b1ea4e
BV
657static void show_pd_detail(void)
658{
659 GSList *l;
660 struct srd_decoder *dec;
d142a3f7
BV
661 struct srd_decoder_option *o;
662 char **pdtokens, **pdtok, *optsep, **ann, *val, *doc;
e9ff6974 663 struct srd_probe *p;
71b1ea4e
BV
664
665 pdtokens = g_strsplit(opt_pds, ",", -1);
666 for (pdtok = pdtokens; *pdtok; pdtok++) {
d142a3f7
BV
667 /* Strip options. */
668 if ((optsep = strchr(*pdtok, ':')))
669 *optsep = '\0';
2358775c 670 if (!(dec = srd_decoder_get_by_id(*pdtok))) {
f8ccd825 671 g_critical("Protocol decoder %s not found.", *pdtok);
71b1ea4e
BV
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);
e9ff6974 677 printf("Annotations:\n");
71b1ea4e 678 if (dec->annotations) {
71b1ea4e
BV
679 for (l = dec->annotations; l; l = l->next) {
680 ann = l->data;
681 printf("- %s\n %s\n", ann[0], ann[1]);
682 }
e9ff6974
UH
683 } else {
684 printf("None.\n");
685 }
e9ff6974
UH
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");
71b1ea4e 705 }
d142a3f7
BV
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 }
4359a4da 715 if ((doc = srd_decoder_doc_get(dec))) {
e9ff6974
UH
716 printf("Documentation:\n%s\n",
717 doc[0] == '\n' ? doc + 1 : doc);
71b1ea4e
BV
718 g_free(doc);
719 }
720 }
721
722 g_strfreev(pdtokens);
71b1ea4e 723}
de0a066e 724#endif
71b1ea4e 725
c27450ea
BV
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
37d5ccc1 745static void datafeed_in(const struct sr_dev_inst *sdi,
74f6195b 746 const struct sr_datafeed_packet *packet, void *cb_data)
43e5747a 747{
7e97afa0 748 const struct sr_datafeed_meta *meta;
c27450ea
BV
749 const struct sr_datafeed_logic *logic;
750 const struct sr_datafeed_analog *analog;
7e97afa0 751 struct sr_config *src;
43e5747a 752 static struct sr_output *o = NULL;
c27450ea 753 static GArray *logic_probelist = NULL;
43e5747a
UH
754 static uint64_t received_samples = 0;
755 static int unitsize = 0;
756 static int triggered = 0;
757 static FILE *outfile = NULL;
1616f663
BV
758 GSList *l;
759 GString *out;
c27450ea 760 int sample_size, ret;
d80c8dd0 761 uint64_t samplerate, output_len, filter_out_len, end_sample;
8de01efe 762 uint8_t *output_buf, *filter_out;
43e5747a 763
74f6195b
ML
764 (void) cb_data;
765
43e5747a
UH
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:
8170b8ea 773 g_debug("cli: Received SR_DF_HEADER");
43e5747a 774 /* Initialize the output module. */
c2c4a0de 775 if (!(o = g_try_malloc(sizeof(struct sr_output)))) {
8170b8ea 776 g_critical("Output module malloc failed.");
43e5747a
UH
777 exit(1);
778 }
779 o->format = output_format;
37d5ccc1 780 o->sdi = (struct sr_dev_inst *)sdi;
43e5747a
UH
781 o->param = output_format_param;
782 if (o->format->init) {
783 if (o->format->init(o) != SR_OK) {
8170b8ea 784 g_critical("Output format initialization failed.");
43e5747a
UH
785 exit(1);
786 }
787 }
c27450ea
BV
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
de0a066e 810#ifdef HAVE_SRD
7d559a46 811 GVariant *gvar;
c27450ea 812 if (opt_pds && logic_probelist->len) {
3f2d32a4 813 if (sr_config_get(sdi->driver, sdi, NULL, SR_CONF_SAMPLERATE,
1c4eb5c6 814 &gvar) == SR_OK) {
d80c8dd0
BV
815 samplerate = g_variant_get_uint64(gvar);
816 g_variant_unref(gvar);
817 if (srd_session_metadata_set(srd_sess, SRD_CONF_SAMPLERATE,
a0e36511 818 g_variant_new_uint64(samplerate)) != SRD_OK) {
d80c8dd0
BV
819 g_critical("Failed to configure decode session.");
820 break;
821 }
a0e36511
BV
822 }
823 if (srd_session_start(srd_sess) != SRD_OK) {
824 g_critical("Failed to start decode session.");
825 break;
826 }
c27450ea 827 }
de0a066e 828#endif
43e5747a 829 break;
53993299 830
7e97afa0
BV
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) {
b5c63de9 837 case SR_CONF_SAMPLERATE:
1616f663
BV
838 samplerate = g_variant_get_uint64(src->data);
839 g_debug("cli: got samplerate %"PRIu64" Hz", samplerate);
d80c8dd0
BV
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
5570e0f2
BV
848 break;
849 case SR_CONF_SAMPLE_INTERVAL:
1616f663
BV
850 samplerate = g_variant_get_uint64(src->data);
851 g_debug("cli: got sample interval %"PRIu64" ms", samplerate);
7e97afa0
BV
852 break;
853 default:
854 /* Unknown metadata is not an error. */
855 break;
856 }
857 }
858 break;
859
43e5747a 860 case SR_DF_TRIGGER:
8170b8ea 861 g_debug("cli: received SR_DF_TRIGGER");
43e5747a
UH
862 if (o->format->event)
863 o->format->event(o, SR_DF_TRIGGER, &output_buf,
864 &output_len);
865 triggered = 1;
866 break;
53993299 867
43e5747a
UH
868 case SR_DF_LOGIC:
869 logic = packet->payload;
b46c4414 870 g_message("cli: received SR_DF_LOGIC, %"PRIu64" bytes", logic->length);
53993299
BV
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;
43e5747a 878
53993299
BV
879 if (limit_samples && received_samples >= limit_samples)
880 break;
43e5747a 881
53993299 882 ret = sr_filter_probes(sample_size, unitsize, logic_probelist,
f8ccd825
BV
883 logic->data, logic->length,
884 &filter_out, &filter_out_len);
53993299
BV
885 if (ret != SR_OK)
886 break;
43e5747a 887
d80c8dd0
BV
888 /*
889 * What comes out of the filter is guaranteed to be packed into the
53993299 890 * minimum size needed to support the number of samples at this sample
d80c8dd0 891 * size. however, the driver may have submitted too much. Cut off
53993299
BV
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;
43e5747a 897
c27450ea
BV
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);
53993299 901 } else {
c27450ea 902 if (opt_pds) {
de0a066e 903#ifdef HAVE_SRD
d80c8dd0
BV
904 end_sample = received_samples + filter_out_len / unitsize;
905 if (srd_session_send(srd_sess, received_samples, end_sample,
a0e36511 906 (uint8_t*)filter_out, filter_out_len) != SRD_OK)
c27450ea 907 sr_session_stop();
de0a066e 908#endif
c27450ea
BV
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);
a172e2a0 914 if (output_len) {
c27450ea
BV
915 fwrite(output_buf, 1, output_len, outfile);
916 fflush(outfile);
917 g_free(output_buf);
918 }
53993299
BV
919 }
920 }
53993299 921 g_free(filter_out);
43e5747a 922
c27450ea 923 received_samples += logic->length / sample_size;
53993299
BV
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
48f71481
BV
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);
e09810e9 941 fflush(outfile);
48f71481 942 g_free(output_buf);
c8db7172 943 }
53993299
BV
944 }
945
53993299 946 received_samples += analog->num_samples;
ce48d892
BV
947 break;
948
949 case SR_DF_FRAME_BEGIN:
48f71481
BV
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);
e09810e9 956 fflush(outfile);
48f71481
BV
957 g_free(output_buf);
958 }
959 }
ce48d892
BV
960 break;
961
962 case SR_DF_FRAME_END:
48f71481
BV
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);
e09810e9 969 fflush(outfile);
48f71481
BV
970 g_free(output_buf);
971 }
972 }
ce48d892 973 break;
53993299
BV
974
975 default:
c27450ea 976 break;
43e5747a
UH
977 }
978
644bb1e8
BV
979 if (o && o->format->receive) {
980 if (o->format->receive(o, sdi, packet, &out) == SR_OK && out) {
05e7fa2c
BV
981 fwrite(out->str, 1, out->len, outfile);
982 fflush(outfile);
644bb1e8 983 g_string_free(out, TRUE);
05e7fa2c
BV
984 }
985 }
986
644bb1e8 987 /* SR_DF_END needs to be handled after the output module's receive()
bea29a44
BV
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
9eee58d8 1020 if (opt_output_file && default_output_format && savebuf->len) {
bea29a44
BV
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
43e5747a
UH
1028}
1029
de0a066e 1030#ifdef HAVE_SRD
d142a3f7
BV
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)) {
e536047e 1053 val_int = strtoll(val_str, &conv, 0);
d142a3f7
BV
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);
7058a9b8 1090 all_probes = g_slist_concat(all_probes, g_slist_copy(dec->opt_probes));
d142a3f7
BV
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
9f4a898e
BV
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"
43e5747a
UH
1115 * That will instantiate two SPI decoders on the clock but different data
1116 * lines.
1117 */
1e0f9ed9 1118static int register_pds(struct sr_dev *dev, const char *pdstring)
43e5747a 1119{
d142a3f7
BV
1120 struct srd_decoder *dec;
1121 GHashTable *pd_opthash, *options, *probes;
1122 GList *leftover, *l;
878e90d9 1123 struct srd_decoder_inst *di;
445950d3 1124 int ret;
a1418b73 1125 char **pdtokens, **pdtok, *pd_name;
43e5747a 1126
1e0f9ed9 1127 (void)dev;
43e5747a 1128
120f9ee7
BV
1129 pd_ann_visible = g_hash_table_new_full(g_str_hash, g_int_equal,
1130 g_free, NULL);
283833bf 1131 ret = 0;
a1418b73 1132 pd_name = NULL;
d142a3f7 1133 pd_opthash = options = probes = NULL;
120f9ee7 1134 pdtokens = g_strsplit(pdstring, ",", 0);
43e5747a 1135 for (pdtok = pdtokens; *pdtok; pdtok++) {
63bb454c 1136 if (!(pd_opthash = parse_generic_arg(*pdtok, TRUE))) {
8170b8ea 1137 g_critical("Invalid protocol decoder option '%s'.", *pdtok);
d142a3f7 1138 break;
43e5747a 1139 }
a1418b73 1140
9720f23a
BV
1141 pd_name = g_strdup(g_hash_table_lookup(pd_opthash, "sigrok_key"));
1142 g_hash_table_remove(pd_opthash, "sigrok_key");
2358775c 1143 if (srd_decoder_load(pd_name) != SRD_OK) {
8170b8ea 1144 g_critical("Failed to load protocol decoder %s.", pd_name);
445950d3 1145 ret = 1;
d142a3f7
BV
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;
15d920a9 1158 }
d142a3f7
BV
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
a0e36511 1167 if (!(di = srd_inst_new(srd_sess, pd_name, options))) {
8170b8ea 1168 g_critical("Failed to instantiate protocol decoder %s.", pd_name);
445950d3 1169 ret = 1;
d142a3f7 1170 break;
43e5747a 1171 }
120f9ee7
BV
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 */
b6bd032d
UH
1177 if (!opt_pd_annotations)
1178 g_hash_table_insert(pd_ann_visible,
283833bf 1179 g_strdup(di->inst_id), GINT_TO_POINTER(-1));
a1418b73 1180
d142a3f7
BV
1181 /* Remap the probes if needed. */
1182 if (srd_inst_probe_set_all(di, probes) != SRD_OK) {
445950d3 1183 ret = 1;
d142a3f7 1184 break;
445950d3 1185 }
67ce0d27 1186 }
43e5747a 1187
43e5747a 1188 g_strfreev(pdtokens);
9720f23a
BV
1189 if (pd_opthash)
1190 g_hash_table_destroy(pd_opthash);
d142a3f7
BV
1191 if (options)
1192 g_hash_table_destroy(options);
1193 if (probes)
1194 g_hash_table_destroy(probes);
a1418b73
BV
1195 if (pd_name)
1196 g_free(pd_name);
43e5747a 1197
445950d3 1198 return ret;
43e5747a
UH
1199}
1200
120f9ee7
BV
1201int setup_pd_stack(void)
1202{
1203 struct srd_decoder_inst *di_from, *di_to;
1204 int ret, i;
41e915a6 1205 char **pds, **ids;
120f9ee7
BV
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
41e915a6
BV
1221 /* First PD goes at the bottom of the stack. */
1222 ids = g_strsplit(pds[0], ":", 0);
a0e36511 1223 if (!(di_from = srd_inst_find_by_id(srd_sess, ids[0]))) {
41e915a6 1224 g_strfreev(ids);
120f9ee7
BV
1225 g_critical("Cannot stack protocol decoder '%s': "
1226 "instance not found.", pds[0]);
1227 return 1;
1228 }
41e915a6
BV
1229 g_strfreev(ids);
1230
1231 /* Every subsequent PD goes on top. */
120f9ee7 1232 for (i = 1; pds[i]; i++) {
41e915a6 1233 ids = g_strsplit(pds[i], ":", 0);
a0e36511 1234 if (!(di_to = srd_inst_find_by_id(srd_sess, ids[0]))) {
41e915a6 1235 g_strfreev(ids);
120f9ee7
BV
1236 g_critical("Cannot stack protocol decoder '%s': "
1237 "instance not found.", pds[i]);
1238 return 1;
1239 }
41e915a6 1240 g_strfreev(ids);
a0e36511 1241 if ((ret = srd_inst_stack(srd_sess, di_from, di_to)) != SRD_OK)
120f9ee7
BV
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 */
478a782d 1248 if (!opt_pd_annotations)
b6bd032d
UH
1249 g_hash_table_remove(pd_ann_visible,
1250 di_from->inst_id);
120f9ee7
BV
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;
283833bf 1264 int ann_class;
120f9ee7
BV
1265 char **pds, **pdtok, **keyval, **ann_descr;
1266
1267 /* Set up custom list of PDs and annotations to show. */
f1c146f0
BV
1268 pds = g_strsplit(opt_pd_annotations, ",", 0);
1269 for (pdtok = pds; *pdtok && **pdtok; pdtok++) {
f1c146f0
BV
1270 keyval = g_strsplit(*pdtok, "=", 0);
1271 if (!(dec = srd_decoder_get_by_id(keyval[0]))) {
1272 g_critical("Protocol decoder '%s' not found.", keyval[0]);
1273 return 1;
1274 }
1275 if (!dec->annotations) {
1276 g_critical("Protocol decoder '%s' has no annotations.", keyval[0]);
1277 return 1;
1278 }
283833bf 1279 ann_class = 0;
f1c146f0 1280 if (g_strv_length(keyval) == 2) {
283833bf 1281 for (l = dec->annotations; l; l = l->next, ann_class++) {
f1c146f0
BV
1282 ann_descr = l->data;
1283 if (!canon_cmp(ann_descr[0], keyval[1]))
1284 /* Found it. */
1285 break;
120f9ee7 1286 }
f1c146f0
BV
1287 if (!l) {
1288 g_critical("Annotation '%s' not found "
1289 "for protocol decoder '%s'.", keyval[1], keyval[0]);
120f9ee7
BV
1290 return 1;
1291 }
283833bf
BV
1292 g_debug("cli: Showing protocol decoder %s annotation "
1293 "class %d (%s).", keyval[0], ann_class, ann_descr[0]);
1294 } else {
1295 /* No class specified: show all of them. */
1296 ann_class = -1;
1297 g_debug("cli: Showing all annotation classes for protocol "
1298 "decoder %s.", keyval[0]);
120f9ee7 1299 }
283833bf 1300 g_hash_table_insert(pd_ann_visible, g_strdup(keyval[0]), GINT_TO_POINTER(ann_class));
f1c146f0 1301 g_strfreev(keyval);
120f9ee7 1302 }
f1c146f0
BV
1303 g_strfreev(pds);
1304
1305 return 0;
1306}
1307
1308int setup_pd_meta(void)
1309{
1310 struct srd_decoder *dec;
1311 char **pds, **pdtok;
1312
1313 pd_meta_visible = g_hash_table_new_full(g_str_hash, g_int_equal,
1314 g_free, NULL);
1315 pds = g_strsplit(opt_pd_meta, ",", 0);
1316 for (pdtok = pds; *pdtok && **pdtok; pdtok++) {
1317 if (!(dec = srd_decoder_get_by_id(*pdtok))) {
1318 g_critical("Protocol decoder '%s' not found.", *pdtok);
1319 return 1;
1320 }
1321 g_debug("cli: Showing protocol decoder meta output from '%s'.", *pdtok);
1322 g_hash_table_insert(pd_meta_visible, g_strdup(*pdtok), NULL);
1323 }
1324 g_strfreev(pds);
120f9ee7
BV
1325
1326 return 0;
1327}
1328
de0a066e
BV
1329void show_pd_annotations(struct srd_proto_data *pdata, void *cb_data)
1330{
4cc804ff 1331 struct srd_proto_data_annotation *pda;
7c4a2b15 1332 gpointer ann_format;
283833bf 1333 int format;
de0a066e
BV
1334
1335 /* 'cb_data' is not used in this specific callback. */
1336 (void)cb_data;
1337
1338 if (!pd_ann_visible)
1339 return;
1340
1341 if (!g_hash_table_lookup_extended(pd_ann_visible, pdata->pdo->di->inst_id,
1342 NULL, &ann_format))
1343 /* Not in the list of PDs whose annotations we're showing. */
1344 return;
1345
283833bf 1346 format = GPOINTER_TO_INT(ann_format);
4cc804ff 1347 pda = pdata->data;
283833bf 1348 if (format != -1 && pda->ann_format != format)
de0a066e
BV
1349 /* We don't want this particular format from the PD. */
1350 return;
1351
de0a066e
BV
1352 if (opt_loglevel > SR_LOG_WARN)
1353 printf("%"PRIu64"-%"PRIu64" ", pdata->start_sample, pdata->end_sample);
1354 printf("%s: ", pdata->pdo->proto_id);
e947e227
BV
1355 /* Show only the longest annotation. */
1356 printf("\"%s\" ", pda->ann_text[0]);
de0a066e
BV
1357 printf("\n");
1358 fflush(stdout);
1359}
f1c146f0
BV
1360
1361void show_pd_meta(struct srd_proto_data *pdata, void *cb_data)
1362{
1363
1364 /* 'cb_data' is not used in this specific callback. */
1365 (void)cb_data;
1366
1367 if (!g_hash_table_lookup_extended(pd_meta_visible,
1368 pdata->pdo->di->decoder->id, NULL, NULL))
1369 /* Not in the list of PDs whose meta output we're showing. */
1370 return;
1371
1372 if (opt_loglevel > SR_LOG_WARN)
1373 printf("%"PRIu64"-%"PRIu64" ", pdata->start_sample, pdata->end_sample);
1374 printf("%s: ", pdata->pdo->proto_id);
1375 printf("%s: %s", pdata->pdo->meta_name, g_variant_print(pdata->data, FALSE));
1376 printf("\n");
1377 fflush(stdout);
1378}
de0a066e
BV
1379#endif
1380
ad2bc491
BV
1381int setup_output_format(void)
1382{
1383 GHashTable *fmtargs;
1384 GHashTableIter iter;
1385 gpointer key, value;
1386 struct sr_output_format **outputs;
1387 int i;
1388 char *fmtspec;
1389
c25c8e45
BV
1390 if (opt_output_format && !strcmp(opt_output_format, "sigrok")) {
1391 /* Doesn't really exist as an output module - this is
1392 * the session save mode. */
1393 g_free(opt_output_format);
1394 opt_output_format = NULL;
1395 }
1396
ad2bc491
BV
1397 if (!opt_output_format) {
1398 opt_output_format = DEFAULT_OUTPUT_FORMAT;
1399 /* we'll need to remember this so when saving to a file
1400 * later, sigrok session format will be used.
1401 */
1402 default_output_format = TRUE;
1403 }
48f71481 1404
63bb454c 1405 fmtargs = parse_generic_arg(opt_output_format, TRUE);
ad2bc491
BV
1406 fmtspec = g_hash_table_lookup(fmtargs, "sigrok_key");
1407 if (!fmtspec) {
1408 g_critical("Invalid output format.");
1409 return 1;
1410 }
1411 outputs = sr_output_list();
1412 for (i = 0; outputs[i]; i++) {
1413 if (strcmp(outputs[i]->id, fmtspec))
1414 continue;
1415 g_hash_table_remove(fmtargs, "sigrok_key");
1416 output_format = outputs[i];
1417 g_hash_table_iter_init(&iter, fmtargs);
1418 while (g_hash_table_iter_next(&iter, &key, &value)) {
1419 /* only supporting one parameter per output module
1420 * for now, and only its value */
1421 output_format_param = g_strdup(value);
1422 break;
1423 }
1424 break;
1425 }
1426 if (!output_format) {
1427 g_critical("Invalid output format %s.", opt_output_format);
1428 return 1;
1429 }
1430 g_hash_table_destroy(fmtargs);
1431
1432 return 0;
1433}
1434
37d5ccc1 1435static int select_probes(struct sr_dev_inst *sdi)
43e5747a 1436{
497f5362
BV
1437 struct sr_probe *probe;
1438 GSList *selected_probes, *l;
43e5747a
UH
1439
1440 if (!opt_probes)
1441 return SR_OK;
1442
497f5362 1443 if (!(selected_probes = parse_probestring(sdi, opt_probes)))
43e5747a 1444 return SR_ERR;
43e5747a 1445
497f5362
BV
1446 for (l = sdi->probes; l; l = l->next) {
1447 probe = l->data;
1448 if (g_slist_find(selected_probes, probe))
1449 probe->enabled = TRUE;
1450 else
1451 probe->enabled = FALSE;
43e5747a 1452 }
497f5362 1453 g_slist_free(selected_probes);
43e5747a
UH
1454
1455 return SR_OK;
1456}
1457
1458/**
1459 * Return the input file format which the CLI tool should use.
1460 *
1461 * If the user specified -I / --input-format, use that one. Otherwise, try to
1462 * autodetect the format as good as possible. Failing that, return NULL.
1463 *
1464 * @param filename The filename of the input file. Must not be NULL.
1465 * @param opt The -I / --input-file option the user specified (or NULL).
1466 *
1467 * @return A pointer to the 'struct sr_input_format' that should be used,
1468 * or NULL if no input format was selected or auto-detected.
1469 */
1470static struct sr_input_format *determine_input_file_format(
1471 const char *filename, const char *opt)
1472{
1473 int i;
1474 struct sr_input_format **inputs;
1475
1476 /* If there are no input formats, return NULL right away. */
1477 inputs = sr_input_list();
1478 if (!inputs) {
8170b8ea 1479 g_critical("No supported input formats available.");
43e5747a
UH
1480 return NULL;
1481 }
1482
1483 /* If the user specified -I / --input-format, use that one. */
1484 if (opt) {
1485 for (i = 0; inputs[i]; i++) {
943d0c08 1486 if (strcasecmp(inputs[i]->id, opt))
43e5747a 1487 continue;
8170b8ea
BV
1488 g_debug("Using user-specified input file format '%s'.",
1489 inputs[i]->id);
43e5747a
UH
1490 return inputs[i];
1491 }
1492
1493 /* The user specified an unknown input format, return NULL. */
8170b8ea 1494 g_critical("Error: specified input file format '%s' is "
943d0c08 1495 "unknown.", opt);
43e5747a
UH
1496 return NULL;
1497 }
1498
1499 /* Otherwise, try to find an input module that can handle this file. */
1500 for (i = 0; inputs[i]; i++) {
1501 if (inputs[i]->format_match(filename))
1502 break;
1503 }
1504
1505 /* Return NULL if no input module wanted to touch this. */
1506 if (!inputs[i]) {
8170b8ea 1507 g_critical("Error: no matching input module found.");
43e5747a
UH
1508 return NULL;
1509 }
78912cc1
UH
1510
1511 g_debug("cli: Autodetected '%s' input format for file '%s'.",
1512 inputs[i]->id, filename);
43e5747a 1513
43e5747a
UH
1514 return inputs[i];
1515}
1516
1517static void load_input_file_format(void)
1518{
943d0c08 1519 GHashTable *fmtargs = NULL;
43e5747a
UH
1520 struct stat st;
1521 struct sr_input *in;
1522 struct sr_input_format *input_format;
943d0c08
TÅ 
1523 char *fmtspec = NULL;
1524
1525 if (opt_input_format) {
3e8e0c2d 1526 fmtargs = parse_generic_arg(opt_input_format, TRUE);
943d0c08
TÅ 
1527 fmtspec = g_hash_table_lookup(fmtargs, "sigrok_key");
1528 }
43e5747a 1529
8170b8ea 1530 if (!(input_format = determine_input_file_format(opt_input_file,
943d0c08 1531 fmtspec))) {
8170b8ea 1532 /* The exact cause was already logged. */
43e5747a 1533 return;
943d0c08 1534 }
3e8e0c2d 1535
943d0c08
TÅ 
1536 if (fmtargs)
1537 g_hash_table_remove(fmtargs, "sigrok_key");
43e5747a
UH
1538
1539 if (stat(opt_input_file, &st) == -1) {
8170b8ea 1540 g_critical("Failed to load %s: %s", opt_input_file,
43e5747a
UH
1541 strerror(errno));
1542 exit(1);
1543 }
1544
1545 /* Initialize the input module. */
c2c4a0de 1546 if (!(in = g_try_malloc(sizeof(struct sr_input)))) {
8170b8ea 1547 g_critical("Failed to allocate input module.");
43e5747a
UH
1548 exit(1);
1549 }
1550 in->format = input_format;
943d0c08 1551 in->param = fmtargs;
43e5747a 1552 if (in->format->init) {
41602d35 1553 if (in->format->init(in, opt_input_file) != SR_OK) {
8170b8ea 1554 g_critical("Input format init failed.");
43e5747a
UH
1555 exit(1);
1556 }
1557 }
1558
37d5ccc1 1559 if (select_probes(in->sdi) > 0)
c27450ea 1560 return;
43e5747a
UH
1561
1562 sr_session_new();
74f6195b 1563 sr_session_datafeed_callback_add(datafeed_in, NULL);
37d5ccc1 1564 if (sr_session_dev_add(in->sdi) != SR_OK) {
8170b8ea 1565 g_critical("Failed to use device.");
43e5747a
UH
1566 sr_session_destroy();
1567 return;
1568 }
1569
1570 input_format->loadfile(in, opt_input_file);
c27450ea 1571
43e5747a 1572 sr_session_destroy();
943d0c08
TÅ 
1573
1574 if (fmtargs)
1575 g_hash_table_destroy(fmtargs);
43e5747a
UH
1576}
1577
1578static void load_input_file(void)
1579{
1580
1581 if (sr_session_load(opt_input_file) == SR_OK) {
1582 /* sigrok session file */
74f6195b 1583 sr_session_datafeed_callback_add(datafeed_in, NULL);
43e5747a
UH
1584 sr_session_start();
1585 sr_session_run();
1586 sr_session_stop();
1587 }
1588 else {
1589 /* fall back on input modules */
1590 load_input_file_format();
1591 }
43e5747a
UH
1592}
1593
37d5ccc1 1594static int set_dev_options(struct sr_dev_inst *sdi, GHashTable *args)
43e5747a 1595{
995713f4 1596 const struct sr_config_info *srci;
dd671ce7 1597 struct sr_probe_group *pg;
43e5747a
UH
1598 GHashTableIter iter;
1599 gpointer key, value;
cfd3ec6e 1600 int ret;
2f50086c 1601 double tmp_double;
43d3d80b 1602 uint64_t tmp_u64, p, q, low, high;
43e5747a 1603 gboolean tmp_bool;
43d3d80b 1604 GVariant *val, *rational[2], *range[2];
43e5747a
UH
1605
1606 g_hash_table_iter_init(&iter, args);
1607 while (g_hash_table_iter_next(&iter, &key, &value)) {
74b9bf0c 1608 if (!(srci = sr_config_info_name_get(key))) {
cfd3ec6e
BV
1609 g_critical("Unknown device option '%s'.", (char *) key);
1610 return SR_ERR;
1611 }
1612
1613 if ((value == NULL) &&
995713f4 1614 (srci->datatype != SR_T_BOOL)) {
cfd3ec6e
BV
1615 g_critical("Option '%s' needs a value.", (char *)key);
1616 return SR_ERR;
1617 }
1618 val = NULL;
995713f4 1619 switch (srci->datatype) {
cfd3ec6e
BV
1620 case SR_T_UINT64:
1621 ret = sr_parse_sizestring(value, &tmp_u64);
1622 if (ret != SR_OK)
8f3b8464 1623 break;
2f50086c 1624 val = g_variant_new_uint64(tmp_u64);
cfd3ec6e
BV
1625 break;
1626 case SR_T_CHAR:
2f50086c 1627 val = g_variant_new_string(value);
cfd3ec6e
BV
1628 break;
1629 case SR_T_BOOL:
1630 if (!value)
1631 tmp_bool = TRUE;
43e5747a 1632 else
cfd3ec6e 1633 tmp_bool = sr_parse_boolstring(value);
2f50086c 1634 val = g_variant_new_boolean(tmp_bool);
cfd3ec6e
BV
1635 break;
1636 case SR_T_FLOAT:
2f50086c
BV
1637 tmp_double = strtof(value, NULL);
1638 val = g_variant_new_double(tmp_double);
cfd3ec6e
BV
1639 break;
1640 case SR_T_RATIONAL_PERIOD:
bd31fc3f 1641 if ((ret = sr_parse_period(value, &p, &q)) != SR_OK)
cfd3ec6e 1642 break;
bd31fc3f
BV
1643 rational[0] = g_variant_new_uint64(p);
1644 rational[1] = g_variant_new_uint64(q);
1645 val = g_variant_new_tuple(rational, 2);
cfd3ec6e
BV
1646 break;
1647 case SR_T_RATIONAL_VOLT:
bd31fc3f 1648 if ((ret = sr_parse_voltage(value, &p, &q)) != SR_OK)
43e5747a 1649 break;
bd31fc3f
BV
1650 rational[0] = g_variant_new_uint64(p);
1651 rational[1] = g_variant_new_uint64(q);
1652 val = g_variant_new_tuple(rational, 2);
cfd3ec6e 1653 break;
43d3d80b
BV
1654 case SR_T_UINT64_RANGE:
1655 if (sscanf(value, "%"PRIu64"-%"PRIu64, &low, &high) != 2) {
1656 ret = SR_ERR;
1657 break;
1658 } else {
1659 range[0] = g_variant_new_uint64(low);
1660 range[1] = g_variant_new_uint64(high);
1661 val = g_variant_new_tuple(range, 2);
1662 }
1663 break;
cfd3ec6e
BV
1664 default:
1665 ret = SR_ERR;
43e5747a 1666 }
dd671ce7
BV
1667 if (val) {
1668 pg = select_probe_group(sdi);
1669 ret = sr_config_set(sdi, pg, srci->key, val);
1670 }
cfd3ec6e
BV
1671 if (ret != SR_OK) {
1672 g_critical("Failed to set device option '%s'.", (char *)key);
1673 return ret;
43e5747a
UH
1674 }
1675 }
1676
1677 return SR_OK;
1678}
1679
2d73284e
BV
1680static void set_options(void)
1681{
1682 struct sr_dev_inst *sdi;
1683 GSList *devices;
1684 GHashTable *devargs;
1685
ea7741ee 1686 if (!opt_config) {
2d73284e
BV
1687 g_critical("No setting specified.");
1688 return;
1689 }
1690
ea7741ee 1691 if (!(devargs = parse_generic_arg(opt_config, FALSE)))
2d73284e
BV
1692 return;
1693
1694 if (!(devices = device_scan())) {
1695 g_critical("No devices found.");
1696 return;
1697 }
1698 sdi = devices->data;
1699
0687f23d
BV
1700 if (sr_dev_open(sdi) != SR_OK) {
1701 g_critical("Failed to open device.");
2d73284e
BV
1702 return;
1703 }
1704
1705 set_dev_options(sdi, devargs);
1706
0687f23d 1707 sr_dev_close(sdi);
2d73284e
BV
1708 g_slist_free(devices);
1709 g_hash_table_destroy(devargs);
1710
1711}
1712
37d5ccc1 1713static int set_limit_time(const struct sr_dev_inst *sdi)
43e5747a 1714{
1616f663 1715 GVariant *gvar;
9c9c1080 1716 uint64_t time_msec;
1616f663 1717 uint64_t samplerate;
43e5747a 1718
43c062e6 1719 if (!(time_msec = sr_parse_timestring(opt_time))) {
37d5ccc1 1720 g_critical("Invalid time '%s'", opt_time);
37d5ccc1 1721 return SR_ERR;
43e5747a
UH
1722 }
1723
e4ffb9d6 1724 if (sr_dev_has_option(sdi, SR_CONF_LIMIT_MSEC)) {
1616f663 1725 gvar = g_variant_new_uint64(time_msec);
3f2d32a4 1726 if (sr_config_set(sdi, NULL, SR_CONF_LIMIT_MSEC, gvar) != SR_OK) {
37d5ccc1 1727 g_critical("Failed to configure time limit.");
37d5ccc1 1728 return SR_ERR;
43e5747a 1729 }
43c062e6
BV
1730 } else if (sr_dev_has_option(sdi, SR_CONF_SAMPLERATE)) {
1731 /* Convert to samples based on the samplerate. */
3f2d32a4 1732 sr_config_get(sdi->driver, sdi, NULL, SR_CONF_SAMPLERATE, &gvar);
1616f663
BV
1733 samplerate = g_variant_get_uint64(gvar);
1734 g_variant_unref(gvar);
1735 limit_samples = (samplerate) * time_msec / (uint64_t)1000;
37d5ccc1
BV
1736 if (limit_samples == 0) {
1737 g_critical("Not enough time at this samplerate.");
37d5ccc1 1738 return SR_ERR;
43e5747a 1739 }
1616f663 1740 gvar = g_variant_new_uint64(limit_samples);
3f2d32a4 1741 if (sr_config_set(sdi, NULL, SR_CONF_LIMIT_SAMPLES, gvar) != SR_OK) {
37d5ccc1 1742 g_critical("Failed to configure time-based sample limit.");
37d5ccc1 1743 return SR_ERR;
43e5747a 1744 }
43c062e6
BV
1745 } else {
1746 g_critical("This device does not support time limits.");
1747 return SR_ERR;
37d5ccc1 1748 }
43e5747a 1749
37d5ccc1
BV
1750 return SR_OK;
1751}
1752
1753static void run_session(void)
1754{
06a3fb10 1755 GSList *devices;
37d5ccc1 1756 GHashTable *devargs;
1616f663 1757 GVariant *gvar;
37d5ccc1
BV
1758 struct sr_dev_inst *sdi;
1759 int max_probes, i;
06a3fb10
BV
1760 char **triggerlist;
1761
1762 devices = device_scan();
1763 if (!devices) {
1764 g_critical("No devices found.");
1765 return;
1766 }
1767 if (g_slist_length(devices) > 1) {
1768 g_critical("sigrok-cli only supports one device for capturing.");
1769 return;
1770 }
1771 sdi = devices->data;
37d5ccc1
BV
1772
1773 sr_session_new();
74f6195b 1774 sr_session_datafeed_callback_add(datafeed_in, NULL);
37d5ccc1 1775
0687f23d
BV
1776 if (sr_dev_open(sdi) != SR_OK) {
1777 g_critical("Failed to open device.");
1778 return;
1779 }
1780
8ab6aafc 1781 if (sr_session_dev_add(sdi) != SR_OK) {
0687f23d 1782 g_critical("Failed to add device to session.");
8ab6aafc
BV
1783 sr_session_destroy();
1784 return;
1785 }
1786
ea7741ee
BV
1787 if (opt_config) {
1788 if ((devargs = parse_generic_arg(opt_config, FALSE))) {
06a3fb10
BV
1789 if (set_dev_options(sdi, devargs) != SR_OK)
1790 return;
1791 g_hash_table_destroy(devargs);
43e5747a 1792 }
06a3fb10 1793 }
43e5747a 1794
06a3fb10
BV
1795 if (select_probes(sdi) != SR_OK) {
1796 g_critical("Failed to set probes.");
1797 sr_session_destroy();
1798 return;
1799 }
1800
1801 if (opt_triggers) {
1802 if (!(triggerlist = sr_parse_triggerstring(sdi, opt_triggers))) {
43e5747a
UH
1803 sr_session_destroy();
1804 return;
1805 }
06a3fb10
BV
1806 max_probes = g_slist_length(sdi->probes);
1807 for (i = 0; i < max_probes; i++) {
1808 if (triggerlist[i]) {
1809 sr_dev_trigger_set(sdi, i, triggerlist[i]);
1810 g_free(triggerlist[i]);
43e5747a
UH
1811 }
1812 }
06a3fb10
BV
1813 g_free(triggerlist);
1814 }
9c9c1080 1815
06a3fb10 1816 if (opt_continuous) {
e4ffb9d6 1817 if (!sr_dev_has_option(sdi, SR_CONF_CONTINUOUS)) {
06a3fb10 1818 g_critical("This device does not support continuous sampling.");
37d5ccc1
BV
1819 sr_session_destroy();
1820 return;
1821 }
37d5ccc1
BV
1822 }
1823
1824 if (opt_time) {
1825 if (set_limit_time(sdi) != SR_OK) {
1826 sr_session_destroy();
1827 return;
43e5747a
UH
1828 }
1829 }
1830
1831 if (opt_samples) {
1616f663
BV
1832 if ((sr_parse_sizestring(opt_samples, &limit_samples) != SR_OK)) {
1833 g_critical("Invalid sample limit '%s'.", opt_samples);
1834 sr_session_destroy();
1835 return;
1836 }
1837 gvar = g_variant_new_uint64(limit_samples);
3f2d32a4 1838 if (sr_config_set(sdi, NULL, SR_CONF_LIMIT_SAMPLES, gvar) != SR_OK) {
8170b8ea 1839 g_critical("Failed to configure sample limit.");
43e5747a
UH
1840 sr_session_destroy();
1841 return;
1842 }
1843 }
1844
ce48d892 1845 if (opt_frames) {
1616f663
BV
1846 if ((sr_parse_sizestring(opt_frames, &limit_frames) != SR_OK)) {
1847 g_critical("Invalid sample limit '%s'.", opt_samples);
1848 sr_session_destroy();
1849 return;
1850 }
2f50086c 1851 gvar = g_variant_new_uint64(limit_frames);
3f2d32a4 1852 if (sr_config_set(sdi, NULL, SR_CONF_LIMIT_FRAMES, gvar) != SR_OK) {
f8ccd825 1853 g_critical("Failed to configure frame limit.");
ce48d892
BV
1854 sr_session_destroy();
1855 return;
1856 }
1857 }
1858
43e5747a 1859 if (sr_session_start() != SR_OK) {
8170b8ea 1860 g_critical("Failed to start session.");
43e5747a
UH
1861 sr_session_destroy();
1862 return;
1863 }
1864
1865 if (opt_continuous)
1866 add_anykey();
1867
1868 sr_session_run();
1869
1870 if (opt_continuous)
1871 clear_anykey();
1872
1e484911 1873 sr_session_datafeed_callback_remove_all();
43e5747a 1874 sr_session_destroy();
37d5ccc1
BV
1875 g_slist_free(devices);
1876
43e5747a
UH
1877}
1878
1879static void logger(const gchar *log_domain, GLogLevelFlags log_level,
68cdf174 1880 const gchar *message, gpointer cb_data)
43e5747a 1881{
43e5747a 1882 (void)log_domain;
68cdf174 1883 (void)cb_data;
43e5747a
UH
1884
1885 /*
1886 * All messages, warnings, errors etc. go to stderr (not stdout) in
1887 * order to not mess up the CLI tool data output, e.g. VCD output.
1888 */
2d6ff326 1889 if (log_level & (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING)
d740e6ac 1890 || opt_loglevel > SR_LOG_WARN) {
43e5747a
UH
1891 fprintf(stderr, "%s\n", message);
1892 fflush(stderr);
43e5747a 1893 }
608beef3
BV
1894
1895 if (log_level & (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL))
1896 exit(1);
1897
43e5747a
UH
1898}
1899
1900int main(int argc, char **argv)
1901{
43e5747a
UH
1902 GOptionContext *context;
1903 GError *error;
17982bc9
BV
1904 int ret;
1905 char *help;
43e5747a
UH
1906
1907 g_log_set_default_handler(logger, NULL);
43e5747a 1908
43e5747a
UH
1909 context = g_option_context_new(NULL);
1910 g_option_context_add_main_entries(context, optargs, NULL);
1911
17982bc9
BV
1912 ret = 1;
1913 error = NULL;
43e5747a 1914 if (!g_option_context_parse(context, &argc, &argv, &error)) {
8170b8ea 1915 g_critical("%s", error->message);
5acb7682 1916 goto done;
43e5747a
UH
1917 }
1918
1919 /* Set the loglevel (amount of messages to output) for libsigrok. */
120f9ee7 1920 if (sr_log_loglevel_set(opt_loglevel) != SR_OK)
5acb7682 1921 goto done;
43e5747a 1922
de0a066e 1923 if (sr_init(&sr_ctx) != SR_OK)
5acb7682 1924 goto done;
6de7ec06 1925
de0a066e
BV
1926#ifdef HAVE_SRD
1927 /* Set the loglevel (amount of messages to output) for libsigrokdecode. */
1928 if (srd_log_loglevel_set(opt_loglevel) != SRD_OK)
5acb7682 1929 goto done;
43e5747a
UH
1930
1931 if (opt_pds) {
120f9ee7 1932 if (srd_init(NULL) != SRD_OK)
198f4c6c 1933 goto done;
a0e36511
BV
1934 if (srd_session_new(&srd_sess) != SRD_OK) {
1935 g_critical("Failed to create new decode session.");
1936 goto done;
1937 }
120f9ee7 1938 if (register_pds(NULL, opt_pds) != 0)
198f4c6c 1939 goto done;
a0e36511 1940 if (srd_pd_output_callback_add(srd_sess, SRD_OUTPUT_ANN,
b6bd032d 1941 show_pd_annotations, NULL) != SRD_OK)
198f4c6c 1942 goto done;
120f9ee7 1943 if (setup_pd_stack() != 0)
198f4c6c 1944 goto done;
f1c146f0
BV
1945 if (opt_pd_annotations)
1946 if (setup_pd_annotations() != 0)
1947 goto done;
1948 if (opt_pd_meta) {
1949 if (setup_pd_meta() != 0)
1950 goto done;
1951 if (srd_pd_output_callback_add(srd_sess, SRD_OUTPUT_META,
1952 show_pd_meta, NULL) != SRD_OK)
1953 goto done;
1954 }
9f4a898e 1955 }
de0a066e 1956#endif
9f4a898e 1957
ad2bc491 1958 if (setup_output_format() != 0)
198f4c6c 1959 goto done;
43e5747a
UH
1960
1961 if (opt_version)
1962 show_version();
ea7741ee 1963 else if (opt_scan_devs)
1e0f9ed9 1964 show_dev_list();
de0a066e 1965#ifdef HAVE_SRD
f83fbc57
BV
1966 else if (opt_pds && opt_show)
1967 show_pd_detail();
de0a066e 1968#endif
22981b2c
BV
1969 else if (opt_show)
1970 show_dev_detail();
43e5747a
UH
1971 else if (opt_input_file)
1972 load_input_file();
2d73284e
BV
1973 else if (opt_set)
1974 set_options();
ce48d892 1975 else if (opt_samples || opt_time || opt_frames || opt_continuous)
43e5747a 1976 run_session();
17982bc9
BV
1977 else {
1978 help = g_option_context_get_help(context, TRUE, NULL);
1979 printf("%s", help);
1980 g_free(help);
1981 }
43e5747a 1982
de0a066e 1983#ifdef HAVE_SRD
43e5747a
UH
1984 if (opt_pds)
1985 srd_exit();
de0a066e 1986#endif
43e5747a 1987
198f4c6c
PS
1988 ret = 0;
1989
1990done:
5acb7682
PS
1991 if (sr_ctx)
1992 sr_exit(sr_ctx);
198f4c6c 1993
8630d4a8 1994 g_option_context_free(context);
43e5747a 1995
198f4c6c 1996 return ret;
43e5747a 1997}