Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DBusWatch and DBusTimeout examples

Tags:

c

dbus

I need to write an application in C for asynchronous sending and reading messages on the dbus message queue. I've read that for doing that I should use the DBusWatch and DBusTimeout objects that the connection provides, but I cannot find an example of how to use these anywhere...

For the moment i use dbus_connection_read_write_dispatch in order to do that, but I've read that it is not recommended for asynchronous operations, so I'll have to switch to creating my own main loop and using it...

The closest answer to my question was this one:

http://lists.freedesktop.org/archives/dbus/2007-September/008555.html ,

suggesting to look through the dbus-gmain.c file, which I did, but all I found there was a call of the dbus_connection_set_watch_functions and dbus_connection_set_timeout_functions, with other functions as parameters - should I overwrite those functions? Should I use them as they are?

I simply cannot figure out how to use these in order to read and write something to the dbus message queue...

Any idea would be more than welcome...

like image 546
Ioanna Avatar asked Feb 21 '12 13:02

Ioanna


2 Answers

Here's something I wrote some time ago. I removed application specific code, you should just add your snippets where you handle DBus messages meant for your application and that should be it.

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/socket.h>
#include <arpa/inet.h>

#include <dbus/dbus.h>

struct dbus_ctx {
    DBusConnection *conn;
    struct event_base *evbase;
    struct event dispatch_ev;
    void *extra;
};

static void dispatch(int fd, short ev, void *x)
{
    struct dbus_ctx *ctx = x;
    DBusConnection *c = ctx->conn;

    logger(LOG_DEBUG "dispatching\n");

    while (dbus_connection_get_dispatch_status(c) == DBUS_DISPATCH_DATA_REMAINS)
        dbus_connection_dispatch(c);
}

static void handle_dispatch_status(DBusConnection *c,
                                   DBusDispatchStatus status, void *data)
{
    struct dbus_ctx *ctx = data;

    logger(LOG_DEBUG "new dbus dispatch status: %d\n", status);

    if (status == DBUS_DISPATCH_DATA_REMAINS) {
        struct timeval tv = {
            .tv_sec = 0,
            .tv_usec = 0,
        };
        event_add(&ctx->dispatch_ev, &tv);
    }
}

static void handle_watch(int fd, short events, void *x)
{
    struct dbus_ctx *ctx = x;
    struct DBusWatch *watch = ctx->extra;

    unsigned int flags = 0;
    if (events & EV_READ)
        flags |= DBUS_WATCH_READABLE;
    if (events & EV_WRITE)
        flags |= DBUS_WATCH_WRITABLE;
    /*if (events & HUP)
        flags |= DBUS_WATCH_HANGUP;
    if (events & ERR)
        flags |= DBUS_WATCH_ERROR;*/

    logger(LOG_DEBUG "got dbus watch event fd=%d watch=%p ev=%d\n",
           fd, watch, events);
    if (dbus_watch_handle(watch, flags) == FALSE)
        logger(LOG_ERROR "dbus_watch_handle() failed\n");

    handle_dispatch_status(ctx->conn, DBUS_DISPATCH_DATA_REMAINS, ctx);
}

static dbus_bool_t add_watch(DBusWatch *w, void *data)
{
    if (!dbus_watch_get_enabled(w))
        return TRUE;

    struct dbus_ctx *ctx = data;
    ctx->extra = w;

    int fd = dbus_watch_get_unix_fd(w);
    unsigned int flags = dbus_watch_get_flags(w);
    short cond = EV_PERSIST;
    if (flags & DBUS_WATCH_READABLE)
        cond |= EV_READ;
    if (flags & DBUS_WATCH_WRITABLE)
        cond |= EV_WRITE;

    struct event *event = event_new(ctx->evbase, fd, cond, handle_watch, ctx);
    if (!event)
        return FALSE;

    event_add(event, NULL);

    dbus_watch_set_data(w, event, NULL);

    logger(LOG_DEBUG "added dbus watch fd=%d watch=%p cond=%d\n", fd, w, cond);
    return TRUE;
}

static void remove_watch(DBusWatch *w, void *data)
{
    struct event *event = dbus_watch_get_data(w);

    if (event)
        event_free(event);

    dbus_watch_set_data(w, NULL, NULL);

    logger(LOG_DEBUG "removed dbus watch watch=%p\n", w);
}

