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