
import matplotlib.pyplot as mplt
import matplotlib.dates as mdates
import matplotlib.ticker as mticker
import matplotlib.patches as mpatches

battery_t = []
battery_val = []

suspends = []
charges = []

totalChargeTime = 0
totalSuspendTime = 0
totalTime = 0

with open("battery.log", "r") as file:
    for line in file:
        time, event = line[1:].split("] ")
        if event.startswith("com.lab126.powerd battLevelChanged"):
            battery_t.append(mdates.datestr2num(time))
            battery_val.append(event[35:-1])
        elif event.startswith("com.lab126.powerd suspending"):
            suspends.append((mdates.datestr2num(time),0))
        elif event.startswith("com.lab126.powerd resuming"):
            suspends[-1]=(suspends[-1][0],mdates.datestr2num(time)-suspends[-1][0])
        elif event.startswith("com.lab126.powerd charging"):
            charges.append((mdates.datestr2num(time),0))
        elif event.startswith("com.lab126.powerd notCharging"):
            charges[-1]=(charges[-1][0],mdates.datestr2num(time)-charges[-1][0])

fig, ax = mplt.subplots()

ax.plot(battery_t, battery_val)

ax.xaxis.set_major_locator(mdates.DayLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter('%d.%m'))

for (a,b) in suspends:
    ax.add_patch(mpatches.Rectangle((a,0),b,100, linewidth=0,alpha=0.4, color='gray'));
    totalSuspendTime += b

for (a,b) in charges:
    ax.add_patch(mpatches.Rectangle((a,0),b,100, linewidth=0,alpha=0.4, color='green'));
    totalChargeTime +=b

totalTime = battery_t[-1]-battery_t[0]

textstr = '\n'.join( ("Total measurement time: %.2fh"%(totalTime*24),
                     "Charge time: %.2fh"%(totalChargeTime*24),
                     "Suspended time: %.2fh"%(totalSuspendTime*24),
                     "Active time: %.2fh"%((totalTime-totalSuspendTime)*24) ) )

ax.text(0.05, 0, textstr, transform=ax.transAxes, fontsize=14,
        verticalalignment='bottom')

ax.set(xlabel='Time', ylabel='Battery charge (%)')
ax.grid()
fig.autofmt_xdate()

fig.savefig("test.png")