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