]> sigrok.org Git - sigrok-cli.git/blob - session.c
46bb4d9676967027b9b984e2ccf23f09c600e044
[sigrok-cli.git] / session.c
1 /*
2  * This file is part of the sigrok-cli project.
3  *
4  * Copyright (C) 2013 Bert Vermeulen <bert@biot.com>
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 "sigrok-cli.h"
21 #include <glib.h>
22 #include <glib/gstdio.h>
23 #include <string.h>
24 #include <stdlib.h>
25
26 static int default_output_format = FALSE;
27 static uint64_t limit_samples = 0;
28 static uint64_t limit_frames = 0;
29
30 #ifdef HAVE_SRD
31 extern struct srd_session *srd_sess;
32 #endif
33
34 static int set_limit_time(const struct sr_dev_inst *sdi)
35 {
36         GVariant *gvar;
37         uint64_t time_msec;
38         uint64_t samplerate;
39
40         if (!(time_msec = sr_parse_timestring(opt_time))) {
41                 g_critical("Invalid time '%s'", opt_time);
42                 return SR_ERR;
43         }
44
45         if (sr_dev_has_option(sdi, SR_CONF_LIMIT_MSEC)) {
46                 gvar = g_variant_new_uint64(time_msec);
47                 if (sr_config_set(sdi, NULL, SR_CONF_LIMIT_MSEC, gvar) != SR_OK) {
48                         g_critical("Failed to configure time limit.");
49                         return SR_ERR;
50                 }
51         } else if (sr_dev_has_option(sdi, SR_CONF_SAMPLERATE)) {
52                 /* Convert to samples based on the samplerate.  */
53                 sr_config_get(sdi->driver, sdi, NULL, SR_CONF_SAMPLERATE, &gvar);
54                 samplerate = g_variant_get_uint64(gvar);
55                 g_variant_unref(gvar);
56                 limit_samples = (samplerate) * time_msec / (uint64_t)1000;
57                 if (limit_samples == 0) {
58                         g_critical("Not enough time at this samplerate.");
59                         return SR_ERR;
60                 }
61                 gvar = g_variant_new_uint64(limit_samples);
62                 if (sr_config_set(sdi, NULL, SR_CONF_LIMIT_SAMPLES, gvar) != SR_OK) {
63                         g_critical("Failed to configure time-based sample limit.");
64                         return SR_ERR;
65                 }
66         } else {
67                 g_critical("This device does not support time limits.");
68                 return SR_ERR;
69         }
70
71         return SR_OK;
72 }
73
74 GHashTable *generic_arg_to_opt(const struct sr_option *opts, GHashTable *genargs)
75 {
76         GHashTable *hash;
77         GVariant *gvar;
78         const struct sr_option *opt;
79         char *s;
80
81         hash = g_hash_table_new_full(g_str_hash, g_str_equal, g_free,
82                         (GDestroyNotify)g_variant_unref);
83         for (opt = opts; opt->id && opt->def; opt++) {
84                 if (!(s = g_hash_table_lookup(genargs, opt->id)))
85                         continue;
86                 if (g_variant_is_of_type(opt->def, G_VARIANT_TYPE_UINT32)) {
87                         gvar = g_variant_new_uint32(strtoul(s, NULL, 10));
88                         g_hash_table_insert(hash, g_strdup(opt->id),
89                                         g_variant_ref_sink(gvar));
90                 } else if (g_variant_is_of_type(opt->def, G_VARIANT_TYPE_DOUBLE)) {
91                         gvar = g_variant_new_double(strtod(s, NULL));
92                         g_hash_table_insert(hash, g_strdup(opt->id),
93                                         g_variant_ref_sink(gvar));
94                 } else {
95                         g_critical("Don't know GVariant type for option '%s'!", opt->id);
96                  }
97         }
98
99         return hash;
100 }
101
102 const struct sr_output *setup_output_format(const struct sr_dev_inst *sdi)
103 {
104         const struct sr_output_module *omod;
105         const struct sr_option *opts;
106         const struct sr_output *o;
107         GHashTable *fmtargs, *fmtopts;
108         char *fmtspec;
109
110         if (opt_output_format && !strcmp(opt_output_format, "sigrok")) {
111                 /* Doesn't really exist as an output module - this is
112                  * the session save mode. */
113                 g_free(opt_output_format);
114                 opt_output_format = NULL;
115         }
116
117         if (!opt_output_format) {
118                 opt_output_format = DEFAULT_OUTPUT_FORMAT;
119                 /* we'll need to remember this so when saving to a file
120                  * later, sigrok session format will be used.
121                  */
122                 default_output_format = TRUE;
123         }
124
125         fmtargs = parse_generic_arg(opt_output_format, TRUE);
126         fmtspec = g_hash_table_lookup(fmtargs, "sigrok_key");
127         if (!fmtspec)
128                 g_critical("Invalid output format.");
129         if (!(omod = sr_output_find(fmtspec)))
130                 g_critical("Unknown output format '%s'.", fmtspec);
131         g_hash_table_remove(fmtargs, "sigrok_key");
132         if ((opts = sr_output_options_get(omod))) {
133                 fmtopts = generic_arg_to_opt(opts, fmtargs);
134                 sr_output_options_free(omod);
135         } else
136                 fmtopts = NULL;
137         o = sr_output_new(omod, fmtopts, sdi);
138         if (fmtopts)
139                 g_hash_table_destroy(fmtopts);
140         g_hash_table_destroy(fmtargs);
141
142         return o;
143 }
144
145 void datafeed_in(const struct sr_dev_inst *sdi,
146                 const struct sr_datafeed_packet *packet, void *cb_data)
147 {
148         const struct sr_datafeed_meta *meta;
149         const struct sr_datafeed_logic *logic;
150         const struct sr_datafeed_analog *analog;
151         struct sr_session *session;
152         struct sr_config *src;
153         struct sr_channel *ch;
154         static const struct sr_output *o = NULL;
155         static const struct sr_output *oa = NULL;
156         static uint64_t rcvd_samples_logic = 0;
157         static uint64_t rcvd_samples_analog = 0;
158         static uint64_t samplerate = 0;
159         static int triggered = 0;
160         static FILE *outfile = NULL;
161         GSList *l;
162         GString *out;
163         GVariant *gvar;
164         uint64_t end_sample;
165         uint64_t input_len;
166         int i;
167         char **channels;
168
169         /* If the first packet to come in isn't a header, don't even try. */
170         if (packet->type != SR_DF_HEADER && o == NULL)
171                 return;
172
173         session = cb_data;
174         switch (packet->type) {
175         case SR_DF_HEADER:
176                 g_debug("cli: Received SR_DF_HEADER.");
177                 o = setup_output_format(sdi);
178
179                 /* Set up backup analog output module. */
180                 oa = sr_output_new(sr_output_find("analog"), NULL, sdi);
181
182                 /* Prepare non-stdout output. */
183                 outfile = stdout;
184                 if (opt_output_file) {
185                         if (default_output_format) {
186                                 outfile = NULL;
187                         } else {
188                                 /* saving to a file in whatever format was set
189                                  * with --format, so all we need is a filehandle */
190                                 outfile = g_fopen(opt_output_file, "wb");
191                         }
192                 }
193                 rcvd_samples_logic = rcvd_samples_analog = 0;
194
195                 if (sr_config_get(sdi->driver, sdi, NULL, SR_CONF_SAMPLERATE,
196                                 &gvar) == SR_OK) {
197                         samplerate = g_variant_get_uint64(gvar);
198                         g_variant_unref(gvar);
199                 }
200
201 #ifdef HAVE_SRD
202                 if (opt_pds) {
203                         if (samplerate) {
204                                 if (srd_session_metadata_set(srd_sess, SRD_CONF_SAMPLERATE,
205                                                 g_variant_new_uint64(samplerate)) != SRD_OK) {
206                                         g_critical("Failed to configure decode session.");
207                                         break;
208                                 }
209                         }
210                         if (srd_session_start(srd_sess) != SRD_OK) {
211                                 g_critical("Failed to start decode session.");
212                                 break;
213                         }
214                 }
215 #endif
216                 break;
217
218         case SR_DF_META:
219                 g_debug("cli: Received SR_DF_META.");
220                 meta = packet->payload;
221                 for (l = meta->config; l; l = l->next) {
222                         src = l->data;
223                         switch (src->key) {
224                         case SR_CONF_SAMPLERATE:
225                                 samplerate = g_variant_get_uint64(src->data);
226                                 g_debug("cli: Got samplerate %"PRIu64" Hz.", samplerate);
227 #ifdef HAVE_SRD
228                                 if (opt_pds) {
229                                         if (srd_session_metadata_set(srd_sess, SRD_CONF_SAMPLERATE,
230                                                         g_variant_new_uint64(samplerate)) != SRD_OK) {
231                                                 g_critical("Failed to pass samplerate to decoder.");
232                                         }
233                                 }
234 #endif
235                                 break;
236                         case SR_CONF_SAMPLE_INTERVAL:
237                                 samplerate = g_variant_get_uint64(src->data);
238                                 g_debug("cli: Got sample interval %"PRIu64" ms.", samplerate);
239                                 break;
240                         default:
241                                 /* Unknown metadata is not an error. */
242                                 break;
243                         }
244                 }
245                 break;
246
247         case SR_DF_TRIGGER:
248                 g_debug("cli: Received SR_DF_TRIGGER.");
249                 triggered = 1;
250                 break;
251
252         case SR_DF_LOGIC:
253                 logic = packet->payload;
254                 g_message("cli: Received SR_DF_LOGIC (%"PRIu64" bytes, unitsize = %d).",
255                                 logic->length, logic->unitsize);
256                 if (logic->length == 0)
257                         break;
258
259                 /* Don't store any samples until triggered. */
260                 if (opt_wait_trigger && !triggered)
261                         break;
262
263                 if (limit_samples && rcvd_samples_logic >= limit_samples)
264                         break;
265
266                 end_sample = rcvd_samples_logic + logic->length / logic->unitsize;
267                 /* Cut off last packet according to the sample limit. */
268                 if (limit_samples && end_sample > limit_samples)
269                         end_sample = limit_samples;
270                 input_len = (end_sample - rcvd_samples_logic) * logic->unitsize;
271
272                 if (opt_output_file && default_output_format) {
273                         /* Saving to a session file. */
274                         if (rcvd_samples_logic == 0) {
275                                 /* First packet with logic data, init session file. */
276                                 channels = g_malloc(sizeof(char *) * g_slist_length(sdi->channels));
277                                 for (i = 0, l = sdi->channels; l; l = l->next) {
278                                         ch = l->data;
279                                         if (ch->enabled && ch->type == SR_CHANNEL_LOGIC)
280                                                 channels[i++] = ch->name;
281                                 }
282                                 channels[i] = NULL;
283                                 sr_session_save_init(session, opt_output_file,
284                                                 samplerate, channels);
285                                 g_free(channels);
286                         }
287                         save_chunk_logic(session, logic->data, input_len, logic->unitsize);
288                 } else {
289                         if (opt_pds) {
290 #ifdef HAVE_SRD
291                                 if (srd_session_send(srd_sess, rcvd_samples_logic, end_sample,
292                                                 logic->data, input_len) != SRD_OK)
293                                         sr_session_stop(session);
294 #endif
295                         }
296                 }
297
298                 rcvd_samples_logic = end_sample;
299                 break;
300
301         case SR_DF_ANALOG:
302                 analog = packet->payload;
303                 g_message("cli: Received SR_DF_ANALOG (%d samples).", analog->num_samples);
304                 if (analog->num_samples == 0)
305                         break;
306
307                 if (limit_samples && rcvd_samples_analog >= limit_samples)
308                         break;
309
310                 rcvd_samples_analog += analog->num_samples;
311                 break;
312
313         case SR_DF_FRAME_BEGIN:
314                 g_debug("cli: Received SR_DF_FRAME_BEGIN.");
315                 break;
316
317         case SR_DF_FRAME_END:
318                 g_debug("cli: Received SR_DF_FRAME_END.");
319                 break;
320
321         default:
322                 break;
323         }
324
325         if (o && outfile && !opt_pds) {
326                 if (sr_output_send(o, packet, &out) == SR_OK) {
327                         if (!out || (out->len == 0 && default_output_format
328                                         && packet->type == SR_DF_ANALOG)) {
329                                 /* The user didn't specify an output module,
330                                  * but needs to see this analog data. */
331                                 sr_output_send(oa, packet, &out);
332                         }
333                         if (out && out->len > 0) {
334                                 fwrite(out->str, 1, out->len, outfile);
335                                 fflush(outfile);
336                         }
337                         if (out)
338                                 g_string_free(out, TRUE);
339                 }
340         }
341
342         /* SR_DF_END needs to be handled after the output module's receive()
343          * is called, so it can properly clean up that module. */
344         if (packet->type == SR_DF_END) {
345                 g_debug("cli: Received SR_DF_END.");
346
347                 if (o)
348                         sr_output_free(o);
349                 o = NULL;
350
351                 sr_output_free(oa);
352                 oa = NULL;
353
354                 if (outfile && outfile != stdout)
355                         fclose(outfile);
356
357                 if (opt_output_file && default_output_format)
358                         /* Flush whatever is left out to the session file. */
359                         save_chunk_logic(session, NULL, 0, 0);
360
361                 if (limit_samples) {
362                         if (rcvd_samples_logic > 0 && rcvd_samples_logic < limit_samples)
363                                 g_warning("Device only sent %" PRIu64 " samples.",
364                                            rcvd_samples_logic);
365                         else if (rcvd_samples_analog > 0 && rcvd_samples_analog < limit_samples)
366                                 g_warning("Device only sent %" PRIu64 " samples.",
367                                            rcvd_samples_analog);
368                 }
369         }
370
371 }
372
373 int opt_to_gvar(char *key, char *value, struct sr_config *src)
374 {
375         const struct sr_config_info *srci;
376         double tmp_double, dlow, dhigh;
377         uint64_t tmp_u64, p, q, low, high;
378         GVariant *rational[2], *range[2];
379         gboolean tmp_bool;
380         int ret;
381
382         if (!(srci = sr_config_info_name_get(key))) {
383                 g_critical("Unknown device option '%s'.", (char *) key);
384                 return -1;
385         }
386         src->key = srci->key;
387
388         if ((value == NULL) &&
389                 (srci->datatype != SR_T_BOOL)) {
390                 g_critical("Option '%s' needs a value.", (char *)key);
391                 return -1;
392         }
393
394         ret = 0;
395         switch (srci->datatype) {
396         case SR_T_UINT64:
397                 ret = sr_parse_sizestring(value, &tmp_u64);
398                 if (ret != 0)
399                         break;
400                 src->data = g_variant_new_uint64(tmp_u64);
401                 break;
402         case SR_T_INT32:
403                 ret = sr_parse_sizestring(value, &tmp_u64);
404                 if (ret != 0)
405                         break;
406                 src->data = g_variant_new_int32(tmp_u64);
407                 break;
408         case SR_T_STRING:
409                 src->data = g_variant_new_string(value);
410                 break;
411         case SR_T_BOOL:
412                 if (!value)
413                         tmp_bool = TRUE;
414                 else
415                         tmp_bool = sr_parse_boolstring(value);
416                 src->data = g_variant_new_boolean(tmp_bool);
417                 break;
418         case SR_T_FLOAT:
419                 tmp_double = strtof(value, NULL);
420                 src->data = g_variant_new_double(tmp_double);
421                 break;
422         case SR_T_RATIONAL_PERIOD:
423                 if ((ret = sr_parse_period(value, &p, &q)) != SR_OK)
424                         break;
425                 rational[0] = g_variant_new_uint64(p);
426                 rational[1] = g_variant_new_uint64(q);
427                 src->data = g_variant_new_tuple(rational, 2);
428                 break;
429         case SR_T_RATIONAL_VOLT:
430                 if ((ret = sr_parse_voltage(value, &p, &q)) != SR_OK)
431                         break;
432                 rational[0] = g_variant_new_uint64(p);
433                 rational[1] = g_variant_new_uint64(q);
434                 src->data = g_variant_new_tuple(rational, 2);
435                 break;
436         case SR_T_UINT64_RANGE:
437                 if (sscanf(value, "%"PRIu64"-%"PRIu64, &low, &high) != 2) {
438                         ret = -1;
439                         break;
440                 } else {
441                         range[0] = g_variant_new_uint64(low);
442                         range[1] = g_variant_new_uint64(high);
443                         src->data = g_variant_new_tuple(range, 2);
444                 }
445                 break;
446         case SR_T_DOUBLE_RANGE:
447                 if (sscanf(value, "%lf-%lf", &dlow, &dhigh) != 2) {
448                         ret = -1;
449                         break;
450                 } else {
451                         range[0] = g_variant_new_double(dlow);
452                         range[1] = g_variant_new_double(dhigh);
453                         src->data = g_variant_new_tuple(range, 2);
454                 }
455                 break;
456         default:
457                 ret = -1;
458         }
459
460         return ret;
461 }
462
463 int set_dev_options(struct sr_dev_inst *sdi, GHashTable *args)
464 {
465         struct sr_config src;
466         struct sr_channel_group *cg;
467         GHashTableIter iter;
468         gpointer key, value;
469         int ret;
470
471         g_hash_table_iter_init(&iter, args);
472         while (g_hash_table_iter_next(&iter, &key, &value)) {
473                 if ((ret = opt_to_gvar(key, value, &src)) != 0)
474                         return ret;
475                 cg = select_channel_group(sdi);
476                 ret = sr_config_set(sdi, cg, src.key, src.data);
477                 if (ret != SR_OK) {
478                         g_critical("Failed to set device option '%s'.", (char *)key);
479                         return ret;
480                 }
481         }
482
483         return SR_OK;
484 }
485
486 void run_session(void)
487 {
488         GSList *devices;
489         GHashTable *devargs;
490         GVariant *gvar;
491         struct sr_session *session;
492         struct sr_trigger *trigger;
493         struct sr_dev_inst *sdi;
494         uint64_t min_samples, max_samples;
495
496         devices = device_scan();
497         if (!devices) {
498                 g_critical("No devices found.");
499                 return;
500         }
501         if (g_slist_length(devices) > 1) {
502                 g_critical("sigrok-cli only supports one device for capturing.");
503                 g_slist_free(devices);
504                 return;
505         }
506         sdi = devices->data;
507         g_slist_free(devices);
508
509         sr_session_new(&session);
510         sr_session_datafeed_callback_add(session, datafeed_in, NULL);
511
512         if (sr_dev_open(sdi) != SR_OK) {
513                 g_critical("Failed to open device.");
514                 return;
515         }
516
517         if (sr_session_dev_add(session, sdi) != SR_OK) {
518                 g_critical("Failed to add device to session.");
519                 sr_session_destroy(session);
520                 return;
521         }
522
523         if (opt_config) {
524                 if ((devargs = parse_generic_arg(opt_config, FALSE))) {
525                         if (set_dev_options(sdi, devargs) != SR_OK)
526                                 return;
527                         g_hash_table_destroy(devargs);
528                 }
529         }
530
531         if (select_channels(sdi) != SR_OK) {
532                 g_critical("Failed to set channels.");
533                 sr_session_destroy(session);
534                 return;
535         }
536
537         if (opt_triggers) {
538                 if (!parse_triggerstring(sdi, opt_triggers, &trigger)) {
539                         sr_session_destroy(session);
540                         return;
541                 }
542                 if (sr_session_trigger_set(session, trigger) != SR_OK) {
543                         sr_session_destroy(session);
544                         return;
545                 }
546         }
547
548         if (opt_continuous) {
549                 if (!sr_dev_has_option(sdi, SR_CONF_CONTINUOUS)) {
550                         g_critical("This device does not support continuous sampling.");
551                         sr_session_destroy(session);
552                         return;
553                 }
554         }
555
556         if (opt_time) {
557                 if (set_limit_time(sdi) != SR_OK) {
558                         sr_session_destroy(session);
559                         return;
560                 }
561         }
562
563         if (opt_samples) {
564                 if ((sr_parse_sizestring(opt_samples, &limit_samples) != SR_OK)) {
565                         g_critical("Invalid sample limit '%s'.", opt_samples);
566                         sr_session_destroy(session);
567                         return;
568                 }
569                 if (sr_config_list(sdi->driver, sdi, NULL,
570                                 SR_CONF_LIMIT_SAMPLES, &gvar) == SR_OK) {
571                         /* The device has no compression, or compression is turned
572                          * off, and publishes its sample memory size. */
573                         g_variant_get(gvar, "(tt)", &min_samples, &max_samples);
574                         g_variant_unref(gvar);
575                         if (limit_samples < min_samples) {
576                                 g_critical("The device stores at least %"PRIu64
577                                                 " samples with the current settings.", min_samples);
578                         }
579                         if (limit_samples > max_samples) {
580                                 g_critical("The device can store only %"PRIu64
581                                                 " samples with the current settings.", max_samples);
582                         }
583                 }
584                 gvar = g_variant_new_uint64(limit_samples);
585                 if (sr_config_set(sdi, NULL, SR_CONF_LIMIT_SAMPLES, gvar) != SR_OK) {
586                         g_critical("Failed to configure sample limit.");
587                         sr_session_destroy(session);
588                         return;
589                 }
590         }
591
592         if (opt_frames) {
593                 if ((sr_parse_sizestring(opt_frames, &limit_frames) != SR_OK)) {
594                         g_critical("Invalid sample limit '%s'.", opt_samples);
595                         sr_session_destroy(session);
596                         return;
597                 }
598                 gvar = g_variant_new_uint64(limit_frames);
599                 if (sr_config_set(sdi, NULL, SR_CONF_LIMIT_FRAMES, gvar) != SR_OK) {
600                         g_critical("Failed to configure frame limit.");
601                         sr_session_destroy(session);
602                         return;
603                 }
604         }
605
606         if (sr_session_start(session) != SR_OK) {
607                 g_critical("Failed to start session.");
608                 sr_session_destroy(session);
609                 return;
610         }
611
612         if (opt_continuous)
613                 add_anykey(session);
614
615         sr_session_run(session);
616
617         if (opt_continuous)
618                 clear_anykey();
619
620         sr_session_datafeed_callback_remove_all(session);
621         sr_session_destroy(session);
622
623 }
624
625 void save_chunk_logic(struct sr_session *session, uint8_t *data,
626                 uint64_t data_len, int unitsize)
627 {
628         static uint8_t *buf = NULL;
629         static int buf_len = 0;
630         static int last_unitsize = 0;
631         int max;
632
633         if (!buf)
634                 buf = g_malloc(SAVE_CHUNK_SIZE);
635
636         while (data_len > SAVE_CHUNK_SIZE) {
637                 save_chunk_logic(session, data, SAVE_CHUNK_SIZE, unitsize);
638                 data += SAVE_CHUNK_SIZE;
639                 data_len -= SAVE_CHUNK_SIZE;
640         }
641
642         if (buf_len + data_len > SAVE_CHUNK_SIZE) {
643                 max = (SAVE_CHUNK_SIZE - buf_len) / unitsize * unitsize;
644                 memcpy(buf + buf_len, data, max);
645                 sr_session_append(session, opt_output_file, buf, unitsize,
646                                 (buf_len + max) / unitsize);
647                 memcpy(buf, data + max, data_len - max);
648                 buf_len = data_len - max;
649         } else if (data_len == 0 && last_unitsize != 0) {
650                 /* End of data, flush the buffer out. */
651                 sr_session_append(session, opt_output_file, buf, last_unitsize,
652                                 buf_len / last_unitsize);
653         } else {
654                 /* Buffer chunk. */
655                 memcpy(buf + buf_len, data, data_len);
656                 buf_len += data_len;
657         }
658         last_unitsize = unitsize;
659
660 }