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