Skip to content

Instantly share code, notes, and snippets.

@SkyyySi
Last active October 18, 2023 16:43
Show Gist options
  • Save SkyyySi/6a5403481d83fcb6545fe976c944830a to your computer and use it in GitHub Desktop.
Save SkyyySi/6a5403481d83fcb6545fe976c944830a to your computer and use it in GitHub Desktop.
A standalone script to get the current charging percentage of your device's battery, written in Lua. Requires LGI. Linux only (maybe BSD too; probably not, though).
#!/usr/bin/env luajit
local script_version = "1.1.1"
local lgi = require("lgi")
local GLib = lgi.GLib
local UPowerGlib = lgi.UPowerGlib
local function get_battery()
for _, device in pairs(UPowerGlib.Client():get_devices()) do
if device:get_object_path():match("/battery_BAT[0-9]+$") then
return device
end
end
error("No battery found! Are you on a desktop PC or server?")
end
local function get_charge(battery)
battery = battery or get_battery()
return 100 * (battery["energy"] / battery["energy-full"])
end
local function print_charge(charge)
print(("%3.02f%%"):format(charge or get_charge()))
end
local function print_help()
print(([===[
%s (version %s): Get the current charge of the device's battery
Supported arguments:
-h, --help Show this help text and exit
-v, --version Print the current version and exit
-w, --watch Keep printing updates instead of only printing once (blocking)
]===]):format(arg[0]:gsub("^.*/", ""), script_version))
end
local options = {
watch = false,
}
local function pasrse_arg()
for k, v in pairs(arg) do
if k < 1 then
goto _continue_0
end
if (v == "-h") or (v == "--help") then
print_help()
os.exit(0)
elseif (v == "-v") or (v == "--version") then
print(script_version)
os.exit(0)
elseif (v == "-w") or (v == "--watch") then
options.watch = true
else
print("ERROR: Unsupported arguments '" .. v .. "'!")
print()
print_help()
os.exit(1)
end
::_continue_0::
end
end
local function main(watch)
pasrse_arg()
print_charge()
if not watch then
return
end
local battery = get_battery()
local previous_charge
function battery:on_notify()
local current_charge = get_charge(battery)
if current_charge == previous_charge then
return
end
print_charge()
previous_charge = current_charge
end
GLib.MainLoop():run()
end
if (arg ~= nil and arg[1] ~= nil) or (... == nil) then
main(options.watch)
return
end
return {
main = main,
print_charge = print_charge,
get_charge = get_charge,
get_battery = get_battery,
version = script_version,
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment