/*
* Example low-level D-Bus code.
* Written by Matthew Johnson
*
* This code has been released into the Public Domain.
* You may do whatever you like with it.
*/
#include
#include
#include
#include
#include
#include
class dbus_server
{
public:
// Constructor/destructor
dbus_server ();
~dbus_server ();
// Interaction functions
void handle_requests (std::string &retval, bool &has_command);
private:
// Data
DBusMessage *msg;
DBusMessageIter args;
DBusConnection *conn;
DBusError err;
bool is_connected;
};
dbus_server::dbus_server ()
: is_connected (false)
{
// initialise the errors
dbus_error_init (&err);
// connect to the bus and check for errors
conn = dbus_bus_get (DBUS_BUS_SESSION, &err);
if (dbus_error_is_set (&err) || conn == NULL)
return;
// request our name on the bus and check for errors
const int ret = dbus_bus_request_name (conn, "org.octave.some_instance",
DBUS_NAME_FLAG_REPLACE_EXISTING , &err);
if (dbus_error_is_set (&err) || ret != DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER)
return;
// add a rule for which messages we want to see
dbus_bus_add_match (conn, "type='signal',interface='org.octave.interface'", &err);
dbus_connection_flush (conn);
if (dbus_error_is_set (&err))
return;
// We've connected successfully to the bus
is_connected = true;
}
dbus_server::~dbus_server ()
{
dbus_error_free (&err);
}
void dbus_server::handle_requests (std::string &retval, bool &has_command)
{
char *code;
has_command = false;
if (!is_connected)
return;
// non blocking read of the next available message
dbus_connection_read_write (conn, 0);
msg = dbus_connection_pop_message (conn);
// loop again if we haven't read a message
if (msg == NULL)
return;
// check if the message is a signal from the correct interface and with the correct name
if (dbus_message_is_signal (msg, "org.octave.interface", "evaluate")
&& dbus_message_iter_init (msg, &args)
&& dbus_message_iter_get_arg_type (&args) == DBUS_TYPE_STRING)
{
// read the parameters
dbus_message_iter_get_basic (&args, &code);
retval = code;
has_command = true;
}
// free the message
dbus_message_unref (msg);
}