How to create my own simple battery widget

32Ok, finally I did it, I paste it here (with comments) in case anyone needs it =)

-- Create the textbox that will be used to print the battery percentage and initialize it with an empty string

batterywidget = wibox.widget.textbox()

batterywidget:set_text("")

-- Create the imagebox that will be used to show battery icon and initialize it

-- with "empty battery" one

batteryicon = wibox.widget.imagebox()

batteryicon:set_image(theme.widget_bat_empty)

-- Create the timer which will allow to repeat battery status command (every 5 sec)

batterywidgettimer = timer({ timeout = 5 })

-- Initialize the timer and execute the function every 5 seconds

batterywidgettimer:connect_signal("timeout",

function()

-- Cut the 'acpi' output, so that it only remains the percentage number;

-- Put it into the file 'fperc', then put its content into the numeric

-- variable 'perc'

fperc = assert(io.popen("acpi | cut -d' ' -f 4 | cut -d% -f 1", "r"))

local perc = fperc:read("*number")

-- Set 'batterywidget' textbox with the percentage

batterywidget:set_text(perc..'%')

-- Cut the 'acpi' output, so that it only remains the status string (which

-- Can be " Full", " Charging" or " Discharging"; put it into the file

-- 'fstatus', then put its content into the variable 'status'

fstatus = assert(io.popen("acpi | cut -d: -f 2,2 | cut -d, -f 1,1", "r"))

local status = fstatus:read("*l")

-- if status is " Discharging", set batteryicon imagebox with the proper

-- icon, depending charge status (0-19, 20-49, 50-79, 80-100). If the

-- status is different (" Full" or " Charging"), set it with "A/C" icon

if status == " Discharging" then

     if perc > 80 then

         batteryicon:set_image(theme.widget_bat_full)

     elseif perc > 50 then

         batteryicon:set_image(theme.widget_bat_med)

     elseif perc > 20 then

         batteryicon:set_image(theme.widget_bat_low)

     else

         batteryicon:set_image(theme.widget_bat_empty)

     end

else

     batteryicon:set_image(theme.widget_ac)

end

-- Close the files

fperc:close()

fstatus:close()

end

)

-- Start the timer

batterywidgettimer:start()

Of course remember to draw the elements in the wibox (i choose to align the widget to the right)

right_layout:add(batteryicon)

right_layout:add(batterywidget)

layout:set_right(right_layout)

mywibox[s]:set_widget(layout)

... And put the icons into theme.lua

theme.widget_ac = themes .. "/icons/brontosaurus/ac.png"

theme.widget_bat_full = themes .. "/icons/brontosaurus/bat_full.png"

theme.widget_bat_med = themes .. "/icons/brontosaurus /bat_med.png"

theme.widget_bat_low = themes .. "/icons/brontosaurus/bat_low.png"

theme.widget_bat_empty = themes .. "/icons/brontosaurus/bat_empty.png"

Hope that helps!

/r/awesomewm Thread