qtqdbus

QtDBus Simply Example With PowerManager


I'm trying to use QtDbus to communicate with interface provided by PowerManager in my system. My goal is very simple. I will be writing code which causes my system to hibernate using DBus interface.

So, I installed d-feet application to see what interfaces DBus is available on my system, and what I saw:

enter image description here

As we see, I have a few interfaces and methods from which I can choose something. My choice is Hibernate(), from interface org.freedesktop.PowerManagment

In this goal I prepared some extremely simple code to only understand mechanism. I of course used Qt library:

#include <QtCore/QCoreApplication>
#include <QtCore/QDebug>
#include <QtCore/QStringList>
#include <QtDBus/QtDBus>
#include <QDBusInterface>
int main(int argc, char **argv)
{
    QCoreApplication app(argc, argv);

    if (!QDBusConnection::sessionBus().isConnected()) {
        fprintf(stderr, "Cannot connect to the D-Bus session bus.\n"
                "To start it, run:\n"
                "\teval `dbus-launch --auto-syntax`\n");
        return 1;
    }
    QDBusInterface iface("org.freedesktop.PowerManagement" ,"/" , "" , QDBusConnection::sessionBus());
    if(iface.isValid())
    {
        qDebug() << "Is good";
        QDBusReply<QString> reply = iface.call("Methods" , "Hibernate");
        if(reply.isValid())
        {
            qDebug() << "Hibernate by by " <<  qPrintable(reply.value());
        }

        qDebug() << "some error " <<  qPrintable(reply.error().message());

    }

    return 0;
}

Unfortunately I get error in my terminal:

Is good
some error Method "Methods" with signature "s" on interface "(null)" doesn't exist

So please tell me what's wrong with this code? I am sure that I forgot some arguments in function QDBusInterface::call() but what ?


Solution

  • When creating interface you have to specify correct interface, path, service. So that's why your iface object should be created like this:

    QDBusInterface iface("org.freedesktop.PowerManagement",  // from list on left
                         "/org/freedesktop/PowerManagement", // from first line of screenshot
                         "org.freedesktop.PowerManagement",  // from above Methods
                         QDBusConnection::sessionBus());
    

    Moreover, when calling a method you need to use it's name and arguments (if any):

    iface.call("Hibernate");
    

    And Hibernate() doesn't have an output argument, so you have to use QDBusReply<void> and you can't check for .value()

    QDBusReply<void> reply = iface.call("Hibernate");
    if(reply.isValid())
    {
        // reply.value() is not valid here
    }