1

I need a way to prevent the computer from sleeping, turn it on/off at runtime.

I believe SetThreadExecutionState does that for windows, now I am looking for a way to do that in Linux.

HBatalha
  • 109

2 Answers2

1

Answer for Linux only, I unfortunately don't know how this works on Unix systems:

You should use systemd inhibitors for this (inhibitor locks are also available on non-systemd distributions, provided by elogind). These can be controlled using DBus API so if you are using Qt you can use the QDBus module for that (other DBus libraries are also available, I don't think there is a specific library for C/C++ for working with systemd inhibitors, the DBus API is simple and language-idependent).

0

There are some C++ wrappers:

https://github.com/martinhaefner/simppl

https://github.com/makercrew/dbus-sample

https://dbus-cxx.github.io/

http://dbus-cplusplus.sourceforge.net/

And DBusBindings https://www.freedesktop.org/wiki/Software/DBusBindings/

I am on Qt and below is the code I am using which is a modified version of the code in this answer

void MainWindow::toggleSleepPevention()
{
#ifdef Q_OS_LINUX
    const int MAX_SERVICES = 2;
QDBusConnection bus = QDBusConnection::sessionBus();
if(bus.isConnected())
{
    QString services[MAX_SERVICES] =
    {
        "org.freedesktop.ScreenSaver",
        "org.gnome.SessionManager"
    };
    QString paths[MAX_SERVICES] =
    {
        "/org/freedesktop/ScreenSaver",
        "/org/gnome/SessionManager"
    };


    static uint cookies[2];

    for(int i = 0; i < MAX_SERVICES ; i++)
    {
        QDBusInterface screenSaverInterface( services[i], paths[i],services[i], bus);

        if (!screenSaverInterface.isValid())
            continue;

        QDBusReply<uint> reply;

        if(preferences.preventSleep == true)
        {
            reply = screenSaverInterface.call("Inhibit", "nzuri-video Downloader", "REASON");
        }
        else
        {
            reply  = screenSaverInterface.call("UnInhibit", cookies[i]);
        }

        if (reply.isValid())
        {
            cookies[i] = reply.value();

            // qDebug()<<"succesful: " << reply;
        }
        else
        {
            // QDBusError error =reply.error();
            // qDebug()<<error.message()<<error.name();
        }
    }
}

#elif defined Q_OS_WIN

EXECUTION_STATE result;

if(preferences.preventSleep == true)
    result = SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED);
else
    result = SetThreadExecutionState(ES_CONTINUOUS);

if(result == NULL)
    qDebug() << "EXECUTION_STATE failed";

#endif }

HBatalha
  • 109