For a long time, I have used gnome-power to look at battery use graphs. However, its graphs are difficult to read. The x-axis isn’t well-labelled and it is difficult to understand what the battery percentage is at a certain hour.

However, I realized that most of the information found in gnome-power are actually derived from upower. What made me excited was that I found that upower logs the battery changes at /var/lib/upower/history-charge-<battery-id>.dat.

Opening up the file, there are 3 information columns: unix-timestamp, the battery percentage, and the battery state. And so I decided to do-away with using a program and just use R to help me understand my battery history.

Note: updated on [2023-02-19 Sun]

library(lubridate)
library(dplyr)
library(ggplot2)

start_time = paste(Sys.Date(), " 06:00:00")
end_time = Sys.time()
# source file

bat <- list("/var/lib/upower/history-charge-01AV424-24-4992.dat",
            "/var/lib/upower/history-charge-01AV489-23-6222.dat")

# function to save plot
savePlot <- function(x,myPlot) {
        pdf(paste("bat", x, ".pdf", sep = ""))
        print(myPlot)
        dev.off()
}

for (x in 1:2) {
dat <- readLines(bat[[x]])
df = as.data.frame(do.call(rbind, strsplit(dat, split="\\s{1,}")), stringsAsFactors=FALSE)
df$V1 <- as.POSIXct(as.numeric(df$V1), origin="1970-01-01")
df$V2 <- as.numeric(df$V2)

# Generate some times
t_seq <- seq(from = ymd_hms(start_time, tz= Sys.timezone()),
             to = ymd_hms(end_time, tz = Sys.timezone()),
             by = "10 min")

myPlot <- df %>%
filter(V1 >= start_time) %>%
filter(V1 <= end_time) %>%
ggplot(aes(V1,V2)) +
  geom_point(na.rm=TRUE) +
  scale_x_datetime(date_labels = "%m-%d %H:%M", breaks = t_seq) +
  scale_y_continuous(limits = c(0, 100), breaks = seq(0, 100, 10)) +
  theme(axis.text.x=element_text(angle=90))

savePlot(x,myPlot)

}

Replace bat with your own battery.dat files.

This program converts the unix-timestamp to year-month-date-hour-minutes-seconds format. The battery percentage is on the y-axis, with the time on the x-axis. This creates a graph of the battery usage from 6am up to the time that you run the script.

To run the script, use the Rscript <file> command. Then, view the files in your working directory with a PDF viewer.

Now you can look at you battery history with better knowledge of what the percentage was at a certain time.