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