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