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