Rename 'probe' to 'channel' in most places.
[sigrok-cli.git] / session.c
blob8b64f49630a608d5d89d93098d973410a26dfc36
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 "sigrok-cli.h"
21 #include "config.h"
22 #include <glib.h>
23 #include <glib/gstdio.h>
24 #include <string.h>
25 #include <stdlib.h>
27 static struct sr_output_format *output_format = NULL;
28 static int default_output_format = FALSE;
29 static char *output_format_param = NULL;
30 static uint64_t limit_samples = 0;
31 static uint64_t limit_frames = 0;
33 extern gchar *opt_output_file;
34 extern gchar *opt_output_format;
35 extern gchar *opt_pds;
36 extern gboolean opt_wait_trigger;
37 extern gchar *opt_time;
38 extern gchar *opt_samples;
39 extern gchar *opt_frames;
40 extern gchar *opt_continuous;
41 extern gchar *opt_config;
42 extern gchar *opt_triggers;
43 #ifdef HAVE_SRD
44 extern struct srd_session *srd_sess;
45 #endif
47 static int set_limit_time(const struct sr_dev_inst *sdi)
49 GVariant *gvar;
50 uint64_t time_msec;
51 uint64_t samplerate;
53 if (!(time_msec = sr_parse_timestring(opt_time))) {
54 g_critical("Invalid time '%s'", opt_time);
55 return SR_ERR;
58 if (sr_dev_has_option(sdi, SR_CONF_LIMIT_MSEC)) {
59 gvar = g_variant_new_uint64(time_msec);
60 if (sr_config_set(sdi, NULL, SR_CONF_LIMIT_MSEC, gvar) != SR_OK) {
61 g_critical("Failed to configure time limit.");
62 return SR_ERR;
64 } else if (sr_dev_has_option(sdi, SR_CONF_SAMPLERATE)) {
65 /* Convert to samples based on the samplerate. */
66 sr_config_get(sdi->driver, sdi, NULL, SR_CONF_SAMPLERATE, &gvar);
67 samplerate = g_variant_get_uint64(gvar);
68 g_variant_unref(gvar);
69 limit_samples = (samplerate) * time_msec / (uint64_t)1000;
70 if (limit_samples == 0) {
71 g_critical("Not enough time at this samplerate.");
72 return SR_ERR;
74 gvar = g_variant_new_uint64(limit_samples);
75 if (sr_config_set(sdi, NULL, SR_CONF_LIMIT_SAMPLES, gvar) != SR_OK) {
76 g_critical("Failed to configure time-based sample limit.");
77 return SR_ERR;
79 } else {
80 g_critical("This device does not support time limits.");
81 return SR_ERR;
84 return SR_OK;
87 int setup_output_format(void)
89 GHashTable *fmtargs;
90 GHashTableIter iter;
91 gpointer key, value;
92 struct sr_output_format **outputs;
93 int i;
94 char *fmtspec;
96 if (opt_output_format && !strcmp(opt_output_format, "sigrok")) {
97 /* Doesn't really exist as an output module - this is
98 * the session save mode. */
99 g_free(opt_output_format);
100 opt_output_format = NULL;
103 if (!opt_output_format) {
104 opt_output_format = DEFAULT_OUTPUT_FORMAT;
105 /* we'll need to remember this so when saving to a file
106 * later, sigrok session format will be used.
108 default_output_format = TRUE;
111 fmtargs = parse_generic_arg(opt_output_format, TRUE);
112 fmtspec = g_hash_table_lookup(fmtargs, "sigrok_key");
113 if (!fmtspec) {
114 g_critical("Invalid output format.");
115 return 1;
117 outputs = sr_output_list();
118 for (i = 0; outputs[i]; i++) {
119 if (strcmp(outputs[i]->id, fmtspec))
120 continue;
121 g_hash_table_remove(fmtargs, "sigrok_key");
122 output_format = outputs[i];
123 g_hash_table_iter_init(&iter, fmtargs);
124 while (g_hash_table_iter_next(&iter, &key, &value)) {
125 /* only supporting one parameter per output module
126 * for now, and only its value */
127 output_format_param = g_strdup(value);
128 break;
130 break;
132 if (!output_format) {
133 g_critical("Invalid output format %s.", opt_output_format);
134 return 1;
136 g_hash_table_destroy(fmtargs);
138 return 0;
141 void datafeed_in(const struct sr_dev_inst *sdi,
142 const struct sr_datafeed_packet *packet, void *cb_data)
144 const struct sr_datafeed_meta *meta;
145 const struct sr_datafeed_logic *logic;
146 const struct sr_datafeed_analog *analog;
147 struct sr_config *src;
148 struct sr_channel *ch;
149 static struct sr_output *o = NULL;
150 static uint64_t rcvd_samples_logic = 0;
151 static uint64_t rcvd_samples_analog = 0;
152 static uint64_t samplerate = 0;
153 static int triggered = 0;
154 static FILE *outfile = NULL;
155 GSList *l;
156 GString *out;
157 uint64_t end_sample;
158 uint64_t output_len, input_len;
159 uint8_t *output_buf;
160 int i;
161 char **channels;
163 (void) cb_data;
165 /* If the first packet to come in isn't a header, don't even try. */
166 if (packet->type != SR_DF_HEADER && o == NULL)
167 return;
169 switch (packet->type) {
170 case SR_DF_HEADER:
171 g_debug("cli: Received SR_DF_HEADER");
172 /* Initialize the output module. */
173 if (!(o = g_try_malloc(sizeof(struct sr_output)))) {
174 g_critical("Output module malloc failed.");
175 exit(1);
177 o->format = output_format;
178 o->sdi = (struct sr_dev_inst *)sdi;
179 o->param = output_format_param;
180 if (o->format->init) {
181 if (o->format->init(o) != SR_OK) {
182 g_critical("Output format initialization failed.");
183 exit(1);
187 /* Prepare non-stdout output. */
188 outfile = stdout;
189 if (opt_output_file) {
190 if (default_output_format) {
191 outfile = NULL;
192 } else {
193 /* saving to a file in whatever format was set
194 * with --format, so all we need is a filehandle */
195 outfile = g_fopen(opt_output_file, "wb");
198 rcvd_samples_logic = rcvd_samples_analog = 0;
200 #ifdef HAVE_SRD
201 if (opt_pds) {
202 GVariant *gvar;
203 if (sr_config_get(sdi->driver, sdi, NULL, SR_CONF_SAMPLERATE,
204 &gvar) == SR_OK) {
205 samplerate = g_variant_get_uint64(gvar);
206 g_variant_unref(gvar);
207 if (srd_session_metadata_set(srd_sess, SRD_CONF_SAMPLERATE,
208 g_variant_new_uint64(samplerate)) != SRD_OK) {
209 g_critical("Failed to configure decode session.");
210 break;
213 if (srd_session_start(srd_sess) != SRD_OK) {
214 g_critical("Failed to start decode session.");
215 break;
218 #endif
219 break;
221 case SR_DF_META:
222 g_debug("cli: received SR_DF_META");
223 meta = packet->payload;
224 for (l = meta->config; l; l = l->next) {
225 src = l->data;
226 switch (src->key) {
227 case SR_CONF_SAMPLERATE:
228 samplerate = g_variant_get_uint64(src->data);
229 g_debug("cli: got samplerate %"PRIu64" Hz", samplerate);
230 #ifdef HAVE_SRD
231 if (opt_pds) {
232 if (srd_session_metadata_set(srd_sess, SRD_CONF_SAMPLERATE,
233 g_variant_new_uint64(samplerate)) != SRD_OK) {
234 g_critical("Failed to pass samplerate to decoder.");
237 #endif
238 break;
239 case SR_CONF_SAMPLE_INTERVAL:
240 samplerate = g_variant_get_uint64(src->data);
241 g_debug("cli: got sample interval %"PRIu64" ms", samplerate);
242 break;
243 default:
244 /* Unknown metadata is not an error. */
245 break;
248 break;
250 case SR_DF_TRIGGER:
251 g_debug("cli: received SR_DF_TRIGGER");
252 if (o->format->event)
253 o->format->event(o, SR_DF_TRIGGER, &output_buf,
254 &output_len);
255 triggered = 1;
256 break;
258 case SR_DF_LOGIC:
259 logic = packet->payload;
260 g_message("cli: received SR_DF_LOGIC, %"PRIu64" bytes", logic->length);
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_output_file && default_output_format) {
278 /* Saving to a session file. */
279 if (rcvd_samples_logic == 0) {
280 /* First packet with logic data, init session file. */
281 channels = g_malloc(sizeof(char *) * g_slist_length(sdi->channels));
282 for (i = 0, l = sdi->channels; l; l = l->next) {
283 ch = l->data;
284 if (ch->enabled && ch->type == SR_CHANNEL_LOGIC)
285 channels[i++] = ch->name;
287 channels[i] = NULL;
288 sr_session_save_init(opt_output_file, samplerate,
289 channels);
290 g_free(channels);
292 save_chunk_logic(logic->data, input_len, logic->unitsize);
293 } else {
294 if (opt_pds) {
295 #ifdef HAVE_SRD
296 if (srd_session_send(srd_sess, rcvd_samples_logic, end_sample,
297 logic->data, input_len) != SRD_OK)
298 sr_session_stop();
299 #endif
300 } else {
301 output_len = 0;
302 if (o->format->data && packet->type == o->format->df_type)
303 o->format->data(o, logic->data, input_len,
304 &output_buf, &output_len);
305 if (output_len) {
306 fwrite(output_buf, 1, output_len, outfile);
307 fflush(outfile);
308 g_free(output_buf);
313 rcvd_samples_logic = end_sample;
314 break;
316 case SR_DF_ANALOG:
317 analog = packet->payload;
318 g_message("cli: received SR_DF_ANALOG, %d samples", analog->num_samples);
319 if (analog->num_samples == 0)
320 break;
322 if (limit_samples && rcvd_samples_analog >= limit_samples)
323 break;
325 if (o->format->data && packet->type == o->format->df_type) {
326 o->format->data(o, (const uint8_t *)analog->data,
327 analog->num_samples * sizeof(float),
328 &output_buf, &output_len);
329 if (output_buf) {
330 fwrite(output_buf, 1, output_len, outfile);
331 fflush(outfile);
332 g_free(output_buf);
336 rcvd_samples_analog += analog->num_samples;
337 break;
339 case SR_DF_FRAME_BEGIN:
340 g_debug("cli: received SR_DF_FRAME_BEGIN");
341 if (o->format->event) {
342 o->format->event(o, SR_DF_FRAME_BEGIN, &output_buf,
343 &output_len);
344 if (output_buf) {
345 fwrite(output_buf, 1, output_len, outfile);
346 fflush(outfile);
347 g_free(output_buf);
350 break;
352 case SR_DF_FRAME_END:
353 g_debug("cli: received SR_DF_FRAME_END");
354 if (o->format->event) {
355 o->format->event(o, SR_DF_FRAME_END, &output_buf,
356 &output_len);
357 if (output_buf) {
358 fwrite(output_buf, 1, output_len, outfile);
359 fflush(outfile);
360 g_free(output_buf);
363 break;
365 default:
366 break;
369 if (o && o->format->receive) {
370 if (o->format->receive(o, sdi, packet, &out) == SR_OK && out) {
371 fwrite(out->str, 1, out->len, outfile);
372 fflush(outfile);
373 g_string_free(out, TRUE);
377 /* SR_DF_END needs to be handled after the output module's receive()
378 * is called, so it can properly clean up that module. */
379 if (packet->type == SR_DF_END) {
380 g_debug("cli: Received SR_DF_END");
382 if (o->format->event) {
383 o->format->event(o, SR_DF_END, &output_buf, &output_len);
384 if (output_buf) {
385 if (outfile)
386 fwrite(output_buf, 1, output_len, outfile);
387 g_free(output_buf);
388 output_len = 0;
392 if (o->format->cleanup)
393 o->format->cleanup(o);
394 g_free(o);
395 o = NULL;
397 if (outfile && outfile != stdout)
398 fclose(outfile);
400 if (opt_output_file && default_output_format)
401 /* Flush whatever is left out to the session file. */
402 save_chunk_logic(NULL, 0, 0);
404 if (limit_samples) {
405 if (rcvd_samples_logic > 0 && rcvd_samples_logic < limit_samples)
406 g_warning("Device only sent %" PRIu64 " samples.",
407 rcvd_samples_logic);
408 else if (rcvd_samples_analog > 0 && rcvd_samples_analog < limit_samples)
409 g_warning("Device only sent %" PRIu64 " samples.",
410 rcvd_samples_analog);
416 int opt_to_gvar(char *key, char *value, struct sr_config *src)
418 const struct sr_config_info *srci;
419 double tmp_double, dlow, dhigh;
420 uint64_t tmp_u64, p, q, low, high;
421 GVariant *rational[2], *range[2];
422 gboolean tmp_bool;
423 int ret;
425 if (!(srci = sr_config_info_name_get(key))) {
426 g_critical("Unknown device option '%s'.", (char *) key);
427 return -1;
429 src->key = srci->key;
431 if ((value == NULL) &&
432 (srci->datatype != SR_T_BOOL)) {
433 g_critical("Option '%s' needs a value.", (char *)key);
434 return -1;
437 ret = 0;
438 switch (srci->datatype) {
439 case SR_T_UINT64:
440 ret = sr_parse_sizestring(value, &tmp_u64);
441 if (ret != 0)
442 break;
443 src->data = g_variant_new_uint64(tmp_u64);
444 break;
445 case SR_T_INT32:
446 ret = sr_parse_sizestring(value, &tmp_u64);
447 if (ret != 0)
448 break;
449 src->data = g_variant_new_int32(tmp_u64);
450 break;
451 case SR_T_CHAR:
452 src->data = g_variant_new_string(value);
453 break;
454 case SR_T_BOOL:
455 if (!value)
456 tmp_bool = TRUE;
457 else
458 tmp_bool = sr_parse_boolstring(value);
459 src->data = g_variant_new_boolean(tmp_bool);
460 break;
461 case SR_T_FLOAT:
462 tmp_double = strtof(value, NULL);
463 src->data = g_variant_new_double(tmp_double);
464 break;
465 case SR_T_RATIONAL_PERIOD:
466 if ((ret = sr_parse_period(value, &p, &q)) != SR_OK)
467 break;
468 rational[0] = g_variant_new_uint64(p);
469 rational[1] = g_variant_new_uint64(q);
470 src->data = g_variant_new_tuple(rational, 2);
471 break;
472 case SR_T_RATIONAL_VOLT:
473 if ((ret = sr_parse_voltage(value, &p, &q)) != SR_OK)
474 break;
475 rational[0] = g_variant_new_uint64(p);
476 rational[1] = g_variant_new_uint64(q);
477 src->data = g_variant_new_tuple(rational, 2);
478 break;
479 case SR_T_UINT64_RANGE:
480 if (sscanf(value, "%"PRIu64"-%"PRIu64, &low, &high) != 2) {
481 ret = -1;
482 break;
483 } else {
484 range[0] = g_variant_new_uint64(low);
485 range[1] = g_variant_new_uint64(high);
486 src->data = g_variant_new_tuple(range, 2);
488 break;
489 case SR_T_DOUBLE_RANGE:
490 if (sscanf(value, "%lf-%lf", &dlow, &dhigh) != 2) {
491 ret = -1;
492 break;
493 } else {
494 range[0] = g_variant_new_double(dlow);
495 range[1] = g_variant_new_double(dhigh);
496 src->data = g_variant_new_tuple(range, 2);
498 break;
499 default:
500 ret = -1;
503 return ret;
506 int set_dev_options(struct sr_dev_inst *sdi, GHashTable *args)
508 struct sr_config src;
509 struct sr_channel_group *cg;
510 GHashTableIter iter;
511 gpointer key, value;
512 int ret;
514 g_hash_table_iter_init(&iter, args);
515 while (g_hash_table_iter_next(&iter, &key, &value)) {
516 if ((ret = opt_to_gvar(key, value, &src)) != 0)
517 return ret;
518 cg = select_channel_group(sdi);
519 ret = sr_config_set(sdi, cg, src.key, src.data);
520 if (ret != SR_OK) {
521 g_critical("Failed to set device option '%s'.", (char *)key);
522 return ret;
526 return SR_OK;
529 void run_session(void)
531 GSList *devices;
532 GHashTable *devargs;
533 GVariant *gvar;
534 struct sr_dev_inst *sdi;
535 uint64_t min_samples, max_samples;
536 int max_channels, i;
537 char **triggerlist;
539 devices = device_scan();
540 if (!devices) {
541 g_critical("No devices found.");
542 return;
544 if (g_slist_length(devices) > 1) {
545 g_critical("sigrok-cli only supports one device for capturing.");
546 return;
548 sdi = devices->data;
550 sr_session_new();
551 sr_session_datafeed_callback_add(datafeed_in, NULL);
553 if (sr_dev_open(sdi) != SR_OK) {
554 g_critical("Failed to open device.");
555 return;
558 if (sr_session_dev_add(sdi) != SR_OK) {
559 g_critical("Failed to add device to session.");
560 sr_session_destroy();
561 return;
564 if (opt_config) {
565 if ((devargs = parse_generic_arg(opt_config, FALSE))) {
566 if (set_dev_options(sdi, devargs) != SR_OK)
567 return;
568 g_hash_table_destroy(devargs);
572 if (select_channels(sdi) != SR_OK) {
573 g_critical("Failed to set channels.");
574 sr_session_destroy();
575 return;
578 if (opt_triggers) {
579 if (!(triggerlist = sr_parse_triggerstring(sdi, opt_triggers))) {
580 sr_session_destroy();
581 return;
583 max_channels = g_slist_length(sdi->channels);
584 for (i = 0; i < max_channels; i++) {
585 if (triggerlist[i]) {
586 sr_dev_trigger_set(sdi, i, triggerlist[i]);
587 g_free(triggerlist[i]);
590 g_free(triggerlist);
593 if (opt_continuous) {
594 if (!sr_dev_has_option(sdi, SR_CONF_CONTINUOUS)) {
595 g_critical("This device does not support continuous sampling.");
596 sr_session_destroy();
597 return;
601 if (opt_time) {
602 if (set_limit_time(sdi) != SR_OK) {
603 sr_session_destroy();
604 return;
608 if (opt_samples) {
609 if ((sr_parse_sizestring(opt_samples, &limit_samples) != SR_OK)) {
610 g_critical("Invalid sample limit '%s'.", opt_samples);
611 sr_session_destroy();
612 return;
614 if (sr_config_list(sdi->driver, sdi, NULL,
615 SR_CONF_LIMIT_SAMPLES, &gvar) == SR_OK) {
616 /* The device has no compression, or compression is turned
617 * off, and publishes its sample memory size. */
618 g_variant_get(gvar, "(tt)", &min_samples, &max_samples);
619 g_variant_unref(gvar);
620 if (limit_samples < min_samples) {
621 g_critical("The device stores at least %"PRIu64
622 " samples with the current settings.", min_samples);
624 if (limit_samples > max_samples) {
625 g_critical("The device can store only %"PRIu64
626 " samples with the current settings.", max_samples);
629 gvar = g_variant_new_uint64(limit_samples);
630 if (sr_config_set(sdi, NULL, SR_CONF_LIMIT_SAMPLES, gvar) != SR_OK) {
631 g_critical("Failed to configure sample limit.");
632 sr_session_destroy();
633 return;
637 if (opt_frames) {
638 if ((sr_parse_sizestring(opt_frames, &limit_frames) != SR_OK)) {
639 g_critical("Invalid sample limit '%s'.", opt_samples);
640 sr_session_destroy();
641 return;
643 gvar = g_variant_new_uint64(limit_frames);
644 if (sr_config_set(sdi, NULL, SR_CONF_LIMIT_FRAMES, gvar) != SR_OK) {
645 g_critical("Failed to configure frame limit.");
646 sr_session_destroy();
647 return;
651 if (sr_session_start() != SR_OK) {
652 g_critical("Failed to start session.");
653 sr_session_destroy();
654 return;
657 if (opt_continuous)
658 add_anykey();
660 sr_session_run();
662 if (opt_continuous)
663 clear_anykey();
665 sr_session_datafeed_callback_remove_all();
666 sr_session_destroy();
667 g_slist_free(devices);
671 void save_chunk_logic(uint8_t *data, uint64_t data_len, int unitsize)
673 static uint8_t *buf = NULL;
674 static int buf_len = 0;
675 static int last_unitsize = 0;
676 int max;
678 if (!buf)
679 buf = g_malloc(SAVE_CHUNK_SIZE);
681 if (buf_len + data_len > SAVE_CHUNK_SIZE) {
682 max = (SAVE_CHUNK_SIZE - buf_len) / unitsize * unitsize;
683 memcpy(buf + buf_len, data, max);
684 sr_session_append(opt_output_file, buf, unitsize,
685 (buf_len + max) / unitsize);
686 memcpy(buf, data + max, data_len - max);
687 buf_len = data_len - max;
688 } else if (data_len == 0) {
689 /* End of data, flush the buffer out. */
690 sr_session_append(opt_output_file, buf, last_unitsize,
691 buf_len / last_unitsize);
692 } else {
693 /* Buffer chunk. */
694 memcpy(buf + buf_len, data, data_len);
695 buf_len += data_len;
697 last_unitsize = unitsize;