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