Gigamo Battery Widget

From awesome
Jump to: navigation, search

A simple battery widget using "/sys/class/power_supply". It also uses naughty for notification when battery gets low.

Widget creation:

 batterywidget = widget({type = "textbox", name = "batterywidget", align = "right" })

The function:

 function batteryInfo(adapter)
     spacer = " "
     local fcur = io.open("/sys/class/power_supply/"..adapter.."/charge_now")    
     local fcap = io.open("/sys/class/power_supply/"..adapter.."/charge_full")
     local fsta = io.open("/sys/class/power_supply/"..adapter.."/status")
     local cur = fcur:read()
     local cap = fcap:read()
     local sta = fsta:read()
     local battery = math.floor(cur * 100 / cap)
     if sta:match("Charging") then
         dir = "^"
         battery = "A/C ("..battery..")"
     elseif sta:match("Discharging") then
         dir = "v"
         if tonumber(battery) > 25 and tonumber(battery) < 75 then
             battery = battery
         elseif tonumber(battery) < 25 then
             if tonumber(battery) < 10 then
                 naughty.notify({ title      = "Battery Warning"
                                , text       = "Battery low!"..spacer..battery.."%"..spacer.."left!"
                                , timeout    = 5
                                , position   = "top_right"
                                , fg         = beautiful.fg_focus
                                , bg         = beautiful.bg_focus
                                })
             end
             battery = battery
         else
             battery = battery
         end
     else
         dir = "="
         battery = "A/C"
     end
     batterywidget.text = spacer.."Bat:"..spacer..dir..battery..dir..spacer
     fcur:close()
     fcap:close()
     fsta:close()
 end

Then, call the function in a hook, like this:

 awful.hooks.timer.register(20, function()
     batteryInfo("BAT1")
 end)

Change the 20 to the time you want, or BAT1 to BAT0 if that's what you use.

Addendum

I can second this widget as working great for me. Checking the AC status is slightly different for me though. I had to do:

 local fsta = io.open("/sys/class/power_supply/AC/online")

And check it with:

 if sta:match("1") then
   ...
 elseif sta:match("0") then
   ...

Also you can add nice colours to the battery indicator using:

 battery = "<span color='orange'>" .. battery .. "</span>"
Personal tools