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