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