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