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