static void toggle_watch(DBusWatch *w, void *data)
{
    logger(LOG_DEBUG "toggling dbus watch watch=%p\n", w);

    if (dbus_watch_get_enabled(w))
        add_watch(w, data);
    else
        remove_watch(w, data);
}

static void handle_timeout(int fd, short ev, void *x)
{
    struct dbus_ctx *ctx = x;
    DBusTimeout *t = ctx->extra;

    logger(LOG_DEBUG "got dbus handle timeout event %p\n", t);

    dbus_timeout_handle(t);
}

static dbus_bool_t add_timeout(DBusTimeout *t, void *data)
{
    struct dbus_ctx *ctx = data;

    if (!dbus_timeout_get_enabled(t))
        return TRUE;

    logger(LOG_DEBUG "adding timeout %p\n", t);

    struct event *event = event_new(ctx->evbase, -1, EV_TIMEOUT|EV_PERSIST,
                                    handle_timeout, t);
    if (!event) {
        logger(LOG_ERROR "failed to allocate new event for timeout\n");
        return FALSE;
    }

    int ms = dbus_timeout_get_interval(t);
    struct timeval tv = {
        .tv_sec = ms / 1000,
        .tv_usec = (ms % 1000) * 1000,
    };
    event_add(event, &tv);

    dbus_timeout_set_data(t, event, NULL);

    return TRUE;
}

static void remove_timeout(DBusTimeout *t, void *data)
{
    struct event *event = dbus_timeout_get_data(t);

    logger(LOG_DEBUG "removing timeout %p\n", t);

    event_free(event);

    dbus_timeout_set_data(t, NULL, NULL);
}

static void toggle_timeout(DBusTimeout *t, void *data)
{
    logger(LOG_DEBUG "toggling timeout %p\n", t);

    if (dbus_timeout_get_enabled(t))
        add_timeout(t, data);
    else
        remove_timeout(t, data);
}

static DBusHandlerResult handle_nameownerchanged(DBusMessage *message,
                                                 void *data)
{
    struct dbus_ctx *ctx = data;
    char *name, *old, *new;
    if (dbus_message_get_args(message, NULL,
                              DBUS_TYPE_STRING, &name,
                              DBUS_TYPE_STRING, &old,
                              DBUS_TYPE_STRING, &new,
                              DBUS_TYPE_INVALID) == FALSE) {
        logger(LOG_ERROR "spurious NameOwnerChanged signal\n");
        return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
    }
    logger(LOG_DEBUG "dbus NameOwnerChanged %s -> %s\n", old, new);

    if (new[0] != '\0')
        return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;

    /* XXX handle disconnecting clients */

    return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
}

static DBusHandlerResult msg_filter(DBusConnection *connection,
                                    DBusMessage *message, void *data)
{
    if (dbus_message_is_signal(message, DBUS_INTERFACE_DBUS,
                               "NameOwnerChanged"))
        return handle_nameownerchanged(message, data);

    logger(LOG_DEBUG "got dbus message %d %s -> %s %s/%s/%s %s\n",
           dbus_message_get_type(message),
           dbus_message_get_sender(message),
           dbus_message_get_destination(message),
           dbus_message_get_path(message),
           dbus_message_get_interface(message),
           dbus_message_get_member(message),
           dbus_message_get_type(message) == DBUS_MESSAGE_TYPE_ERROR ?
           dbus_message_get_error_name(message) : "");

    return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
}

static void unregister_func(DBusConnection *connection, void *data)
{
}

static DBusHandlerResult message_func(DBusConnection *connection,
                                      DBusMessage *message, void *data)
{
    struct dbus_ctx *ctx = data;

    logger(LOG_DEBUG "got dbus message sent to %s %s %s\n",
           dbus_message_get_destination(message),
           dbus_message_get_interface(message),
           dbus_message_get_path(message));

    /* XXX handle DBus message */

    return DBUS_HANDLER_RESULT_HANDLED;
}

static DBusObjectPathVTable dbus_vtable = {
    .unregister_function = unregister_func,
    .message_function = message_func,
};

struct dbus_ctx *dbus_init(struct event_base *eb)
{
    DBusConnection *conn = NULL;
    struct dbus_ctx *ctx = calloc(1, sizeof(struct dbus_ctx));
    if (!ctx) {
        logger_perror("can't allocate dbus_ctx\n");
        goto out;
    }

