2 * This file is part of the libsigrok project.
4 * Copyright (C) 2010-2012 Bert Vermeulen <bert@biot.com>
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.
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.
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/>.
25 #include "libsigrok.h"
26 #include "libsigrok-internal.h"
29 #define LOG_PREFIX "session"
35 * Creating, using, or destroying libsigrok sessions.
39 * @defgroup grp_session Session handling
41 * Creating, using, or destroying libsigrok sessions.
48 sr_receive_data_callback cb;
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.
57 struct datafeed_callback {
58 sr_datafeed_callback cb;
62 /* There can currently only be one session at a time. */
63 /* 'sr_current_session' is not static, it's used elsewhere (via 'extern'). */
64 struct sr_session *sr_current_session;
67 * Create a new session.
68 * Currently, there can be only one session at a time within the same process.
70 * @retval SR_OK Success.
71 * @retval SR_ERR_BUG A session exists already.
75 SR_API int sr_session_new(struct sr_session **session)
77 if (sr_current_session) {
78 sr_err("%s: session already exists", __func__);
82 sr_current_session = g_malloc0(sizeof(struct sr_session));
84 sr_current_session->source_timeout = -1;
85 sr_current_session->running = FALSE;
86 sr_current_session->abort_session = FALSE;
87 g_mutex_init(&sr_current_session->stop_mutex);
89 *session = sr_current_session;
96 * This frees up all memory used by the session.
98 * @retval SR_OK Success.
99 * @retval SR_ERR_ARG Invalid session passed.
103 SR_API int sr_session_destroy(struct sr_session *session)
106 sr_err("%s: session was NULL", __func__);
110 sr_session_dev_remove_all(session);
111 g_mutex_clear(&session->stop_mutex);
112 if (session->trigger)
113 sr_trigger_free(session->trigger);
117 if (session == sr_current_session)
118 sr_current_session = NULL;
124 * Remove all the devices from a session.
126 * The session itself (i.e., the struct sr_session) is not free'd and still
127 * exists after this function returns.
129 * @retval SR_OK Success.
130 * @retval SR_ERR_BUG Invalid session passed.
134 SR_API int sr_session_dev_remove_all(struct sr_session *session)
136 struct sr_dev_inst *sdi;
140 sr_err("%s: session was NULL", __func__);
144 for (l = session->devs; l; l = l->next) {
145 sdi = (struct sr_dev_inst *) l->data;
149 g_slist_free(session->devs);
150 session->devs = NULL;
156 * Add a device instance to a session.
158 * @param sdi The device instance to add to a session. Must not
159 * be NULL. Also, sdi->driver and sdi->driver->dev_open must
162 * @retval SR_OK Success.
163 * @retval SR_ERR_ARG Invalid argument.
167 SR_API int sr_session_dev_add(struct sr_session *session,
168 struct sr_dev_inst *sdi)
173 sr_err("%s: sdi was NULL", __func__);
178 sr_err("%s: session was NULL", __func__);
182 /* If sdi->session is not NULL, the device is already in this or
183 * another session. */
185 sr_err("%s: already assigned to session", __func__);
189 /* If sdi->driver is NULL, this is a virtual device. */
191 sr_dbg("%s: sdi->driver was NULL, this seems to be "
192 "a virtual device; continuing", __func__);
193 /* Just add the device, don't run dev_open(). */
194 session->devs = g_slist_append(session->devs, (gpointer)sdi);
195 sdi->session = session;
199 /* sdi->driver is non-NULL (i.e. we have a real device). */
200 if (!sdi->driver->dev_open) {
201 sr_err("%s: sdi->driver->dev_open was NULL", __func__);
205 session->devs = g_slist_append(session->devs, (gpointer)sdi);
206 sdi->session = session;
208 if (session->running) {
209 /* Adding a device to a running session. Commit settings
210 * and start acquisition on that device now. */
211 if ((ret = sr_config_commit(sdi)) != SR_OK) {
212 sr_err("Failed to commit device settings before "
213 "starting acquisition in running session (%s)",
217 if ((ret = sdi->driver->dev_acquisition_start(sdi,
218 (void *)sdi)) != SR_OK) {
219 sr_err("Failed to start acquisition of device in "
220 "running session (%s)", sr_strerror(ret));
229 * List all device instances attached to a session.
231 * @param devlist A pointer where the device instance list will be
232 * stored on return. If no devices are in the session,
233 * this will be NULL. Each element in the list points
234 * to a struct sr_dev_inst *.
235 * The list must be freed by the caller, but not the
236 * elements pointed to.
238 * @retval SR_OK Success.
239 * @retval SR_ERR_ARG Invalid argument.
243 SR_API int sr_session_dev_list(struct sr_session *session, GSList **devlist)
251 *devlist = g_slist_copy(session->devs);
257 * Remove all datafeed callbacks in a session.
259 * @retval SR_OK Success.
260 * @retval SR_ERR_ARG Invalid session passed.
264 SR_API int sr_session_datafeed_callback_remove_all(struct sr_session *session)
267 sr_err("%s: session was NULL", __func__);
271 g_slist_free_full(session->datafeed_callbacks, g_free);
272 session->datafeed_callbacks = NULL;
278 * Add a datafeed callback to a session.
280 * @param cb Function to call when a chunk of data is received.
282 * @param cb_data Opaque pointer passed in by the caller.
284 * @retval SR_OK Success.
285 * @retval SR_ERR_BUG No session exists.
289 SR_API int sr_session_datafeed_callback_add(struct sr_session *session,
290 sr_datafeed_callback cb, void *cb_data)
292 struct datafeed_callback *cb_struct;
295 sr_err("%s: session was NULL", __func__);
300 sr_err("%s: cb was NULL", __func__);
304 if (!(cb_struct = g_try_malloc0(sizeof(struct datafeed_callback))))
305 return SR_ERR_MALLOC;
308 cb_struct->cb_data = cb_data;
310 session->datafeed_callbacks =
311 g_slist_append(session->datafeed_callbacks, cb_struct);
316 SR_API struct sr_trigger *sr_session_trigger_get(struct sr_session *session)
318 return session->trigger;
321 SR_API int sr_session_trigger_set(struct sr_session *session, struct sr_trigger *trig)
323 session->trigger = trig;
329 * Call every device in the current session's callback.
331 * For sessions not driven by select loops such as sr_session_run(),
332 * but driven by another scheduler, this can be used to poll the devices
333 * from within that scheduler.
335 * @param block If TRUE, this call will wait for any of the session's
336 * sources to fire an event on the file descriptors, or
337 * any of their timeouts to activate. In other words, this
338 * can be used as a select loop.
339 * If FALSE, all sources have their callback run, regardless
340 * of file descriptor or timeout status.
342 * @retval SR_OK Success.
343 * @retval SR_ERR Error occured.
345 static int sr_session_iteration(gboolean block)
347 struct sr_session *session = sr_current_session;
351 ret = g_poll(session->pollfds, session->num_sources,
352 block ? session->source_timeout : 0);
353 for (i = 0; i < session->num_sources; i++) {
354 if (session->pollfds[i].revents > 0 || (ret == 0
355 && session->source_timeout == session->sources[i].timeout)) {
357 * Invoke the source's callback on an event,
358 * or if the poll timed out and this source
359 * asked for that timeout.
361 if (!session->sources[i].cb(session->pollfds[i].fd,
362 session->pollfds[i].revents,
363 session->sources[i].cb_data))
364 sr_session_source_remove(session,
365 session->sources[i].poll_object);
368 * We want to take as little time as possible to stop
369 * the session if we have been told to do so. Therefore,
370 * we check the flag after processing every source, not
371 * just once per main event loop.
373 g_mutex_lock(&session->stop_mutex);
374 if (session->abort_session) {
375 sr_session_stop_sync(session);
376 /* But once is enough. */
377 session->abort_session = FALSE;
379 g_mutex_unlock(&session->stop_mutex);
386 static int verify_trigger(struct sr_trigger *trigger)
388 struct sr_trigger_stage *stage;
389 struct sr_trigger_match *match;
392 if (!trigger->stages) {
393 sr_err("No trigger stages defined.");
397 sr_spew("Checking trigger:");
398 for (l = trigger->stages; l; l = l->next) {
400 if (!stage->matches) {
401 sr_err("Stage %d has no matches defined.", stage->stage);
404 for (m = stage->matches; m; m = m->next) {
406 if (!match->channel) {
407 sr_err("Stage %d match has no channel.", stage->stage);
411 sr_err("Stage %d match is not defined.", stage->stage);
414 sr_spew("Stage %d match on channel %s, match %d", stage->stage,
415 match->channel->name, match->match);
424 * @retval SR_OK Success.
425 * @retval SR_ERR_ARG Invalid session passed.
429 SR_API int sr_session_start(struct sr_session *session)
431 struct sr_dev_inst *sdi;
436 sr_err("%s: session was NULL", __func__);
440 if (!session->devs) {
441 sr_err("%s: session->devs was NULL; a session "
442 "cannot be started without devices.", __func__);
446 if (session->trigger && verify_trigger(session->trigger) != SR_OK)
449 sr_info("Starting.");
452 for (l = session->devs; l; l = l->next) {
454 if ((ret = sr_config_commit(sdi)) != SR_OK) {
455 sr_err("Failed to commit device settings before "
456 "starting acquisition (%s)", sr_strerror(ret));
459 if ((ret = sdi->driver->dev_acquisition_start(sdi, sdi)) != SR_OK) {
460 sr_err("%s: could not start an acquisition "
461 "(%s)", __func__, sr_strerror(ret));
466 /* TODO: What if there are multiple devices? Which return code? */
474 * @retval SR_OK Success.
475 * @retval SR_ERR_ARG Invalid session passed.
479 SR_API int sr_session_run(struct sr_session *session)
482 sr_err("%s: session was NULL", __func__);
486 if (!session->devs) {
487 /* TODO: Actually the case? */
488 sr_err("%s: session->devs was NULL; a session "
489 "cannot be run without devices.", __func__);
492 session->running = TRUE;
496 /* Do we have real sources? */
497 if (session->num_sources == 1 && session->pollfds[0].fd == -1) {
498 /* Dummy source, freewheel over it. */
499 while (session->num_sources)
500 session->sources[0].cb(-1, 0, session->sources[0].cb_data);
502 /* Real sources, use g_poll() main loop. */
503 while (session->num_sources)
504 sr_session_iteration(TRUE);
513 * The session is stopped immediately, with all acquisition sessions stopped
514 * and hardware drivers cleaned up.
516 * This must be called from within the session thread, to prevent freeing
517 * resources that the session thread will try to use.
519 * @retval SR_OK Success.
520 * @retval SR_ERR_ARG Invalid session passed.
524 SR_PRIV int sr_session_stop_sync(struct sr_session *session)
526 struct sr_dev_inst *sdi;
530 sr_err("%s: session was NULL", __func__);
534 sr_info("Stopping.");
536 for (l = session->devs; l; l = l->next) {
539 if (sdi->driver->dev_acquisition_stop)
540 sdi->driver->dev_acquisition_stop(sdi, sdi);
543 session->running = FALSE;
551 * The session is stopped immediately, with all acquisition sessions being
552 * stopped and hardware drivers cleaned up.
554 * If the session is run in a separate thread, this function will not block
555 * until the session is finished executing. It is the caller's responsibility
556 * to wait for the session thread to return before assuming that the session is
557 * completely decommissioned.
559 * @retval SR_OK Success.
560 * @retval SR_ERR_ARG Invalid session passed.
564 SR_API int sr_session_stop(struct sr_session *session)
567 sr_err("%s: session was NULL", __func__);
571 g_mutex_lock(&session->stop_mutex);
572 session->abort_session = TRUE;
573 g_mutex_unlock(&session->stop_mutex);
581 * @param packet The packet to show debugging information for.
583 static void datafeed_dump(const struct sr_datafeed_packet *packet)
585 const struct sr_datafeed_logic *logic;
586 const struct sr_datafeed_analog *analog;
588 switch (packet->type) {
590 sr_dbg("bus: Received SR_DF_HEADER packet.");
593 sr_dbg("bus: Received SR_DF_TRIGGER packet.");
596 sr_dbg("bus: Received SR_DF_META packet.");
599 logic = packet->payload;
600 sr_dbg("bus: Received SR_DF_LOGIC packet (%" PRIu64 " bytes, "
601 "unitsize = %d).", logic->length, logic->unitsize);
604 analog = packet->payload;
605 sr_dbg("bus: Received SR_DF_ANALOG packet (%d samples).",
606 analog->num_samples);
609 sr_dbg("bus: Received SR_DF_END packet.");
611 case SR_DF_FRAME_BEGIN:
612 sr_dbg("bus: Received SR_DF_FRAME_BEGIN packet.");
614 case SR_DF_FRAME_END:
615 sr_dbg("bus: Received SR_DF_FRAME_END packet.");
618 sr_dbg("bus: Received unknown packet type: %d.", packet->type);
624 * Send a packet to whatever is listening on the datafeed bus.
626 * Hardware drivers use this to send a data packet to the frontend.
629 * @param packet The datafeed packet to send to the session bus.
631 * @retval SR_OK Success.
632 * @retval SR_ERR_ARG Invalid argument.
636 SR_PRIV int sr_session_send(const struct sr_dev_inst *sdi,
637 const struct sr_datafeed_packet *packet)
640 struct datafeed_callback *cb_struct;
643 sr_err("%s: sdi was NULL", __func__);
648 sr_err("%s: packet was NULL", __func__);
652 for (l = sr_current_session->datafeed_callbacks; l; l = l->next) {
653 if (sr_log_loglevel_get() >= SR_LOG_DBG)
654 datafeed_dump(packet);
656 cb_struct->cb(sdi, packet, cb_struct->cb_data);
663 * Add an event source for a file descriptor.
665 * @param pollfd The GPollFD.
666 * @param[in] timeout Max time to wait before the callback is called,
668 * @param cb Callback function to add. Must not be NULL.
669 * @param cb_data Data for the callback function. Can be NULL.
670 * @param poll_object TODO.
672 * @retval SR_OK Success.
673 * @retval SR_ERR_ARG Invalid argument.
674 * @retval SR_ERR_MALLOC Memory allocation error.
676 static int _sr_session_source_add(GPollFD *pollfd, int timeout,
677 sr_receive_data_callback cb, void *cb_data, gintptr poll_object)
679 struct sr_session *session = sr_current_session;
680 struct source *new_sources, *s;
681 GPollFD *new_pollfds;
684 sr_err("%s: cb was NULL", __func__);
688 /* Note: cb_data can be NULL, that's not a bug. */
690 new_pollfds = g_try_realloc(session->pollfds,
691 sizeof(GPollFD) * (session->num_sources + 1));
693 sr_err("%s: new_pollfds malloc failed", __func__);
694 return SR_ERR_MALLOC;
697 new_sources = g_try_realloc(session->sources, sizeof(struct source) *
698 (session->num_sources + 1));
700 sr_err("%s: new_sources malloc failed", __func__);
701 return SR_ERR_MALLOC;
704 new_pollfds[session->num_sources] = *pollfd;
705 s = &new_sources[session->num_sources++];
706 s->timeout = timeout;
708 s->cb_data = cb_data;
709 s->poll_object = poll_object;
710 session->pollfds = new_pollfds;
711 session->sources = new_sources;
713 if (timeout != session->source_timeout && timeout > 0
714 && (session->source_timeout == -1 || timeout < session->source_timeout))
715 session->source_timeout = timeout;
721 * Add an event source for a file descriptor.
723 * @param fd The file descriptor.
724 * @param events Events to check for.
725 * @param timeout Max time to wait before the callback is called, ignored if 0.
726 * @param cb Callback function to add. Must not be NULL.
727 * @param cb_data Data for the callback function. Can be NULL.
729 * @retval SR_OK Success.
730 * @retval SR_ERR_ARG Invalid argument.
731 * @retval SR_ERR_MALLOC Memory allocation error.
735 SR_API int sr_session_source_add(struct sr_session *session, int fd,
736 int events, int timeout, sr_receive_data_callback cb, void *cb_data)
745 return _sr_session_source_add(&p, timeout, cb, cb_data, (gintptr)fd);
749 * Add an event source for a GPollFD.
751 * @param pollfd The GPollFD.
752 * @param timeout Max time to wait before the callback is called, ignored if 0.
753 * @param cb Callback function to add. Must not be NULL.
754 * @param cb_data Data for the callback function. Can be NULL.
756 * @retval SR_OK Success.
757 * @retval SR_ERR_ARG Invalid argument.
758 * @retval SR_ERR_MALLOC Memory allocation error.
762 SR_API int sr_session_source_add_pollfd(struct sr_session *session,
763 GPollFD *pollfd, int timeout, sr_receive_data_callback cb,
768 return _sr_session_source_add(pollfd, timeout, cb,
769 cb_data, (gintptr)pollfd);
773 * Add an event source for a GIOChannel.
775 * @param channel The GIOChannel.
776 * @param events Events to poll on.
777 * @param timeout Max time to wait before the callback is called, ignored if 0.
778 * @param cb Callback function to add. Must not be NULL.
779 * @param cb_data Data for the callback function. Can be NULL.
781 * @retval SR_OK Success.
782 * @retval SR_ERR_ARG Invalid argument.
783 * @retval SR_ERR_MALLOC Memory allocation error.
787 SR_API int sr_session_source_add_channel(struct sr_session *session,
788 GIOChannel *channel, int events, int timeout,
789 sr_receive_data_callback cb, void *cb_data)
796 g_io_channel_win32_make_pollfd(channel, events, &p);
798 p.fd = g_io_channel_unix_get_fd(channel);
802 return _sr_session_source_add(&p, timeout, cb, cb_data, (gintptr)channel);
806 * Remove the source belonging to the specified channel.
808 * @todo Add more error checks and logging.
810 * @param poll_object The channel for which the source should be removed.
812 * @retval SR_OK Success
813 * @retval SR_ERR_ARG Invalid arguments
814 * @retval SR_ERR_MALLOC Memory allocation error
815 * @retval SR_ERR_BUG Internal error
817 static int _sr_session_source_remove(gintptr poll_object)
819 struct sr_session *session = sr_current_session;
820 struct source *new_sources;
821 GPollFD *new_pollfds;
824 if (!session->sources || !session->num_sources) {
825 sr_err("%s: sources was NULL", __func__);
829 for (old = 0; old < session->num_sources; old++) {
830 if (session->sources[old].poll_object == poll_object)
834 /* fd not found, nothing to do */
835 if (old == session->num_sources)
838 session->num_sources -= 1;
840 if (old != session->num_sources) {
841 memmove(&session->pollfds[old], &session->pollfds[old+1],
842 (session->num_sources - old) * sizeof(GPollFD));
843 memmove(&session->sources[old], &session->sources[old+1],
844 (session->num_sources - old) * sizeof(struct source));
847 new_pollfds = g_try_realloc(session->pollfds, sizeof(GPollFD) * session->num_sources);
848 if (!new_pollfds && session->num_sources > 0) {
849 sr_err("%s: new_pollfds malloc failed", __func__);
850 return SR_ERR_MALLOC;
853 new_sources = g_try_realloc(session->sources, sizeof(struct source) * session->num_sources);
854 if (!new_sources && session->num_sources > 0) {
855 sr_err("%s: new_sources malloc failed", __func__);
856 return SR_ERR_MALLOC;
859 session->pollfds = new_pollfds;
860 session->sources = new_sources;
866 * Remove the source belonging to the specified file descriptor.
868 * @param fd The file descriptor for which the source should be removed.
870 * @retval SR_OK Success
871 * @retval SR_ERR_ARG Invalid argument
872 * @retval SR_ERR_MALLOC Memory allocation error.
873 * @retval SR_ERR_BUG Internal error.
877 SR_API int sr_session_source_remove(struct sr_session *session, int fd)
881 return _sr_session_source_remove((gintptr)fd);
885 * Remove the source belonging to the specified poll descriptor.
887 * @param pollfd The poll descriptor for which the source should be removed.
889 * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments, or
890 * SR_ERR_MALLOC upon memory allocation errors, SR_ERR_BUG upon
895 SR_API int sr_session_source_remove_pollfd(struct sr_session *session,
900 return _sr_session_source_remove((gintptr)pollfd);
904 * Remove the source belonging to the specified channel.
906 * @param channel The channel for which the source should be removed.
908 * @retval SR_OK Success.
909 * @retval SR_ERR_ARG Invalid argument.
910 * @retval SR_ERR_MALLOC Memory allocation error.
911 * @return SR_ERR_BUG Internal error.
915 SR_API int sr_session_source_remove_channel(struct sr_session *session,
920 return _sr_session_source_remove((gintptr)channel);