decode: Optionally print sample numbers with protocol decoder annotations
[sigrok-cli.git] / session.c
blob6b31ef5ce027afed17c215f9456e9877e5d4c8ce
1 /*
2 * This file is part of the sigrok-cli project.
4 * Copyright (C) 2013 Bert Vermeulen <bert@biot.com>
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.
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.
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/>.
20 #include <config.h>
21 #include <glib.h>
22 #include <glib/gstdio.h>
23 #include <string.h>
24 #include <stdlib.h>
25 #include "sigrok-cli.h"
27 static uint64_t limit_samples = 0;
28 static uint64_t limit_frames = 0;
30 #ifdef HAVE_SRD
31 extern struct srd_session *srd_sess;
32 #endif
34 static int set_limit_time(const struct sr_dev_inst *sdi)
36 GVariant *gvar;
37 uint64_t time_msec;
38 uint64_t samplerate;
39 struct sr_dev_driver *driver;
41 driver = sr_dev_inst_driver_get(sdi);
43 if (!(time_msec = sr_parse_timestring(opt_time))) {
44 g_critical("Invalid time '%s'", opt_time);
45 return SR_ERR;
48 if (sr_dev_config_capabilities_list(sdi, NULL, SR_CONF_LIMIT_MSEC)
49 & SR_CONF_SET) {
50 gvar = g_variant_new_uint64(time_msec);
51 if (sr_config_set(sdi, NULL, SR_CONF_LIMIT_MSEC, gvar) != SR_OK) {
52 g_critical("Failed to configure time limit.");
53 return SR_ERR;
55 } else if (sr_dev_config_capabilities_list(sdi, NULL, SR_CONF_SAMPLERATE)
56 & (SR_CONF_GET | SR_CONF_SET)) {
57 /* Convert to samples based on the samplerate. */
58 sr_config_get(driver, sdi, NULL, SR_CONF_SAMPLERATE, &gvar);
59 samplerate = g_variant_get_uint64(gvar);
60 g_variant_unref(gvar);
61 limit_samples = (samplerate) * time_msec / (uint64_t)1000;
62 if (limit_samples == 0) {
63 g_critical("Not enough time at this samplerate.");
64 return SR_ERR;
66 gvar = g_variant_new_uint64(limit_samples);
67 if (sr_config_set(sdi, NULL, SR_CONF_LIMIT_SAMPLES, gvar) != SR_OK) {
68 g_critical("Failed to configure time-based sample limit.");
69 return SR_ERR;
71 } else {
72 g_critical("This device does not support time limits.");
73 return SR_ERR;
76 return SR_OK;
79 const struct sr_output *setup_output_format(const struct sr_dev_inst *sdi, FILE **outfile)
81 const struct sr_output_module *omod;
82 const struct sr_option **options;
83 const struct sr_output *o;
84 GHashTable *fmtargs, *fmtopts;
85 char *fmtspec;
87 if (!opt_output_format) {
88 if (opt_output_file) {
89 opt_output_format = DEFAULT_OUTPUT_FORMAT_FILE;
90 } else {
91 opt_output_format = DEFAULT_OUTPUT_FORMAT_NOFILE;
95 fmtargs = parse_generic_arg(opt_output_format, TRUE);
96 fmtspec = g_hash_table_lookup(fmtargs, "sigrok_key");
97 if (!fmtspec)
98 g_critical("Invalid output format.");
99 if (!(omod = sr_output_find(fmtspec)))
100 g_critical("Unknown output module '%s'.", fmtspec);
101 g_hash_table_remove(fmtargs, "sigrok_key");
102 if ((options = sr_output_options_get(omod))) {
103 fmtopts = generic_arg_to_opt(options, fmtargs);
104 sr_output_options_free(options);
105 } else
106 fmtopts = NULL;
107 o = sr_output_new(omod, fmtopts, sdi, opt_output_file);
109 if (opt_output_file) {
110 if (!sr_output_test_flag(omod, SR_OUTPUT_INTERNAL_IO_HANDLING))
111 *outfile = g_fopen(opt_output_file, "wb");
112 else
113 *outfile = NULL;
114 } else {
115 *outfile = stdout;
118 if (fmtopts)
119 g_hash_table_destroy(fmtopts);
120 g_hash_table_destroy(fmtargs);
122 return o;
125 const struct sr_transform *setup_transform_module(const struct sr_dev_inst *sdi)
127 const struct sr_transform_module *tmod;
128 const struct sr_option **options;
129 const struct sr_transform *t;
130 GHashTable *fmtargs, *fmtopts;
131 char *fmtspec;
133 if (!opt_transform_module)
134 opt_transform_module = "nop";
136 fmtargs = parse_generic_arg(opt_transform_module, TRUE);
137 fmtspec = g_hash_table_lookup(fmtargs, "sigrok_key");
138 if (!fmtspec)
139 g_critical("Invalid transform module.");
140 if (!(tmod = sr_transform_find(fmtspec)))
141 g_critical("Unknown transform module '%s'.", fmtspec);
142 g_hash_table_remove(fmtargs, "sigrok_key");
143 if ((options = sr_transform_options_get(tmod))) {
144 fmtopts = generic_arg_to_opt(options, fmtargs);
145 sr_transform_options_free(options);
146 } else
147 fmtopts = NULL;
148 t = sr_transform_new(tmod, fmtopts, sdi);
149 if (fmtopts)
150 g_hash_table_destroy(fmtopts);
151 g_hash_table_destroy(fmtargs);
153 return t;
156 void datafeed_in(const struct sr_dev_inst *sdi,
157 const struct sr_datafeed_packet *packet, void *cb_data)
159 const struct sr_datafeed_meta *meta;
160 const struct sr_datafeed_logic *logic;
161 const struct sr_datafeed_analog *analog;
162 struct sr_session *session;
163 struct sr_config *src;
164 static const struct sr_output *o = NULL;
165 static const struct sr_output *oa = NULL;
166 static uint64_t rcvd_samples_logic = 0;
167 static uint64_t rcvd_samples_analog = 0;
168 static uint64_t samplerate = 0;
169 static int triggered = 0;
170 static FILE *outfile = NULL;
171 GSList *l;
172 GString *out;
173 GVariant *gvar;
174 uint64_t end_sample;
175 uint64_t input_len;
176 struct sr_dev_driver *driver;
178 /* Avoid warnings when building without decoder support. */
179 (void)session;
180 (void)input_len;
182 driver = sr_dev_inst_driver_get(sdi);
184 /* If the first packet to come in isn't a header, don't even try. */
185 if (packet->type != SR_DF_HEADER && !o)
186 return;
188 session = cb_data;
189 switch (packet->type) {
190 case SR_DF_HEADER:
191 g_debug("cli: Received SR_DF_HEADER.");
192 if (!(o = setup_output_format(sdi, &outfile)))
193 g_critical("Failed to initialize output module.");
195 /* Set up backup analog output module. */
196 oa = sr_output_new(sr_output_find("analog"), NULL, sdi, NULL);
198 rcvd_samples_logic = rcvd_samples_analog = 0;
200 if (maybe_config_get(driver, sdi, NULL, SR_CONF_SAMPLERATE,
201 &gvar) == SR_OK) {
202 samplerate = g_variant_get_uint64(gvar);
203 g_variant_unref(gvar);
206 #ifdef HAVE_SRD
207 if (opt_pds) {
208 if (samplerate) {
209 if (srd_session_metadata_set(srd_sess, SRD_CONF_SAMPLERATE,
210 g_variant_new_uint64(samplerate)) != SRD_OK) {
211 g_critical("Failed to configure decode session.");
212 break;
215 if (srd_session_start(srd_sess) != SRD_OK) {
216 g_critical("Failed to start decode session.");
217 break;
220 #endif
221 break;
223 case SR_DF_META:
224 g_debug("cli: Received SR_DF_META.");
225 meta = packet->payload;
226 for (l = meta->config; l; l = l->next) {
227 src = l->data;
228 switch (src->key) {
229 case SR_CONF_SAMPLERATE:
230 samplerate = g_variant_get_uint64(src->data);
231 g_debug("cli: Got samplerate %"PRIu64" Hz.", samplerate);
232 #ifdef HAVE_SRD
233 if (opt_pds) {
234 if (srd_session_metadata_set(srd_sess, SRD_CONF_SAMPLERATE,
235 g_variant_new_uint64(samplerate)) != SRD_OK) {
236 g_critical("Failed to pass samplerate to decoder.");
239 #endif
240 break;
241 case SR_CONF_SAMPLE_INTERVAL:
242 samplerate = g_variant_get_uint64(src->data);
243 g_debug("cli: Got sample interval %"PRIu64" ms.", samplerate);
244 break;
245 default:
246 /* Unknown metadata is not an error. */
247 break;
250 break;
252 case SR_DF_TRIGGER:
253 g_debug("cli: Received SR_DF_TRIGGER.");
254 triggered = 1;
255 break;
257 case SR_DF_LOGIC:
258 logic = packet->payload;
259 g_message("cli: Received SR_DF_LOGIC (%"PRIu64" bytes, unitsize = %d).",
260 logic->length, logic->unitsize);
261 if (logic->length == 0)
262 break;
264 /* Don't store any samples until triggered. */
265 if (opt_wait_trigger && !triggered)
266 break;
268 if (limit_samples && rcvd_samples_logic >= limit_samples)
269 break;
271 end_sample = rcvd_samples_logic + logic->length / logic->unitsize;
272 /* Cut off last packet according to the sample limit. */
273 if (limit_samples && end_sample > limit_samples)
274 end_sample = limit_samples;
275 input_len = (end_sample - rcvd_samples_logic) * logic->unitsize;
277 if (opt_pds) {
278 #ifdef HAVE_SRD
279 if (srd_session_send(srd_sess, rcvd_samples_logic, end_sample,
280 logic->data, input_len, logic->unitsize) != SRD_OK)
281 sr_session_stop(session);
282 #endif
285 rcvd_samples_logic = end_sample;
286 break;
288 case SR_DF_ANALOG:
289 analog = packet->payload;
290 g_message("cli: Received SR_DF_ANALOG (%d samples).", analog->num_samples);
291 if (analog->num_samples == 0)
292 break;
294 if (limit_samples && rcvd_samples_analog >= limit_samples)
295 break;
297 rcvd_samples_analog += analog->num_samples;
298 break;
300 case SR_DF_FRAME_BEGIN:
301 g_debug("cli: Received SR_DF_FRAME_BEGIN.");
302 break;
304 case SR_DF_FRAME_END:
305 g_debug("cli: Received SR_DF_FRAME_END.");
306 break;
308 default:
309 break;
312 if (o && !opt_pds) {
313 if (sr_output_send(o, packet, &out) == SR_OK) {
314 if (!out || (out->len == 0
315 && !opt_output_format
316 && packet->type == SR_DF_ANALOG)) {
318 * The user didn't specify an output module,
319 * but needs to see this analog data.
321 sr_output_send(oa, packet, &out);
323 if (outfile && out && out->len > 0) {
324 fwrite(out->str, 1, out->len, outfile);
325 fflush(outfile);
327 if (out)
328 g_string_free(out, TRUE);
333 * SR_DF_END needs to be handled after the output module's receive()
334 * is called, so it can properly clean up that module.
336 if (packet->type == SR_DF_END) {
337 g_debug("cli: Received SR_DF_END.");
339 if (o)
340 sr_output_free(o);
341 o = NULL;
343 sr_output_free(oa);
344 oa = NULL;
346 if (outfile && outfile != stdout)
347 fclose(outfile);
349 if (limit_samples) {
350 if (rcvd_samples_logic > 0 && rcvd_samples_logic < limit_samples)
351 g_warning("Device only sent %" PRIu64 " samples.",
352 rcvd_samples_logic);
353 else if (rcvd_samples_analog > 0 && rcvd_samples_analog < limit_samples)
354 g_warning("Device only sent %" PRIu64 " samples.",
355 rcvd_samples_analog);
361 int opt_to_gvar(char *key, char *value, struct sr_config *src)
363 const struct sr_key_info *srci, *srmqi;
364 double tmp_double, dlow, dhigh;
365 uint64_t tmp_u64, p, q, low, high, mqflags;
366 uint32_t mq;
367 GVariant *rational[2], *range[2], *gtup[2];
368 GVariantBuilder *vbl;
369 gboolean tmp_bool;
370 gchar **keyval;
371 int ret, i;
373 if (!(srci = sr_key_info_name_get(SR_KEY_CONFIG, key))) {
374 g_critical("Unknown device option '%s'.", (char *) key);
375 return -1;
377 src->key = srci->key;
379 if ((!value || strlen(value) == 0) &&
380 (srci->datatype != SR_T_BOOL)) {
381 g_critical("Option '%s' needs a value.", (char *)key);
382 return -1;
385 ret = 0;
386 switch (srci->datatype) {
387 case SR_T_UINT64:
388 ret = sr_parse_sizestring(value, &tmp_u64);
389 if (ret != 0)
390 break;
391 src->data = g_variant_new_uint64(tmp_u64);
392 break;
393 case SR_T_INT32:
394 ret = sr_parse_sizestring(value, &tmp_u64);
395 if (ret != 0)
396 break;
397 src->data = g_variant_new_int32(tmp_u64);
398 break;
399 case SR_T_STRING:
400 src->data = g_variant_new_string(value);
401 break;
402 case SR_T_BOOL:
403 if (!value)
404 tmp_bool = TRUE;
405 else
406 tmp_bool = sr_parse_boolstring(value);
407 src->data = g_variant_new_boolean(tmp_bool);
408 break;
409 case SR_T_FLOAT:
410 tmp_double = strtof(value, NULL);
411 src->data = g_variant_new_double(tmp_double);
412 break;
413 case SR_T_RATIONAL_PERIOD:
414 if ((ret = sr_parse_period(value, &p, &q)) != SR_OK)
415 break;
416 rational[0] = g_variant_new_uint64(p);
417 rational[1] = g_variant_new_uint64(q);
418 src->data = g_variant_new_tuple(rational, 2);
419 break;
420 case SR_T_RATIONAL_VOLT:
421 if ((ret = sr_parse_voltage(value, &p, &q)) != SR_OK)
422 break;
423 rational[0] = g_variant_new_uint64(p);
424 rational[1] = g_variant_new_uint64(q);
425 src->data = g_variant_new_tuple(rational, 2);
426 break;
427 case SR_T_UINT64_RANGE:
428 if (sscanf(value, "%"PRIu64"-%"PRIu64, &low, &high) != 2) {
429 ret = -1;
430 break;
431 } else {
432 range[0] = g_variant_new_uint64(low);
433 range[1] = g_variant_new_uint64(high);
434 src->data = g_variant_new_tuple(range, 2);
436 break;
437 case SR_T_DOUBLE_RANGE:
438 if (sscanf(value, "%lf-%lf", &dlow, &dhigh) != 2) {
439 ret = -1;
440 break;
441 } else {
442 range[0] = g_variant_new_double(dlow);
443 range[1] = g_variant_new_double(dhigh);
444 src->data = g_variant_new_tuple(range, 2);
446 break;
447 case SR_T_KEYVALUE:
448 /* Expects the argument to be in the form of key=value. */
449 keyval = g_strsplit(value, "=", 2);
450 if (!keyval[0] || !keyval[1]) {
451 g_strfreev(keyval);
452 ret = -1;
453 break;
454 } else {
455 vbl = g_variant_builder_new(G_VARIANT_TYPE_DICTIONARY);
456 g_variant_builder_add(vbl, "{ss}",
457 keyval[0], keyval[1]);
458 src->data = g_variant_builder_end(vbl);
459 g_strfreev(keyval);
461 break;
462 case SR_T_MQ:
464 Argument is MQ id e.g. ("voltage") optionally followed by one
465 or more /<mqflag> e.g. "/ac".
467 keyval = g_strsplit(value, "/", 0);
468 if (!keyval[0] || !(srmqi = sr_key_info_name_get(SR_KEY_MQ, keyval[0]))) {
469 g_strfreev(keyval);
470 ret = -1;
471 break;
473 mq = srmqi->key;
474 mqflags = 0;
475 for (i = 1; keyval[i]; i++) {
476 if (!(srmqi = sr_key_info_name_get(SR_KEY_MQFLAGS, keyval[i]))) {
477 ret = -1;
478 break;
480 mqflags |= srmqi->key;
482 g_strfreev(keyval);
483 if (ret != -1) {
484 gtup[0] = g_variant_new_uint32(mq);
485 gtup[1] = g_variant_new_uint64(mqflags);
486 src->data = g_variant_new_tuple(gtup, 2);
488 break;
489 default:
490 g_critical("Unknown data type specified for option '%s' "
491 "(driver implementation bug?).", key);
492 ret = -1;
495 if (ret < 0)
496 g_critical("Invalid value: '%s' for option '%s'", value, key);
498 return ret;
501 int set_dev_options(struct sr_dev_inst *sdi, GHashTable *args)
503 struct sr_config src;
504 struct sr_channel_group *cg;
505 GHashTableIter iter;
506 gpointer key, value;
507 int ret;
509 g_hash_table_iter_init(&iter, args);
510 while (g_hash_table_iter_next(&iter, &key, &value)) {
511 if ((ret = opt_to_gvar(key, value, &src)) != 0)
512 return ret;
513 cg = select_channel_group(sdi);
514 if ((ret = maybe_config_set(sr_dev_inst_driver_get(sdi), sdi, cg,
515 src.key, src.data)) != SR_OK) {
516 g_critical("Failed to set device option '%s': %s.",
517 (char *)key, sr_strerror(ret));
518 return ret;
522 return SR_OK;
525 void run_session(void)
527 GSList *devices, *real_devices, *sd;
528 GHashTable *devargs;
529 GVariant *gvar;
530 struct sr_session *session;
531 struct sr_trigger *trigger;
532 struct sr_dev_inst *sdi;
533 uint64_t min_samples, max_samples;
534 GArray *drv_opts;
535 guint i;
536 int is_demo_dev;
537 struct sr_dev_driver *driver;
538 const struct sr_transform *t;
539 GMainLoop *main_loop;
541 devices = device_scan();
542 if (!devices) {
543 g_critical("No devices found.");
544 return;
547 real_devices = NULL;
548 for (sd = devices; sd; sd = sd->next) {
549 sdi = sd->data;
551 driver = sr_dev_inst_driver_get(sdi);
553 if (!(drv_opts = sr_dev_options(driver, NULL, NULL))) {
554 g_critical("Failed to query list of driver options.");
555 return;
558 is_demo_dev = 0;
559 for (i = 0; i < drv_opts->len; i++) {
560 if (g_array_index(drv_opts, uint32_t, i) == SR_CONF_DEMO_DEV)
561 is_demo_dev = 1;
564 g_array_free(drv_opts, TRUE);
566 if (!is_demo_dev)
567 real_devices = g_slist_append(real_devices, sdi);
570 if (g_slist_length(devices) > 1) {
571 if (g_slist_length(real_devices) != 1) {
572 g_critical("sigrok-cli only supports one device for capturing.");
573 return;
574 } else {
575 /* We only have one non-demo device. */
576 g_slist_free(devices);
577 devices = real_devices;
578 real_devices = NULL;
582 sdi = devices->data;
583 g_slist_free(devices);
584 g_slist_free(real_devices);
586 sr_session_new(sr_ctx, &session);
587 sr_session_datafeed_callback_add(session, datafeed_in, NULL);
589 if (sr_dev_open(sdi) != SR_OK) {
590 g_critical("Failed to open device.");
591 return;
594 if (sr_session_dev_add(session, sdi) != SR_OK) {
595 g_critical("Failed to add device to session.");
596 sr_session_destroy(session);
597 return;
600 if (opt_config) {
601 if ((devargs = parse_generic_arg(opt_config, FALSE))) {
602 if (set_dev_options(sdi, devargs) != SR_OK)
603 return;
604 g_hash_table_destroy(devargs);
608 if (select_channels(sdi) != SR_OK) {
609 g_critical("Failed to set channels.");
610 sr_session_destroy(session);
611 return;
614 trigger = NULL;
615 if (opt_triggers) {
616 if (!parse_triggerstring(sdi, opt_triggers, &trigger)) {
617 sr_session_destroy(session);
618 return;
620 if (sr_session_trigger_set(session, trigger) != SR_OK) {
621 sr_session_destroy(session);
622 return;
626 if (opt_continuous) {
627 if (!sr_dev_has_option(sdi, SR_CONF_CONTINUOUS)) {
628 g_critical("This device does not support continuous sampling.");
629 sr_session_destroy(session);
630 return;
634 if (opt_time) {
635 if (set_limit_time(sdi) != SR_OK) {
636 sr_session_destroy(session);
637 return;
641 if (opt_samples) {
642 if ((sr_parse_sizestring(opt_samples, &limit_samples) != SR_OK)) {
643 g_critical("Invalid sample limit '%s'.", opt_samples);
644 sr_session_destroy(session);
645 return;
647 if (maybe_config_list(driver, sdi, NULL, SR_CONF_LIMIT_SAMPLES,
648 &gvar) == SR_OK) {
650 * The device has no compression, or compression is turned
651 * off, and publishes its sample memory size.
653 g_variant_get(gvar, "(tt)", &min_samples, &max_samples);
654 g_variant_unref(gvar);
655 if (limit_samples < min_samples) {
656 g_critical("The device stores at least %"PRIu64
657 " samples with the current settings.", min_samples);
659 if (limit_samples > max_samples) {
660 g_critical("The device can store only %"PRIu64
661 " samples with the current settings.", max_samples);
664 gvar = g_variant_new_uint64(limit_samples);
665 if (maybe_config_set(sr_dev_inst_driver_get(sdi), sdi, NULL, SR_CONF_LIMIT_SAMPLES, gvar) != SR_OK) {
666 g_critical("Failed to configure sample limit.");
667 sr_session_destroy(session);
668 return;
672 if (opt_frames) {
673 if ((sr_parse_sizestring(opt_frames, &limit_frames) != SR_OK)) {
674 g_critical("Invalid sample limit '%s'.", opt_samples);
675 sr_session_destroy(session);
676 return;
678 gvar = g_variant_new_uint64(limit_frames);
679 if (maybe_config_set(sr_dev_inst_driver_get(sdi), sdi, NULL, SR_CONF_LIMIT_FRAMES, gvar) != SR_OK) {
680 g_critical("Failed to configure frame limit.");
681 sr_session_destroy(session);
682 return;
686 if (!(t = setup_transform_module(sdi)))
687 g_critical("Failed to initialize transform module.");
689 main_loop = g_main_loop_new(NULL, FALSE);
691 sr_session_stopped_callback_set(session,
692 (sr_session_stopped_callback)g_main_loop_quit, main_loop);
694 if (sr_session_start(session) != SR_OK) {
695 g_critical("Failed to start session.");
696 g_main_loop_unref(main_loop);
697 sr_session_destroy(session);
698 return;
701 if (opt_continuous)
702 add_anykey(session);
704 g_main_loop_run(main_loop);
706 if (opt_continuous)
707 clear_anykey();
709 if (trigger)
710 sr_trigger_free(trigger);
712 sr_session_datafeed_callback_remove_all(session);
713 g_main_loop_unref(main_loop);
714 sr_session_destroy(session);