    conn = dbus_bus_get_private(DBUS_BUS_SESSION, NULL);
    if (conn == NULL) {
        logger(LOG_ERROR "failed to get bus\n");
        goto out;
    }

    dbus_connection_set_exit_on_disconnect(conn, FALSE);

    ctx->conn = conn;
    ctx->evbase = eb;
    event_assign(&ctx->dispatch_ev, eb, -1, EV_TIMEOUT, dispatch, ctx);

    if (!dbus_connection_set_watch_functions(conn, add_watch, remove_watch,
                                             toggle_watch, ctx, NULL)) {
        logger(LOG_ERROR "dbus_connection_set_watch_functions() failed\n");
        goto out;
    }

    if (!dbus_connection_set_timeout_functions(conn, add_timeout,
                                               remove_timeout, toggle_timeout,
                                               ctx, NULL)) {
        logger(LOG_ERROR "dbus_connection_set_timeout_functions() failed\n");
        goto out;
    }

    if (dbus_connection_add_filter(conn, msg_filter, ctx, NULL) == FALSE) {
        logger(LOG_ERROR "dbus_connection_add_filter() failed\n");
        goto out;
    }

    dbus_connection_set_dispatch_status_function(conn, handle_dispatch_status,
                                                 ctx, NULL);

    char match[256];
    snprintf(match,
             sizeof(match),
             "type='signal',interface='%s',member='NameOwnerChanged'",
             DBUS_INTERFACE_DBUS);
    DBusError error;
    dbus_error_init(&error);
    dbus_bus_add_match(conn, match, &error);
    if (dbus_error_is_set(&error)) {
        logger(LOG_ERROR "dbus_bus_add_match() %s failed: %s\n",
               "NameOwnerChanged", error.message);
        dbus_error_free(&error);
        goto out;
    }

    snprintf(match,
             sizeof(match),
             "type='signal',interface='%s',member='%s'",
             GNP_IPC_INTERFACE, GNP_IPC_SIGNAL_DELIVER_SA);
    dbus_error_init(&error);
    dbus_bus_add_match(conn, match, &error);
    if (dbus_error_is_set(&error)) {
        logger(LOG_ERROR "dbus_bus_add_match() %s failed: %s\n",
               GNP_IPC_SIGNAL_DELIVER_SA, error.message);
        dbus_error_free(&error);
        goto out;
    }

    if (dbus_connection_register_object_path(conn, GNP_IPC_PATH, &dbus_vtable,
                                             ctx) != TRUE) {
        logger(LOG_ERROR "failed to register object path\n");
        goto out;
    }

    return ctx;

out:
    if (conn) {
        dbus_connection_close(conn);
        dbus_connection_unref(conn);
    }
    if (ctx)
        free(ctx);
    return NULL;
}

void dbus_close(struct dbus_ctx *ctx)
{
    if (ctx && ctx->conn) {
        dbus_connection_flush(ctx->conn);
        dbus_connection_close(ctx->conn);
        dbus_connection_unref(ctx->conn);
        event_del(&ctx->dispatch_ev);
    }
    if (ctx)
        free(ctx);
}
like image 155
ldx Avatar answered Sep 21 '22 22:09

ldx


I have written an example for implementing main loop for dbus. I have tested it with bluez DBUS API and it works without any problem.

I have removed the bluetooth part of my application. I have used libevent to implement event loop.

Note: It is in C++. You can easily convert it to C programming language.

#include "dbus-ble/libevent.h"

#include <stdlib.h>
#include <errno.h>

#include <event2/event.h>
#include <event2/util.h>
#include <dbus/dbus.h>

struct watch_handler {
    struct event *ev;
    DBusConnection *dbus_cnx;
    DBusWatch *watch;
};

struct timeout_handler {
    struct event *ev;
    DBusConnection *dbus_cnx;
    DBusTimeout *timeout;
};

static struct event_base *ev_base = nullptr;

static void timeout_handler_free(void *data)
{
    struct timeout_handler *to_handler = reinterpret_cast<struct timeout_handler *>(data);

    if (to_handler == nullptr)
        return;

    if (to_handler->ev != nullptr) {
        event_del(to_handler->ev);
        event_free(to_handler->ev);
    }

    if (to_handler->dbus_cnx != nullptr)
        dbus_connection_unref(to_handler->dbus_cnx);

    free(to_handler);
}

