]> sigrok.org Git - libsigrok.git/blob - src/session.c
session: Do not expect meaningful errno on non-UNIX
[libsigrok.git] / src / session.c
1 /*
2  * This file is part of the libsigrok project.
3  *
4  * Copyright (C) 2010-2012 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 <errno.h>
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <unistd.h>
24 #include <string.h>
25 #include <glib.h>
26 #include <libsigrok/libsigrok.h>
27 #include "libsigrok-internal.h"
28
29 /** @cond PRIVATE */
30 #define LOG_PREFIX "session"
31 /** @endcond */
32
33 /**
34  * @file
35  *
36  * Creating, using, or destroying libsigrok sessions.
37  */
38
39 /**
40  * @defgroup grp_session Session handling
41  *
42  * Creating, using, or destroying libsigrok sessions.
43  *
44  * @{
45  */
46
47 struct source {
48         int timeout;
49         sr_receive_data_callback cb;
50         void *cb_data;
51
52         /* This is used to keep track of the object (fd, pollfd or channel) which is
53          * being polled and will be used to match the source when removing it again.
54          */
55         gintptr poll_object;
56 };
57
58 struct datafeed_callback {
59         sr_datafeed_callback cb;
60         void *cb_data;
61 };
62
63 /**
64  * Create a new session.
65  *
66  * @param ctx         The context in which to create the new session.
67  * @param new_session This will contain a pointer to the newly created
68  *                    session if the return value is SR_OK, otherwise the value
69  *                    is undefined and should not be used. Must not be NULL.
70  *
71  * @retval SR_OK Success.
72  * @retval SR_ERR_ARG Invalid argument.
73  *
74  * @since 0.4.0
75  */
76 SR_API int sr_session_new(struct sr_context *ctx,
77                 struct sr_session **new_session)
78 {
79         struct sr_session *session;
80
81         if (!new_session)
82                 return SR_ERR_ARG;
83
84         session = g_malloc0(sizeof(struct sr_session));
85
86         session->ctx = ctx;
87         session->source_timeout = -1;
88         session->running = FALSE;
89         session->abort_session = FALSE;
90         g_mutex_init(&session->stop_mutex);
91
92         *new_session = session;
93
94         return SR_OK;
95 }
96
97 /**
98  * Destroy a session.
99  * This frees up all memory used by the session.
100  *
101  * @param session The session to destroy. Must not be NULL.
102  *
103  * @retval SR_OK Success.
104  * @retval SR_ERR_ARG Invalid session passed.
105  *
106  * @since 0.4.0
107  */
108 SR_API int sr_session_destroy(struct sr_session *session)
109 {
110         if (!session) {
111                 sr_err("%s: session was NULL", __func__);
112                 return SR_ERR_ARG;
113         }
114
115         sr_session_dev_remove_all(session);
116         g_mutex_clear(&session->stop_mutex);
117         if (session->trigger)
118                 sr_trigger_free(session->trigger);
119
120         g_slist_free_full(session->owned_devs, (GDestroyNotify)sr_dev_inst_free);
121
122         g_free(session);
123
124         return SR_OK;
125 }
126
127 /**
128  * Remove all the devices from a session.
129  *
130  * The session itself (i.e., the struct sr_session) is not free'd and still
131  * exists after this function returns.
132  *
133  * @param session The session to use. Must not be NULL.
134  *
135  * @retval SR_OK Success.
136  * @retval SR_ERR_BUG Invalid session passed.
137  *
138  * @since 0.4.0
139  */
140 SR_API int sr_session_dev_remove_all(struct sr_session *session)
141 {
142         struct sr_dev_inst *sdi;
143         GSList *l;
144
145         if (!session) {
146                 sr_err("%s: session was NULL", __func__);
147                 return SR_ERR_ARG;
148         }
149
150         for (l = session->devs; l; l = l->next) {
151                 sdi = (struct sr_dev_inst *) l->data;
152                 sdi->session = NULL;
153         }
154
155         g_slist_free(session->devs);
156         session->devs = NULL;
157
158         return SR_OK;
159 }
160
161 /**
162  * Add a device instance to a session.
163  *
164  * @param session The session to add to. Must not be NULL.
165  * @param sdi The device instance to add to a session. Must not
166  *            be NULL. Also, sdi->driver and sdi->driver->dev_open must
167  *            not be NULL.
168  *
169  * @retval SR_OK Success.
170  * @retval SR_ERR_ARG Invalid argument.
171  *
172  * @since 0.4.0
173  */
174 SR_API int sr_session_dev_add(struct sr_session *session,
175                 struct sr_dev_inst *sdi)
176 {
177         int ret;
178
179         if (!sdi) {
180                 sr_err("%s: sdi was NULL", __func__);
181                 return SR_ERR_ARG;
182         }
183
184         if (!session) {
185                 sr_err("%s: session was NULL", __func__);
186                 return SR_ERR_ARG;
187         }
188
189         /* If sdi->session is not NULL, the device is already in this or
190          * another session. */
191         if (sdi->session) {
192                 sr_err("%s: already assigned to session", __func__);
193                 return SR_ERR_ARG;
194         }
195
196         /* If sdi->driver is NULL, this is a virtual device. */
197         if (!sdi->driver) {
198                 /* Just add the device, don't run dev_open(). */
199                 session->devs = g_slist_append(session->devs, (gpointer)sdi);
200                 sdi->session = session;
201                 return SR_OK;
202         }
203
204         /* sdi->driver is non-NULL (i.e. we have a real device). */
205         if (!sdi->driver->dev_open) {
206                 sr_err("%s: sdi->driver->dev_open was NULL", __func__);
207                 return SR_ERR_BUG;
208         }
209
210         session->devs = g_slist_append(session->devs, (gpointer)sdi);
211         sdi->session = session;
212
213         if (session->running) {
214                 /* Adding a device to a running session. Commit settings
215                  * and start acquisition on that device now. */
216                 if ((ret = sr_config_commit(sdi)) != SR_OK) {
217                         sr_err("Failed to commit device settings before "
218                                "starting acquisition in running session (%s)",
219                                sr_strerror(ret));
220                         return ret;
221                 }
222                 if ((ret = sdi->driver->dev_acquisition_start(sdi,
223                                                 (void *)sdi)) != SR_OK) {
224                         sr_err("Failed to start acquisition of device in "
225                                "running session (%s)", sr_strerror(ret));
226                         return ret;
227                 }
228         }
229
230         return SR_OK;
231 }
232
233 /**
234  * List all device instances attached to a session.
235  *
236  * @param session The session to use. Must not be NULL.
237  * @param devlist A pointer where the device instance list will be
238  *                stored on return. If no devices are in the session,
239  *                this will be NULL. Each element in the list points
240  *                to a struct sr_dev_inst *.
241  *                The list must be freed by the caller, but not the
242  *                elements pointed to.
243  *
244  * @retval SR_OK Success.
245  * @retval SR_ERR_ARG Invalid argument.
246  *
247  * @since 0.4.0
248  */
249 SR_API int sr_session_dev_list(struct sr_session *session, GSList **devlist)
250 {
251         if (!session)
252                 return SR_ERR_ARG;
253
254         if (!devlist)
255                 return SR_ERR_ARG;
256
257         *devlist = g_slist_copy(session->devs);
258
259         return SR_OK;
260 }
261
262 /**
263  * Remove all datafeed callbacks in a session.
264  *
265  * @param session The session to use. Must not be NULL.
266  *
267  * @retval SR_OK Success.
268  * @retval SR_ERR_ARG Invalid session passed.
269  *
270  * @since 0.4.0
271  */
272 SR_API int sr_session_datafeed_callback_remove_all(struct sr_session *session)
273 {
274         if (!session) {
275                 sr_err("%s: session was NULL", __func__);
276                 return SR_ERR_ARG;
277         }
278
279         g_slist_free_full(session->datafeed_callbacks, g_free);
280         session->datafeed_callbacks = NULL;
281
282         return SR_OK;
283 }
284
285 /**
286  * Add a datafeed callback to a session.
287  *
288  * @param session The session to use. Must not be NULL.
289  * @param cb Function to call when a chunk of data is received.
290  *           Must not be NULL.
291  * @param cb_data Opaque pointer passed in by the caller.
292  *
293  * @retval SR_OK Success.
294  * @retval SR_ERR_BUG No session exists.
295  *
296  * @since 0.3.0
297  */
298 SR_API int sr_session_datafeed_callback_add(struct sr_session *session,
299                 sr_datafeed_callback cb, void *cb_data)
300 {
301         struct datafeed_callback *cb_struct;
302
303         if (!session) {
304                 sr_err("%s: session was NULL", __func__);
305                 return SR_ERR_BUG;
306         }
307
308         if (!cb) {
309                 sr_err("%s: cb was NULL", __func__);
310                 return SR_ERR_ARG;
311         }
312
313         cb_struct = g_malloc0(sizeof(struct datafeed_callback));
314         cb_struct->cb = cb;
315         cb_struct->cb_data = cb_data;
316
317         session->datafeed_callbacks =
318             g_slist_append(session->datafeed_callbacks, cb_struct);
319
320         return SR_OK;
321 }
322
323 /**
324  * Get the trigger assigned to this session.
325  *
326  * @param session The session to use.
327  *
328  * @retval NULL Invalid (NULL) session was passed to the function.
329  * @retval other The trigger assigned to this session (can be NULL).
330  *
331  * @since 0.4.0
332  */
333 SR_API struct sr_trigger *sr_session_trigger_get(struct sr_session *session)
334 {
335         if (!session)
336                 return NULL;
337
338         return session->trigger;
339 }
340
341 /**
342  * Set the trigger of this session.
343  *
344  * @param session The session to use. Must not be NULL.
345  * @param trig The trigger to assign to this session. Can be NULL.
346  *
347  * @retval SR_OK Success.
348  * @retval SR_ERR_ARG Invalid argument.
349  *
350  * @since 0.4.0
351  */
352 SR_API int sr_session_trigger_set(struct sr_session *session, struct sr_trigger *trig)
353 {
354         if (!session)
355                 return SR_ERR_ARG;
356
357         session->trigger = trig;
358
359         return SR_OK;
360 }
361
362 static gboolean sr_session_check_aborted(struct sr_session *session)
363 {
364         gboolean stop;
365
366         g_mutex_lock(&session->stop_mutex);
367         stop = session->abort_session;
368         if (stop) {
369                 sr_session_stop_sync(session);
370                 /* But once is enough. */
371                 session->abort_session = FALSE;
372         }
373         g_mutex_unlock(&session->stop_mutex);
374
375         return stop;
376 }
377
378 /**
379  * Call every device in the current session's callback.
380  *
381  * For sessions not driven by select loops such as sr_session_run(),
382  * but driven by another scheduler, this can be used to poll the devices
383  * from within that scheduler.
384  *
385  * @param session The session to use. Must not be NULL.
386  * @param block If TRUE, this call will wait for any of the session's
387  *              sources to fire an event on the file descriptors, or
388  *              any of their timeouts to activate. In other words, this
389  *              can be used as a select loop.
390  *              If FALSE, return immediately if none of the sources has
391  *              events pending.
392  * @retval SR_OK Success.
393  * @retval SR_ERR Error occurred.
394  */
395 static int sr_session_iteration(struct sr_session *session, gboolean block)
396 {
397         unsigned int i;
398         int ret, timeout;
399         int revents;
400         gboolean stop_checked;
401         gboolean stopped;
402         struct source *source;
403         GPollFD *pollfd;
404 #ifdef HAVE_LIBUSB_1_0
405         int usb_timeout;
406         struct timeval tv;
407 #endif
408
409         timeout = block ? session->source_timeout : 0;
410
411 #ifdef HAVE_LIBUSB_1_0
412         if (session->ctx->usb_source_present) {
413                 ret = libusb_get_next_timeout(session->ctx->libusb_ctx, &tv);
414                 if (ret < 0) {
415                         sr_err("Error getting libusb timeout: %s",
416                                 libusb_error_name(ret));
417                         return SR_ERR;
418                 } else if (ret == 1) {
419                         usb_timeout = tv.tv_sec * 1000 + tv.tv_usec / 1000;
420                         timeout = MIN(timeout, usb_timeout);
421                 }
422         }
423 #endif
424
425         ret = g_poll(session->pollfds, session->num_sources, timeout);
426 #ifdef G_OS_UNIX
427         if (ret < 0 && errno != EINTR) {
428                 sr_err("Error in poll: %s", g_strerror(errno));
429                 return SR_ERR;
430         }
431 #else
432         if (ret < 0) {
433                 sr_err("Error in poll: %d", ret);
434                 return SR_ERR;
435         }
436 #endif
437         stop_checked = FALSE;
438         stopped = FALSE;
439
440         for (i = 0; i < session->num_sources; i++) {
441                 source = &session->sources[i];
442                 pollfd = &session->pollfds[i];
443                 revents = (ret > 0) ? pollfd->revents : 0;
444
445                 if (revents > 0 || (ret == 0
446                         && session->source_timeout == source->timeout)) {
447                         /*
448                          * Invoke the source's callback on an event,
449                          * or if the poll timed out and this source
450                          * asked for that timeout.
451                          */
452                         if (!source->cb(pollfd->fd, revents, source->cb_data))
453                                 sr_session_source_remove(session,
454                                                 source->poll_object);
455                         /*
456                          * We want to take as little time as possible to stop
457                          * the session if we have been told to do so. Therefore,
458                          * we check the flag after processing every source, not
459                          * just once per main event loop.
460                          */
461                         if (!stopped) {
462                                 stopped = sr_session_check_aborted(session);
463                                 stop_checked = TRUE;
464                         }
465                 }
466         }
467         if (!stop_checked)
468                 sr_session_check_aborted(session);
469
470         return SR_OK;
471 }
472
473 static int verify_trigger(struct sr_trigger *trigger)
474 {
475         struct sr_trigger_stage *stage;
476         struct sr_trigger_match *match;
477         GSList *l, *m;
478
479         if (!trigger->stages) {
480                 sr_err("No trigger stages defined.");
481                 return SR_ERR;
482         }
483
484         sr_spew("Checking trigger:");
485         for (l = trigger->stages; l; l = l->next) {
486                 stage = l->data;
487                 if (!stage->matches) {
488                         sr_err("Stage %d has no matches defined.", stage->stage);
489                         return SR_ERR;
490                 }
491                 for (m = stage->matches; m; m = m->next) {
492                         match = m->data;
493                         if (!match->channel) {
494                                 sr_err("Stage %d match has no channel.", stage->stage);
495                                 return SR_ERR;
496                         }
497                         if (!match->match) {
498                                 sr_err("Stage %d match is not defined.", stage->stage);
499                                 return SR_ERR;
500                         }
501                         sr_spew("Stage %d match on channel %s, match %d", stage->stage,
502                                         match->channel->name, match->match);
503                 }
504         }
505
506         return SR_OK;
507 }
508
509 /**
510  * Start a session.
511  *
512  * @param session The session to use. Must not be NULL.
513  *
514  * @retval SR_OK Success.
515  * @retval SR_ERR_ARG Invalid session passed.
516  *
517  * @since 0.4.0
518  */
519 SR_API int sr_session_start(struct sr_session *session)
520 {
521         struct sr_dev_inst *sdi;
522         struct sr_channel *ch;
523         GSList *l, *c;
524         int enabled_channels, ret;
525
526         if (!session) {
527                 sr_err("%s: session was NULL", __func__);
528                 return SR_ERR_ARG;
529         }
530
531         if (!session->devs) {
532                 sr_err("%s: session->devs was NULL; a session "
533                        "cannot be started without devices.", __func__);
534                 return SR_ERR_ARG;
535         }
536
537         if (session->trigger && verify_trigger(session->trigger) != SR_OK)
538                 return SR_ERR;
539
540         sr_info("Starting.");
541
542         ret = SR_OK;
543         for (l = session->devs; l; l = l->next) {
544                 sdi = l->data;
545                 enabled_channels = 0;
546                 for (c = sdi->channels; c; c = c->next) {
547                         ch = c->data;
548                         if (ch->enabled) {
549                                 enabled_channels++;
550                                 break;
551                         }
552                 }
553                 if (enabled_channels == 0) {
554                         ret = SR_ERR;
555                         sr_err("%s using connection %s has no enabled channels!",
556                                         sdi->driver->name, sdi->connection_id);
557                         break;
558                 }
559
560                 if ((ret = sr_config_commit(sdi)) != SR_OK) {
561                         sr_err("Failed to commit device settings before "
562                                "starting acquisition (%s)", sr_strerror(ret));
563                         break;
564                 }
565                 if ((ret = sdi->driver->dev_acquisition_start(sdi, sdi)) != SR_OK) {
566                         sr_err("%s: could not start an acquisition "
567                                "(%s)", __func__, sr_strerror(ret));
568                         break;
569                 }
570         }
571
572         /* TODO: What if there are multiple devices? Which return code? */
573
574         return ret;
575 }
576
577 /**
578  * Run a session.
579  *
580  * @param session The session to use. Must not be NULL.
581  *
582  * @retval SR_OK Success.
583  * @retval SR_ERR_ARG Invalid session passed.
584  *
585  * @since 0.4.0
586  */
587 SR_API int sr_session_run(struct sr_session *session)
588 {
589         if (!session) {
590                 sr_err("%s: session was NULL", __func__);
591                 return SR_ERR_ARG;
592         }
593
594         if (!session->devs) {
595                 /* TODO: Actually the case? */
596                 sr_err("%s: session->devs was NULL; a session "
597                        "cannot be run without devices.", __func__);
598                 return SR_ERR_ARG;
599         }
600         session->running = TRUE;
601
602         sr_info("Running.");
603
604         /* Do we have real sources? */
605         if (session->num_sources == 1 && session->pollfds[0].fd == -1) {
606                 /* Dummy source, freewheel over it. */
607                 while (session->num_sources)
608                         session->sources[0].cb(-1, 0, session->sources[0].cb_data);
609         } else {
610                 /* Real sources, use g_poll() main loop. */
611                 while (session->num_sources)
612                         sr_session_iteration(session, TRUE);
613         }
614
615         return SR_OK;
616 }
617
618 /**
619  * Stop a session.
620  *
621  * The session is stopped immediately, with all acquisition sessions stopped
622  * and hardware drivers cleaned up.
623  *
624  * This must be called from within the session thread, to prevent freeing
625  * resources that the session thread will try to use.
626  *
627  * @param session The session to use. Must not be NULL.
628  *
629  * @retval SR_OK Success.
630  * @retval SR_ERR_ARG Invalid session passed.
631  *
632  * @private
633  */
634 SR_PRIV int sr_session_stop_sync(struct sr_session *session)
635 {
636         struct sr_dev_inst *sdi;
637         GSList *l;
638
639         if (!session) {
640                 sr_err("%s: session was NULL", __func__);
641                 return SR_ERR_ARG;
642         }
643
644         sr_info("Stopping.");
645
646         for (l = session->devs; l; l = l->next) {
647                 sdi = l->data;
648                 if (sdi->driver) {
649                         if (sdi->driver->dev_acquisition_stop)
650                                 sdi->driver->dev_acquisition_stop(sdi, sdi);
651                 }
652         }
653         session->running = FALSE;
654
655         return SR_OK;
656 }
657
658 /**
659  * Stop a session.
660  *
661  * The session is stopped immediately, with all acquisition sessions being
662  * stopped and hardware drivers cleaned up.
663  *
664  * If the session is run in a separate thread, this function will not block
665  * until the session is finished executing. It is the caller's responsibility
666  * to wait for the session thread to return before assuming that the session is
667  * completely decommissioned.
668  *
669  * @param session The session to use. Must not be NULL.
670  *
671  * @retval SR_OK Success.
672  * @retval SR_ERR_ARG Invalid session passed.
673  *
674  * @since 0.4.0
675  */
676 SR_API int sr_session_stop(struct sr_session *session)
677 {
678         if (!session) {
679                 sr_err("%s: session was NULL", __func__);
680                 return SR_ERR_BUG;
681         }
682
683         g_mutex_lock(&session->stop_mutex);
684         session->abort_session = TRUE;
685         g_mutex_unlock(&session->stop_mutex);
686
687         return SR_OK;
688 }
689
690 /**
691  * Debug helper.
692  *
693  * @param packet The packet to show debugging information for.
694  */
695 static void datafeed_dump(const struct sr_datafeed_packet *packet)
696 {
697         const struct sr_datafeed_logic *logic;
698         const struct sr_datafeed_analog *analog;
699         const struct sr_datafeed_analog2 *analog2;
700
701         /* Please use the same order as in libsigrok.h. */
702         switch (packet->type) {
703         case SR_DF_HEADER:
704                 sr_dbg("bus: Received SR_DF_HEADER packet.");
705                 break;
706         case SR_DF_END:
707                 sr_dbg("bus: Received SR_DF_END packet.");
708                 break;
709         case SR_DF_META:
710                 sr_dbg("bus: Received SR_DF_META packet.");
711                 break;
712         case SR_DF_TRIGGER:
713                 sr_dbg("bus: Received SR_DF_TRIGGER packet.");
714                 break;
715         case SR_DF_LOGIC:
716                 logic = packet->payload;
717                 sr_dbg("bus: Received SR_DF_LOGIC packet (%" PRIu64 " bytes, "
718                        "unitsize = %d).", logic->length, logic->unitsize);
719                 break;
720         case SR_DF_ANALOG:
721                 analog = packet->payload;
722                 sr_dbg("bus: Received SR_DF_ANALOG packet (%d samples).",
723                        analog->num_samples);
724                 break;
725         case SR_DF_FRAME_BEGIN:
726                 sr_dbg("bus: Received SR_DF_FRAME_BEGIN packet.");
727                 break;
728         case SR_DF_FRAME_END:
729                 sr_dbg("bus: Received SR_DF_FRAME_END packet.");
730                 break;
731         case SR_DF_ANALOG2:
732                 analog2 = packet->payload;
733                 sr_dbg("bus: Received SR_DF_ANALOG2 packet (%d samples).",
734                        analog2->num_samples);
735                 break;
736         default:
737                 sr_dbg("bus: Received unknown packet type: %d.", packet->type);
738                 break;
739         }
740 }
741
742 /**
743  * Send a packet to whatever is listening on the datafeed bus.
744  *
745  * Hardware drivers use this to send a data packet to the frontend.
746  *
747  * @param sdi TODO.
748  * @param packet The datafeed packet to send to the session bus.
749  *
750  * @retval SR_OK Success.
751  * @retval SR_ERR_ARG Invalid argument.
752  *
753  * @private
754  */
755 SR_PRIV int sr_session_send(const struct sr_dev_inst *sdi,
756                 const struct sr_datafeed_packet *packet)
757 {
758         GSList *l;
759         struct datafeed_callback *cb_struct;
760         struct sr_datafeed_packet *packet_in, *packet_out;
761         struct sr_transform *t;
762         int ret;
763
764         if (!sdi) {
765                 sr_err("%s: sdi was NULL", __func__);
766                 return SR_ERR_ARG;
767         }
768
769         if (!packet) {
770                 sr_err("%s: packet was NULL", __func__);
771                 return SR_ERR_ARG;
772         }
773
774         if (!sdi->session) {
775                 sr_err("%s: session was NULL", __func__);
776                 return SR_ERR_BUG;
777         }
778
779         /*
780          * Pass the packet to the first transform module. If that returns
781          * another packet (instead of NULL), pass that packet to the next
782          * transform module in the list, and so on.
783          */
784         packet_in = (struct sr_datafeed_packet *)packet;
785         for (l = sdi->session->transforms; l; l = l->next) {
786                 t = l->data;
787                 sr_spew("Running transform module '%s'.", t->module->id);
788                 ret = t->module->receive(t, packet_in, &packet_out);
789                 if (ret < 0) {
790                         sr_err("Error while running transform module: %d.", ret);
791                         return SR_ERR;
792                 }
793                 if (!packet_out) {
794                         /*
795                          * If any of the transforms don't return an output
796                          * packet, abort.
797                          */
798                         sr_spew("Transform module didn't return a packet, aborting.");
799                         return SR_OK;
800                 } else {
801                         /*
802                          * Use this transform module's output packet as input
803                          * for the next transform module.
804                          */
805                         packet_in = packet_out;
806                 }
807         }
808         packet = packet_in;
809
810         /*
811          * If the last transform did output a packet, pass it to all datafeed
812          * callbacks.
813          */
814         for (l = sdi->session->datafeed_callbacks; l; l = l->next) {
815                 if (sr_log_loglevel_get() >= SR_LOG_DBG)
816                         datafeed_dump(packet);
817                 cb_struct = l->data;
818                 cb_struct->cb(sdi, packet, cb_struct->cb_data);
819         }
820
821         return SR_OK;
822 }
823
824 /**
825  * Add an event source for a file descriptor.
826  *
827  * @param session The session to use. Must not be NULL.
828  * @param pollfd The GPollFD.
829  * @param[in] timeout Max time to wait before the callback is called,
830  *              ignored if 0.
831  * @param cb Callback function to add. Must not be NULL.
832  * @param cb_data Data for the callback function. Can be NULL.
833  * @param poll_object TODO.
834  *
835  * @retval SR_OK Success.
836  * @retval SR_ERR_ARG Invalid argument.
837  */
838 static int _sr_session_source_add(struct sr_session *session, GPollFD *pollfd,
839                 int timeout, sr_receive_data_callback cb, void *cb_data, gintptr poll_object)
840 {
841         struct source *new_sources, *s;
842         GPollFD *new_pollfds;
843
844         if (!cb) {
845                 sr_err("%s: cb was NULL", __func__);
846                 return SR_ERR_ARG;
847         }
848
849         /* Note: cb_data can be NULL, that's not a bug. */
850
851         new_pollfds = g_realloc(session->pollfds,
852                         sizeof(GPollFD) * (session->num_sources + 1));
853         new_sources = g_realloc(session->sources, sizeof(struct source) *
854                         (session->num_sources + 1));
855
856         new_pollfds[session->num_sources] = *pollfd;
857         s = &new_sources[session->num_sources++];
858         s->timeout = timeout;
859         s->cb = cb;
860         s->cb_data = cb_data;
861         s->poll_object = poll_object;
862         session->pollfds = new_pollfds;
863         session->sources = new_sources;
864
865         if (timeout != session->source_timeout && timeout > 0
866             && (session->source_timeout == -1 || timeout < session->source_timeout))
867                 session->source_timeout = timeout;
868
869         return SR_OK;
870 }
871
872 /**
873  * Add an event source for a file descriptor.
874  *
875  * @param session The session to use. Must not be NULL.
876  * @param fd The file descriptor.
877  * @param events Events to check for.
878  * @param timeout Max time to wait before the callback is called, ignored if 0.
879  * @param cb Callback function to add. Must not be NULL.
880  * @param cb_data Data for the callback function. Can be NULL.
881  *
882  * @retval SR_OK Success.
883  * @retval SR_ERR_ARG Invalid argument.
884  *
885  * @since 0.3.0
886  */
887 SR_API int sr_session_source_add(struct sr_session *session, int fd,
888                 int events, int timeout, sr_receive_data_callback cb, void *cb_data)
889 {
890         GPollFD p;
891
892         p.fd = fd;
893         p.events = events;
894         p.revents = 0;
895
896         return _sr_session_source_add(session, &p, timeout, cb, cb_data, (gintptr)fd);
897 }
898
899 /**
900  * Add an event source for a GPollFD.
901  *
902  * @param session The session to use. Must not be NULL.
903  * @param pollfd The GPollFD.
904  * @param timeout Max time to wait before the callback is called, ignored if 0.
905  * @param cb Callback function to add. Must not be NULL.
906  * @param cb_data Data for the callback function. Can be NULL.
907  *
908  * @retval SR_OK Success.
909  * @retval SR_ERR_ARG Invalid argument.
910  *
911  * @since 0.3.0
912  */
913 SR_API int sr_session_source_add_pollfd(struct sr_session *session,
914                 GPollFD *pollfd, int timeout, sr_receive_data_callback cb,
915                 void *cb_data)
916 {
917         return _sr_session_source_add(session, pollfd, timeout, cb,
918                         cb_data, (gintptr)pollfd);
919 }
920
921 /**
922  * Add an event source for a GIOChannel.
923  *
924  * @param session The session to use. Must not be NULL.
925  * @param channel The GIOChannel.
926  * @param events Events to poll on.
927  * @param timeout Max time to wait before the callback is called, ignored if 0.
928  * @param cb Callback function to add. Must not be NULL.
929  * @param cb_data Data for the callback function. Can be NULL.
930  *
931  * @retval SR_OK Success.
932  * @retval SR_ERR_ARG Invalid argument.
933  *
934  * @since 0.3.0
935  */
936 SR_API int sr_session_source_add_channel(struct sr_session *session,
937                 GIOChannel *channel, int events, int timeout,
938                 sr_receive_data_callback cb, void *cb_data)
939 {
940         GPollFD p;
941
942 #ifdef _WIN32
943         g_io_channel_win32_make_pollfd(channel, events, &p);
944 #else
945         p.fd = g_io_channel_unix_get_fd(channel);
946         p.events = events;
947         p.revents = 0;
948 #endif
949
950         return _sr_session_source_add(session, &p, timeout, cb, cb_data, (gintptr)channel);
951 }
952
953 /**
954  * Remove the source belonging to the specified channel.
955  *
956  * @param session The session to use. Must not be NULL.
957  * @param poll_object The channel for which the source should be removed.
958  *
959  * @retval SR_OK Success
960  * @retval SR_ERR_ARG Invalid arguments
961  * @retval SR_ERR_BUG Internal error
962  */
963 static int _sr_session_source_remove(struct sr_session *session, gintptr poll_object)
964 {
965         unsigned int old;
966
967         if (!session->sources || !session->num_sources) {
968                 sr_err("%s: sources was NULL", __func__);
969                 return SR_ERR_BUG;
970         }
971
972         for (old = 0; old < session->num_sources; old++) {
973                 if (session->sources[old].poll_object == poll_object)
974                         break;
975         }
976
977         /* fd not found, nothing to do */
978         if (old == session->num_sources)
979                 return SR_OK;
980
981         session->num_sources--;
982
983         if (old != session->num_sources) {
984                 memmove(&session->pollfds[old], &session->pollfds[old + 1],
985                         (session->num_sources - old) * sizeof(GPollFD));
986                 memmove(&session->sources[old], &session->sources[old + 1],
987                         (session->num_sources - old) * sizeof(struct source));
988         }
989
990         session->pollfds = g_realloc(session->pollfds, sizeof(GPollFD) * session->num_sources);
991         session->sources = g_realloc(session->sources, sizeof(struct source) * session->num_sources);
992
993         return SR_OK;
994 }
995
996 /**
997  * Remove the source belonging to the specified file descriptor.
998  *
999  * @param session The session to use. Must not be NULL.
1000  * @param fd The file descriptor for which the source should be removed.
1001  *
1002  * @retval SR_OK Success
1003  * @retval SR_ERR_ARG Invalid argument
1004  * @retval SR_ERR_BUG Internal error.
1005  *
1006  * @since 0.3.0
1007  */
1008 SR_API int sr_session_source_remove(struct sr_session *session, int fd)
1009 {
1010         return _sr_session_source_remove(session, (gintptr)fd);
1011 }
1012
1013 /**
1014  * Remove the source belonging to the specified poll descriptor.
1015  *
1016  * @param session The session to use. Must not be NULL.
1017  * @param pollfd The poll descriptor for which the source should be removed.
1018  *
1019  * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments, or
1020  *         SR_ERR_MALLOC upon memory allocation errors, SR_ERR_BUG upon
1021  *         internal errors.
1022  *
1023  * @since 0.2.0
1024  */
1025 SR_API int sr_session_source_remove_pollfd(struct sr_session *session,
1026                 GPollFD *pollfd)
1027 {
1028         return _sr_session_source_remove(session, (gintptr)pollfd);
1029 }
1030
1031 /**
1032  * Remove the source belonging to the specified channel.
1033  *
1034  * @param session The session to use. Must not be NULL.
1035  * @param channel The channel for which the source should be removed.
1036  *
1037  * @retval SR_OK Success.
1038  * @retval SR_ERR_ARG Invalid argument.
1039  * @return SR_ERR_BUG Internal error.
1040  *
1041  * @since 0.2.0
1042  */
1043 SR_API int sr_session_source_remove_channel(struct sr_session *session,
1044                 GIOChannel *channel)
1045 {
1046         return _sr_session_source_remove(session, (gintptr)channel);
1047 }
1048
1049 static void copy_src(struct sr_config *src, struct sr_datafeed_meta *meta_copy)
1050 {
1051         g_variant_ref(src->data);
1052         meta_copy->config = g_slist_append(meta_copy->config,
1053                                            g_memdup(src, sizeof(struct sr_config)));
1054 }
1055
1056 SR_PRIV int sr_packet_copy(const struct sr_datafeed_packet *packet,
1057                 struct sr_datafeed_packet **copy)
1058 {
1059         const struct sr_datafeed_meta *meta;
1060         struct sr_datafeed_meta *meta_copy;
1061         const struct sr_datafeed_logic *logic;
1062         struct sr_datafeed_logic *logic_copy;
1063         const struct sr_datafeed_analog *analog;
1064         struct sr_datafeed_analog *analog_copy;
1065         uint8_t *payload;
1066
1067         *copy = g_malloc0(sizeof(struct sr_datafeed_packet));
1068         (*copy)->type = packet->type;
1069
1070         switch (packet->type) {
1071         case SR_DF_TRIGGER:
1072         case SR_DF_END:
1073                 /* No payload. */
1074                 break;
1075         case SR_DF_HEADER:
1076                 payload = g_malloc(sizeof(struct sr_datafeed_header));
1077                 memcpy(payload, packet->payload, sizeof(struct sr_datafeed_header));
1078                 (*copy)->payload = payload;
1079                 break;
1080         case SR_DF_META:
1081                 meta = packet->payload;
1082                 meta_copy = g_malloc0(sizeof(struct sr_datafeed_meta));
1083                 g_slist_foreach(meta->config, (GFunc)copy_src, meta_copy->config);
1084                 (*copy)->payload = meta_copy;
1085                 break;
1086         case SR_DF_LOGIC:
1087                 logic = packet->payload;
1088                 logic_copy = g_malloc(sizeof(logic));
1089                 logic_copy->length = logic->length;
1090                 logic_copy->unitsize = logic->unitsize;
1091                 memcpy(logic_copy->data, logic->data, logic->length * logic->unitsize);
1092                 (*copy)->payload = logic_copy;
1093                 break;
1094         case SR_DF_ANALOG:
1095                 analog = packet->payload;
1096                 analog_copy = g_malloc(sizeof(analog));
1097                 analog_copy->channels = g_slist_copy(analog->channels);
1098                 analog_copy->num_samples = analog->num_samples;
1099                 analog_copy->mq = analog->mq;
1100                 analog_copy->unit = analog->unit;
1101                 analog_copy->mqflags = analog->mqflags;
1102                 memcpy(analog_copy->data, analog->data,
1103                                 analog->num_samples * sizeof(float));
1104                 (*copy)->payload = analog_copy;
1105                 break;
1106         default:
1107                 sr_err("Unknown packet type %d", packet->type);
1108                 return SR_ERR;
1109         }
1110
1111         return SR_OK;
1112 }
1113
1114 void sr_packet_free(struct sr_datafeed_packet *packet)
1115 {
1116         const struct sr_datafeed_meta *meta;
1117         const struct sr_datafeed_logic *logic;
1118         const struct sr_datafeed_analog *analog;
1119         struct sr_config *src;
1120         GSList *l;
1121
1122         switch (packet->type) {
1123         case SR_DF_TRIGGER:
1124         case SR_DF_END:
1125                 /* No payload. */
1126                 break;
1127         case SR_DF_HEADER:
1128                 /* Payload is a simple struct. */
1129                 g_free((void *)packet->payload);
1130                 break;
1131         case SR_DF_META:
1132                 meta = packet->payload;
1133                 for (l = meta->config; l; l = l->next) {
1134                         src = l->data;
1135                         g_variant_unref(src->data);
1136                         g_free(src);
1137                 }
1138                 g_slist_free(meta->config);
1139                 g_free((void *)packet->payload);
1140                 break;
1141         case SR_DF_LOGIC:
1142                 logic = packet->payload;
1143                 g_free(logic->data);
1144                 g_free((void *)packet->payload);
1145                 break;
1146         case SR_DF_ANALOG:
1147                 analog = packet->payload;
1148                 g_slist_free(analog->channels);
1149                 g_free(analog->data);
1150                 g_free((void *)packet->payload);
1151                 break;
1152         default:
1153                 sr_err("Unknown packet type %d", packet->type);
1154         }
1155         g_free(packet);
1156
1157 }
1158
1159 /** @} */