awesomewm/classes/battery/battery.lua

124 lines
2.6 KiB
Lua

local widget_types = {
arc = require("classes/battery/arc_widget"),
prog = require("classes/battery/prog_widget")
}
local P = {
name = "battery"
}
P.__index = P
---
-- Internal methods
---
function P:_get_status()
awful.spawn.easy_async(
script_dir .. "battery",
function(stdout, stderr, exitreason, exitcode)
local bat = string.match(stdout, "(%d?%d?%d)%%")
bat = tonumber(string.format("% 3d", bat))
local discharging = string.match(stdout, "discharging") or false
self._ready = true
self.battery_percent = bat
self.charging = not discharging
self:_update_widget()
self:_check_notification()
end
)
return true
end
function P:_update_widget()
if (not self._ready) then
self._widget:set_state("error")
self._widget:set_value(100);
self._widget:set_tooltip("Battery error");
return
end
if (self.charging) then
self._widget:set_state("charging")
else
self._widget:set_state("discharging")
end
self._widget:set_value(self.battery_percent);
self._widget:set_tooltip("Battery " .. math.floor(self.battery_percent) .. "%");
end
function P:_check_notification()
if not self.charging then
for i=1, #self.warnings do
local v = self.warnings[i]
if (self.battery_percent <= v) and (not self._warning_log[i]) then
self._warning_log[i] = true
naughty.notify({
title = "Low power",
text = "Battery is at " .. tostring(self.battery_percent) .. "%",
icon = beautiful.icons.battery.caution,
timeout = 5,
ignore_suspend = true,
border_color = beautiful.color.battery.danger,
preset = beautiful.notification_templates.bottom_right
})
break
end
end
else
for i=1, #self.warnings do
if (self.battery_percent >= self.warnings[i]) then
self._warning_log[i] = false
end
end
end
end
---
-- Create new
---
function P:new(args)
-- Arguments
local b = {
update_interval = args.update_interal or 5,
widget_type = args.widget_type or "arc",
warnings = {5, 10, 25, 50}, -- Percentages to warn at (must be in order)
_warning_log = {},
_ready = false, -- is all the information in this class up-to-date?
-- if this is false, ui will show an error and most methods will
-- do nothing. Updated in _get_status()
}
-- Initialize warning log
for i=1, #b.warnings do
b._warning_log[i] = false
end
b._widget = widget_types[b.widget_type]:new()
b.widget = b._widget.widget
setmetatable(b, self)
self.__index = self
-- This timer keeps mute and volume status up-to-date.
b.timer = gears.timer {
timeout = b.update_interval,
call_now = true,
autostart = true,
callback = function()
b:_get_status()
end
}
return b
end
return P