static void libevent_dispatch_dbus(int fd, short event, void *data)
{
    struct timeout_handler *to_handler = reinterpret_cast<struct timeout_handler *>(data);
    DBusConnection *dbus_cnx = to_handler->dbus_cnx;

    dbus_connection_ref(dbus_cnx);

    while (dbus_connection_dispatch(dbus_cnx) == DBUS_DISPATCH_DATA_REMAINS);

    dbus_connection_unref(dbus_cnx);

    timeout_handler_free(to_handler);
}

static inline void throw_libevent_dispatch_dbus(DBusConnection *dbus_cnx)
{
    const struct timeval timeout = {0,0};
    struct timeout_handler *to_handler = reinterpret_cast<struct timeout_handler *>(calloc(1, sizeof(struct timeout_handler)));
    if (to_handler == nullptr)
        return;

    to_handler->dbus_cnx = dbus_connection_ref(dbus_cnx);

    to_handler->ev = evtimer_new(ev_base, libevent_dispatch_dbus, to_handler);

    evtimer_add(to_handler->ev, &timeout);
}

static void watch_handler_dispatch(int fd, short event, void *data)
{
    struct watch_handler *io_handler = reinterpret_cast<struct watch_handler *>(data);
    DBusDispatchStatus status;
    unsigned int flags = 0;

    dbus_connection_ref(io_handler->dbus_cnx);

    if (evutil_socket_geterror(fd) != 0)
        flags |= DBUS_WATCH_ERROR;

    if (event & EV_READ)
        flags |= DBUS_WATCH_READABLE;
    if (event & EV_WRITE)
        flags |= DBUS_WATCH_WRITABLE;

    dbus_watch_handle(io_handler->watch, flags);

    status = dbus_connection_get_dispatch_status(io_handler->dbus_cnx);
    if (status == DBUS_DISPATCH_DATA_REMAINS)
        throw_libevent_dispatch_dbus(io_handler->dbus_cnx);

    dbus_connection_unref(io_handler->dbus_cnx);
}

static void watch_handler_free(void *data)
{
    struct watch_handler *io_handler = reinterpret_cast<struct watch_handler *>(data);

    if (io_handler == nullptr)
        return;

    if (io_handler->ev != nullptr) {
        event_del(io_handler->ev);
        event_free(io_handler->ev);
    }

    dbus_connection_unref(io_handler->dbus_cnx);

    free(io_handler);
}

static dbus_bool_t libevent_dbus_watch_add(DBusWatch *watch, void *data)
{
    DBusConnection *dbus_cnx = reinterpret_cast<DBusConnection *>(data);
    struct watch_handler *io_handler;
    unsigned int flags;
    short io_condition;
    int io_fd;

    if (dbus_watch_get_enabled(watch) == FALSE)
        return TRUE;

    io_handler = reinterpret_cast<struct watch_handler *>(calloc(1, sizeof(struct watch_handler)));
    if (io_handler == nullptr)
        return FALSE;

    io_handler->dbus_cnx = dbus_connection_ref(dbus_cnx);
    io_handler->watch = watch;

    dbus_watch_set_data(watch, io_handler, watch_handler_free);

    flags = dbus_watch_get_flags(watch);

    io_condition = EV_PERSIST;

    if (flags & DBUS_WATCH_READABLE)
        io_condition |= EV_READ;
    if (flags & DBUS_WATCH_WRITABLE)
        io_condition |= EV_WRITE;

    io_fd = dbus_watch_get_unix_fd(watch);

    io_handler->ev = event_new(ev_base, io_fd, io_condition,
                    watch_handler_dispatch, io_handler);

    event_add(io_handler->ev, nullptr);

    return TRUE;
}

static void libevent_dbus_watch_remove(DBusWatch *watch, void *data)
{
    if (dbus_watch_get_enabled(watch) == TRUE)
        return;

    dbus_watch_set_data(watch, nullptr, nullptr);
}

static void libevent_dbus_watch_toggled(DBusWatch *watch, void *data)
{
    if (dbus_watch_get_enabled(watch) == TRUE)
        libevent_dbus_watch_add(watch, data);
    else
        libevent_dbus_watch_remove(watch, data);
}

