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