Collect Shelly plug power live in JMeter energy experiments

This commit is contained in:
Steffen committed 2026-10-07 22:12:58 +02:00
1 parent a69b9b2118
commit e50cf0a011
13 files changed
+634 -22

No files matched your search

+19 -2
View File
@@ -4,6 +4,7 @@ import xml.etree.ElementTree as E
import argparse, csv, datetime as dt, hashlib, json, os, platform, subprocess, time, ssl, urllib.request
from pathlib import Path
from perfmon import check_agent, summarize
import shelly
HERE=Path(__file__).resolve().parent
p=argparse.ArgumentParser()
p.add_argument('scenario',choices=['recording','review','correction','professional','mixed','idle'])
@@ -17,12 +18,16 @@ p.add_argument('--output',required=True);p.add_argument('--jmeter',default=str(P
p.add_argument('--allow-shared-read-account',action='store_true')
p.add_argument('--perfmon-host');p.add_argument('--perfmon-port',type=int,default=4444)
p.add_argument('--perfmon-interval-ms',type=int,default=5000);p.add_argument('--no-perfmon',action='store_true')
p.add_argument('--shelly-host',default='192.168.1.44');p.add_argument('--shelly-port',type=int,default=80)
p.add_argument('--shelly-switch-id',type=int,default=0);p.add_argument('--shelly-interval-ms',type=int,default=5000);p.add_argument('--no-shelly',action='store_true')
a=p.parse_args()
if a.users<1 or a.duration<1 or a.warmup<0 or a.ramp<0 or min(a.think_mean_ms,a.think_stddev_ms,a.session_pause_ms,a.session_stddev_ms)<0: p.error('Invalid timing/concurrency')
if a.scenario!='idle' and not a.users_file: p.error('--users-file is required')
if a.perfmon_interval_ms<1000 or a.perfmon_interval_ms%1000: p.error('PerfMon interval must be a whole number of seconds, at least 1000 ms')
agent_host=a.perfmon_host or a.host
if not a.no_perfmon: check_agent(agent_host,a.perfmon_port)
if a.shelly_interval_ms<1000 or a.shelly_switch_id<0:p.error('Invalid Shelly interval/switch ID')
shelly_info=None if a.no_shelly else shelly.check_plug(a.shelly_host,a.shelly_port,a.shelly_switch_id)
rows=[]
if a.users_file:
with open(a.users_file,newline='') as f:
@@ -54,7 +59,7 @@ for row in {r['account_id']:r for r in rows}.values():
overview=get('/api/patients/'+row['patient_id']+'/overview?from='+period_from+'&to='+period_to,token)
if overview['insight'] is None or overview['latestObservation'] is None: p.error('Seed patient history before running')
out=Path(a.output).resolve();out.mkdir(parents=True,mode=0o700,exist_ok=False)
metadata={'scenario':a.scenario,'users':a.users,'measurement_duration_seconds':a.duration,'warmup_seconds':a.warmup,'ramp_seconds':a.ramp,'think_mean_ms':a.think_mean_ms,'think_stddev_ms':a.think_stddev_ms,'session_pause_ms':a.session_pause_ms,'session_stddev_ms':a.session_stddev_ms,'random_seed':a.seed,'host':a.host,'port':a.port,'period_from':period_from,'period_to':period_to,'load_generator':platform.platform(),'distinct_accounts':len({r['account_id'] for r in rows}),'login':'initial login and renewal before expiry included','energy':'External power meter required; JMeter does not measure energy'}
metadata={'scenario':a.scenario,'users':a.users,'measurement_duration_seconds':a.duration,'warmup_seconds':a.warmup,'ramp_seconds':a.ramp,'think_mean_ms':a.think_mean_ms,'think_stddev_ms':a.think_stddev_ms,'session_pause_ms':a.session_pause_ms,'session_stddev_ms':a.session_stddev_ms,'random_seed':a.seed,'host':a.host,'port':a.port,'period_from':period_from,'period_to':period_to,'load_generator':platform.platform(),'distinct_accounts':len({r['account_id'] for r in rows}),'login':'initial login and renewal before expiry included','energy':'Shelly status polled live by JMeter; calculations exclude warmup'}
runtime_csv=out/'runtime-users.csv'
with runtime_csv.open('x') as f:
os.chmod(f.name,0o600); w=csv.DictWriter(f,fieldnames=['account_id','password','patient_id']);w.writeheader();w.writerows(rows)
@@ -62,10 +67,16 @@ source_plan=HERE/'plans'/(a.scenario+'.jmx');metadata['plan_sha256']=hashlib.sha
plan=out/'runtime.jmx'; document=E.parse(source_plan)
for collector in document.iter('kg.apc.jmeter.perfmon.PerfMonCollector'):
collector.set('enabled','false' if a.no_perfmon else 'true')
for group in document.iter('ThreadGroup'):
if group.get('testname')=='Shelly live power':group.set('enabled','false' if a.no_shelly else 'true')
document.write(plan,encoding='utf-8',xml_declaration=True)
cmd=[a.jmeter,'-n','-t',str(plan),'-l',str(out/'samples.csv'),'-j',str(out/'jmeter.log'),'-Jhost='+a.host,'-Jport='+str(a.port),'-Jusers_file='+str(runtime_csv),'-Jusers='+str(a.users),'-Jduration_seconds='+str(a.duration),'-Jwarmup_seconds='+str(a.warmup),'-Jtotal_duration_seconds='+str(a.warmup+a.duration+5),'-Jtimeline_file='+str(out/'timeline.json'),'-Jramp_seconds='+str(a.ramp),'-Jthink_mean_ms='+str(a.think_mean_ms),'-Jthink_stddev_ms='+str(a.think_stddev_ms),'-Jsession_pause_ms='+str(a.session_pause_ms),'-Jsession_stddev_ms='+str(a.session_stddev_ms),'-Jrandom_seed='+str(a.seed),'-Jperiod_from='+period_from,'-Jperiod_to='+period_to,'-Jjmeter.save.saveservice.autoflush=true','-Jjmeter.save.saveservice.output_format=csv','-Jjmeter.save.saveservice.print_field_names=true','-Jjmeter.save.saveservice.response_data=false','-Jjmeter.save.saveservice.samplerData=false','-Jjmeter.save.saveservice.requestHeaders=false','-Jjmeter.save.saveservice.responseHeaders=false']
drain_seconds=max(5,a.shelly_interval_ms//1000+5) if not a.no_shelly else 5
total_duration_seconds=a.warmup+a.duration+drain_seconds
cmd=[a.jmeter,'-n','-t',str(plan),'-l',str(out/'samples.csv'),'-j',str(out/'jmeter.log'),'-Jhost='+a.host,'-Jport='+str(a.port),'-Jusers_file='+str(runtime_csv),'-Jusers='+str(a.users),'-Jduration_seconds='+str(a.duration),'-Jwarmup_seconds='+str(a.warmup),'-Jtotal_duration_seconds='+str(total_duration_seconds),'-Jtimeline_file='+str(out/'timeline.json'),'-Jramp_seconds='+str(a.ramp),'-Jthink_mean_ms='+str(a.think_mean_ms),'-Jthink_stddev_ms='+str(a.think_stddev_ms),'-Jsession_pause_ms='+str(a.session_pause_ms),'-Jsession_stddev_ms='+str(a.session_stddev_ms),'-Jrandom_seed='+str(a.seed),'-Jperiod_from='+period_from,'-Jperiod_to='+period_to,'-Jjmeter.save.saveservice.autoflush=true','-Jjmeter.save.saveservice.output_format=csv','-Jjmeter.save.saveservice.print_field_names=true','-Jjmeter.save.saveservice.response_data=false','-Jjmeter.save.saveservice.samplerData=false','-Jjmeter.save.saveservice.requestHeaders=false','-Jjmeter.save.saveservice.responseHeaders=false']
metadata['jmeter_version']=subprocess.check_output([a.jmeter,'--version'],text=True).strip()
cmd += ['-Jperfmon_host='+agent_host,'-Jperfmon_port='+str(a.perfmon_port),'-Jperfmon_file='+str(out/'perfmon.csv'),'-JjmeterPlugin.perfmon.interval='+str(a.perfmon_interval_ms),'-JjmeterPlugin.perfmon.useUDP=false']
cmd += ['-Jshelly_host='+a.shelly_host,'-Jshelly_port='+str(a.shelly_port),'-Jshelly_switch_id='+str(a.shelly_switch_id),'-Jshelly_interval_ms='+str(a.shelly_interval_ms),'-Jshelly_file='+str(out/'shelly.csv'),'-Jsample_variables='+','.join(shelly.VARIABLES)]
metadata['shelly']={'enabled':not a.no_shelly,'host':a.shelly_host,'port':a.shelly_port,'switch_id':a.shelly_switch_id,'interval_ms':a.shelly_interval_ms,'device':shelly_info}
metadata['perfmon']={'enabled':not a.no_perfmon,'host':agent_host,'port':a.perfmon_port,'interval_ms':a.perfmon_interval_ms}
metadata['started_utc']=dt.datetime.now(dt.timezone.utc).isoformat(); started=time.monotonic()
(out/'run.json').write_text(json.dumps(metadata,indent=2))
@@ -102,6 +113,12 @@ if not a.no_perfmon:
print('Live PerfMon metrics saved and measurement interval validated')
except (OSError,ValueError,KeyError) as error:
metadata['monitoring_error']=str(error);print('Invalid monitoring:',error);code=1
if not a.no_shelly:
try:
metadata['power_energy']=shelly.summarize(out/'shelly.csv',out/'shelly-measured.csv',metadata['measurement_start_ms'],metadata['measurement_end_ms'],a.shelly_interval_ms)
print('Live Shelly power and measured-window energy saved')
except (OSError,ValueError,KeyError) as error:
metadata['power_error']=str(error);print('Invalid power measurement:',error);code=1
metadata['exit_code']=code
(out/'run.json').write_text(json.dumps(metadata,indent=2))
raise SystemExit(code)