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