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