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