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