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