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