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