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