static void timeout_handler_dispatch(int fd, short event, void *data)
{
    struct timeout_handler *to_handler = reinterpret_cast<struct timeout_handler *>(data);

    dbus_timeout_handle(to_handler->timeout);
}

static inline void _set_timer(struct timeval *timer, long int milliseconds)
{
    timer->tv_sec = milliseconds / 1000;
    timer->tv_usec = (milliseconds % 1000) * 1000;
}

static dbus_bool_t libevent_dbus_timeout_add(DBusTimeout *timeout, void *data)
{
    struct timeout_handler *to_handler;
    struct timeval timer;

    if (dbus_timeout_get_enabled(timeout) == FALSE)
        return TRUE;

    to_handler = reinterpret_cast<struct timeout_handler *>(calloc(1, sizeof(struct timeout_handler)));
    if (to_handler == nullptr)
        return FALSE;

    dbus_timeout_set_data(timeout, to_handler, timeout_handler_free);

    _set_timer(&timer, dbus_timeout_get_interval(timeout));

    to_handler->ev = evtimer_new(ev_base, timeout_handler_dispatch, to_handler);
    evtimer_add(to_handler->ev, (const struct timeval *) &timer);

    return TRUE;
}

static void libevent_dbus_timeout_remove(DBusTimeout *timeout, void *data)
{
    dbus_timeout_set_data(timeout, nullptr, nullptr);
}

static void libevent_dbus_timeout_toggled(DBusTimeout *timeout, void *data)
{
    if (dbus_timeout_get_enabled(timeout) == TRUE)
        libevent_dbus_timeout_add(timeout, data);
    else
        libevent_dbus_timeout_remove(timeout, data);
}

static void libevent_dbus_dispatch_status(DBusConnection *dbus_cnx,
                DBusDispatchStatus new_status, void *data)
{
    DBusDispatchStatus status;

    if (dbus_connection_get_is_connected(dbus_cnx) == FALSE)
        return;

    status = dbus_connection_get_dispatch_status(dbus_cnx);
    if (status == DBUS_DISPATCH_DATA_REMAINS)
        throw_libevent_dispatch_dbus(dbus_cnx);
}

static dbus_bool_t setup_dbus_in_libevent_mainloop(DBusConnection *dbus_cnx)
{
    DBusDispatchStatus status;

    if (dbus_connection_set_watch_functions(dbus_cnx,
            libevent_dbus_watch_add, libevent_dbus_watch_remove,
            libevent_dbus_watch_toggled, dbus_cnx, nullptr) == FALSE)
        return FALSE;

    if (dbus_connection_set_timeout_functions(dbus_cnx,
            libevent_dbus_timeout_add, libevent_dbus_timeout_remove,
            libevent_dbus_timeout_toggled, dbus_cnx, nullptr) == FALSE)
        return FALSE;

    dbus_connection_set_dispatch_status_function(dbus_cnx,
            libevent_dbus_dispatch_status, dbus_cnx, nullptr);

    status = dbus_connection_get_dispatch_status(dbus_cnx);
    if (status == DBUS_DISPATCH_DATA_REMAINS)
        throw_libevent_dispatch_dbus(dbus_cnx);

    return TRUE;
}

int setup_event_loop_for_dbus(DBusConnection *dbus_cnx)
{
    if (ev_base == nullptr)
        ev_base = event_base_new();
    if (ev_base == nullptr)
        return -1;

    if (setup_dbus_in_libevent_mainloop(dbus_cnx) == FALSE) {
        dbus_connection_unref(dbus_cnx);
        event_base_free(ev_base);
        return -1;
    }

    return 0;
}

int libevent_run_loop_dbus(void)
{
    return event_base_loop(ev_base, 0);
}


void dbus_cleanup_event_loop(DBusConnection *dbus_cnx)
{
    if (dbus_cnx == nullptr)
        return;

    dbus_connection_set_watch_functions(dbus_cnx,
                        nullptr, nullptr, nullptr, nullptr, nullptr);
    dbus_connection_set_timeout_functions(dbus_cnx,
                        nullptr, nullptr, nullptr, nullptr, nullptr);
    dbus_connection_set_dispatch_status_function(dbus_cnx,
                            nullptr, nullptr, nullptr);
}
like image 24
abhiarora Avatar answered Sep 21 '22 22:09

abhiarora