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