Skip to content

Instantly share code, notes, and snippets.

@santiago-salas-v
Last active June 6, 2025 19:09
Show Gist options
  • Save santiago-salas-v/9ba967b35c82e46553b81a52fd29adc2 to your computer and use it in GitHub Desktop.
Save santiago-salas-v/9ba967b35c82e46553b81a52fd29adc2 to your computer and use it in GitHub Desktop.
check battery plot
#!/bin/env python
import subprocess
from time import sleep
from datetime import datetime,timedelta
import json
import plotext as plt
from math import ceil
plt.date_form('H:M:S')
plt.theme('pro')
plt.limit_size(False,True)
plt.plotsize(55, 15)
avg_wind=4 # avg. window for dSOC/dt
def step(times,dt,top_vars,past,avg_wind):
output=json.loads(subprocess.check_output('termux-battery-status').decode())
top_vars+=[[output['current'],output['voltage'],output['percentage']]]
plt.clt() # to clear the terminal
plt.cld() # to clear the data only
plt.subplots(2,1)
plt.subplots(1,1).plotsize(plt.tw(),int(ceil(plt.th()*0.9))) # should not work but int(ceil(plt.th()*2/3)) results smaller than height
plt.subplots(2,1).plotsize(plt.tw(),int(ceil(plt.th()*0.9))) # should not work but int(ceil(plt.th()*1/3)) results smaller than height
plt.subplot(1,1)
#times+=[datetime.now().strftime('%H:%M:%S')]
now=datetime.now()
dt+=[now-past]
past=now
times+=[times[-1]+dt[-1]]
currents=[x[0] for x in top_vars]
voltages=[x[1] for x in top_vars]
soc=[x[2] for x in top_vars]
dsocdt=min(avg_wind,len(times))*[0]+[(sum(soc[j+1:j+1+avg_wind])-sum(soc[j:j+avg_wind]))/sum([x.total_seconds() for x in dt[j:j+avg_wind]]) for j in range(len(times)-avg_wind)] # moving avg. window (4)
plt.plot(currents,yside='left',label='current')
plt.plot(voltages,yside='right',label='voltage')
plt.title('current (left), voltage/mV (right)')
plt.subplot(2,1)
plt.plot(soc,yside='left',label='soc/%')
plt.plot(dsocdt,yside='right',label='(dsoc/dt)/(%/s)')
plt.title('SoC/% (left), (dSoC/dt)/(%/s) mv. avg. 20s (right)')
plt.show()
if len(times)>250: # show up to 250 points
times.pop(0)
top_vars.pop(0)
dt.pop(0)
past=datetime.now()
print('press CTRL+C to quit')
sleep(1)
return times,dt,top_vars,past
try:
# init.
past=datetime.now()
times=[past];dt=[timedelta(seconds=1)];top_vars=[]
output=json.loads(subprocess.check_output('termux-battery-status').decode())
top_vars+=[[output['current'],output['voltage'],output['percentage']]]
while True:
times,dt,top_vars,past=step(times,dt,top_vars,past,avg_wind)
except KeyboardInterrupt:
pass
while ($true) {(Get-Counter '\prozess(*)\prozessorzeit (%)').CounterSamples | Select-Object -Property instancename, cookedvalue | Sort-Object -Property cookedvalue -Descending | Select-Object -First 20 | ft InstanceName,@{L='CPU';E={($_.Cookedvalue/100/$env:NUMBER_OF_PROCESSORS).toString('P')}} -AutoSize | Out-File -FilePath $env:home\cpu_consumption.txt; Get-Content -Path $env:home\cpu_consumption.txt; sleep 1}
#!/bin/env python
import subprocess
from os import name,system
from numpy import fromregex,concatenate,unique,bincount,empty
from os.path import sep
from os import environ
from time import sleep
from datetime import datetime
from pandas import DataFrame
import plotext as plt
plt.date_form('H:M:S')
plt.limit_size(False,True)
plt.plotsize(55, 15)
filename=sep.join([environ['HOME'],'cpu_consumption.txt'])
past=datetime.now()
t=0
times=[];top_vars=[]
powershell_path=r'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe'
while True:
subprocess.run([powershell_path,"(Get-Counter '\prozess(*)\prozessorzeit (%)').CounterSamples | Select-Object -Property instancename, cookedvalue | Sort-Object -Property cookedvalue -Descending | Select-Object -First 20 | ft InstanceName,@{L='CPU';E={($_.Cookedvalue/100/$env:NUMBER_OF_PROCESSORS).toString('P')}} -AutoSize | Out-File -FilePath $env:home\cpu_consumption.txt"]) #; Get-Content -Path $env:home\cpu_consumption.txt"])
#system('cls' if name == 'nt' else 'clear')
plt.clt() # to clear the terminal
plt.cld() # to clear the data only
times+=[datetime.now().strftime('%H:%M:%S')]
dt=(datetime.now()-past).total_seconds()
t+=dt
dat=fromregex(sep.join([environ['HOME'],'cpu_consumption.txt']),r'(\w+)\s+(\d+\.\d+)',[('key','U25'),('CPU',float)],encoding='utf16')
cpu_inst=dat['CPU'].copy()/100
dat['CPU']=cpu_inst*dt
names_inst=dat['key'].copy()
#dat=DataFrame(dat,index=dat['key']).drop(columns='key')
if 'dat_old' in locals():
dat=concatenate([dat,dat_old])
u,idx=unique(dat['key'],return_inverse=True) # get all uniques and indexes of these in array
s=bincount(idx,weights=dat['CPU']) # get cumulative sum
dat=empty([len(u)],dtype=[('key','U25'),('CPU',float)]) # clear for merged data
dat['key']=u # unique
dat['CPU']=s # result
dat=dat[dat['CPU'].argsort()[::-1]] # sort highest CPU consumers
dat=dat[:20] # track only highest consumers
dat_old=dat.copy()
cpu_pct=empty(dat['CPU'].shape)
cpu_pct[dat['key']!='_total']=dat['CPU'][dat['key']!='_total']/dat['CPU'][dat['key']!='_total'].sum()
cpu_pct[dat['key']=='_total']=1
printstr='{:30s} {:<11.5s} {:<11.5s} {:<11.5s}\n'.format('proc','CPU/s','CPU/%','CPU_inst/%')
for j, row in enumerate(dat):
cpu_inst_row=cpu_inst[names_inst==row['key']].sum()
if not cpu_inst_row:
cpu_inst_row=0
printstr+='{:30s} {:<11.5g} {:<11.5g} {:<11.5g}\n'.format(row['key'],row['CPU'],cpu_pct[j]*100,cpu_inst_row*100)
print(printstr)
print('dt={:0.4g} seconds. Total: {:0.4g} seconds'.format(dt,t))
idx=(dat['key']!='_total')&(dat['key']!='idle')
top_vars+=[cpu_pct[idx][:5]*100]
for j in range(5):
plt.plot([y[j] for y in top_vars])
plt.show()
if len(times)>20:
times.pop(0)
top_vars.pop(0)
past=datetime.now()
sleep(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment