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