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 only be one session at a time. */
63 /* 'session' is not static, it's used elsewhere (via 'extern'). */
64 struct sr_session *session;
67 * Create a new session.
69 * @todo Should it use the file-global "session" variable or take an argument?
70 * The same question applies to all the other session functions.
73 * @retval other A pointer to the newly allocated session.
75 SR_API struct sr_session *sr_session_new(void)
77 if (!(session = g_try_malloc0(sizeof(struct sr_session)))) {
78 sr_err("Session malloc failed.");
82 session->source_timeout = -1;
83 session->running = FALSE;
84 session->abort_session = FALSE;
85 g_mutex_init(&session->stop_mutex);
91 * Destroy the current session.
92 * This frees up all memory used by the session.
94 * @retval SR_OK Success.
95 * @retval SR_ERR_BUG No session exists.
97 SR_API int sr_session_destroy(void)
100 sr_err("%s: session was NULL", __func__);
104 sr_session_dev_remove_all();
106 /* TODO: Error checks needed? */
108 g_mutex_clear(&session->stop_mutex);
117 * Remove all the devices from the current session.
119 * The session itself (i.e., the struct sr_session) is not free'd and still
120 * exists after this function returns.
122 * @retval SR_OK Success.
123 * @retval SR_ERR_BUG No session exists.
125 SR_API int sr_session_dev_remove_all(void)
128 sr_err("%s: session was NULL", __func__);
132 g_slist_free(session->devs);
133 session->devs = NULL;
139 * Add a device instance to the current session.
141 * @param sdi The device instance to add to the current session. Must not
142 * be NULL. Also, sdi->driver and sdi->driver->dev_open must
145 * @retval SR_OK Success.
146 * @retval SR_ERR_ARG Invalid argument.
147 * @retval SR_ERR_BUG No session exists.
149 SR_API int sr_session_dev_add(const struct sr_dev_inst *sdi)
154 sr_err("%s: sdi was NULL", __func__);
159 sr_err("%s: session was NULL", __func__);
163 /* If sdi->driver is NULL, this is a virtual device. */
165 sr_dbg("%s: sdi->driver was NULL, this seems to be "
166 "a virtual device; continuing", __func__);
167 /* Just add the device, don't run dev_open(). */
168 session->devs = g_slist_append(session->devs, (gpointer)sdi);
172 /* sdi->driver is non-NULL (i.e. we have a real device). */
173 if (!sdi->driver->dev_open) {
174 sr_err("%s: sdi->driver->dev_open was NULL", __func__);
178 session->devs = g_slist_append(session->devs, (gpointer)sdi);
180 if (session->running) {
181 /* Adding a device to a running session. Commit settings
182 * and start acquisition on that device now. */
183 if ((ret = sr_config_commit(sdi)) != SR_OK) {
184 sr_err("Failed to commit device settings before "
185 "starting acquisition in running session (%s)",
189 if ((ret = sdi->driver->dev_acquisition_start(sdi,
190 (void *)sdi)) != SR_OK) {
191 sr_err("Failed to start acquisition of device in "
192 "running session (%s)", sr_strerror(ret));
201 * List all device instances attached to the current session.
203 * @param devlist A pointer where the device instance list will be
204 * stored on return. If no devices are in the session,
205 * this will be NULL. Each element in the list points
206 * to a struct sr_dev_inst *.
207 * The list must be freed by the caller, but not the
208 * elements pointed to.
210 * @retval SR_OK Success.
211 * @retval SR_ERR Invalid argument.
213 SR_API int sr_session_dev_list(GSList **devlist)
221 *devlist = g_slist_copy(session->devs);
227 * Remove all datafeed callbacks in the current session.
229 * @retval SR_OK Success.
230 * @retval SR_ERR_BUG No session exists.
232 SR_API int sr_session_datafeed_callback_remove_all(void)
235 sr_err("%s: session was NULL", __func__);
239 g_slist_free_full(session->datafeed_callbacks, g_free);
240 session->datafeed_callbacks = NULL;
246 * Add a datafeed callback to the current session.
248 * @param cb Function to call when a chunk of data is received.
250 * @param cb_data Opaque pointer passed in by the caller.
252 * @retval SR_OK Success.
253 * @retval SR_ERR_BUG No session exists.
255 SR_API int sr_session_datafeed_callback_add(sr_datafeed_callback cb, void *cb_data)
257 struct datafeed_callback *cb_struct;
260 sr_err("%s: session was NULL", __func__);
265 sr_err("%s: cb was NULL", __func__);
269 if (!(cb_struct = g_try_malloc0(sizeof(struct datafeed_callback))))
270 return SR_ERR_MALLOC;
273 cb_struct->cb_data = cb_data;
275 session->datafeed_callbacks =
276 g_slist_append(session->datafeed_callbacks, cb_struct);
282 * Call every device in the session's callback.
284 * For sessions not driven by select loops such as sr_session_run(),
285 * but driven by another scheduler, this can be used to poll the devices
286 * from within that scheduler.
288 * @param block If TRUE, this call will wait for any of the session's
289 * sources to fire an event on the file descriptors, or
290 * any of their timeouts to activate. In other words, this
291 * can be used as a select loop.
292 * If FALSE, all sources have their callback run, regardless
293 * of file descriptor or timeout status.
295 * @retval SR_OK Success.
296 * @retval SR_ERR Error occured.
298 static int sr_session_iteration(gboolean block)
303 ret = g_poll(session->pollfds, session->num_sources,
304 block ? session->source_timeout : 0);
305 for (i = 0; i < session->num_sources; i++) {
306 if (session->pollfds[i].revents > 0 || (ret == 0
307 && session->source_timeout == session->sources[i].timeout)) {
309 * Invoke the source's callback on an event,
310 * or if the poll timed out and this source
311 * asked for that timeout.
313 if (!session->sources[i].cb(session->pollfds[i].fd,
314 session->pollfds[i].revents,
315 session->sources[i].cb_data))
316 sr_session_source_remove(session->sources[i].poll_object);
319 * We want to take as little time as possible to stop
320 * the session if we have been told to do so. Therefore,
321 * we check the flag after processing every source, not
322 * just once per main event loop.
324 g_mutex_lock(&session->stop_mutex);
325 if (session->abort_session) {
326 sr_session_stop_sync();
327 /* But once is enough. */
328 session->abort_session = FALSE;
330 g_mutex_unlock(&session->stop_mutex);
339 * There can only be one session at a time.
341 * @retval SR_OK Success.
342 * @retval SR_ERR Error occured.
344 SR_API int sr_session_start(void)
346 struct sr_dev_inst *sdi;
351 sr_err("%s: session was NULL; a session must be "
352 "created before starting it.", __func__);
356 if (!session->devs) {
357 sr_err("%s: session->devs was NULL; a session "
358 "cannot be started without devices.", __func__);
362 sr_info("Starting.");
365 for (l = session->devs; l; l = l->next) {
367 if ((ret = sr_config_commit(sdi)) != SR_OK) {
368 sr_err("Failed to commit device settings before "
369 "starting acquisition (%s)", sr_strerror(ret));
372 if ((ret = sdi->driver->dev_acquisition_start(sdi, sdi)) != SR_OK) {
373 sr_err("%s: could not start an acquisition "
374 "(%s)", __func__, sr_strerror(ret));
379 /* TODO: What if there are multiple devices? Which return code? */
387 * @retval SR_OK Success.
388 * @retval SR_ERR_BUG Error occured.
390 SR_API int sr_session_run(void)
393 sr_err("%s: session was NULL; a session must be "
394 "created first, before running it.", __func__);
398 if (!session->devs) {
399 /* TODO: Actually the case? */
400 sr_err("%s: session->devs was NULL; a session "
401 "cannot be run without devices.", __func__);
404 session->running = TRUE;
408 /* Do we have real sources? */
409 if (session->num_sources == 1 && session->pollfds[0].fd == -1) {
410 /* Dummy source, freewheel over it. */
411 while (session->num_sources)
412 session->sources[0].cb(-1, 0, session->sources[0].cb_data);
414 /* Real sources, use g_poll() main loop. */
415 while (session->num_sources)
416 sr_session_iteration(TRUE);
423 * Stop the current session.
425 * The current session is stopped immediately, with all acquisition sessions
426 * being stopped and hardware drivers cleaned up.
428 * This must be called from within the session thread, to prevent freeing
429 * resources that the session thread will try to use.
431 * @retval SR_OK Success.
432 * @retval SR_ERR_BUG No session exists.
436 SR_PRIV int sr_session_stop_sync(void)
438 struct sr_dev_inst *sdi;
442 sr_err("%s: session was NULL", __func__);
446 sr_info("Stopping.");
448 for (l = session->devs; l; l = l->next) {
451 if (sdi->driver->dev_acquisition_stop)
452 sdi->driver->dev_acquisition_stop(sdi, sdi);
455 session->running = FALSE;
461 * Stop the current session.
463 * The current session is stopped immediately, with all acquisition sessions
464 * being stopped and hardware drivers cleaned up.
466 * If the session is run in a separate thread, this function will not block
467 * until the session is finished executing. It is the caller's responsibility
468 * to wait for the session thread to return before assuming that the session is
469 * completely decommissioned.
471 * @retval SR_OK Success.
472 * @retval SR_ERR_BUG No session exists.
474 SR_API int sr_session_stop(void)
477 sr_err("%s: session was NULL", __func__);
481 g_mutex_lock(&session->stop_mutex);
482 session->abort_session = TRUE;
483 g_mutex_unlock(&session->stop_mutex);
491 * @param packet The packet to show debugging information for.
493 static void datafeed_dump(const struct sr_datafeed_packet *packet)
495 const struct sr_datafeed_logic *logic;
496 const struct sr_datafeed_analog *analog;
498 switch (packet->type) {
500 sr_dbg("bus: Received SR_DF_HEADER packet.");
503 sr_dbg("bus: Received SR_DF_TRIGGER packet.");
506 sr_dbg("bus: Received SR_DF_META packet.");
509 logic = packet->payload;
510 sr_dbg("bus: Received SR_DF_LOGIC packet (%" PRIu64 " bytes, "
511 "unitsize = %d).", logic->length, logic->unitsize);
514 analog = packet->payload;
515 sr_dbg("bus: Received SR_DF_ANALOG packet (%d samples).",
516 analog->num_samples);
519 sr_dbg("bus: Received SR_DF_END packet.");
521 case SR_DF_FRAME_BEGIN:
522 sr_dbg("bus: Received SR_DF_FRAME_BEGIN packet.");
524 case SR_DF_FRAME_END:
525 sr_dbg("bus: Received SR_DF_FRAME_END packet.");
528 sr_dbg("bus: Received unknown packet type: %d.", packet->type);
534 * Send a packet to whatever is listening on the datafeed bus.
536 * Hardware drivers use this to send a data packet to the frontend.
539 * @param packet The datafeed packet to send to the session bus.
541 * @retval SR_OK Success.
542 * @retval SR_ERR_ARG Invalid argument.
546 SR_PRIV int sr_session_send(const struct sr_dev_inst *sdi,
547 const struct sr_datafeed_packet *packet)
550 struct datafeed_callback *cb_struct;
553 sr_err("%s: sdi was NULL", __func__);
558 sr_err("%s: packet was NULL", __func__);
562 for (l = session->datafeed_callbacks; l; l = l->next) {
563 if (sr_log_loglevel_get() >= SR_LOG_DBG)
564 datafeed_dump(packet);
566 cb_struct->cb(sdi, packet, cb_struct->cb_data);
573 * Add an event source for a file descriptor.
575 * @param pollfd The GPollFD.
576 * @param[in] timeout Max time to wait before the callback is called,
578 * @param cb Callback function to add. Must not be NULL.
579 * @param cb_data Data for the callback function. Can be NULL.
580 * @param poll_object TODO.
582 * @retval SR_OK Success.
583 * @retval SR_ERR_ARG Invalid argument.
584 * @retval SR_ERR_MALLOC Memory allocation error.
586 static int _sr_session_source_add(GPollFD *pollfd, int timeout,
587 sr_receive_data_callback cb, void *cb_data, gintptr poll_object)
589 struct source *new_sources, *s;
590 GPollFD *new_pollfds;
593 sr_err("%s: cb was NULL", __func__);
597 /* Note: cb_data can be NULL, that's not a bug. */
599 new_pollfds = g_try_realloc(session->pollfds,
600 sizeof(GPollFD) * (session->num_sources + 1));
602 sr_err("%s: new_pollfds malloc failed", __func__);
603 return SR_ERR_MALLOC;
606 new_sources = g_try_realloc(session->sources, sizeof(struct source) *
607 (session->num_sources + 1));
609 sr_err("%s: new_sources malloc failed", __func__);
610 return SR_ERR_MALLOC;
613 new_pollfds[session->num_sources] = *pollfd;
614 s = &new_sources[session->num_sources++];
615 s->timeout = timeout;
617 s->cb_data = cb_data;
618 s->poll_object = poll_object;
619 session->pollfds = new_pollfds;
620 session->sources = new_sources;
622 if (timeout != session->source_timeout && timeout > 0
623 && (session->source_timeout == -1 || timeout < session->source_timeout))
624 session->source_timeout = timeout;
630 * Add an event source for a file descriptor.
632 * @param fd The file descriptor.
633 * @param events Events to check for.
634 * @param timeout Max time to wait before the callback is called, ignored if 0.
635 * @param cb Callback function to add. Must not be NULL.
636 * @param cb_data Data for the callback function. Can be NULL.
638 * @retval SR_OK Success.
639 * @retval SR_ERR_ARG Invalid argument.
640 * @retval SR_ERR_MALLOC Memory allocation error.
642 SR_API int sr_session_source_add(int fd, int events, int timeout,
643 sr_receive_data_callback cb, void *cb_data)
650 return _sr_session_source_add(&p, timeout, cb, cb_data, (gintptr)fd);
654 * Add an event source for a GPollFD.
656 * @param pollfd The GPollFD.
657 * @param timeout Max time to wait before the callback is called, ignored if 0.
658 * @param cb Callback function to add. Must not be NULL.
659 * @param cb_data Data for the callback function. Can be NULL.
661 * @retval SR_OK Success.
662 * @retval SR_ERR_ARG Invalid argument.
663 * @retval SR_ERR_MALLOC Memory allocation error.
665 SR_API int sr_session_source_add_pollfd(GPollFD *pollfd, int timeout,
666 sr_receive_data_callback cb, void *cb_data)
668 return _sr_session_source_add(pollfd, timeout, cb,
669 cb_data, (gintptr)pollfd);
673 * Add an event source for a GIOChannel.
675 * @param channel The GIOChannel.
676 * @param events Events to poll on.
677 * @param timeout Max time to wait before the callback is called, ignored if 0.
678 * @param cb Callback function to add. Must not be NULL.
679 * @param cb_data Data for the callback function. Can be NULL.
681 * @retval SR_OK Success.
682 * @retval SR_ERR_ARG Invalid argument.
683 * @retval SR_ERR_MALLOC Memory allocation error.
685 SR_API int sr_session_source_add_channel(GIOChannel *channel, int events,
686 int timeout, sr_receive_data_callback cb, void *cb_data)
691 g_io_channel_win32_make_pollfd(channel, events, &p);
693 p.fd = g_io_channel_unix_get_fd(channel);
697 return _sr_session_source_add(&p, timeout, cb, cb_data, (gintptr)channel);
701 * Remove the source belonging to the specified channel.
703 * @todo Add more error checks and logging.
705 * @param poll_object The channel for which the source should be removed.
707 * @retval SR_OK Success
708 * @retval SR_ERR_ARG Invalid arguments
709 * @retval SR_ERR_MALLOC Memory allocation error
710 * @retval SR_ERR_BUG Internal error
712 static int _sr_session_source_remove(gintptr poll_object)
714 struct source *new_sources;
715 GPollFD *new_pollfds;
718 if (!session->sources || !session->num_sources) {
719 sr_err("%s: sources was NULL", __func__);
723 for (old = 0; old < session->num_sources; old++) {
724 if (session->sources[old].poll_object == poll_object)
728 /* fd not found, nothing to do */
729 if (old == session->num_sources)
732 session->num_sources -= 1;
734 if (old != session->num_sources) {
735 memmove(&session->pollfds[old], &session->pollfds[old+1],
736 (session->num_sources - old) * sizeof(GPollFD));
737 memmove(&session->sources[old], &session->sources[old+1],
738 (session->num_sources - old) * sizeof(struct source));
741 new_pollfds = g_try_realloc(session->pollfds, sizeof(GPollFD) * session->num_sources);
742 if (!new_pollfds && session->num_sources > 0) {
743 sr_err("%s: new_pollfds malloc failed", __func__);
744 return SR_ERR_MALLOC;
747 new_sources = g_try_realloc(session->sources, sizeof(struct source) * session->num_sources);
748 if (!new_sources && session->num_sources > 0) {
749 sr_err("%s: new_sources malloc failed", __func__);
750 return SR_ERR_MALLOC;
753 session->pollfds = new_pollfds;
754 session->sources = new_sources;
760 * Remove the source belonging to the specified file descriptor.
762 * @param fd The file descriptor for which the source should be removed.
764 * @retval SR_OK Success
765 * @retval SR_ERR_ARG Invalid argument
766 * @retval SR_ERR_MALLOC Memory allocation error.
767 * @retval SR_ERR_BUG Internal error.
769 SR_API int sr_session_source_remove(int fd)
771 return _sr_session_source_remove((gintptr)fd);
775 * Remove the source belonging to the specified poll descriptor.
777 * @param pollfd The poll descriptor for which the source should be removed.
779 * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments, or
780 * SR_ERR_MALLOC upon memory allocation errors, SR_ERR_BUG upon
783 SR_API int sr_session_source_remove_pollfd(GPollFD *pollfd)
785 return _sr_session_source_remove((gintptr)pollfd);
789 * Remove the source belonging to the specified channel.
791 * @param channel The channel for which the source should be removed.
793 * @retval SR_OK Success.
794 * @retval SR_ERR_ARG Invalid argument.
795 * @retval SR_ERR_MALLOC Memory allocation error.
796 * @return SR_ERR_BUG Internal error.
798 SR_API int sr_session_source_remove_channel(GIOChannel *channel)
800 return _sr_session_source_remove((gintptr)channel);