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