Root/src/powersaver.cpp

Source at commit 73ceffa51d3450d2d20ce933e7fc6da187e09fc8 created 7 years 5 months ago.
By Maarten ter Huurne, Fix bug in section directory creation method
1#include "powersaver.h"
2#include "debug.h"
3
4#include <cassert>
5#include <cerrno>
6#include <cstdio>
7#include <cstring>
8#include <fcntl.h>
9#include <unistd.h>
10
11PowerSaver *PowerSaver::instance = nullptr;
12
13Uint32 screenTimerCallback(Uint32 timeout, void *d) {
14    unsigned int * old_ticks = (unsigned int *) d;
15    unsigned int new_ticks = SDL_GetTicks();
16
17    if (new_ticks > *old_ticks + timeout + 1000) {
18        DEBUG("Suspend occured, restarting timer\n");
19        *old_ticks = new_ticks;
20        return timeout;
21    }
22
23    DEBUG("Disable Backlight Event\n");
24    PowerSaver::instance->disableScreen();
25    return 0;
26}
27
28PowerSaver::PowerSaver()
29    : screenState(false)
30    , screenTimeout(0)
31    , screenTimer(nullptr)
32{
33    enableScreen();
34    assert(!instance);
35    instance = this;
36}
37
38PowerSaver::~PowerSaver() {
39    removeScreenTimer();
40    instance = nullptr;
41    enableScreen();
42}
43
44void PowerSaver::setScreenTimeout(unsigned int seconds) {
45    screenTimeout = seconds;
46    resetScreenTimer();
47}
48
49void PowerSaver::resetScreenTimer() {
50    removeScreenTimer();
51    enableScreen();
52    if (screenTimeout != 0) {
53        addScreenTimer();
54    }
55}
56
57void PowerSaver::addScreenTimer() {
58    assert(!screenTimer);
59    timeout_startms = SDL_GetTicks();
60    screenTimer = SDL_AddTimer(
61            screenTimeout * 1000, screenTimerCallback, &timeout_startms);
62    if (!screenTimer) {
63        ERROR("Could not initialize SDLTimer: %s\n", SDL_GetError());
64    }
65}
66
67void PowerSaver::removeScreenTimer() {
68    if (screenTimer) {
69        SDL_RemoveTimer(screenTimer);
70        screenTimer = nullptr;
71    }
72}
73
74#define SCREEN_BLANK_PATH "/sys/class/graphics/fb0/blank"
75void PowerSaver::setScreenBlanking(bool state) {
76    const char *path = SCREEN_BLANK_PATH;
77    const char *blank = state
78        ? "0" /* FB_BLANK_UNBLANK */
79        : "4" /* FB_BLANK_POWERDOWN */;
80
81    int fd = open(path, O_RDWR);
82    if (fd == -1) {
83        WARNING("Failed to open '%s': %s\n", path, strerror(errno));
84    } else {
85        ssize_t written = write(fd, blank, strlen(blank));
86        if (written == -1) {
87            WARNING("Error writing '%s': %s\n", path, strerror(errno));
88        }
89        close(fd);
90    }
91    screenState = state;
92}
93
94void PowerSaver::enableScreen() {
95    if (!screenState) {
96        setScreenBlanking(true);
97    }
98}
99
100void PowerSaver::disableScreen() {
101    if (screenState) {
102        setScreenBlanking(false);
103    }
104}
105

Archive Download this file



interactive