]> sigrok.org Git - sigrok-cli.git/blame - sigrok-cli.c
New option -M for OUTPUT_META
[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
445950d3 1129 ret = 0;
120f9ee7
BV
1130 pd_ann_visible = g_hash_table_new_full(g_str_hash, g_int_equal,
1131 g_free, NULL);
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,
1179 g_strdup(di->inst_id), NULL);
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;
1264 int ann;
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++) {
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;
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 }
120f9ee7 1292 }
f1c146f0
BV
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);
120f9ee7 1296 }
f1c146f0
BV
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);
120f9ee7
BV
1319
1320 return 0;
1321}
1322
de0a066e
BV
1323void show_pd_annotations(struct srd_proto_data *pdata, void *cb_data)
1324{
4cc804ff 1325 struct srd_proto_data_annotation *pda;
7c4a2b15 1326 gpointer ann_format;
4cc804ff 1327 int i;
de0a066e
BV
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
4cc804ff
BV
1340 pda = pdata->data;
1341 if (pda->ann_format != GPOINTER_TO_INT(ann_format))
de0a066e
BV
1342 /* We don't want this particular format from the PD. */
1343 return;
1344
de0a066e
BV
1345 if (opt_loglevel > SR_LOG_WARN)
1346 printf("%"PRIu64"-%"PRIu64" ", pdata->start_sample, pdata->end_sample);
1347 printf("%s: ", pdata->pdo->proto_id);
4cc804ff
BV
1348 for (i = 0; pda->ann_text[i]; i++)
1349 printf("\"%s\" ", pda->ann_text[i]);
de0a066e
BV
1350 printf("\n");
1351 fflush(stdout);
1352}
f1c146f0
BV
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}
de0a066e
BV
1372#endif
1373
ad2bc491
BV
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
c25c8e45
BV
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
ad2bc491
BV
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 }
48f71481 1397
63bb454c 1398 fmtargs = parse_generic_arg(opt_output_format, TRUE);
ad2bc491
BV
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
37d5ccc1 1428static int select_probes(struct sr_dev_inst *sdi)
43e5747a 1429{
497f5362
BV
1430 struct sr_probe *probe;
1431 GSList *selected_probes, *l;
43e5747a
UH
1432
1433 if (!opt_probes)
1434 return SR_OK;
1435
497f5362 1436 if (!(selected_probes = parse_probestring(sdi, opt_probes)))
43e5747a 1437 return SR_ERR;
43e5747a 1438
497f5362
BV
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;
43e5747a 1445 }
497f5362 1446 g_slist_free(selected_probes);
43e5747a
UH
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) {
8170b8ea 1472 g_critical("No supported input formats available.");
43e5747a
UH
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++) {
943d0c08 1479 if (strcasecmp(inputs[i]->id, opt))
43e5747a 1480 continue;
8170b8ea
BV
1481 g_debug("Using user-specified input file format '%s'.",
1482 inputs[i]->id);
43e5747a
UH
1483 return inputs[i];
1484 }
1485
1486 /* The user specified an unknown input format, return NULL. */
8170b8ea 1487 g_critical("Error: specified input file format '%s' is "
943d0c08 1488 "unknown.", opt);
43e5747a
UH
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]) {
8170b8ea 1500 g_critical("Error: no matching input module found.");
43e5747a
UH
1501 return NULL;
1502 }
78912cc1
UH
1503
1504 g_debug("cli: Autodetected '%s' input format for file '%s'.",
1505 inputs[i]->id, filename);
43e5747a 1506
43e5747a
UH
1507 return inputs[i];
1508}
1509
1510static void load_input_file_format(void)
1511{
943d0c08 1512 GHashTable *fmtargs = NULL;
43e5747a
UH
1513 struct stat st;
1514 struct sr_input *in;
1515 struct sr_input_format *input_format;
943d0c08
TÅ 
1516 char *fmtspec = NULL;
1517
1518 if (opt_input_format) {
3e8e0c2d 1519 fmtargs = parse_generic_arg(opt_input_format, TRUE);
943d0c08
TÅ 
1520 fmtspec = g_hash_table_lookup(fmtargs, "sigrok_key");
1521 }
43e5747a 1522
8170b8ea 1523 if (!(input_format = determine_input_file_format(opt_input_file,
943d0c08 1524 fmtspec))) {
8170b8ea 1525 /* The exact cause was already logged. */
43e5747a 1526 return;
943d0c08 1527 }
3e8e0c2d 1528
943d0c08
TÅ 
1529 if (fmtargs)
1530 g_hash_table_remove(fmtargs, "sigrok_key");
43e5747a
UH
1531
1532 if (stat(opt_input_file, &st) == -1) {
8170b8ea 1533 g_critical("Failed to load %s: %s", opt_input_file,
43e5747a
UH
1534 strerror(errno));
1535 exit(1);
1536 }
1537
1538 /* Initialize the input module. */
c2c4a0de 1539 if (!(in = g_try_malloc(sizeof(struct sr_input)))) {
8170b8ea 1540 g_critical("Failed to allocate input module.");
43e5747a
UH
1541 exit(1);
1542 }
1543 in->format = input_format;
943d0c08 1544 in->param = fmtargs;
43e5747a 1545 if (in->format->init) {
41602d35 1546 if (in->format->init(in, opt_input_file) != SR_OK) {
8170b8ea 1547 g_critical("Input format init failed.");
43e5747a
UH
1548 exit(1);
1549 }
1550 }
1551
37d5ccc1 1552 if (select_probes(in->sdi) > 0)
c27450ea 1553 return;
43e5747a
UH
1554
1555 sr_session_new();
74f6195b 1556 sr_session_datafeed_callback_add(datafeed_in, NULL);
37d5ccc1 1557 if (sr_session_dev_add(in->sdi) != SR_OK) {
8170b8ea 1558 g_critical("Failed to use device.");
43e5747a
UH
1559 sr_session_destroy();
1560 return;
1561 }
1562
1563 input_format->loadfile(in, opt_input_file);
c27450ea 1564
43e5747a 1565 sr_session_destroy();
943d0c08
TÅ 
1566
1567 if (fmtargs)
1568 g_hash_table_destroy(fmtargs);
43e5747a
UH
1569}
1570
1571static void load_input_file(void)
1572{
1573
1574 if (sr_session_load(opt_input_file) == SR_OK) {
1575 /* sigrok session file */
74f6195b 1576 sr_session_datafeed_callback_add(datafeed_in, NULL);
43e5747a
UH
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 }
43e5747a
UH
1585}
1586
37d5ccc1 1587static int set_dev_options(struct sr_dev_inst *sdi, GHashTable *args)
43e5747a 1588{
995713f4 1589 const struct sr_config_info *srci;
dd671ce7 1590 struct sr_probe_group *pg;
43e5747a
UH
1591 GHashTableIter iter;
1592 gpointer key, value;
cfd3ec6e 1593 int ret;
2f50086c 1594 double tmp_double;
43d3d80b 1595 uint64_t tmp_u64, p, q, low, high;
43e5747a 1596 gboolean tmp_bool;
43d3d80b 1597 GVariant *val, *rational[2], *range[2];
43e5747a
UH
1598
1599 g_hash_table_iter_init(&iter, args);
1600 while (g_hash_table_iter_next(&iter, &key, &value)) {
74b9bf0c 1601 if (!(srci = sr_config_info_name_get(key))) {
cfd3ec6e
BV
1602 g_critical("Unknown device option '%s'.", (char *) key);
1603 return SR_ERR;
1604 }
1605
1606 if ((value == NULL) &&
995713f4 1607 (srci->datatype != SR_T_BOOL)) {
cfd3ec6e
BV
1608 g_critical("Option '%s' needs a value.", (char *)key);
1609 return SR_ERR;
1610 }
1611 val = NULL;
995713f4 1612 switch (srci->datatype) {
cfd3ec6e
BV
1613 case SR_T_UINT64:
1614 ret = sr_parse_sizestring(value, &tmp_u64);
1615 if (ret != SR_OK)
8f3b8464 1616 break;
2f50086c 1617 val = g_variant_new_uint64(tmp_u64);
cfd3ec6e
BV
1618 break;
1619 case SR_T_CHAR:
2f50086c 1620 val = g_variant_new_string(value);
cfd3ec6e
BV
1621 break;
1622 case SR_T_BOOL:
1623 if (!value)
1624 tmp_bool = TRUE;
43e5747a 1625 else
cfd3ec6e 1626 tmp_bool = sr_parse_boolstring(value);
2f50086c 1627 val = g_variant_new_boolean(tmp_bool);
cfd3ec6e
BV
1628 break;
1629 case SR_T_FLOAT:
2f50086c
BV
1630 tmp_double = strtof(value, NULL);
1631 val = g_variant_new_double(tmp_double);
cfd3ec6e
BV
1632 break;
1633 case SR_T_RATIONAL_PERIOD:
bd31fc3f 1634 if ((ret = sr_parse_period(value, &p, &q)) != SR_OK)
cfd3ec6e 1635 break;
bd31fc3f
BV
1636 rational[0] = g_variant_new_uint64(p);
1637 rational[1] = g_variant_new_uint64(q);
1638 val = g_variant_new_tuple(rational, 2);
cfd3ec6e
BV
1639 break;
1640 case SR_T_RATIONAL_VOLT:
bd31fc3f 1641 if ((ret = sr_parse_voltage(value, &p, &q)) != SR_OK)
43e5747a 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 1646 break;
43d3d80b
BV
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;
cfd3ec6e
BV
1657 default:
1658 ret = SR_ERR;
43e5747a 1659 }
dd671ce7
BV
1660 if (val) {
1661 pg = select_probe_group(sdi);
1662 ret = sr_config_set(sdi, pg, srci->key, val);
1663 }
cfd3ec6e
BV
1664 if (ret != SR_OK) {
1665 g_critical("Failed to set device option '%s'.", (char *)key);
1666 return ret;
43e5747a
UH
1667 }
1668 }
1669
1670 return SR_OK;
1671}
1672
2d73284e
BV
1673static void set_options(void)
1674{
1675 struct sr_dev_inst *sdi;
1676 GSList *devices;
1677 GHashTable *devargs;
1678
ea7741ee 1679 if (!opt_config) {
2d73284e
BV
1680 g_critical("No setting specified.");
1681 return;
1682 }
1683
ea7741ee 1684 if (!(devargs = parse_generic_arg(opt_config, FALSE)))
2d73284e
BV
1685 return;
1686
1687 if (!(devices = device_scan())) {
1688 g_critical("No devices found.");
1689 return;
1690 }
1691 sdi = devices->data;
1692
0687f23d
BV
1693 if (sr_dev_open(sdi) != SR_OK) {
1694 g_critical("Failed to open device.");
2d73284e
BV
1695 return;
1696 }
1697
1698 set_dev_options(sdi, devargs);
1699
0687f23d 1700 sr_dev_close(sdi);
2d73284e
BV
1701 g_slist_free(devices);
1702 g_hash_table_destroy(devargs);
1703
1704}
1705
37d5ccc1 1706static int set_limit_time(const struct sr_dev_inst *sdi)
43e5747a 1707{
1616f663 1708 GVariant *gvar;
9c9c1080 1709 uint64_t time_msec;
1616f663 1710 uint64_t samplerate;
43e5747a 1711
43c062e6 1712 if (!(time_msec = sr_parse_timestring(opt_time))) {
37d5ccc1 1713 g_critical("Invalid time '%s'", opt_time);
37d5ccc1 1714 return SR_ERR;
43e5747a
UH
1715 }
1716
e4ffb9d6 1717 if (sr_dev_has_option(sdi, SR_CONF_LIMIT_MSEC)) {
1616f663 1718 gvar = g_variant_new_uint64(time_msec);
3f2d32a4 1719 if (sr_config_set(sdi, NULL, SR_CONF_LIMIT_MSEC, gvar) != SR_OK) {
37d5ccc1 1720 g_critical("Failed to configure time limit.");
37d5ccc1 1721 return SR_ERR;
43e5747a 1722 }
43c062e6
BV
1723 } else if (sr_dev_has_option(sdi, SR_CONF_SAMPLERATE)) {
1724 /* Convert to samples based on the samplerate. */
3f2d32a4 1725 sr_config_get(sdi->driver, sdi, NULL, SR_CONF_SAMPLERATE, &gvar);
1616f663
BV
1726 samplerate = g_variant_get_uint64(gvar);
1727 g_variant_unref(gvar);
1728 limit_samples = (samplerate) * time_msec / (uint64_t)1000;
37d5ccc1
BV
1729 if (limit_samples == 0) {
1730 g_critical("Not enough time at this samplerate.");
37d5ccc1 1731 return SR_ERR;
43e5747a 1732 }
1616f663 1733 gvar = g_variant_new_uint64(limit_samples);
3f2d32a4 1734 if (sr_config_set(sdi, NULL, SR_CONF_LIMIT_SAMPLES, gvar) != SR_OK) {
37d5ccc1 1735 g_critical("Failed to configure time-based sample limit.");
37d5ccc1 1736 return SR_ERR;
43e5747a 1737 }
43c062e6
BV
1738 } else {
1739 g_critical("This device does not support time limits.");
1740 return SR_ERR;
37d5ccc1 1741 }
43e5747a 1742
37d5ccc1
BV
1743 return SR_OK;
1744}
1745
1746static void run_session(void)
1747{
06a3fb10 1748 GSList *devices;
37d5ccc1 1749 GHashTable *devargs;
1616f663 1750 GVariant *gvar;
37d5ccc1
BV
1751 struct sr_dev_inst *sdi;
1752 int max_probes, i;
06a3fb10
BV
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;
37d5ccc1
BV
1765
1766 sr_session_new();
74f6195b 1767 sr_session_datafeed_callback_add(datafeed_in, NULL);
37d5ccc1 1768
0687f23d
BV
1769 if (sr_dev_open(sdi) != SR_OK) {
1770 g_critical("Failed to open device.");
1771 return;
1772 }
1773
8ab6aafc 1774 if (sr_session_dev_add(sdi) != SR_OK) {
0687f23d 1775 g_critical("Failed to add device to session.");
8ab6aafc
BV
1776 sr_session_destroy();
1777 return;
1778 }
1779
ea7741ee
BV
1780 if (opt_config) {
1781 if ((devargs = parse_generic_arg(opt_config, FALSE))) {
06a3fb10
BV
1782 if (set_dev_options(sdi, devargs) != SR_OK)
1783 return;
1784 g_hash_table_destroy(devargs);
43e5747a 1785 }
06a3fb10 1786 }
43e5747a 1787
06a3fb10
BV
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))) {
43e5747a
UH
1796 sr_session_destroy();
1797 return;
1798 }
06a3fb10
BV
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]);
43e5747a
UH
1804 }
1805 }
06a3fb10
BV
1806 g_free(triggerlist);
1807 }
9c9c1080 1808
06a3fb10 1809 if (opt_continuous) {
e4ffb9d6 1810 if (!sr_dev_has_option(sdi, SR_CONF_CONTINUOUS)) {
06a3fb10 1811 g_critical("This device does not support continuous sampling.");
37d5ccc1
BV
1812 sr_session_destroy();
1813 return;
1814 }
37d5ccc1
BV
1815 }
1816
1817 if (opt_time) {
1818 if (set_limit_time(sdi) != SR_OK) {
1819 sr_session_destroy();
1820 return;
43e5747a
UH
1821 }
1822 }
1823
1824 if (opt_samples) {
1616f663
BV
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);
3f2d32a4 1831 if (sr_config_set(sdi, NULL, SR_CONF_LIMIT_SAMPLES, gvar) != SR_OK) {
8170b8ea 1832 g_critical("Failed to configure sample limit.");
43e5747a
UH
1833 sr_session_destroy();
1834 return;
1835 }
1836 }
1837
ce48d892 1838 if (opt_frames) {
1616f663
BV
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 }
2f50086c 1844 gvar = g_variant_new_uint64(limit_frames);
3f2d32a4 1845 if (sr_config_set(sdi, NULL, SR_CONF_LIMIT_FRAMES, gvar) != SR_OK) {
f8ccd825 1846 g_critical("Failed to configure frame limit.");
ce48d892
BV
1847 sr_session_destroy();
1848 return;
1849 }
1850 }
1851
43e5747a 1852 if (sr_session_start() != SR_OK) {
8170b8ea 1853 g_critical("Failed to start session.");
43e5747a
UH
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
1e484911 1866 sr_session_datafeed_callback_remove_all();
43e5747a 1867 sr_session_destroy();
37d5ccc1
BV
1868 g_slist_free(devices);
1869
43e5747a
UH
1870}
1871
1872static void logger(const gchar *log_domain, GLogLevelFlags log_level,
68cdf174 1873 const gchar *message, gpointer cb_data)
43e5747a 1874{
43e5747a 1875 (void)log_domain;
68cdf174 1876 (void)cb_data;
43e5747a
UH
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 */
2d6ff326 1882 if (log_level & (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING)
d740e6ac 1883 || opt_loglevel > SR_LOG_WARN) {
43e5747a
UH
1884 fprintf(stderr, "%s\n", message);
1885 fflush(stderr);
43e5747a 1886 }
608beef3
BV
1887
1888 if (log_level & (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL))
1889 exit(1);
1890
43e5747a
UH
1891}
1892
1893int main(int argc, char **argv)
1894{
43e5747a
UH
1895 GOptionContext *context;
1896 GError *error;
17982bc9
BV
1897 int ret;
1898 char *help;
43e5747a
UH
1899
1900 g_log_set_default_handler(logger, NULL);
43e5747a 1901
43e5747a
UH
1902 context = g_option_context_new(NULL);
1903 g_option_context_add_main_entries(context, optargs, NULL);
1904
17982bc9
BV
1905 ret = 1;
1906 error = NULL;
43e5747a 1907 if (!g_option_context_parse(context, &argc, &argv, &error)) {
8170b8ea 1908 g_critical("%s", error->message);
5acb7682 1909 goto done;
43e5747a
UH
1910 }
1911
1912 /* Set the loglevel (amount of messages to output) for libsigrok. */
120f9ee7 1913 if (sr_log_loglevel_set(opt_loglevel) != SR_OK)
5acb7682 1914 goto done;
43e5747a 1915
de0a066e 1916 if (sr_init(&sr_ctx) != SR_OK)
5acb7682 1917 goto done;
6de7ec06 1918
de0a066e
BV
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)
5acb7682 1922 goto done;
43e5747a
UH
1923
1924 if (opt_pds) {
120f9ee7 1925 if (srd_init(NULL) != SRD_OK)
198f4c6c 1926 goto done;
a0e36511
BV
1927 if (srd_session_new(&srd_sess) != SRD_OK) {
1928 g_critical("Failed to create new decode session.");
1929 goto done;
1930 }
120f9ee7 1931 if (register_pds(NULL, opt_pds) != 0)
198f4c6c 1932 goto done;
a0e36511 1933 if (srd_pd_output_callback_add(srd_sess, SRD_OUTPUT_ANN,
b6bd032d 1934 show_pd_annotations, NULL) != SRD_OK)
198f4c6c 1935 goto done;
120f9ee7 1936 if (setup_pd_stack() != 0)
198f4c6c 1937 goto done;
f1c146f0
BV
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 }
9f4a898e 1948 }
de0a066e 1949#endif
9f4a898e 1950
ad2bc491 1951 if (setup_output_format() != 0)
198f4c6c 1952 goto done;
43e5747a
UH
1953
1954 if (opt_version)
1955 show_version();
ea7741ee 1956 else if (opt_scan_devs)
1e0f9ed9 1957 show_dev_list();
de0a066e 1958#ifdef HAVE_SRD
f83fbc57
BV
1959 else if (opt_pds && opt_show)
1960 show_pd_detail();
de0a066e 1961#endif
22981b2c
BV
1962 else if (opt_show)
1963 show_dev_detail();
43e5747a
UH
1964 else if (opt_input_file)
1965 load_input_file();
2d73284e
BV
1966 else if (opt_set)
1967 set_options();
ce48d892 1968 else if (opt_samples || opt_time || opt_frames || opt_continuous)
43e5747a 1969 run_session();
17982bc9
BV
1970 else {
1971 help = g_option_context_get_help(context, TRUE, NULL);
1972 printf("%s", help);
1973 g_free(help);
1974 }
43e5747a 1975
de0a066e 1976#ifdef HAVE_SRD
43e5747a
UH
1977 if (opt_pds)
1978 srd_exit();
de0a066e 1979#endif
43e5747a 1980
198f4c6c
PS
1981 ret = 0;
1982
1983done:
5acb7682
PS
1984 if (sr_ctx)
1985 sr_exit(sr_ctx);
198f4c6c 1986
8630d4a8 1987 g_option_context_free(context);
43e5747a 1988
198f4c6c 1989 return ret;
43e5747a 1990}