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