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