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