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