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