Refresh battery list on change checked every 2s (configurable)

This commit is contained in:
Alice Gaudon 2021-07-18 16:03:22 +02:00
parent 00533c13f6
commit ecbf661115
2 changed files with 65 additions and 46 deletions

View File

@ -171,7 +171,8 @@ config.widgets = {
battery = { battery = {
enabled = true, enabled = true,
screens = { 1, 2 }, screens = { 1, 2 },
refresh_interval = 30, -- In seconds refresh_interval = 15, -- In seconds
list_refresh_interval = 2, -- In seconds
precision = 0, -- How many decimals precision = 0, -- How many decimals
}, },
}, },

View File

@ -135,14 +135,9 @@ gears.timer {
--- ---
--- Batteries --- Batteries
--- ---
local rawBatteries = readCommand("ls -A1 /sys/class/power_supply") rawBatteries = {}
function refreshRawBatteries()
function getBatteries() rawBatteries = readCommand("ls -A1 /sys/class/power_supply")
return rawBatteries:gmatch("([^\n]+)")
end
function hasBattery()
return rawBatteries:len() > 0
end end
function getBatteryLevel(battery) function getBatteryLevel(battery)
@ -170,8 +165,25 @@ end
local batteryContainer = wibox.widget { local batteryContainer = wibox.widget {
layout = wibox.layout.flex.horizontal layout = wibox.layout.flex.horizontal
} }
if hasBattery() then local timers = {}
for battery in getBatteries() do function refreshBatteries()
-- refresh raw batteries and check for change
local oldBatteries = rawBatteries
refreshRawBatteries()
if rawBatteries == oldBatteries then
return
end
-- clear timers
for i,v in ipairs(timers) do
v:stop()
end
timers = {};
-- clear layout
batteryContainer:set_children({})
for battery in rawBatteries:gmatch("([^\n]+)") do
local path = "/sys/class/power_supply/" .. battery local path = "/sys/class/power_supply/" .. battery
if readCommand("cat " .. path .. "/type"):match("Battery") then if readCommand("cat " .. path .. "/type"):match("Battery") then
-- widget -- widget
@ -195,7 +207,7 @@ if hasBattery() then
-- update battery level -- update battery level
local batteryText = widget:get_children()[1] local batteryText = widget:get_children()[1]
gears.timer { local timer = gears.timer {
timeout = config.battery.refresh_interval, timeout = config.battery.refresh_interval,
call_now = true, call_now = true,
autostart = true, autostart = true,
@ -203,15 +215,21 @@ if hasBattery() then
batteryText.markup = (isCharging(path) and "+" or "") .. getBatteryLevel(path) batteryText.markup = (isCharging(path) and "+" or "") .. getBatteryLevel(path)
end end
} }
table.insert(timers, timer)
batteryContainer:add(widget) batteryContainer:add(widget)
end end
end end
else
batteryContainer = nil
end end
gears.timer {
timeout = config.battery.list_refresh_interval,
call_now = true,
autostart = true,
callback = function()
refreshBatteries()
end
}
return { return {
bars = bars, bars = bars,