]> sigrok.org Git - sigrok-cli.git/blame - sigrok-cli.c
sigrok-cli.c: Fix memory leak in parsing of hardware options
[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;
f8ccd825 47static struct sr_datastore *singleds = NULL;
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
BV
114
115/* Convert driver options hash to GSList of struct sr_hwopt. */
116static GSList *hash_to_hwopt(GHashTable *hash)
117{
cfd3ec6e 118 const struct sr_hwcap_option *hwo;
9e2e414f
BV
119 struct sr_hwopt *hwopt;
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;
cfd3ec6e 128 if (!(hwo = sr_drvopt_name_get(key))) {
9e2e414f
BV
129 g_critical("Unknown option %s", key);
130 return NULL;
131 }
cfd3ec6e
BV
132 hwopt = g_try_malloc(sizeof(struct sr_hwopt));
133 hwopt->hwopt = hwo->hwcap;
134 value = g_hash_table_lookup(hash, key);
135 hwopt->value = g_strdup(value);
136 opts = g_slist_append(opts, hwopt);
9e2e414f
BV
137 }
138 g_list_free(keys);
139
140 return opts;
141}
142
a2853311
AG
143static void free_hwopt(struct sr_hwopt *hwopt)
144{
145 g_free((void *)hwopt->value);
146 g_free(hwopt);
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);
a2853311 183 g_slist_free_full(drvopts, (GDestroyNotify)free_hwopt);
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;
3a06774c 300 const struct sr_hwcap_option *hwo;
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
22981b2c
BV
335 if (sr_info_get(sdi->driver, SR_DI_TRIGGER_TYPES, (const void **)&charopts,
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
22981b2c
BV
345 if ((sr_info_get(sdi->driver, SR_DI_HWOPTS, (const void **)&hwopts,
346 NULL) == SR_OK) && hwopts) {
347 printf("Supported driver options:\n");
348 for (i = 0; hwopts[i]; i++) {
349 if (!(hwo = sr_drvopt_get(hwopts[i])))
350 continue;
351 printf(" %s\n", hwo->shortname);
352 }
353 }
354
355 title = "Supported device options:\n";
356 if ((sr_info_get(sdi->driver, SR_DI_HWCAPS, (const void **)&hwcaps,
357 NULL) != SR_OK) || !hwcaps)
358 /* Driver supports no device instance options. */
359 return;
360
edd79b3f 361 for (cap = 0; hwcaps[cap]; cap++) {
5d1fb573 362 if (!(hwo = sr_devopt_get(hwcaps[cap])))
43e5747a
UH
363 continue;
364
365 if (title) {
366 printf("%s", title);
367 title = NULL;
368 }
369
edd79b3f 370 if (hwo->hwcap == SR_HWCAP_PATTERN_MODE) {
c8db7172 371 /* Pattern generator modes */
43e5747a 372 printf(" %s", hwo->shortname);
22981b2c
BV
373 if (sr_info_get(sdi->driver, SR_DI_PATTERNS,
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
edd79b3f 382 } else if (hwo->hwcap == SR_HWCAP_SAMPLERATE) {
43e5747a 383 /* Supported samplerates */
c8db7172 384 printf(" %s", hwo->shortname);
22981b2c
BV
385 if (sr_info_get(sdi->driver, SR_DI_SAMPLERATES,
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
BV
411
412 } else if (hwo->hwcap == SR_HWCAP_BUFFERSIZE) {
413 /* Supported buffer sizes */
414 printf(" %s", hwo->shortname);
22981b2c
BV
415 if (sr_info_get(sdi->driver, SR_DI_BUFFERSIZES,
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
424 } else if (hwo->hwcap == SR_HWCAP_TIMEBASE) {
425 /* Supported time bases */
426 printf(" %s", hwo->shortname);
22981b2c
BV
427 if (sr_info_get(sdi->driver, SR_DI_TIMEBASES,
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
437 } else if (hwo->hwcap == SR_HWCAP_TRIGGER_SOURCE) {
438 /* Supported trigger sources */
439 printf(" %s", hwo->shortname);
22981b2c
BV
440 if (sr_info_get(sdi->driver, SR_DI_TRIGGER_SOURCES,
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
2850fca1 449 } else if (hwo->hwcap == SR_HWCAP_FILTER) {
e54290bd 450 /* Supported filters */
2850fca1 451 printf(" %s", hwo->shortname);
22981b2c
BV
452 if (sr_info_get(sdi->driver, SR_DI_FILTERS,
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
8f3b8464
BV
461 } else if (hwo->hwcap == SR_HWCAP_VDIV) {
462 /* Supported volts/div values */
463 printf(" %s", hwo->shortname);
22981b2c
BV
464 if (sr_info_get(sdi->driver, SR_DI_VDIVS,
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
498f9167
BV
473 } else if (hwo->hwcap == SR_HWCAP_COUPLING) {
474 /* Supported coupling settings */
475 printf(" %s", hwo->shortname);
22981b2c
BV
476 if (sr_info_get(sdi->driver, SR_DI_COUPLING,
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 */
43e5747a
UH
487 printf(" %s\n", hwo->shortname);
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
37d5ccc1 549static void datafeed_in(const struct sr_dev_inst *sdi,
3d905bcc 550 const struct sr_datafeed_packet *packet)
43e5747a
UH
551{
552 static struct sr_output *o = NULL;
f8ccd825 553 static int logic_probelist[SR_MAX_NUM_PROBES] = { -1 };
43e5747a
UH
554 static uint64_t received_samples = 0;
555 static int unitsize = 0;
556 static int triggered = 0;
557 static FILE *outfile = NULL;
558 struct sr_probe *probe;
3d905bcc
JH
559 const struct sr_datafeed_logic *logic;
560 const struct sr_datafeed_meta_logic *meta_logic;
561 const struct sr_datafeed_analog *analog;
48f71481 562 int num_enabled_probes, sample_size, ret, i;
43e5747a 563 uint64_t output_len, filter_out_len;
8de01efe 564 uint8_t *output_buf, *filter_out;
05e7fa2c 565 GString *out;
43e5747a
UH
566
567 /* If the first packet to come in isn't a header, don't even try. */
568 if (packet->type != SR_DF_HEADER && o == NULL)
569 return;
570
571 sample_size = -1;
572 switch (packet->type) {
573 case SR_DF_HEADER:
8170b8ea 574 g_debug("cli: Received SR_DF_HEADER");
43e5747a 575 /* Initialize the output module. */
c2c4a0de 576 if (!(o = g_try_malloc(sizeof(struct sr_output)))) {
8170b8ea 577 g_critical("Output module malloc failed.");
43e5747a
UH
578 exit(1);
579 }
580 o->format = output_format;
37d5ccc1 581 o->sdi = (struct sr_dev_inst *)sdi;
43e5747a
UH
582 o->param = output_format_param;
583 if (o->format->init) {
584 if (o->format->init(o) != SR_OK) {
8170b8ea 585 g_critical("Output format initialization failed.");
43e5747a
UH
586 exit(1);
587 }
588 }
43e5747a 589 break;
53993299 590
43e5747a 591 case SR_DF_END:
8170b8ea 592 g_debug("cli: Received SR_DF_END");
43e5747a 593 if (!o) {
8170b8ea 594 g_debug("cli: double end!");
43e5747a
UH
595 break;
596 }
597 if (o->format->event) {
598 o->format->event(o, SR_DF_END, &output_buf, &output_len);
d3f829a1 599 if (output_buf) {
43e5747a
UH
600 if (outfile)
601 fwrite(output_buf, 1, output_len, outfile);
c2c4a0de 602 g_free(output_buf);
43e5747a
UH
603 output_len = 0;
604 }
605 }
606 if (limit_samples && received_samples < limit_samples)
8170b8ea 607 g_warning("Device only sent %" PRIu64 " samples.",
43e5747a
UH
608 received_samples);
609 if (opt_continuous)
8170b8ea 610 g_warning("Device stopped after %" PRIu64 " samples.",
43e5747a 611 received_samples);
43e5747a
UH
612 if (outfile && outfile != stdout)
613 fclose(outfile);
05e7fa2c
BV
614
615 if (o->format->cleanup)
616 o->format->cleanup(o);
c2c4a0de 617 g_free(o);
43e5747a
UH
618 o = NULL;
619 break;
53993299 620
43e5747a 621 case SR_DF_TRIGGER:
8170b8ea 622 g_debug("cli: received SR_DF_TRIGGER");
43e5747a
UH
623 if (o->format->event)
624 o->format->event(o, SR_DF_TRIGGER, &output_buf,
625 &output_len);
626 triggered = 1;
627 break;
53993299
BV
628
629 case SR_DF_META_LOGIC:
630 g_message("cli: Received SR_DF_META_LOGIC");
631 meta_logic = packet->payload;
632 num_enabled_probes = 0;
633 for (i = 0; i < meta_logic->num_probes; i++) {
37d5ccc1 634 probe = g_slist_nth_data(sdi->probes, i);
53993299
BV
635 if (probe->enabled)
636 logic_probelist[num_enabled_probes++] = probe->index;
637 }
8c8056b5 638 logic_probelist[num_enabled_probes] = -1;
53993299
BV
639 /* How many bytes we need to store num_enabled_probes bits */
640 unitsize = (num_enabled_probes + 7) / 8;
641
642 outfile = stdout;
643 if (opt_output_file) {
644 if (default_output_format) {
645 /* output file is in session format, which means we'll
646 * dump everything in the datastore as it comes in,
647 * and save from there after the session. */
648 outfile = NULL;
f8ccd825 649 ret = sr_datastore_new(unitsize, &singleds);
53993299 650 if (ret != SR_OK) {
f8ccd825 651 g_critical("Failed to create datastore.");
53993299
BV
652 exit(1);
653 }
654 } else {
655 /* saving to a file in whatever format was set
656 * with --format, so all we need is a filehandle */
657 outfile = g_fopen(opt_output_file, "wb");
658 }
659 }
660 if (opt_pds)
661 srd_session_start(num_enabled_probes, unitsize,
662 meta_logic->samplerate);
663 break;
664
43e5747a
UH
665 case SR_DF_LOGIC:
666 logic = packet->payload;
b46c4414 667 g_message("cli: received SR_DF_LOGIC, %"PRIu64" bytes", logic->length);
53993299
BV
668 sample_size = logic->unitsize;
669 if (logic->length == 0)
670 break;
671
672 /* Don't store any samples until triggered. */
673 if (opt_wait_trigger && !triggered)
674 break;
43e5747a 675
53993299
BV
676 if (limit_samples && received_samples >= limit_samples)
677 break;
43e5747a 678
53993299 679 ret = sr_filter_probes(sample_size, unitsize, logic_probelist,
f8ccd825
BV
680 logic->data, logic->length,
681 &filter_out, &filter_out_len);
53993299
BV
682 if (ret != SR_OK)
683 break;
43e5747a 684
53993299
BV
685 /* what comes out of the filter is guaranteed to be packed into the
686 * minimum size needed to support the number of samples at this sample
687 * size. however, the driver may have submitted too much -- cut off
688 * the buffer of the last packet according to the sample limit.
689 */
690 if (limit_samples && (received_samples + logic->length / sample_size >
691 limit_samples * sample_size))
692 filter_out_len = limit_samples * sample_size - received_samples;
43e5747a 693
f8ccd825
BV
694 if (singleds)
695 sr_datastore_put(singleds, filter_out,
696 filter_out_len, sample_size, logic_probelist);
43e5747a 697
53993299
BV
698 if (opt_output_file && default_output_format)
699 /* saving to a session file, don't need to do anything else
700 * to this data for now. */
701 goto cleanup;
702
703 if (opt_pds) {
704 if (srd_session_send(received_samples, (uint8_t*)filter_out,
705 filter_out_len) != SRD_OK)
c6ca71bb 706 sr_session_stop();
53993299
BV
707 } else {
708 output_len = 0;
709 if (o->format->data && packet->type == o->format->df_type)
710 o->format->data(o, filter_out, filter_out_len, &output_buf, &output_len);
d3f829a1 711 if (output_buf) {
53993299 712 fwrite(output_buf, 1, output_len, outfile);
e09810e9 713 fflush(outfile);
53993299
BV
714 g_free(output_buf);
715 }
716 }
717
718 cleanup:
719 g_free(filter_out);
720 received_samples += logic->length / sample_size;
721 break;
722
723 case SR_DF_META_ANALOG:
724 g_message("cli: Received SR_DF_META_ANALOG");
43e5747a 725
53993299
BV
726 outfile = stdout;
727 if (opt_output_file) {
728 if (default_output_format) {
729 /* output file is in session format, which means we'll
730 * dump everything in the datastore as it comes in,
731 * and save from there after the session. */
732 outfile = NULL;
f8ccd825 733 ret = sr_datastore_new(unitsize, &singleds);
53993299 734 if (ret != SR_OK) {
f8ccd825 735 g_critical("Failed to create datastore.");
53993299
BV
736 exit(1);
737 }
738 } else {
739 /* saving to a file in whatever format was set
740 * with --format, so all we need is a filehandle */
741 outfile = g_fopen(opt_output_file, "wb");
742 }
43e5747a 743 }
53993299
BV
744 break;
745
746 case SR_DF_ANALOG:
747 analog = packet->payload;
748 g_message("cli: received SR_DF_ANALOG, %d samples", analog->num_samples);
749 if (analog->num_samples == 0)
750 break;
751
752 if (limit_samples && received_samples >= limit_samples)
753 break;
754
48f71481
BV
755 if (o->format->data && packet->type == o->format->df_type) {
756 o->format->data(o, (const uint8_t *)analog->data,
757 analog->num_samples * sizeof(float),
758 &output_buf, &output_len);
759 if (output_buf) {
760 fwrite(output_buf, 1, output_len, outfile);
e09810e9 761 fflush(outfile);
48f71481 762 g_free(output_buf);
c8db7172 763 }
53993299
BV
764 }
765
53993299 766 received_samples += analog->num_samples;
ce48d892
BV
767 break;
768
769 case SR_DF_FRAME_BEGIN:
48f71481
BV
770 g_debug("cli: received SR_DF_FRAME_BEGIN");
771 if (o->format->event) {
772 o->format->event(o, SR_DF_FRAME_BEGIN, &output_buf,
773 &output_len);
774 if (output_buf) {
775 fwrite(output_buf, 1, output_len, outfile);
e09810e9 776 fflush(outfile);
48f71481
BV
777 g_free(output_buf);
778 }
779 }
ce48d892
BV
780 break;
781
782 case SR_DF_FRAME_END:
48f71481
BV
783 g_debug("cli: received SR_DF_FRAME_END");
784 if (o->format->event) {
785 o->format->event(o, SR_DF_FRAME_END, &output_buf,
786 &output_len);
787 if (output_buf) {
788 fwrite(output_buf, 1, output_len, outfile);
e09810e9 789 fflush(outfile);
48f71481
BV
790 g_free(output_buf);
791 }
792 }
ce48d892 793 break;
53993299
BV
794
795 default:
796 g_message("received unknown packet type %d", packet->type);
43e5747a
UH
797 }
798
05e7fa2c
BV
799 if (o && o->format->recv) {
800 out = o->format->recv(o, sdi, packet);
801 if (out && out->len) {
802 fwrite(out->str, 1, out->len, outfile);
803 fflush(outfile);
804 }
805 }
806
43e5747a
UH
807}
808
9f4a898e
BV
809/* Register the given PDs for this session.
810 * Accepts a string of the form: "spi:sck=3:sdata=4,spi:sck=3:sdata=5"
43e5747a
UH
811 * That will instantiate two SPI decoders on the clock but different data
812 * lines.
813 */
1e0f9ed9 814static int register_pds(struct sr_dev *dev, const char *pdstring)
43e5747a 815{
9720f23a 816 GHashTable *pd_opthash;
878e90d9 817 struct srd_decoder_inst *di;
445950d3 818 int ret;
a1418b73 819 char **pdtokens, **pdtok, *pd_name;
43e5747a 820
1e0f9ed9 821 (void)dev;
43e5747a 822
445950d3 823 ret = 0;
120f9ee7
BV
824 pd_ann_visible = g_hash_table_new_full(g_str_hash, g_int_equal,
825 g_free, NULL);
a1418b73 826 pd_name = NULL;
120f9ee7
BV
827 pd_opthash = NULL;
828 pdtokens = g_strsplit(pdstring, ",", 0);
43e5747a 829 for (pdtok = pdtokens; *pdtok; pdtok++) {
63bb454c 830 if (!(pd_opthash = parse_generic_arg(*pdtok, TRUE))) {
8170b8ea 831 g_critical("Invalid protocol decoder option '%s'.", *pdtok);
a1418b73 832 goto err_out;
43e5747a 833 }
a1418b73 834
9720f23a
BV
835 pd_name = g_strdup(g_hash_table_lookup(pd_opthash, "sigrok_key"));
836 g_hash_table_remove(pd_opthash, "sigrok_key");
2358775c 837 if (srd_decoder_load(pd_name) != SRD_OK) {
8170b8ea 838 g_critical("Failed to load protocol decoder %s.", pd_name);
445950d3 839 ret = 1;
15d920a9
BV
840 goto err_out;
841 }
878e90d9 842 if (!(di = srd_inst_new(pd_name, pd_opthash))) {
8170b8ea 843 g_critical("Failed to instantiate protocol decoder %s.", pd_name);
445950d3 844 ret = 1;
a1418b73 845 goto err_out;
43e5747a 846 }
120f9ee7
BV
847
848 /* If no annotation list was specified, add them all in now.
849 * This will be pared down later to leave only the last PD
850 * in the stack.
851 */
b6bd032d
UH
852 if (!opt_pd_annotations)
853 g_hash_table_insert(pd_ann_visible,
854 g_strdup(di->inst_id), NULL);
a1418b73 855
67ce0d27
BV
856 /* Any keys left in the options hash are probes, where the key
857 * is the probe name as specified in the decoder class, and the
858 * value is the probe number i.e. the order in which the PD's
859 * incoming samples are arranged. */
445950d3
BV
860 if (srd_inst_probe_set_all(di, pd_opthash) != SRD_OK) {
861 ret = 1;
67ce0d27 862 goto err_out;
445950d3 863 }
67ce0d27
BV
864 g_hash_table_destroy(pd_opthash);
865 pd_opthash = NULL;
866 }
43e5747a 867
a1418b73 868err_out:
43e5747a 869 g_strfreev(pdtokens);
9720f23a
BV
870 if (pd_opthash)
871 g_hash_table_destroy(pd_opthash);
a1418b73
BV
872 if (pd_name)
873 g_free(pd_name);
43e5747a 874
445950d3 875 return ret;
43e5747a
UH
876}
877
120f9ee7
BV
878int setup_pd_stack(void)
879{
880 struct srd_decoder_inst *di_from, *di_to;
881 int ret, i;
41e915a6 882 char **pds, **ids;
120f9ee7
BV
883
884 /* Set up the protocol decoder stack. */
885 pds = g_strsplit(opt_pds, ",", 0);
886 if (g_strv_length(pds) > 1) {
887 if (opt_pd_stack) {
888 /* A stack setup was specified, use that. */
889 g_strfreev(pds);
890 pds = g_strsplit(opt_pd_stack, ",", 0);
891 if (g_strv_length(pds) < 2) {
892 g_strfreev(pds);
893 g_critical("Specify at least two protocol decoders to stack.");
894 return 1;
895 }
896 }
897
41e915a6
BV
898 /* First PD goes at the bottom of the stack. */
899 ids = g_strsplit(pds[0], ":", 0);
900 if (!(di_from = srd_inst_find_by_id(ids[0]))) {
901 g_strfreev(ids);
120f9ee7
BV
902 g_critical("Cannot stack protocol decoder '%s': "
903 "instance not found.", pds[0]);
904 return 1;
905 }
41e915a6
BV
906 g_strfreev(ids);
907
908 /* Every subsequent PD goes on top. */
120f9ee7 909 for (i = 1; pds[i]; i++) {
41e915a6
BV
910 ids = g_strsplit(pds[i], ":", 0);
911 if (!(di_to = srd_inst_find_by_id(ids[0]))) {
912 g_strfreev(ids);
120f9ee7
BV
913 g_critical("Cannot stack protocol decoder '%s': "
914 "instance not found.", pds[i]);
915 return 1;
916 }
41e915a6 917 g_strfreev(ids);
120f9ee7
BV
918 if ((ret = srd_inst_stack(di_from, di_to)) != SRD_OK)
919 return 1;
920
921 /* Don't show annotation from this PD. Only the last PD in
922 * the stack will be left on the annotation list (unless
923 * the annotation list was specifically provided).
924 */
478a782d 925 if (!opt_pd_annotations)
b6bd032d
UH
926 g_hash_table_remove(pd_ann_visible,
927 di_from->inst_id);
120f9ee7
BV
928
929 di_from = di_to;
930 }
931 }
932 g_strfreev(pds);
933
934 return 0;
935}
936
937int setup_pd_annotations(void)
938{
939 GSList *l;
940 struct srd_decoder *dec;
941 int ann;
942 char **pds, **pdtok, **keyval, **ann_descr;
943
944 /* Set up custom list of PDs and annotations to show. */
b6bd032d
UH
945 if (opt_pd_annotations) {
946 pds = g_strsplit(opt_pd_annotations, ",", 0);
120f9ee7
BV
947 for (pdtok = pds; *pdtok && **pdtok; pdtok++) {
948 ann = 0;
949 keyval = g_strsplit(*pdtok, "=", 0);
950 if (!(dec = srd_decoder_get_by_id(keyval[0]))) {
951 g_critical("Protocol decoder '%s' not found.", keyval[0]);
952 return 1;
953 }
954 if (!dec->annotations) {
955 g_critical("Protocol decoder '%s' has no annotations.", keyval[0]);
956 return 1;
957 }
958 if (g_strv_length(keyval) == 2) {
959 for (l = dec->annotations; l; l = l->next, ann++) {
960 ann_descr = l->data;
961 if (!canon_cmp(ann_descr[0], keyval[1]))
962 /* Found it. */
963 break;
964 }
965 if (!l) {
966 g_critical("Annotation '%s' not found "
967 "for protocol decoder '%s'.", keyval[1], keyval[0]);
968 return 1;
969 }
970 }
971 g_debug("cli: showing protocol decoder annotation %d from '%s'", ann, keyval[0]);
972 g_hash_table_insert(pd_ann_visible, g_strdup(keyval[0]), GINT_TO_POINTER(ann));
973 g_strfreev(keyval);
974 }
975 g_strfreev(pds);
976 }
977
978 return 0;
979}
980
ad2bc491
BV
981int setup_output_format(void)
982{
983 GHashTable *fmtargs;
984 GHashTableIter iter;
985 gpointer key, value;
986 struct sr_output_format **outputs;
987 int i;
988 char *fmtspec;
989
990 if (!opt_output_format) {
991 opt_output_format = DEFAULT_OUTPUT_FORMAT;
992 /* we'll need to remember this so when saving to a file
993 * later, sigrok session format will be used.
994 */
995 default_output_format = TRUE;
996 }
48f71481 997
63bb454c 998 fmtargs = parse_generic_arg(opt_output_format, TRUE);
ad2bc491
BV
999 fmtspec = g_hash_table_lookup(fmtargs, "sigrok_key");
1000 if (!fmtspec) {
1001 g_critical("Invalid output format.");
1002 return 1;
1003 }
1004 outputs = sr_output_list();
1005 for (i = 0; outputs[i]; i++) {
1006 if (strcmp(outputs[i]->id, fmtspec))
1007 continue;
1008 g_hash_table_remove(fmtargs, "sigrok_key");
1009 output_format = outputs[i];
1010 g_hash_table_iter_init(&iter, fmtargs);
1011 while (g_hash_table_iter_next(&iter, &key, &value)) {
1012 /* only supporting one parameter per output module
1013 * for now, and only its value */
1014 output_format_param = g_strdup(value);
1015 break;
1016 }
1017 break;
1018 }
1019 if (!output_format) {
1020 g_critical("Invalid output format %s.", opt_output_format);
1021 return 1;
1022 }
1023 g_hash_table_destroy(fmtargs);
1024
1025 return 0;
1026}
1027
478a782d 1028void show_pd_annotations(struct srd_proto_data *pdata, void *cb_data)
213c6cea
BV
1029{
1030 int i;
ca07c711 1031 char **annotations;
120f9ee7 1032 gpointer ann_format;
213c6cea 1033
68cdf174
UH
1034 /* 'cb_data' is not used in this specific callback. */
1035 (void)cb_data;
7cb9889f 1036
120f9ee7 1037 if (!pd_ann_visible)
213c6cea 1038 return;
213c6cea 1039
120f9ee7
BV
1040 if (!g_hash_table_lookup_extended(pd_ann_visible, pdata->pdo->di->inst_id,
1041 NULL, &ann_format))
9720f23a 1042 /* Not in the list of PDs whose annotations we're showing. */
9f4a898e 1043 return;
120f9ee7
BV
1044
1045 if (pdata->ann_format != GPOINTER_TO_INT(ann_format))
1046 /* We don't want this particular format from the PD. */
1047 return;
9f4a898e 1048
9720f23a 1049 annotations = pdata->data;
41bc9e4f
BV
1050 if (opt_loglevel > SR_LOG_WARN)
1051 printf("%"PRIu64"-%"PRIu64" ", pdata->start_sample, pdata->end_sample);
ca07c711
UH
1052 printf("%s: ", pdata->pdo->proto_id);
1053 for (i = 0; annotations[i]; i++)
1054 printf("\"%s\" ", annotations[i]);
213c6cea 1055 printf("\n");
5befb6d6 1056 fflush(stdout);
213c6cea
BV
1057}
1058
37d5ccc1 1059static int select_probes(struct sr_dev_inst *sdi)
43e5747a 1060{
497f5362
BV
1061 struct sr_probe *probe;
1062 GSList *selected_probes, *l;
43e5747a
UH
1063
1064 if (!opt_probes)
1065 return SR_OK;
1066
497f5362 1067 if (!(selected_probes = parse_probestring(sdi, opt_probes)))
43e5747a 1068 return SR_ERR;
43e5747a 1069
497f5362
BV
1070 for (l = sdi->probes; l; l = l->next) {
1071 probe = l->data;
1072 if (g_slist_find(selected_probes, probe))
1073 probe->enabled = TRUE;
1074 else
1075 probe->enabled = FALSE;
43e5747a 1076 }
497f5362 1077 g_slist_free(selected_probes);
43e5747a
UH
1078
1079 return SR_OK;
1080}
1081
1082/**
1083 * Return the input file format which the CLI tool should use.
1084 *
1085 * If the user specified -I / --input-format, use that one. Otherwise, try to
1086 * autodetect the format as good as possible. Failing that, return NULL.
1087 *
1088 * @param filename The filename of the input file. Must not be NULL.
1089 * @param opt The -I / --input-file option the user specified (or NULL).
1090 *
1091 * @return A pointer to the 'struct sr_input_format' that should be used,
1092 * or NULL if no input format was selected or auto-detected.
1093 */
1094static struct sr_input_format *determine_input_file_format(
1095 const char *filename, const char *opt)
1096{
1097 int i;
1098 struct sr_input_format **inputs;
1099
1100 /* If there are no input formats, return NULL right away. */
1101 inputs = sr_input_list();
1102 if (!inputs) {
8170b8ea 1103 g_critical("No supported input formats available.");
43e5747a
UH
1104 return NULL;
1105 }
1106
1107 /* If the user specified -I / --input-format, use that one. */
1108 if (opt) {
1109 for (i = 0; inputs[i]; i++) {
943d0c08 1110 if (strcasecmp(inputs[i]->id, opt))
43e5747a 1111 continue;
8170b8ea
BV
1112 g_debug("Using user-specified input file format '%s'.",
1113 inputs[i]->id);
43e5747a
UH
1114 return inputs[i];
1115 }
1116
1117 /* The user specified an unknown input format, return NULL. */
8170b8ea 1118 g_critical("Error: specified input file format '%s' is "
943d0c08 1119 "unknown.", opt);
43e5747a
UH
1120 return NULL;
1121 }
1122
1123 /* Otherwise, try to find an input module that can handle this file. */
1124 for (i = 0; inputs[i]; i++) {
1125 if (inputs[i]->format_match(filename))
1126 break;
1127 }
1128
1129 /* Return NULL if no input module wanted to touch this. */
1130 if (!inputs[i]) {
8170b8ea 1131 g_critical("Error: no matching input module found.");
43e5747a
UH
1132 return NULL;
1133 }
78912cc1
UH
1134
1135 g_debug("cli: Autodetected '%s' input format for file '%s'.",
1136 inputs[i]->id, filename);
43e5747a 1137
43e5747a
UH
1138 return inputs[i];
1139}
1140
1141static void load_input_file_format(void)
1142{
943d0c08 1143 GHashTable *fmtargs = NULL;
43e5747a
UH
1144 struct stat st;
1145 struct sr_input *in;
1146 struct sr_input_format *input_format;
943d0c08
TÅ 
1147 char *fmtspec = NULL;
1148
1149 if (opt_input_format) {
3e8e0c2d 1150 fmtargs = parse_generic_arg(opt_input_format, TRUE);
943d0c08
TÅ 
1151 fmtspec = g_hash_table_lookup(fmtargs, "sigrok_key");
1152 }
43e5747a 1153
8170b8ea 1154 if (!(input_format = determine_input_file_format(opt_input_file,
943d0c08 1155 fmtspec))) {
8170b8ea 1156 /* The exact cause was already logged. */
43e5747a 1157 return;
943d0c08 1158 }
3e8e0c2d 1159
943d0c08
TÅ 
1160 if (fmtargs)
1161 g_hash_table_remove(fmtargs, "sigrok_key");
43e5747a
UH
1162
1163 if (stat(opt_input_file, &st) == -1) {
8170b8ea 1164 g_critical("Failed to load %s: %s", opt_input_file,
43e5747a
UH
1165 strerror(errno));
1166 exit(1);
1167 }
1168
1169 /* Initialize the input module. */
c2c4a0de 1170 if (!(in = g_try_malloc(sizeof(struct sr_input)))) {
8170b8ea 1171 g_critical("Failed to allocate input module.");
43e5747a
UH
1172 exit(1);
1173 }
1174 in->format = input_format;
943d0c08 1175 in->param = fmtargs;
43e5747a
UH
1176 if (in->format->init) {
1177 if (in->format->init(in) != SR_OK) {
8170b8ea 1178 g_critical("Input format init failed.");
43e5747a
UH
1179 exit(1);
1180 }
1181 }
1182
37d5ccc1 1183 if (select_probes(in->sdi) > 0)
43e5747a
UH
1184 return;
1185
1186 sr_session_new();
1187 sr_session_datafeed_callback_add(datafeed_in);
37d5ccc1 1188 if (sr_session_dev_add(in->sdi) != SR_OK) {
8170b8ea 1189 g_critical("Failed to use device.");
43e5747a
UH
1190 sr_session_destroy();
1191 return;
1192 }
1193
1194 input_format->loadfile(in, opt_input_file);
1195 if (opt_output_file && default_output_format) {
f8ccd825 1196 if (sr_session_save(opt_output_file, in->sdi, singleds) != SR_OK)
8170b8ea 1197 g_critical("Failed to save session.");
43e5747a
UH
1198 }
1199 sr_session_destroy();
943d0c08
TÅ 
1200
1201 if (fmtargs)
1202 g_hash_table_destroy(fmtargs);
43e5747a
UH
1203}
1204
1205static void load_input_file(void)
1206{
1207
1208 if (sr_session_load(opt_input_file) == SR_OK) {
1209 /* sigrok session file */
1210 sr_session_datafeed_callback_add(datafeed_in);
1211 sr_session_start();
1212 sr_session_run();
1213 sr_session_stop();
1214 }
1215 else {
1216 /* fall back on input modules */
1217 load_input_file_format();
1218 }
43e5747a
UH
1219}
1220
37d5ccc1 1221static int set_dev_options(struct sr_dev_inst *sdi, GHashTable *args)
43e5747a 1222{
cfd3ec6e 1223 const struct sr_hwcap_option *hwo;
43e5747a
UH
1224 GHashTableIter iter;
1225 gpointer key, value;
cfd3ec6e 1226 int ret;
c8db7172 1227 float tmp_float;
43e5747a 1228 uint64_t tmp_u64;
c8db7172 1229 struct sr_rational tmp_rat;
43e5747a 1230 gboolean tmp_bool;
37d5ccc1 1231 void *val;
43e5747a
UH
1232
1233 g_hash_table_iter_init(&iter, args);
1234 while (g_hash_table_iter_next(&iter, &key, &value)) {
cfd3ec6e
BV
1235 if (!(hwo = sr_devopt_name_get(key))) {
1236 g_critical("Unknown device option '%s'.", (char *) key);
1237 return SR_ERR;
1238 }
1239
1240 if ((value == NULL) &&
1241 (hwo->type != SR_T_BOOL)) {
1242 g_critical("Option '%s' needs a value.", (char *)key);
1243 return SR_ERR;
1244 }
1245 val = NULL;
1246 switch (hwo->type) {
1247 case SR_T_UINT64:
1248 ret = sr_parse_sizestring(value, &tmp_u64);
1249 if (ret != SR_OK)
8f3b8464 1250 break;
cfd3ec6e
BV
1251 val = &tmp_u64;
1252 break;
1253 case SR_T_CHAR:
1254 val = value;
1255 break;
1256 case SR_T_BOOL:
1257 if (!value)
1258 tmp_bool = TRUE;
43e5747a 1259 else
cfd3ec6e
BV
1260 tmp_bool = sr_parse_boolstring(value);
1261 val = &tmp_bool;
1262 break;
1263 case SR_T_FLOAT:
1264 tmp_float = strtof(value, NULL);
1265 val = &tmp_float;
1266 break;
1267 case SR_T_RATIONAL_PERIOD:
1268 if ((ret = sr_parse_period(value, &tmp_rat)) != SR_OK)
1269 break;
1270 val = &tmp_rat;
1271 break;
1272 case SR_T_RATIONAL_VOLT:
1273 if ((ret = sr_parse_voltage(value, &tmp_rat)) != SR_OK)
43e5747a 1274 break;
cfd3ec6e
BV
1275 val = &tmp_rat;
1276 break;
1277 default:
1278 ret = SR_ERR;
43e5747a 1279 }
cfd3ec6e 1280 if (val)
4ed6cde9 1281 ret = sr_dev_config_set(sdi, hwo->hwcap, val);
cfd3ec6e
BV
1282 if (ret != SR_OK) {
1283 g_critical("Failed to set device option '%s'.", (char *)key);
1284 return ret;
43e5747a
UH
1285 }
1286 }
1287
1288 return SR_OK;
1289}
1290
37d5ccc1 1291static int set_limit_time(const struct sr_dev_inst *sdi)
43e5747a 1292{
9c9c1080 1293 uint64_t time_msec;
37d5ccc1 1294 uint64_t *samplerate;
43e5747a 1295
37d5ccc1
BV
1296 time_msec = sr_parse_timestring(opt_time);
1297 if (time_msec == 0) {
1298 g_critical("Invalid time '%s'", opt_time);
43e5747a 1299 sr_session_destroy();
37d5ccc1 1300 return SR_ERR;
43e5747a
UH
1301 }
1302
37d5ccc1 1303 if (sr_driver_hwcap_exists(sdi->driver, SR_HWCAP_LIMIT_MSEC)) {
4ed6cde9 1304 if (sr_dev_config_set(sdi, SR_HWCAP_LIMIT_MSEC, &time_msec) != SR_OK) {
37d5ccc1 1305 g_critical("Failed to configure time limit.");
43e5747a 1306 sr_session_destroy();
37d5ccc1 1307 return SR_ERR;
43e5747a 1308 }
43e5747a 1309 }
37d5ccc1
BV
1310 else {
1311 /* time limit set, but device doesn't support this...
1312 * convert to samples based on the samplerate.
1313 */
1314 limit_samples = 0;
1315 if (sr_dev_has_hwcap(sdi, SR_HWCAP_SAMPLERATE)) {
1316 sr_info_get(sdi->driver, SR_DI_CUR_SAMPLERATE,
1317 (const void **)&samplerate, sdi);
1318 limit_samples = (*samplerate) * time_msec / (uint64_t)1000;
1319 }
1320 if (limit_samples == 0) {
1321 g_critical("Not enough time at this samplerate.");
43e5747a 1322 sr_session_destroy();
37d5ccc1 1323 return SR_ERR;
43e5747a 1324 }
43e5747a 1325
4ed6cde9
BV
1326 if (sr_dev_config_set(sdi, SR_HWCAP_LIMIT_SAMPLES,
1327 &limit_samples) != SR_OK) {
37d5ccc1 1328 g_critical("Failed to configure time-based sample limit.");
43e5747a 1329 sr_session_destroy();
37d5ccc1 1330 return SR_ERR;
43e5747a 1331 }
37d5ccc1 1332 }
43e5747a 1333
37d5ccc1
BV
1334 return SR_OK;
1335}
1336
1337static void run_session(void)
1338{
06a3fb10 1339 GSList *devices;
37d5ccc1
BV
1340 GHashTable *devargs;
1341 struct sr_dev_inst *sdi;
1342 int max_probes, i;
06a3fb10
BV
1343 char **triggerlist;
1344
1345 devices = device_scan();
1346 if (!devices) {
1347 g_critical("No devices found.");
1348 return;
1349 }
1350 if (g_slist_length(devices) > 1) {
1351 g_critical("sigrok-cli only supports one device for capturing.");
1352 return;
1353 }
1354 sdi = devices->data;
37d5ccc1
BV
1355
1356 sr_session_new();
1357 sr_session_datafeed_callback_add(datafeed_in);
1358
8ab6aafc
BV
1359 if (sr_session_dev_add(sdi) != SR_OK) {
1360 g_critical("Failed to use device.");
1361 sr_session_destroy();
1362 return;
1363 }
1364
06a3fb10
BV
1365 if (opt_dev) {
1366 if ((devargs = parse_generic_arg(opt_dev, FALSE))) {
1367 if (set_dev_options(sdi, devargs) != SR_OK)
1368 return;
1369 g_hash_table_destroy(devargs);
43e5747a 1370 }
06a3fb10 1371 }
43e5747a 1372
06a3fb10
BV
1373 if (select_probes(sdi) != SR_OK) {
1374 g_critical("Failed to set probes.");
1375 sr_session_destroy();
1376 return;
1377 }
1378
1379 if (opt_triggers) {
1380 if (!(triggerlist = sr_parse_triggerstring(sdi, opt_triggers))) {
43e5747a
UH
1381 sr_session_destroy();
1382 return;
1383 }
06a3fb10
BV
1384 max_probes = g_slist_length(sdi->probes);
1385 for (i = 0; i < max_probes; i++) {
1386 if (triggerlist[i]) {
1387 sr_dev_trigger_set(sdi, i, triggerlist[i]);
1388 g_free(triggerlist[i]);
43e5747a
UH
1389 }
1390 }
06a3fb10
BV
1391 g_free(triggerlist);
1392 }
9c9c1080 1393
06a3fb10
BV
1394 if (opt_continuous) {
1395 if (!sr_driver_hwcap_exists(sdi->driver, SR_HWCAP_CONTINUOUS)) {
1396 g_critical("This device does not support continuous sampling.");
37d5ccc1
BV
1397 sr_session_destroy();
1398 return;
1399 }
37d5ccc1
BV
1400 }
1401
1402 if (opt_time) {
1403 if (set_limit_time(sdi) != SR_OK) {
1404 sr_session_destroy();
1405 return;
43e5747a
UH
1406 }
1407 }
1408
1409 if (opt_samples) {
1410 if ((sr_parse_sizestring(opt_samples, &limit_samples) != SR_OK)
4ed6cde9 1411 || (sr_dev_config_set(sdi, SR_HWCAP_LIMIT_SAMPLES,
37d5ccc1 1412 &limit_samples) != SR_OK)) {
8170b8ea 1413 g_critical("Failed to configure sample limit.");
43e5747a
UH
1414 sr_session_destroy();
1415 return;
1416 }
1417 }
1418
ce48d892
BV
1419 if (opt_frames) {
1420 if ((sr_parse_sizestring(opt_frames, &limit_frames) != SR_OK)
4ed6cde9
BV
1421 || (sr_dev_config_set(sdi, SR_HWCAP_LIMIT_FRAMES,
1422 &limit_frames) != SR_OK)) {
f8ccd825 1423 g_critical("Failed to configure frame limit.");
ce48d892
BV
1424 sr_session_destroy();
1425 return;
1426 }
1427 }
1428
43e5747a 1429 if (sr_session_start() != SR_OK) {
8170b8ea 1430 g_critical("Failed to start session.");
43e5747a
UH
1431 sr_session_destroy();
1432 return;
1433 }
1434
1435 if (opt_continuous)
1436 add_anykey();
1437
1438 sr_session_run();
1439
1440 if (opt_continuous)
1441 clear_anykey();
1442
1443 if (opt_output_file && default_output_format) {
f8ccd825 1444 if (sr_session_save(opt_output_file, sdi, singleds) != SR_OK)
8170b8ea 1445 g_critical("Failed to save session.");
43e5747a
UH
1446 }
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}