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:

 battery_widget = wibox.widget.textbox()
 battery_widget:set_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
     battery_widget:set_markup(spacer.."Bat:"..spacer..dir..battery..dir..spacer)
     fcur:close()
     fcap:close()
     fsta:close()
 end

Then, call the function with a timer, like this:

 battery_timer = timer({timeout = 20})
 battery_timer:connect_signal("timeout", function()
     batteryInfo("BAT1")
 end)
 battery_timer:start()

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