]> sigrok.org Git - libsigrok.git/blob - session.c
Code drop from DreamSourceLabs first source release.
[libsigrok.git] / 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 /* Message logging helpers with subsystem-specific prefix string. */
29 #define LOG_PREFIX "session: "
30 #define sr_log(l, s, args...) sr_log(l, LOG_PREFIX s, ## args)
31 #define sr_spew(s, args...) sr_spew(LOG_PREFIX s, ## args)
32 #define sr_dbg(s, args...) sr_dbg(LOG_PREFIX s, ## args)
33 #define sr_info(s, args...) sr_info(LOG_PREFIX s, ## args)
34 #define sr_warn(s, args...) sr_warn(LOG_PREFIX s, ## args)
35 #define sr_err(s, args...) sr_err(LOG_PREFIX s, ## args)
36
37 /**
38  * @file
39  *
40  * Creating, using, or destroying libsigrok sessions.
41  */
42
43 /**
44  * @defgroup grp_session Session handling
45  *
46  * Creating, using, or destroying libsigrok sessions.
47  *
48  * @{
49  */
50
51 struct source {
52         int timeout;
53         sr_receive_data_callback_t cb;
54         void *cb_data;
55
56         /* This is used to keep track of the object (fd, pollfd or channel) which is
57          * being polled and will be used to match the source when removing it again.
58          */
59         gintptr poll_object;
60 };
61
62 struct datafeed_callback {
63         sr_datafeed_callback_t cb;
64         void *cb_data;
65 };
66
67 /* There can only be one session at a time. */
68 /* 'session' is not static, it's used elsewhere (via 'extern'). */
69 struct sr_session *session;
70
71 /**
72  * Create a new session.
73  *
74  * @todo Should it use the file-global "session" variable or take an argument?
75  *       The same question applies to all the other session functions.
76  *
77  * @return A pointer to the newly allocated session, or NULL upon errors.
78  */
79 SR_API struct sr_session *sr_session_new(void)
80 {
81         if (!(session = g_try_malloc0(sizeof(struct sr_session)))) {
82                 sr_err("Session malloc failed.");
83                 return NULL;
84         }
85
86         session->source_timeout = -1;
87         session->abort_session = FALSE;
88 //      g_mutex_init(&session->stop_mutex);
89
90         return session;
91 }
92
93 /**
94  * Destroy the current session.
95  *
96  * This frees up all memory used by the session.
97  *
98  * @return SR_OK upon success, SR_ERR_BUG if no session exists.
99  */
100 SR_API int sr_session_destroy(void)
101 {
102         if (!session) {
103                 sr_err("%s: session was NULL", __func__);
104                 return SR_ERR_BUG;
105         }
106
107         sr_session_dev_remove_all();
108
109     sr_session_datafeed_callback_remove_all();
110
111     if (session->sources) {
112         g_free(session->sources);
113         session->sources = NULL;
114     }
115
116     if (session->pollfds) {
117         g_free(session->pollfds);
118         session->pollfds = NULL;
119     }
120
121         /* TODO: Error checks needed? */
122
123 //      g_mutex_clear(&session->stop_mutex);
124
125         g_free(session);
126         session = NULL;
127
128         return SR_OK;
129 }
130
131 /**
132  * Remove all the devices from the current session.
133  *
134  * The session itself (i.e., the struct sr_session) is not free'd and still
135  * exists after this function returns.
136  *
137  * @return SR_OK upon success, SR_ERR_BUG if no session exists.
138  */
139 SR_API int sr_session_dev_remove_all(void)
140 {
141         if (!session) {
142                 sr_err("%s: session was NULL", __func__);
143                 return SR_ERR_BUG;
144         }
145
146         g_slist_free(session->devs);
147         session->devs = NULL;
148
149         return SR_OK;
150 }
151
152 /**
153  * Add a device instance to the current session.
154  *
155  * @param sdi The device instance to add to the current session. Must not
156  *            be NULL. Also, sdi->driver and sdi->driver->dev_open must
157  *            not be NULL.
158  *
159  * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments.
160  */
161 SR_API int sr_session_dev_add(const struct sr_dev_inst *sdi)
162 {
163
164         if (!sdi) {
165                 sr_err("%s: sdi was NULL", __func__);
166                 return SR_ERR_ARG;
167         }
168
169         if (!session) {
170                 sr_err("%s: session was NULL", __func__);
171                 return SR_ERR_BUG;
172         }
173
174         /* If sdi->driver is NULL, this is a virtual device. */
175         if (!sdi->driver) {
176                 sr_dbg("%s: sdi->driver was NULL, this seems to be "
177                        "a virtual device; continuing", __func__);
178                 /* Just add the device, don't run dev_open(). */
179                 session->devs = g_slist_append(session->devs, (gpointer)sdi);
180                 return SR_OK;
181         }
182
183         /* sdi->driver is non-NULL (i.e. we have a real device). */
184         if (!sdi->driver->dev_open) {
185                 sr_err("%s: sdi->driver->dev_open was NULL", __func__);
186                 return SR_ERR_BUG;
187         }
188
189         session->devs = g_slist_append(session->devs, (gpointer)sdi);
190
191         return SR_OK;
192 }
193
194 /**
195  * Remove all datafeed callbacks in the current session.
196  *
197  * @return SR_OK upon success, SR_ERR_BUG if no session exists.
198  */
199 SR_API int sr_session_datafeed_callback_remove_all(void)
200 {
201         if (!session) {
202                 sr_err("%s: session was NULL", __func__);
203                 return SR_ERR_BUG;
204         }
205
206         g_slist_free_full(session->datafeed_callbacks, g_free);
207         session->datafeed_callbacks = NULL;
208
209         return SR_OK;
210 }
211
212 /**
213  * Add a datafeed callback to the current session.
214  *
215  * @param cb Function to call when a chunk of data is received.
216  *           Must not be NULL.
217  * @param cb_data Opaque pointer passed in by the caller.
218  *
219  * @return SR_OK upon success, SR_ERR_BUG if no session exists.
220  */
221 SR_API int sr_session_datafeed_callback_add(sr_datafeed_callback_t cb, void *cb_data)
222 {
223         struct datafeed_callback *cb_struct;
224
225         if (!session) {
226                 sr_err("%s: session was NULL", __func__);
227                 return SR_ERR_BUG;
228         }
229
230         if (!cb) {
231                 sr_err("%s: cb was NULL", __func__);
232                 return SR_ERR_ARG;
233         }
234
235         if (!(cb_struct = g_try_malloc0(sizeof(struct datafeed_callback))))
236                 return SR_ERR_MALLOC;
237
238         cb_struct->cb = cb;
239         cb_struct->cb_data = cb_data;
240
241         session->datafeed_callbacks =
242             g_slist_append(session->datafeed_callbacks, cb_struct);
243
244         return SR_OK;
245 }
246
247 static int sr_session_run_poll(void)
248 {
249         unsigned int i;
250         int ret;
251
252         while (session->num_sources > 0) {
253                 ret = g_poll(session->pollfds, session->num_sources,
254                                 session->source_timeout);
255                 for (i = 0; i < session->num_sources; i++) {
256                         if (session->pollfds[i].revents > 0 || (ret == 0
257                                 && session->source_timeout == session->sources[i].timeout)) {
258                                 /*
259                                  * Invoke the source's callback on an event,
260                                  * or if the poll timed out and this source
261                                  * asked for that timeout.
262                                  */
263                                 if (!session->sources[i].cb(session->pollfds[i].fd,
264                                                 session->pollfds[i].revents,
265                                                 session->sources[i].cb_data))
266                                         sr_session_source_remove(session->sources[i].poll_object);
267                         }
268                         /*
269                          * We want to take as little time as possible to stop
270                          * the session if we have been told to do so. Therefore,
271                          * we check the flag after processing every source, not
272                          * just once per main event loop.
273                          */
274 //                      g_mutex_lock(&session->stop_mutex);
275                         if (session->abort_session) {
276                                 sr_session_stop_sync();
277                                 /* But once is enough. */
278                                 session->abort_session = FALSE;
279                         }
280 //                      g_mutex_unlock(&session->stop_mutex);
281                 }
282         }
283
284         return SR_OK;
285 }
286
287 /**
288  * Start a session.
289  *
290  * There can only be one session at a time.
291  *
292  * @return SR_OK upon success, SR_ERR upon errors.
293  */
294 SR_API int sr_session_start(void)
295 {
296         struct sr_dev_inst *sdi;
297         GSList *l;
298         int ret;
299
300         if (!session) {
301                 sr_err("%s: session was NULL; a session must be "
302                        "created before starting it.", __func__);
303                 return SR_ERR_BUG;
304         }
305
306         if (!session->devs) {
307                 sr_err("%s: session->devs was NULL; a session "
308                        "cannot be started without devices.", __func__);
309                 return SR_ERR_BUG;
310         }
311
312         sr_info("Starting.");
313
314         ret = SR_OK;
315         for (l = session->devs; l; l = l->next) {
316                 sdi = l->data;
317                 if ((ret = sdi->driver->dev_acquisition_start(sdi, sdi)) != SR_OK) {
318                         sr_err("%s: could not start an acquisition "
319                                "(%d)", __func__, ret);
320                         break;
321                 }
322         }
323
324         /* TODO: What if there are multiple devices? Which return code? */
325
326         return ret;
327 }
328
329 /**
330  * Run the session.
331  *
332  * @return SR_OK upon success, SR_ERR_BUG upon errors.
333  */
334 SR_API int sr_session_run(void)
335 {
336         if (!session) {
337                 sr_err("%s: session was NULL; a session must be "
338                        "created first, before running it.", __func__);
339                 return SR_ERR_BUG;
340         }
341
342         if (!session->devs) {
343                 /* TODO: Actually the case? */
344                 sr_err("%s: session->devs was NULL; a session "
345                        "cannot be run without devices.", __func__);
346                 return SR_ERR_BUG;
347         }
348
349         sr_info("Running.");
350
351         /* Do we have real sources? */
352         if (session->num_sources == 1 && session->pollfds[0].fd == -1) {
353                 /* Dummy source, freewheel over it. */
354                 while (session->num_sources)
355                         session->sources[0].cb(-1, 0, session->sources[0].cb_data);
356         } else {
357                 /* Real sources, use g_poll() main loop. */
358                 sr_session_run_poll();
359         }
360
361         return SR_OK;
362 }
363
364 /**
365  * Stop the current session.
366  *
367  * The current session is stopped immediately, with all acquisition sessions
368  * being stopped and hardware drivers cleaned up.
369  *
370  * This must be called from within the session thread, to prevent freeing
371  * resources that the session thread will try to use.
372  *
373  * @return SR_OK upon success, SR_ERR_BUG if no session exists.
374  */
375 SR_PRIV int sr_session_stop_sync(void)
376 {
377         struct sr_dev_inst *sdi;
378         GSList *l;
379
380         if (!session) {
381                 sr_err("%s: session was NULL", __func__);
382                 return SR_ERR_BUG;
383         }
384
385         sr_info("Stopping.");
386
387         for (l = session->devs; l; l = l->next) {
388                 sdi = l->data;
389                 if (sdi->driver) {
390                         if (sdi->driver->dev_acquisition_stop)
391                 sdi->driver->dev_acquisition_stop(sdi, NULL);
392                 }
393         }
394
395         return SR_OK;
396 }
397
398 /**
399  * Stop the current session.
400  *
401  * The current session is stopped immediately, with all acquisition sessions
402  * being stopped and hardware drivers cleaned up.
403  *
404  * If the session is run in a separate thread, this function will not block
405  * until the session is finished executing. It is the caller's responsibility
406  * to wait for the session thread to return before assuming that the session is
407  * completely decommissioned.
408  *
409  * @return SR_OK upon success, SR_ERR_BUG if no session exists.
410  */
411 SR_API int sr_session_stop(void)
412 {
413         if (!session) {
414                 sr_err("%s: session was NULL", __func__);
415                 return SR_ERR_BUG;
416         }
417
418 //      g_mutex_lock(&session->stop_mutex);
419         session->abort_session = TRUE;
420 //      g_mutex_unlock(&session->stop_mutex);
421
422         return SR_OK;
423 }
424
425 /**
426  * Debug helper.
427  *
428  * @param packet The packet to show debugging information for.
429  */
430 static void datafeed_dump(const struct sr_datafeed_packet *packet)
431 {
432         const struct sr_datafeed_logic *logic;
433         const struct sr_datafeed_analog *analog;
434
435         switch (packet->type) {
436         case SR_DF_HEADER:
437                 sr_dbg("bus: Received SR_DF_HEADER packet.");
438                 break;
439         case SR_DF_TRIGGER:
440                 sr_dbg("bus: Received SR_DF_TRIGGER packet.");
441                 break;
442         case SR_DF_META:
443                 sr_dbg("bus: Received SR_DF_META packet.");
444                 break;
445         case SR_DF_LOGIC:
446                 logic = packet->payload;
447                 sr_dbg("bus: Received SR_DF_LOGIC packet (%" PRIu64 " bytes).",
448                        logic->length);
449                 break;
450         case SR_DF_ANALOG:
451                 analog = packet->payload;
452                 sr_dbg("bus: Received SR_DF_ANALOG packet (%d samples).",
453                        analog->num_samples);
454                 break;
455         case SR_DF_END:
456                 sr_dbg("bus: Received SR_DF_END packet.");
457                 break;
458         case SR_DF_FRAME_BEGIN:
459                 sr_dbg("bus: Received SR_DF_FRAME_BEGIN packet.");
460                 break;
461         case SR_DF_FRAME_END:
462                 sr_dbg("bus: Received SR_DF_FRAME_END packet.");
463                 break;
464         default:
465                 sr_dbg("bus: Received unknown packet type: %d.", packet->type);
466                 break;
467         }
468 }
469
470 /**
471  * Send a packet to whatever is listening on the datafeed bus.
472  *
473  * Hardware drivers use this to send a data packet to the frontend.
474  *
475  * @param sdi TODO.
476  * @param packet The datafeed packet to send to the session bus.
477  *
478  * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments.
479  *
480  * @private
481  */
482 SR_PRIV int sr_session_send(const struct sr_dev_inst *sdi,
483                             const struct sr_datafeed_packet *packet)
484 {
485         GSList *l;
486         struct datafeed_callback *cb_struct;
487
488         if (!sdi) {
489                 sr_err("%s: sdi was NULL", __func__);
490                 return SR_ERR_ARG;
491         }
492
493         if (!packet) {
494                 sr_err("%s: packet was NULL", __func__);
495                 return SR_ERR_ARG;
496         }
497
498         for (l = session->datafeed_callbacks; l; l = l->next) {
499                 if (sr_log_loglevel_get() >= SR_LOG_DBG)
500                         datafeed_dump(packet);
501                 cb_struct = l->data;
502                 cb_struct->cb(sdi, packet, cb_struct->cb_data);
503         }
504
505         return SR_OK;
506 }
507
508 /**
509  * Add an event source for a file descriptor.
510  *
511  * @param pollfd The GPollFD.
512  * @param timeout Max time to wait before the callback is called, ignored if 0.
513  * @param cb Callback function to add. Must not be NULL.
514  * @param cb_data Data for the callback function. Can be NULL.
515  * @param poll_object TODO.
516  *
517  * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments, or
518  *         SR_ERR_MALLOC upon memory allocation errors.
519  */
520 static int _sr_session_source_add(GPollFD *pollfd, int timeout,
521     sr_receive_data_callback_t cb, const struct sr_dev_inst *sdi, gintptr poll_object)
522 {
523         struct source *new_sources, *s;
524         GPollFD *new_pollfds;
525
526         if (!cb) {
527                 sr_err("%s: cb was NULL", __func__);
528                 return SR_ERR_ARG;
529         }
530
531         /* Note: cb_data can be NULL, that's not a bug. */
532
533         new_pollfds = g_try_realloc(session->pollfds,
534                         sizeof(GPollFD) * (session->num_sources + 1));
535         if (!new_pollfds) {
536                 sr_err("%s: new_pollfds malloc failed", __func__);
537                 return SR_ERR_MALLOC;
538         }
539
540         new_sources = g_try_realloc(session->sources, sizeof(struct source) *
541                         (session->num_sources + 1));
542         if (!new_sources) {
543                 sr_err("%s: new_sources malloc failed", __func__);
544                 return SR_ERR_MALLOC;
545         }
546
547         new_pollfds[session->num_sources] = *pollfd;
548         s = &new_sources[session->num_sources++];
549         s->timeout = timeout;
550         s->cb = cb;
551         s->cb_data = sdi;
552         s->poll_object = poll_object;
553         session->pollfds = new_pollfds;
554         session->sources = new_sources;
555
556         if (timeout != session->source_timeout && timeout > 0
557             && (session->source_timeout == -1 || timeout < session->source_timeout))
558                 session->source_timeout = timeout;
559
560         return SR_OK;
561 }
562
563 /**
564  * Add an event source for a file descriptor.
565  *
566  * @param fd The file descriptor.
567  * @param events Events to check for.
568  * @param timeout Max time to wait before the callback is called, ignored if 0.
569  * @param cb Callback function to add. Must not be NULL.
570  * @param cb_data Data for the callback function. Can be NULL.
571  *
572  * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments, or
573  *         SR_ERR_MALLOC upon memory allocation errors.
574  */
575 SR_API int sr_session_source_add(int fd, int events, int timeout,
576                 sr_receive_data_callback_t cb, const struct sr_dev_inst *sdi)
577 {
578         GPollFD p;
579
580         p.fd = fd;
581         p.events = events;
582
583     return _sr_session_source_add(&p, timeout, cb, sdi, (gintptr)fd);
584 }
585
586 /**
587  * Add an event source for a GPollFD.
588  *
589  * @param pollfd The GPollFD.
590  * @param timeout Max time to wait before the callback is called, ignored if 0.
591  * @param cb Callback function to add. Must not be NULL.
592  * @param cb_data Data for the callback function. Can be NULL.
593  *
594  * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments, or
595  *         SR_ERR_MALLOC upon memory allocation errors.
596  */
597 SR_API int sr_session_source_add_pollfd(GPollFD *pollfd, int timeout,
598                 sr_receive_data_callback_t cb, const struct sr_dev_inst *sdi)
599 {
600     return _sr_session_source_add(pollfd, timeout, cb,
601                       sdi, (gintptr)pollfd);
602 }
603
604 /**
605  * Add an event source for a GIOChannel.
606  *
607  * @param channel The GIOChannel.
608  * @param events Events to poll on.
609  * @param timeout Max time to wait before the callback is called, ignored if 0.
610  * @param cb Callback function to add. Must not be NULL.
611  * @param cb_data Data for the callback function. Can be NULL.
612  *
613  * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments, or
614  *         SR_ERR_MALLOC upon memory allocation errors.
615  */
616 SR_API int sr_session_source_add_channel(GIOChannel *channel, int events,
617                 int timeout, sr_receive_data_callback_t cb, const struct sr_dev_inst *sdi)
618 {
619         GPollFD p;
620
621 #ifdef _WIN32
622         g_io_channel_win32_make_pollfd(channel, events, &p);
623 #else
624         p.fd = g_io_channel_unix_get_fd(channel);
625         p.events = events;
626 #endif
627
628     return _sr_session_source_add(&p, timeout, cb, sdi, (gintptr)channel);
629 }
630
631 /**
632  * Remove the source belonging to the specified channel.
633  *
634  * @todo Add more error checks and logging.
635  *
636  * @param channel The channel for which the source should be removed.
637  *
638  * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments, or
639  *         SR_ERR_MALLOC upon memory allocation errors, SR_ERR_BUG upon
640  *         internal errors.
641  */
642 static int _sr_session_source_remove(gintptr poll_object)
643 {
644         struct source *new_sources;
645         GPollFD *new_pollfds;
646         unsigned int old;
647
648         if (!session->sources || !session->num_sources) {
649                 sr_err("%s: sources was NULL", __func__);
650                 return SR_ERR_BUG;
651         }
652
653         for (old = 0; old < session->num_sources; old++) {
654                 if (session->sources[old].poll_object == poll_object)
655                         break;
656         }
657
658         /* fd not found, nothing to do */
659         if (old == session->num_sources)
660                 return SR_OK;
661
662         session->num_sources -= 1;
663
664         if (old != session->num_sources) {
665                 memmove(&session->pollfds[old], &session->pollfds[old+1],
666                         (session->num_sources - old) * sizeof(GPollFD));
667                 memmove(&session->sources[old], &session->sources[old+1],
668                         (session->num_sources - old) * sizeof(struct source));
669         }
670
671         new_pollfds = g_try_realloc(session->pollfds, sizeof(GPollFD) * session->num_sources);
672         if (!new_pollfds && session->num_sources > 0) {
673                 sr_err("%s: new_pollfds malloc failed", __func__);
674                 return SR_ERR_MALLOC;
675         }
676
677         new_sources = g_try_realloc(session->sources, sizeof(struct source) * session->num_sources);
678         if (!new_sources && session->num_sources > 0) {
679                 sr_err("%s: new_sources malloc failed", __func__);
680                 return SR_ERR_MALLOC;
681         }
682
683         session->pollfds = new_pollfds;
684         session->sources = new_sources;
685
686         return SR_OK;
687 }
688
689 /**
690  * Remove the source belonging to the specified file descriptor.
691  *
692  * @param fd The file descriptor for which the source should be removed.
693  *
694  * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments, or
695  *         SR_ERR_MALLOC upon memory allocation errors, SR_ERR_BUG upon
696  *         internal errors.
697  */
698 SR_API int sr_session_source_remove(int fd)
699 {
700         return _sr_session_source_remove((gintptr)fd);
701 }
702
703 /**
704  * Remove the source belonging to the specified poll descriptor.
705  *
706  * @param pollfd The poll descriptor for which the source should be removed.
707  *
708  * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments, or
709  *         SR_ERR_MALLOC upon memory allocation errors, SR_ERR_BUG upon
710  *         internal errors.
711  */
712 SR_API int sr_session_source_remove_pollfd(GPollFD *pollfd)
713 {
714         return _sr_session_source_remove((gintptr)pollfd);
715 }
716
717 /**
718  * Remove the source belonging to the specified channel.
719  *
720  * @param channel The channel for which the source should be removed.
721  *
722  * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments, or
723  *         SR_ERR_MALLOC upon memory allocation errors, SR_ERR_BUG upon
724  *         internal errors.
725  */
726 SR_API int sr_session_source_remove_channel(GIOChannel *channel)
727 {
728         return _sr_session_source_remove((gintptr)channel);
729 }
730
731 /** @} */