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