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