From e50cf0a0116d02521b3e31be069b4e11a162837c Mon Sep 17 00:00:00 2001 From: Steffen Date: Wed, 7 Oct 2026 22:12:58 +0200 Subject: [PATCH] Collect Shelly plug power live in JMeter energy experiments --- tools/energy-jmeter/README.md | 55 +++++++++++++++- tools/energy-jmeter/generate-plans.py | 32 +++++++++- tools/energy-jmeter/plans/correction.jmx | 74 +++++++++++++++++++++- tools/energy-jmeter/plans/idle.jmx | 74 +++++++++++++++++++++- tools/energy-jmeter/plans/mixed.jmx | 74 +++++++++++++++++++++- tools/energy-jmeter/plans/professional.jmx | 74 +++++++++++++++++++++- tools/energy-jmeter/plans/recording.jmx | 74 +++++++++++++++++++++- tools/energy-jmeter/plans/review.jmx | 74 +++++++++++++++++++++- tools/energy-jmeter/run.py | 21 +++++- tools/energy-jmeter/shelly.py | 36 +++++++++++ tools/energy-jmeter/verify-perfmon.py | 6 +- tools/energy-jmeter/verify-plans.py | 6 +- tools/energy-jmeter/verify-shelly.py | 56 ++++++++++++++++ 13 files changed, 634 insertions(+), 22 deletions(-) create mode 100644 tools/energy-jmeter/shelly.py create mode 100644 tools/energy-jmeter/verify-shelly.py diff --git a/tools/energy-jmeter/README.md b/tools/energy-jmeter/README.md index dc82f99..f71bdaf 100644 --- a/tools/energy-jmeter/README.md +++ b/tools/energy-jmeter/README.md @@ -73,6 +73,54 @@ The validation fixture uses this switch and does not connect to the NUC. [PerfMon listener documentation](https://jmeter-plugins.org/wiki/PerfMon/), [agent metrics/protocol](https://github.com/undera/perfmon-agent). +## Live Shelly power in JMeter + +Every scenario, including idle, contains one **Shelly live power** thread. It polls +`http://192.168.1.44/rpc/Switch.GetStatus?id=0` every five seconds directly from +JMeter, independently of simulated users. There is no cloud dependency and no +post-run network transfer. No switch/set/reset commands are sent. + +`shelly.csv` is written while JMeter runs, with timestamps, request status, +`shelly_power_watts`, `shelly_voltage_volts`, `shelly_current_amps` and cumulative +`shelly_energy_wh`. Raw readings include warmup. `shelly-measured.csv` brackets only +the measured interval, interpolating its boundaries; `run.json` includes mean watts, +integrated joules/kWh and the counter's Wh delta converted to joules/kWh. +The timestamp is approximated by each polling request's midpoint on this computer. +Meter requests are excluded from the application's request-rate and latency summary. +JMeter's overall console summary includes meter polls; use `run.json` and +`measured.csv` for the application-only figures. + +Power integration uses trapezoids. Counter deltas provide a separate cross-check; +the device's counter update granularity can make short runs report little or no +counter change despite nonzero power. Both boundary interpolation and meter accuracy +limit precision; this does not claim calibration. The plug measures what is connected +to its outlet, including the NUC's power-adapter losses. Connect only the intended +measured equipment. Its internal temperature is **not the NUC CPU temperature**. + +The runner defaults to this plug and checks its status before starting. Override with +`--shelly-host`, `--shelly-port`, `--shelly-switch-id` or `--shelly-interval-ms`. +There is a short unmeasured drain after the four-hour window to obtain its closing +boundary. Missing samples, long gaps, failed polls and counter resets invalidate the +power measurement; they are not treated as zero watts. `--no-shelly` is for isolated +workflow testing, and records that power monitoring was disabled. The current plug +has authentication disabled; authenticated device access is not yet implemented. + +The runner configures JMeter's `sample_variables` so the numeric columns are saved. +For a manual GUI/CLI launch, pass: + +```bash +-Jsample_variables=shelly_power_watts,shelly_voltage_volts,shelly_current_amps,shelly_energy_wh +``` + +Use the runner for experiment timing, summaries and completeness checks. A new +power-monitoring-only check can be run without application requests: + +```bash +python3 tools/energy-jmeter/verify-shelly.py --host 192.168.1.44 --output tools/energy-jmeter/results/shelly-check-new +``` + +[Shelly switch status and energy units](https://shelly-api-docs.shelly.cloud/gen2/ComponentsAndServices/Switch/). + ## 1. Prepare distinct test accounts (outside measurement) The installer initially supplies only one ordinary patient account. Use distinct @@ -158,7 +206,7 @@ replaced. Do not use a partial/failed run as a successful four-hour measurement. ## 3. Run a full experiment -Start the external power recording **before** this command, on the NUC only: +Ensure the NUC is powered through the Shelly plug at **192.168.1.44**, then run: ```bash python3 tools/energy-jmeter/run.py mixed --host 192.168.1.125 --ca tools/energy-jmeter/.private/healthapp-ca.crt --users-file tools/energy-jmeter/.private/dataset/users.csv --users 100 --warmup 1800 --duration 14400 --output tools/energy-jmeter/results/mixed-100-run1 @@ -190,7 +238,7 @@ p95 latency, random seed, timings and plan hash. JMeter CSV excludes response bo request headers and passwords. The private runtime credential CSV is deleted at exit; keep the whole result directory private and inspect logs before sharing. -JMeter measures HTTP performance, **not energy**. Export your meter's readings as +JMeter now collects the Shelly readings live and the runner calculates measured-window energy automatically. For another external meter, export its readings as CSV with `timestamp,power_watts` (timezone-qualified ISO timestamps, increasing, covering the full interval), then integrate only the measured four hours: @@ -202,7 +250,7 @@ The tool interpolates interval edges and integrates watts using trapezoids. It r joules, kWh, mean watts and joules per HTTP request. `--idle-watts VALUE` additionally reports energy above the measured idle mean. A request is not a user session; compare scenario/mix and achieved throughput when interpreting efficiency. -Raw meter data must be preserved; missing intervals cannot be repaired by JMeter. +Raw meter data must be preserved; missing intervals cannot be repaired by JMeter. The same rule applies to Shelly polls. JMeter's stock HTTPS client trusts test certificates. The Python runner verifies the provided CA and hostname during preflight; JMeter traffic itself remains encrypted @@ -214,6 +262,7 @@ but does not provide certificate validation. Do not describe this as a TLS secur python3 tools/energy-jmeter/generate-plans.py python3 tools/energy-jmeter/verify-plans.py python3 tools/energy-jmeter/verify-perfmon.py +python3 tools/energy-jmeter/verify-shelly.py ``` The validation script exercises every plan against an isolated local HTTPS contract diff --git a/tools/energy-jmeter/generate-plans.py b/tools/energy-jmeter/generate-plans.py index ea2cf13..02ee796 100644 --- a/tools/energy-jmeter/generate-plans.py +++ b/tools/energy-jmeter/generate-plans.py @@ -70,12 +70,40 @@ def record(t, correction=False): request(t,'Remove duplicate test entry','DELETE','/api/observations/${observation_id}',status=204) request(t,'Confirm removal','GET','/api/observations/${observation_id}',status=404) +def shelly_group(tree): + group,gt=element(tree,'ThreadGroup','ThreadGroupGui','Shelly live power') + prop(group,'ThreadGroup.on_sample_error','continue') + loop=E.SubElement(group,'elementProp',name='ThreadGroup.main_controller',elementType='LoopController',guiclass='LoopControlPanel',testclass='LoopController',enabled='true') + prop(loop,'LoopController.continue_forever',False,'boolProp');prop(loop,'LoopController.loops',-1) + for k,v in [('ThreadGroup.num_threads','1'),('ThreadGroup.ramp_time','0'),('ThreadGroup.duration','${__P(total_duration_seconds,16210)}'),('ThreadGroup.delay','0')]:prop(group,k,v) + prop(group,'ThreadGroup.scheduler',True,'boolProp') + e,t=element(gt,'HTTPSamplerProxy','HttpTestSampleGui','POWER Shelly status') + E.SubElement(E.SubElement(e,'elementProp',name='HTTPsampler.Arguments',elementType='Arguments'),'collectionProp',name='Arguments.arguments') + for k,v in [('HTTPSampler.domain','${__P(shelly_host,192.168.1.44)}'),('HTTPSampler.port','${__P(shelly_port,80)}'),('HTTPSampler.protocol','http'),('HTTPSampler.path','/rpc/Switch.GetStatus?id=${__P(shelly_switch_id,0)}'),('HTTPSampler.method','GET'),('HTTPSampler.implementation','HttpClient4'),('HTTPSampler.connect_timeout','3000'),('HTTPSampler.response_timeout','3000')]:prop(e,k,v) + for k,v in [('HTTPSampler.follow_redirects',False),('HTTPSampler.use_keepalive',True)]:prop(e,k,v,'boolProp') + script(t,'JSR223Timer','Fixed meter cadence', "if (!vars.get('shelly_last_poll_ms')) return 0L; return Math.max(0L, Long.parseLong(vars.get('shelly_last_poll_ms')) + Long.parseLong(props.getProperty('shelly_interval_ms','5000')) - System.currentTimeMillis())") + script(t,'JSR223PreProcessor','Clear stale power values', "['shelly_power_watts','shelly_voltage_volts','shelly_current_amps','shelly_energy_wh'].each { vars.put(it,'') }") + script(t,'JSR223Assertion','Validate and extract plug readings', """vars.put('shelly_last_poll_ms',prev.getStartTime().toString()) +try { + assert prev.getResponseCode() == '200' + def json=new groovy.json.JsonSlurper().parseText(prev.getResponseDataAsString()) + assert json.output == true : 'Outlet is off' + def readings=[shelly_power_watts:json.apower,shelly_voltage_volts:json.voltage,shelly_current_amps:json.current,shelly_energy_wh:json.aenergy?.total] + readings.each { key,value -> assert value instanceof Number && Double.isFinite(value.doubleValue()) && value >= 0; vars.put(key,value.toString()) } +} catch (Throwable error) { + AssertionResult.setFailure(true);AssertionResult.setFailureMessage('Shelly status/measurement unavailable');prev.setSuccessful(false) +} +""") + collector,_=element(gt,'ResultCollector','SimpleDataWriter','Shelly measurements saved live') + prop(collector,'filename','${__P(shelly_file,shelly.csv)}');prop(collector,'ResultCollector.error_logging',False,'boolProp') + for scenario in ['recording','review','correction','professional','mixed','idle']: root=E.Element('jmeterTestPlan',version='1.2',properties='5.0',jmeter='5.6.3'); tree=E.SubElement(root,'hashTree') plan, pt=element(tree,'TestPlan','TestPlanGui','HealthApp energy: '+scenario) - prop(plan,'TestPlan.comments','Synthetic closed-loop sessions; default duration four hours. Setup and energy-meter control are external.') + prop(plan,'TestPlan.comments','Synthetic closed-loop sessions; default duration four hours. Setup is external; Shelly power is collected live without changing the outlet.') prop(plan,'TestPlan.functional_mode',False,'boolProp'); prop(plan,'TestPlan.serialize_threadgroups',False,'boolProp') E.SubElement(E.SubElement(plan,'elementProp',name='TestPlan.user_defined_variables',elementType='Arguments',guiclass='ArgumentsPanel',testclass='Arguments',enabled='true'),'collectionProp',name='Arguments.arguments') + shelly_group(pt) collector, _ = element(pt,'kg.apc.jmeter.perfmon.PerfMonCollector','kg.apc.jmeter.vizualizers.PerfMonGui','NUC live CPU RAM disk and network') collector.set('enabled','true') prop(collector,'filename','${__P(perfmon_file,perfmon.csv)}') @@ -88,7 +116,7 @@ for scenario in ['recording','review','correction','professional','mixed','idle' prop(group,'ThreadGroup.on_sample_error','stopthread') loop=E.SubElement(group,'elementProp',name='ThreadGroup.main_controller',elementType='LoopController',guiclass='LoopControlPanel',testclass='LoopController',enabled='true') prop(loop,'LoopController.continue_forever',False,'boolProp'); prop(loop,'LoopController.loops',-1) - for k,v in [('ThreadGroup.num_threads','${__P(users,1)}'),('ThreadGroup.ramp_time','${__P(ramp_seconds,60)}'),('ThreadGroup.duration','${__P(total_duration_seconds,16205)}'),('ThreadGroup.delay','0')]: prop(group,k,v) + for k,v in [('ThreadGroup.num_threads','${__P(users,1)}'),('ThreadGroup.ramp_time','${__P(ramp_seconds,60)}'),('ThreadGroup.duration','${__P(total_duration_seconds,16210)}'),('ThreadGroup.delay','0')]: prop(group,k,v) prop(group,'ThreadGroup.scheduler',True,'boolProp'); prop(group,'ThreadGroup.same_user_on_next_iteration',True,'boolProp') if scenario=='idle': prop(group,'ThreadGroup.num_threads','1');prop(group,'ThreadGroup.ramp_time','0') diff --git a/tools/energy-jmeter/plans/correction.jmx b/tools/energy-jmeter/plans/correction.jmx index 29a484b..88b5159 100644 --- a/tools/energy-jmeter/plans/correction.jmx +++ b/tools/energy-jmeter/plans/correction.jmx @@ -2,7 +2,7 @@ - Synthetic closed-loop sessions; default duration four hours. Setup and energy-meter control are external. + Synthetic closed-loop sessions; default duration four hours. Setup is external; Shelly power is collected live without changing the outlet. false false @@ -10,6 +10,76 @@ + + continue + + false + -1 + + 1 + 0 + ${__P(total_duration_seconds,16210)} + 0 + true + + + + + + + ${__P(shelly_host,192.168.1.44)} + ${__P(shelly_port,80)} + http + /rpc/Switch.GetStatus?id=${__P(shelly_switch_id,0)} + GET + HttpClient4 + 3000 + 3000 + false + true + + + + groovy + true + + + if (!vars.get('shelly_last_poll_ms')) return 0L; return Math.max(0L, Long.parseLong(vars.get('shelly_last_poll_ms')) + Long.parseLong(props.getProperty('shelly_interval_ms','5000')) - System.currentTimeMillis()) + + + + groovy + true + + + ['shelly_power_watts','shelly_voltage_volts','shelly_current_amps','shelly_energy_wh'].each { vars.put(it,'') } + + + + groovy + true + + + vars.put('shelly_last_poll_ms',prev.getStartTime().toString()) +try { + assert prev.getResponseCode() == '200' + def json=new groovy.json.JsonSlurper().parseText(prev.getResponseDataAsString()) + assert json.output == true : 'Outlet is off' + def readings=[shelly_power_watts:json.apower,shelly_voltage_volts:json.voltage,shelly_current_amps:json.current,shelly_energy_wh:json.aenergy?.total] + readings.each { key,value -> assert value instanceof Number && Double.isFinite(value.doubleValue()) && value >= 0; vars.put(key,value.toString()) } +} catch (Throwable error) { + AssertionResult.setFailure(true);AssertionResult.setFailureMessage('Shelly status/measurement unavailable');prev.setSuccessful(false) +} + + + + + + ${__P(shelly_file,shelly.csv)} + false + + + ${__P(perfmon_file,perfmon.csv)} false @@ -79,7 +149,7 @@ ${__P(users,1)} ${__P(ramp_seconds,60)} - ${__P(total_duration_seconds,16205)} + ${__P(total_duration_seconds,16210)} 0 true true diff --git a/tools/energy-jmeter/plans/idle.jmx b/tools/energy-jmeter/plans/idle.jmx index a74ffc4..9ebc942 100644 --- a/tools/energy-jmeter/plans/idle.jmx +++ b/tools/energy-jmeter/plans/idle.jmx @@ -2,7 +2,7 @@ - Synthetic closed-loop sessions; default duration four hours. Setup and energy-meter control are external. + Synthetic closed-loop sessions; default duration four hours. Setup is external; Shelly power is collected live without changing the outlet. false false @@ -10,6 +10,76 @@ + + continue + + false + -1 + + 1 + 0 + ${__P(total_duration_seconds,16210)} + 0 + true + + + + + + + ${__P(shelly_host,192.168.1.44)} + ${__P(shelly_port,80)} + http + /rpc/Switch.GetStatus?id=${__P(shelly_switch_id,0)} + GET + HttpClient4 + 3000 + 3000 + false + true + + + + groovy + true + + + if (!vars.get('shelly_last_poll_ms')) return 0L; return Math.max(0L, Long.parseLong(vars.get('shelly_last_poll_ms')) + Long.parseLong(props.getProperty('shelly_interval_ms','5000')) - System.currentTimeMillis()) + + + + groovy + true + + + ['shelly_power_watts','shelly_voltage_volts','shelly_current_amps','shelly_energy_wh'].each { vars.put(it,'') } + + + + groovy + true + + + vars.put('shelly_last_poll_ms',prev.getStartTime().toString()) +try { + assert prev.getResponseCode() == '200' + def json=new groovy.json.JsonSlurper().parseText(prev.getResponseDataAsString()) + assert json.output == true : 'Outlet is off' + def readings=[shelly_power_watts:json.apower,shelly_voltage_volts:json.voltage,shelly_current_amps:json.current,shelly_energy_wh:json.aenergy?.total] + readings.each { key,value -> assert value instanceof Number && Double.isFinite(value.doubleValue()) && value >= 0; vars.put(key,value.toString()) } +} catch (Throwable error) { + AssertionResult.setFailure(true);AssertionResult.setFailureMessage('Shelly status/measurement unavailable');prev.setSuccessful(false) +} + + + + + + ${__P(shelly_file,shelly.csv)} + false + + + ${__P(perfmon_file,perfmon.csv)} false @@ -79,7 +149,7 @@ ${__P(users,1)} ${__P(ramp_seconds,60)} - ${__P(total_duration_seconds,16205)} + ${__P(total_duration_seconds,16210)} 0 true true diff --git a/tools/energy-jmeter/plans/mixed.jmx b/tools/energy-jmeter/plans/mixed.jmx index 41404db..43a79d2 100644 --- a/tools/energy-jmeter/plans/mixed.jmx +++ b/tools/energy-jmeter/plans/mixed.jmx @@ -2,7 +2,7 @@ - Synthetic closed-loop sessions; default duration four hours. Setup and energy-meter control are external. + Synthetic closed-loop sessions; default duration four hours. Setup is external; Shelly power is collected live without changing the outlet. false false @@ -10,6 +10,76 @@ + + continue + + false + -1 + + 1 + 0 + ${__P(total_duration_seconds,16210)} + 0 + true + + + + + + + ${__P(shelly_host,192.168.1.44)} + ${__P(shelly_port,80)} + http + /rpc/Switch.GetStatus?id=${__P(shelly_switch_id,0)} + GET + HttpClient4 + 3000 + 3000 + false + true + + + + groovy + true + + + if (!vars.get('shelly_last_poll_ms')) return 0L; return Math.max(0L, Long.parseLong(vars.get('shelly_last_poll_ms')) + Long.parseLong(props.getProperty('shelly_interval_ms','5000')) - System.currentTimeMillis()) + + + + groovy + true + + + ['shelly_power_watts','shelly_voltage_volts','shelly_current_amps','shelly_energy_wh'].each { vars.put(it,'') } + + + + groovy + true + + + vars.put('shelly_last_poll_ms',prev.getStartTime().toString()) +try { + assert prev.getResponseCode() == '200' + def json=new groovy.json.JsonSlurper().parseText(prev.getResponseDataAsString()) + assert json.output == true : 'Outlet is off' + def readings=[shelly_power_watts:json.apower,shelly_voltage_volts:json.voltage,shelly_current_amps:json.current,shelly_energy_wh:json.aenergy?.total] + readings.each { key,value -> assert value instanceof Number && Double.isFinite(value.doubleValue()) && value >= 0; vars.put(key,value.toString()) } +} catch (Throwable error) { + AssertionResult.setFailure(true);AssertionResult.setFailureMessage('Shelly status/measurement unavailable');prev.setSuccessful(false) +} + + + + + + ${__P(shelly_file,shelly.csv)} + false + + + ${__P(perfmon_file,perfmon.csv)} false @@ -79,7 +149,7 @@ ${__P(users,1)} ${__P(ramp_seconds,60)} - ${__P(total_duration_seconds,16205)} + ${__P(total_duration_seconds,16210)} 0 true true diff --git a/tools/energy-jmeter/plans/professional.jmx b/tools/energy-jmeter/plans/professional.jmx index d76b848..de4f7e7 100644 --- a/tools/energy-jmeter/plans/professional.jmx +++ b/tools/energy-jmeter/plans/professional.jmx @@ -2,7 +2,7 @@ - Synthetic closed-loop sessions; default duration four hours. Setup and energy-meter control are external. + Synthetic closed-loop sessions; default duration four hours. Setup is external; Shelly power is collected live without changing the outlet. false false @@ -10,6 +10,76 @@ + + continue + + false + -1 + + 1 + 0 + ${__P(total_duration_seconds,16210)} + 0 + true + + + + + + + ${__P(shelly_host,192.168.1.44)} + ${__P(shelly_port,80)} + http + /rpc/Switch.GetStatus?id=${__P(shelly_switch_id,0)} + GET + HttpClient4 + 3000 + 3000 + false + true + + + + groovy + true + + + if (!vars.get('shelly_last_poll_ms')) return 0L; return Math.max(0L, Long.parseLong(vars.get('shelly_last_poll_ms')) + Long.parseLong(props.getProperty('shelly_interval_ms','5000')) - System.currentTimeMillis()) + + + + groovy + true + + + ['shelly_power_watts','shelly_voltage_volts','shelly_current_amps','shelly_energy_wh'].each { vars.put(it,'') } + + + + groovy + true + + + vars.put('shelly_last_poll_ms',prev.getStartTime().toString()) +try { + assert prev.getResponseCode() == '200' + def json=new groovy.json.JsonSlurper().parseText(prev.getResponseDataAsString()) + assert json.output == true : 'Outlet is off' + def readings=[shelly_power_watts:json.apower,shelly_voltage_volts:json.voltage,shelly_current_amps:json.current,shelly_energy_wh:json.aenergy?.total] + readings.each { key,value -> assert value instanceof Number && Double.isFinite(value.doubleValue()) && value >= 0; vars.put(key,value.toString()) } +} catch (Throwable error) { + AssertionResult.setFailure(true);AssertionResult.setFailureMessage('Shelly status/measurement unavailable');prev.setSuccessful(false) +} + + + + + + ${__P(shelly_file,shelly.csv)} + false + + + ${__P(perfmon_file,perfmon.csv)} false @@ -79,7 +149,7 @@ ${__P(users,1)} ${__P(ramp_seconds,60)} - ${__P(total_duration_seconds,16205)} + ${__P(total_duration_seconds,16210)} 0 true true diff --git a/tools/energy-jmeter/plans/recording.jmx b/tools/energy-jmeter/plans/recording.jmx index bbe20f2..6e62581 100644 --- a/tools/energy-jmeter/plans/recording.jmx +++ b/tools/energy-jmeter/plans/recording.jmx @@ -2,7 +2,7 @@ - Synthetic closed-loop sessions; default duration four hours. Setup and energy-meter control are external. + Synthetic closed-loop sessions; default duration four hours. Setup is external; Shelly power is collected live without changing the outlet. false false @@ -10,6 +10,76 @@ + + continue + + false + -1 + + 1 + 0 + ${__P(total_duration_seconds,16210)} + 0 + true + + + + + + + ${__P(shelly_host,192.168.1.44)} + ${__P(shelly_port,80)} + http + /rpc/Switch.GetStatus?id=${__P(shelly_switch_id,0)} + GET + HttpClient4 + 3000 + 3000 + false + true + + + + groovy + true + + + if (!vars.get('shelly_last_poll_ms')) return 0L; return Math.max(0L, Long.parseLong(vars.get('shelly_last_poll_ms')) + Long.parseLong(props.getProperty('shelly_interval_ms','5000')) - System.currentTimeMillis()) + + + + groovy + true + + + ['shelly_power_watts','shelly_voltage_volts','shelly_current_amps','shelly_energy_wh'].each { vars.put(it,'') } + + + + groovy + true + + + vars.put('shelly_last_poll_ms',prev.getStartTime().toString()) +try { + assert prev.getResponseCode() == '200' + def json=new groovy.json.JsonSlurper().parseText(prev.getResponseDataAsString()) + assert json.output == true : 'Outlet is off' + def readings=[shelly_power_watts:json.apower,shelly_voltage_volts:json.voltage,shelly_current_amps:json.current,shelly_energy_wh:json.aenergy?.total] + readings.each { key,value -> assert value instanceof Number && Double.isFinite(value.doubleValue()) && value >= 0; vars.put(key,value.toString()) } +} catch (Throwable error) { + AssertionResult.setFailure(true);AssertionResult.setFailureMessage('Shelly status/measurement unavailable');prev.setSuccessful(false) +} + + + + + + ${__P(shelly_file,shelly.csv)} + false + + + ${__P(perfmon_file,perfmon.csv)} false @@ -79,7 +149,7 @@ ${__P(users,1)} ${__P(ramp_seconds,60)} - ${__P(total_duration_seconds,16205)} + ${__P(total_duration_seconds,16210)} 0 true true diff --git a/tools/energy-jmeter/plans/review.jmx b/tools/energy-jmeter/plans/review.jmx index 0529782..dd36f91 100644 --- a/tools/energy-jmeter/plans/review.jmx +++ b/tools/energy-jmeter/plans/review.jmx @@ -2,7 +2,7 @@ - Synthetic closed-loop sessions; default duration four hours. Setup and energy-meter control are external. + Synthetic closed-loop sessions; default duration four hours. Setup is external; Shelly power is collected live without changing the outlet. false false @@ -10,6 +10,76 @@ + + continue + + false + -1 + + 1 + 0 + ${__P(total_duration_seconds,16210)} + 0 + true + + + + + + + ${__P(shelly_host,192.168.1.44)} + ${__P(shelly_port,80)} + http + /rpc/Switch.GetStatus?id=${__P(shelly_switch_id,0)} + GET + HttpClient4 + 3000 + 3000 + false + true + + + + groovy + true + + + if (!vars.get('shelly_last_poll_ms')) return 0L; return Math.max(0L, Long.parseLong(vars.get('shelly_last_poll_ms')) + Long.parseLong(props.getProperty('shelly_interval_ms','5000')) - System.currentTimeMillis()) + + + + groovy + true + + + ['shelly_power_watts','shelly_voltage_volts','shelly_current_amps','shelly_energy_wh'].each { vars.put(it,'') } + + + + groovy + true + + + vars.put('shelly_last_poll_ms',prev.getStartTime().toString()) +try { + assert prev.getResponseCode() == '200' + def json=new groovy.json.JsonSlurper().parseText(prev.getResponseDataAsString()) + assert json.output == true : 'Outlet is off' + def readings=[shelly_power_watts:json.apower,shelly_voltage_volts:json.voltage,shelly_current_amps:json.current,shelly_energy_wh:json.aenergy?.total] + readings.each { key,value -> assert value instanceof Number && Double.isFinite(value.doubleValue()) && value >= 0; vars.put(key,value.toString()) } +} catch (Throwable error) { + AssertionResult.setFailure(true);AssertionResult.setFailureMessage('Shelly status/measurement unavailable');prev.setSuccessful(false) +} + + + + + + ${__P(shelly_file,shelly.csv)} + false + + + ${__P(perfmon_file,perfmon.csv)} false @@ -79,7 +149,7 @@ ${__P(users,1)} ${__P(ramp_seconds,60)} - ${__P(total_duration_seconds,16205)} + ${__P(total_duration_seconds,16210)} 0 true true diff --git a/tools/energy-jmeter/run.py b/tools/energy-jmeter/run.py index f1fc595..0b0ab8b 100644 --- a/tools/energy-jmeter/run.py +++ b/tools/energy-jmeter/run.py @@ -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) diff --git a/tools/energy-jmeter/shelly.py b/tools/energy-jmeter/shelly.py new file mode 100644 index 0000000..eaabea1 --- /dev/null +++ b/tools/energy-jmeter/shelly.py @@ -0,0 +1,36 @@ +"""Shelly read-only preflight and measured-window energy calculations.""" +import csv, json, math, urllib.request +VARIABLES=['shelly_power_watts','shelly_voltage_volts','shelly_current_amps','shelly_energy_wh'] +def check_plug(host,port=80,switch_id=0): + def read(method): + with urllib.request.urlopen(f'http://{host}:{port}/rpc/{method}',timeout=5) as r:return json.load(r) + info=read('Shelly.GetDeviceInfo');status=read(f'Switch.GetStatus?id={switch_id}') + if info.get('auth_en'):raise ValueError('Shelly authentication is enabled; this integration requires the current unauthenticated LAN API') + if status.get('output') is not True:raise ValueError('Shelly outlet is off') + values=[status.get('apower'),status.get('voltage'),status.get('current'),status.get('aenergy',{}).get('total')] + if any(not isinstance(v,(float,int)) or not math.isfinite(v) or v<0 for v in values):raise ValueError('Shelly power/voltage/current/energy readings are unavailable') + return {k:info.get(k) for k in ['model','gen','ver','app']} +def summarize(raw,measured,start_ms,end_ms,interval_ms): + with raw.open() as f:rows=list(csv.DictReader(f)) + points=[] + for row in rows: + if row['label']!='POWER Shelly status':continue + if row['success'].lower()!='true':raise ValueError('A Shelly status poll failed; energy measurement is incomplete') + values=[float(row[k]) for k in VARIABLES] + if any(not math.isfinite(v) or v<0 for v in values):raise ValueError('Invalid Shelly metric') + # Approximate the device sampling instant by the HTTP request midpoint. + timestamp=int(row['timeStamp'])+int(row['elapsed'])/2 + points.append((timestamp,*values)) + points.sort() + if len(points)<2 or points[0][0]>start_ms or points[-1][0]interval_ms*3 or b[4]0 print('Unexpected upstream failure correctly invalidates the run') diff --git a/tools/energy-jmeter/verify-shelly.py b/tools/energy-jmeter/verify-shelly.py new file mode 100644 index 0000000..3436185 --- /dev/null +++ b/tools/energy-jmeter/verify-shelly.py @@ -0,0 +1,56 @@ +#!/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 + 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=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')