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