65 lines
4.4 KiB
Python
65 lines
4.4 KiB
Python
#!/usr/bin/env python3
|
|
"""Check power math and optionally exercise live JMeter-to-Shelly collection."""
|
|
import argparse, csv, json, subprocess, tempfile, time, xml.etree.ElementTree as E
|
|
from pathlib import Path
|
|
import shelly
|
|
p=argparse.ArgumentParser();p.add_argument('--host');p.add_argument('--port',type=int,default=80);p.add_argument('--output');a=p.parse_args()
|
|
with tempfile.TemporaryDirectory(prefix='healthapp-shelly-test-') as name:
|
|
root=Path(name);raw=root/'power.csv'
|
|
with raw.open('w') as f:
|
|
fields=['timeStamp','elapsed','label','success',*shelly.VARIABLES];w=csv.DictWriter(f,fieldnames=fields);w.writeheader()
|
|
for t in range(0,20001,1000):
|
|
w.writerow(dict(zip(fields,[t,0,'POWER Shelly status','true',100,230,.5,t/36000])))
|
|
result=shelly.summarize(raw,root/'measured.csv',2500,17500,1000)
|
|
assert result['integrated_joules']==1500 and abs(result['counter_joules']-1500)<.0001
|
|
assert result['measurement_seconds']==15 and result['average_watts']==100
|
|
assert result['power_sample_count']==15 and result['nominal_sample_coverage_seconds']==15
|
|
# Variable power distinguishes a direct sample sum from trapezoidal integration.
|
|
with raw.open() as f: variable=list(csv.DictReader(f))
|
|
variable[3]['shelly_power_watts']='200'
|
|
with raw.open('w') as f:
|
|
w=csv.DictWriter(f,fieldnames=fields);w.writeheader();w.writerows(variable)
|
|
variable_result=shelly.summarize(raw,root/'variable.csv',2500,17500,1000)
|
|
assert variable_result['integrated_joules']==1600
|
|
for start,end in [(-1000,17500),(2500,25000)]:
|
|
try:shelly.summarize(raw,root/'bad.csv',start,end,1000)
|
|
except ValueError:pass
|
|
else:raise AssertionError('Incomplete coverage accepted')
|
|
with raw.open() as f:rows=list(csv.DictReader(f))
|
|
for variant in ['gap','reset','failed']:
|
|
bad=list(rows)
|
|
if variant=='gap':bad=[r for r in bad if not 5000<int(r['timeStamp'])<15000]
|
|
elif variant=='reset':bad=[dict(r,shelly_energy_wh='0') if int(r['timeStamp'])>=10000 else r for r in bad]
|
|
else:bad[6]=dict(bad[6],success='false')
|
|
path=root/(variant+'.csv')
|
|
with path.open('w') as f:w=csv.DictWriter(f,fieldnames=fields);w.writeheader();w.writerows(bad)
|
|
try:shelly.summarize(path,root/'bad.csv',2500,17500,1000)
|
|
except ValueError:pass
|
|
else:raise AssertionError(variant+' accepted')
|
|
with raw.open('w') as f:
|
|
w=csv.DictWriter(f,fieldnames=fields);w.writeheader()
|
|
for t in range(0,16500001,300000):
|
|
w.writerow(dict(zip(fields,[t,0,'POWER Shelly status','true',100,230,.5,t/36000])))
|
|
long_run=shelly.summarize(raw,root/'four-hours.csv',1800000,16200000,300000)
|
|
assert long_run['measurement_seconds']==14400 and long_run['integrated_joules']==1440000
|
|
assert long_run['counter_kWh']==.4
|
|
print('Shelly energy calculation, warmup exclusion, gaps, resets and failed-poll checks passed')
|
|
if a.host:
|
|
if not a.output:p.error('--output is required for live verification')
|
|
print('Device:',shelly.check_plug(a.host,a.port))
|
|
out=Path(a.output).resolve();out.mkdir(parents=True,mode=0o700,exist_ok=False)
|
|
document=E.parse(Path(__file__).parent/'plans/idle.jmx')
|
|
for collector in document.iter('kg.apc.jmeter.perfmon.PerfMonCollector'):collector.set('enabled','false')
|
|
plan=out/'idle.jmx';document.write(plan)
|
|
command=[str(Path.home()/'.local/bin/jmeter'),'-n','-t',str(plan),'-l',str(out/'samples.csv'),'-j',str(out/'jmeter.log'),'-Jshelly_host='+a.host,'-Jshelly_port='+str(a.port),'-Jshelly_file='+str(out/'shelly.csv'),'-Jsample_variables='+','.join(shelly.VARIABLES),'-Jjmeter.save.saveservice.autoflush=true','-Jwarmup_seconds=5','-Jduration_seconds=20','-Jtotal_duration_seconds=35','-Jtimeline_file='+str(out/'timeline.json')]
|
|
process=subprocess.Popen(command);live=False
|
|
while process.poll() is None:
|
|
file=out/'shelly.csv'
|
|
if file.exists() and file.stat().st_size>0:live=True
|
|
time.sleep(.25)
|
|
assert process.returncode==0 and live,'Power readings were not written while JMeter was running'
|
|
timeline=json.loads((out/'timeline.json').read_text())
|
|
result=shelly.summarize(out/'shelly.csv',out/'shelly-measured.csv',timeline['measurement_start_ms'],timeline['measurement_end_ms'],5000)
|
|
(out/'summary.json').write_text(json.dumps(result,indent=2));print(json.dumps(result,indent=2))
|
|
print('Live Shelly JMeter collection passed; no switching commands or application requests sent')
|