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