aboutsummaryrefslogtreecommitdiff
path: root/.config/awesome/services/battery.lua
blob: 98bacc9e640351cd3437f21fb4bb3e175da765b4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
local UPower = require("lgi").UPowerGlib
local gobject = require "gears.object"
local gtimer = require "gears.timer"
local phosphor = require "assets.phosphor"
local qmath = require "quarrel.math"
local qvars = require "quarrel.vars"

local upower = assert(UPower.Client.new_full())
local inner

for _, device in ipairs(upower:get_devices()) do
    if UPower.Device.kind_to_string(device.kind) == "battery" and device.model == "Primary" then
        inner = device
        break
    end
end

local _level, _state

---@class Battery: gears.object
---@field _private { level: number, state: string}
local battery = gobject {
    class = {
        set_level = function(self, level)
            _level = level
            self:emit_signal("level", level)
        end,
        get_level = function()
            return _level
        end,

        set_state = function(self, state)
            _state = state
            self:emit_signal("state", state)
        end,
        get_state = function()
            return _state
        end,
    },
    enable_properties = true,
}

local function icon_handler()
    local icon_data = battery.state == "charging" and { "charging", "green" }
        or qmath.step_value(battery.level, {
            { 0, { "empty", "red" } },
            { 20, { "low", "red" } },
            { 40, { "medium", "yellow" } },
            { 60, { "high", "green" } },
            { 80, { "full", "green" } },
            { 100 },
        })

    battery:emit_signal("icon", phosphor["battery_vertical_" .. icon_data[1] .. "_fill"], qvars.colors[icon_data[2]])
end

local function level_handler()
    battery.level = qmath.percentage(inner.energy, inner.energy_full)
end

local function state_handler()
    battery.state = UPower.Device.state_to_string(inner.state)
end

function inner.on_notify.state()
    state_handler()
    icon_handler()
end

function inner.on_notify.energy()
    level_handler()
    icon_handler()
end

gtimer.delayed_call(function()
    state_handler()
    level_handler()
    icon_handler()
end)

return battery