Collect Shelly plug power live in JMeter energy experiments
This commit is contained in:
1 parent
a69b9b2118
commit
e50cf0a011
13 files changed
+634
-22
No files matched your search
@@ -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
|
||||
|
||||
@@ -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')
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
<jmeterTestPlan version="1.2" properties="5.0" jmeter="5.6.3">
|
||||
<hashTree>
|
||||
<TestPlan guiclass="TestPlanGui" testclass="TestPlan" testname="HealthApp energy: correction" enabled="true">
|
||||
<stringProp name="TestPlan.comments">Synthetic closed-loop sessions; default duration four hours. Setup and energy-meter control are external.</stringProp>
|
||||
<stringProp name="TestPlan.comments">Synthetic closed-loop sessions; default duration four hours. Setup is external; Shelly power is collected live without changing the outlet.</stringProp>
|
||||
<boolProp name="TestPlan.functional_mode">false</boolProp>
|
||||
<boolProp name="TestPlan.serialize_threadgroups">false</boolProp>
|
||||
<elementProp name="TestPlan.user_defined_variables" elementType="Arguments" guiclass="ArgumentsPanel" testclass="Arguments" enabled="true">
|
||||
@@ -10,6 +10,76 @@
|
||||
</elementProp>
|
||||
</TestPlan>
|
||||
<hashTree>
|
||||
<ThreadGroup guiclass="ThreadGroupGui" testclass="ThreadGroup" testname="Shelly live power" enabled="true">
|
||||
<stringProp name="ThreadGroup.on_sample_error">continue</stringProp>
|
||||
<elementProp name="ThreadGroup.main_controller" elementType="LoopController" guiclass="LoopControlPanel" testclass="LoopController" enabled="true">
|
||||
<boolProp name="LoopController.continue_forever">false</boolProp>
|
||||
<stringProp name="LoopController.loops">-1</stringProp>
|
||||
</elementProp>
|
||||
<stringProp name="ThreadGroup.num_threads">1</stringProp>
|
||||
<stringProp name="ThreadGroup.ramp_time">0</stringProp>
|
||||
<stringProp name="ThreadGroup.duration">${__P(total_duration_seconds,16210)}</stringProp>
|
||||
<stringProp name="ThreadGroup.delay">0</stringProp>
|
||||
<boolProp name="ThreadGroup.scheduler">true</boolProp>
|
||||
</ThreadGroup>
|
||||
<hashTree>
|
||||
<HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="POWER Shelly status" enabled="true">
|
||||
<elementProp name="HTTPsampler.Arguments" elementType="Arguments">
|
||||
<collectionProp name="Arguments.arguments" />
|
||||
</elementProp>
|
||||
<stringProp name="HTTPSampler.domain">${__P(shelly_host,192.168.1.44)}</stringProp>
|
||||
<stringProp name="HTTPSampler.port">${__P(shelly_port,80)}</stringProp>
|
||||
<stringProp name="HTTPSampler.protocol">http</stringProp>
|
||||
<stringProp name="HTTPSampler.path">/rpc/Switch.GetStatus?id=${__P(shelly_switch_id,0)}</stringProp>
|
||||
<stringProp name="HTTPSampler.method">GET</stringProp>
|
||||
<stringProp name="HTTPSampler.implementation">HttpClient4</stringProp>
|
||||
<stringProp name="HTTPSampler.connect_timeout">3000</stringProp>
|
||||
<stringProp name="HTTPSampler.response_timeout">3000</stringProp>
|
||||
<boolProp name="HTTPSampler.follow_redirects">false</boolProp>
|
||||
<boolProp name="HTTPSampler.use_keepalive">true</boolProp>
|
||||
</HTTPSamplerProxy>
|
||||
<hashTree>
|
||||
<JSR223Timer guiclass="JSR223TimerGui" testclass="JSR223Timer" testname="Fixed meter cadence" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">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())</stringProp>
|
||||
</JSR223Timer>
|
||||
<hashTree />
|
||||
<JSR223PreProcessor guiclass="JSR223PreProcessorGui" testclass="JSR223PreProcessor" testname="Clear stale power values" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">['shelly_power_watts','shelly_voltage_volts','shelly_current_amps','shelly_energy_wh'].each { vars.put(it,'') }</stringProp>
|
||||
</JSR223PreProcessor>
|
||||
<hashTree />
|
||||
<JSR223Assertion guiclass="JSR223AssertionGui" testclass="JSR223Assertion" testname="Validate and extract plug readings" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">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)
|
||||
}
|
||||
</stringProp>
|
||||
</JSR223Assertion>
|
||||
<hashTree />
|
||||
</hashTree>
|
||||
<ResultCollector guiclass="SimpleDataWriter" testclass="ResultCollector" testname="Shelly measurements saved live" enabled="true">
|
||||
<stringProp name="filename">${__P(shelly_file,shelly.csv)}</stringProp>
|
||||
<boolProp name="ResultCollector.error_logging">false</boolProp>
|
||||
</ResultCollector>
|
||||
<hashTree />
|
||||
</hashTree>
|
||||
<kg.apc.jmeter.perfmon.PerfMonCollector guiclass="kg.apc.jmeter.vizualizers.PerfMonGui" testclass="kg.apc.jmeter.perfmon.PerfMonCollector" testname="NUC live CPU RAM disk and network" enabled="true">
|
||||
<stringProp name="filename">${__P(perfmon_file,perfmon.csv)}</stringProp>
|
||||
<boolProp name="ResultCollector.error_logging">false</boolProp>
|
||||
@@ -79,7 +149,7 @@
|
||||
</elementProp>
|
||||
<stringProp name="ThreadGroup.num_threads">${__P(users,1)}</stringProp>
|
||||
<stringProp name="ThreadGroup.ramp_time">${__P(ramp_seconds,60)}</stringProp>
|
||||
<stringProp name="ThreadGroup.duration">${__P(total_duration_seconds,16205)}</stringProp>
|
||||
<stringProp name="ThreadGroup.duration">${__P(total_duration_seconds,16210)}</stringProp>
|
||||
<stringProp name="ThreadGroup.delay">0</stringProp>
|
||||
<boolProp name="ThreadGroup.scheduler">true</boolProp>
|
||||
<boolProp name="ThreadGroup.same_user_on_next_iteration">true</boolProp>
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
<jmeterTestPlan version="1.2" properties="5.0" jmeter="5.6.3">
|
||||
<hashTree>
|
||||
<TestPlan guiclass="TestPlanGui" testclass="TestPlan" testname="HealthApp energy: idle" enabled="true">
|
||||
<stringProp name="TestPlan.comments">Synthetic closed-loop sessions; default duration four hours. Setup and energy-meter control are external.</stringProp>
|
||||
<stringProp name="TestPlan.comments">Synthetic closed-loop sessions; default duration four hours. Setup is external; Shelly power is collected live without changing the outlet.</stringProp>
|
||||
<boolProp name="TestPlan.functional_mode">false</boolProp>
|
||||
<boolProp name="TestPlan.serialize_threadgroups">false</boolProp>
|
||||
<elementProp name="TestPlan.user_defined_variables" elementType="Arguments" guiclass="ArgumentsPanel" testclass="Arguments" enabled="true">
|
||||
@@ -10,6 +10,76 @@
|
||||
</elementProp>
|
||||
</TestPlan>
|
||||
<hashTree>
|
||||
<ThreadGroup guiclass="ThreadGroupGui" testclass="ThreadGroup" testname="Shelly live power" enabled="true">
|
||||
<stringProp name="ThreadGroup.on_sample_error">continue</stringProp>
|
||||
<elementProp name="ThreadGroup.main_controller" elementType="LoopController" guiclass="LoopControlPanel" testclass="LoopController" enabled="true">
|
||||
<boolProp name="LoopController.continue_forever">false</boolProp>
|
||||
<stringProp name="LoopController.loops">-1</stringProp>
|
||||
</elementProp>
|
||||
<stringProp name="ThreadGroup.num_threads">1</stringProp>
|
||||
<stringProp name="ThreadGroup.ramp_time">0</stringProp>
|
||||
<stringProp name="ThreadGroup.duration">${__P(total_duration_seconds,16210)}</stringProp>
|
||||
<stringProp name="ThreadGroup.delay">0</stringProp>
|
||||
<boolProp name="ThreadGroup.scheduler">true</boolProp>
|
||||
</ThreadGroup>
|
||||
<hashTree>
|
||||
<HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="POWER Shelly status" enabled="true">
|
||||
<elementProp name="HTTPsampler.Arguments" elementType="Arguments">
|
||||
<collectionProp name="Arguments.arguments" />
|
||||
</elementProp>
|
||||
<stringProp name="HTTPSampler.domain">${__P(shelly_host,192.168.1.44)}</stringProp>
|
||||
<stringProp name="HTTPSampler.port">${__P(shelly_port,80)}</stringProp>
|
||||
<stringProp name="HTTPSampler.protocol">http</stringProp>
|
||||
<stringProp name="HTTPSampler.path">/rpc/Switch.GetStatus?id=${__P(shelly_switch_id,0)}</stringProp>
|
||||
<stringProp name="HTTPSampler.method">GET</stringProp>
|
||||
<stringProp name="HTTPSampler.implementation">HttpClient4</stringProp>
|
||||
<stringProp name="HTTPSampler.connect_timeout">3000</stringProp>
|
||||
<stringProp name="HTTPSampler.response_timeout">3000</stringProp>
|
||||
<boolProp name="HTTPSampler.follow_redirects">false</boolProp>
|
||||
<boolProp name="HTTPSampler.use_keepalive">true</boolProp>
|
||||
</HTTPSamplerProxy>
|
||||
<hashTree>
|
||||
<JSR223Timer guiclass="JSR223TimerGui" testclass="JSR223Timer" testname="Fixed meter cadence" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">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())</stringProp>
|
||||
</JSR223Timer>
|
||||
<hashTree />
|
||||
<JSR223PreProcessor guiclass="JSR223PreProcessorGui" testclass="JSR223PreProcessor" testname="Clear stale power values" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">['shelly_power_watts','shelly_voltage_volts','shelly_current_amps','shelly_energy_wh'].each { vars.put(it,'') }</stringProp>
|
||||
</JSR223PreProcessor>
|
||||
<hashTree />
|
||||
<JSR223Assertion guiclass="JSR223AssertionGui" testclass="JSR223Assertion" testname="Validate and extract plug readings" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">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)
|
||||
}
|
||||
</stringProp>
|
||||
</JSR223Assertion>
|
||||
<hashTree />
|
||||
</hashTree>
|
||||
<ResultCollector guiclass="SimpleDataWriter" testclass="ResultCollector" testname="Shelly measurements saved live" enabled="true">
|
||||
<stringProp name="filename">${__P(shelly_file,shelly.csv)}</stringProp>
|
||||
<boolProp name="ResultCollector.error_logging">false</boolProp>
|
||||
</ResultCollector>
|
||||
<hashTree />
|
||||
</hashTree>
|
||||
<kg.apc.jmeter.perfmon.PerfMonCollector guiclass="kg.apc.jmeter.vizualizers.PerfMonGui" testclass="kg.apc.jmeter.perfmon.PerfMonCollector" testname="NUC live CPU RAM disk and network" enabled="true">
|
||||
<stringProp name="filename">${__P(perfmon_file,perfmon.csv)}</stringProp>
|
||||
<boolProp name="ResultCollector.error_logging">false</boolProp>
|
||||
@@ -79,7 +149,7 @@
|
||||
</elementProp>
|
||||
<stringProp name="ThreadGroup.num_threads">${__P(users,1)}</stringProp>
|
||||
<stringProp name="ThreadGroup.ramp_time">${__P(ramp_seconds,60)}</stringProp>
|
||||
<stringProp name="ThreadGroup.duration">${__P(total_duration_seconds,16205)}</stringProp>
|
||||
<stringProp name="ThreadGroup.duration">${__P(total_duration_seconds,16210)}</stringProp>
|
||||
<stringProp name="ThreadGroup.delay">0</stringProp>
|
||||
<boolProp name="ThreadGroup.scheduler">true</boolProp>
|
||||
<boolProp name="ThreadGroup.same_user_on_next_iteration">true</boolProp>
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
<jmeterTestPlan version="1.2" properties="5.0" jmeter="5.6.3">
|
||||
<hashTree>
|
||||
<TestPlan guiclass="TestPlanGui" testclass="TestPlan" testname="HealthApp energy: mixed" enabled="true">
|
||||
<stringProp name="TestPlan.comments">Synthetic closed-loop sessions; default duration four hours. Setup and energy-meter control are external.</stringProp>
|
||||
<stringProp name="TestPlan.comments">Synthetic closed-loop sessions; default duration four hours. Setup is external; Shelly power is collected live without changing the outlet.</stringProp>
|
||||
<boolProp name="TestPlan.functional_mode">false</boolProp>
|
||||
<boolProp name="TestPlan.serialize_threadgroups">false</boolProp>
|
||||
<elementProp name="TestPlan.user_defined_variables" elementType="Arguments" guiclass="ArgumentsPanel" testclass="Arguments" enabled="true">
|
||||
@@ -10,6 +10,76 @@
|
||||
</elementProp>
|
||||
</TestPlan>
|
||||
<hashTree>
|
||||
<ThreadGroup guiclass="ThreadGroupGui" testclass="ThreadGroup" testname="Shelly live power" enabled="true">
|
||||
<stringProp name="ThreadGroup.on_sample_error">continue</stringProp>
|
||||
<elementProp name="ThreadGroup.main_controller" elementType="LoopController" guiclass="LoopControlPanel" testclass="LoopController" enabled="true">
|
||||
<boolProp name="LoopController.continue_forever">false</boolProp>
|
||||
<stringProp name="LoopController.loops">-1</stringProp>
|
||||
</elementProp>
|
||||
<stringProp name="ThreadGroup.num_threads">1</stringProp>
|
||||
<stringProp name="ThreadGroup.ramp_time">0</stringProp>
|
||||
<stringProp name="ThreadGroup.duration">${__P(total_duration_seconds,16210)}</stringProp>
|
||||
<stringProp name="ThreadGroup.delay">0</stringProp>
|
||||
<boolProp name="ThreadGroup.scheduler">true</boolProp>
|
||||
</ThreadGroup>
|
||||
<hashTree>
|
||||
<HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="POWER Shelly status" enabled="true">
|
||||
<elementProp name="HTTPsampler.Arguments" elementType="Arguments">
|
||||
<collectionProp name="Arguments.arguments" />
|
||||
</elementProp>
|
||||
<stringProp name="HTTPSampler.domain">${__P(shelly_host,192.168.1.44)}</stringProp>
|
||||
<stringProp name="HTTPSampler.port">${__P(shelly_port,80)}</stringProp>
|
||||
<stringProp name="HTTPSampler.protocol">http</stringProp>
|
||||
<stringProp name="HTTPSampler.path">/rpc/Switch.GetStatus?id=${__P(shelly_switch_id,0)}</stringProp>
|
||||
<stringProp name="HTTPSampler.method">GET</stringProp>
|
||||
<stringProp name="HTTPSampler.implementation">HttpClient4</stringProp>
|
||||
<stringProp name="HTTPSampler.connect_timeout">3000</stringProp>
|
||||
<stringProp name="HTTPSampler.response_timeout">3000</stringProp>
|
||||
<boolProp name="HTTPSampler.follow_redirects">false</boolProp>
|
||||
<boolProp name="HTTPSampler.use_keepalive">true</boolProp>
|
||||
</HTTPSamplerProxy>
|
||||
<hashTree>
|
||||
<JSR223Timer guiclass="JSR223TimerGui" testclass="JSR223Timer" testname="Fixed meter cadence" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">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())</stringProp>
|
||||
</JSR223Timer>
|
||||
<hashTree />
|
||||
<JSR223PreProcessor guiclass="JSR223PreProcessorGui" testclass="JSR223PreProcessor" testname="Clear stale power values" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">['shelly_power_watts','shelly_voltage_volts','shelly_current_amps','shelly_energy_wh'].each { vars.put(it,'') }</stringProp>
|
||||
</JSR223PreProcessor>
|
||||
<hashTree />
|
||||
<JSR223Assertion guiclass="JSR223AssertionGui" testclass="JSR223Assertion" testname="Validate and extract plug readings" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">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)
|
||||
}
|
||||
</stringProp>
|
||||
</JSR223Assertion>
|
||||
<hashTree />
|
||||
</hashTree>
|
||||
<ResultCollector guiclass="SimpleDataWriter" testclass="ResultCollector" testname="Shelly measurements saved live" enabled="true">
|
||||
<stringProp name="filename">${__P(shelly_file,shelly.csv)}</stringProp>
|
||||
<boolProp name="ResultCollector.error_logging">false</boolProp>
|
||||
</ResultCollector>
|
||||
<hashTree />
|
||||
</hashTree>
|
||||
<kg.apc.jmeter.perfmon.PerfMonCollector guiclass="kg.apc.jmeter.vizualizers.PerfMonGui" testclass="kg.apc.jmeter.perfmon.PerfMonCollector" testname="NUC live CPU RAM disk and network" enabled="true">
|
||||
<stringProp name="filename">${__P(perfmon_file,perfmon.csv)}</stringProp>
|
||||
<boolProp name="ResultCollector.error_logging">false</boolProp>
|
||||
@@ -79,7 +149,7 @@
|
||||
</elementProp>
|
||||
<stringProp name="ThreadGroup.num_threads">${__P(users,1)}</stringProp>
|
||||
<stringProp name="ThreadGroup.ramp_time">${__P(ramp_seconds,60)}</stringProp>
|
||||
<stringProp name="ThreadGroup.duration">${__P(total_duration_seconds,16205)}</stringProp>
|
||||
<stringProp name="ThreadGroup.duration">${__P(total_duration_seconds,16210)}</stringProp>
|
||||
<stringProp name="ThreadGroup.delay">0</stringProp>
|
||||
<boolProp name="ThreadGroup.scheduler">true</boolProp>
|
||||
<boolProp name="ThreadGroup.same_user_on_next_iteration">true</boolProp>
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
<jmeterTestPlan version="1.2" properties="5.0" jmeter="5.6.3">
|
||||
<hashTree>
|
||||
<TestPlan guiclass="TestPlanGui" testclass="TestPlan" testname="HealthApp energy: professional" enabled="true">
|
||||
<stringProp name="TestPlan.comments">Synthetic closed-loop sessions; default duration four hours. Setup and energy-meter control are external.</stringProp>
|
||||
<stringProp name="TestPlan.comments">Synthetic closed-loop sessions; default duration four hours. Setup is external; Shelly power is collected live without changing the outlet.</stringProp>
|
||||
<boolProp name="TestPlan.functional_mode">false</boolProp>
|
||||
<boolProp name="TestPlan.serialize_threadgroups">false</boolProp>
|
||||
<elementProp name="TestPlan.user_defined_variables" elementType="Arguments" guiclass="ArgumentsPanel" testclass="Arguments" enabled="true">
|
||||
@@ -10,6 +10,76 @@
|
||||
</elementProp>
|
||||
</TestPlan>
|
||||
<hashTree>
|
||||
<ThreadGroup guiclass="ThreadGroupGui" testclass="ThreadGroup" testname="Shelly live power" enabled="true">
|
||||
<stringProp name="ThreadGroup.on_sample_error">continue</stringProp>
|
||||
<elementProp name="ThreadGroup.main_controller" elementType="LoopController" guiclass="LoopControlPanel" testclass="LoopController" enabled="true">
|
||||
<boolProp name="LoopController.continue_forever">false</boolProp>
|
||||
<stringProp name="LoopController.loops">-1</stringProp>
|
||||
</elementProp>
|
||||
<stringProp name="ThreadGroup.num_threads">1</stringProp>
|
||||
<stringProp name="ThreadGroup.ramp_time">0</stringProp>
|
||||
<stringProp name="ThreadGroup.duration">${__P(total_duration_seconds,16210)}</stringProp>
|
||||
<stringProp name="ThreadGroup.delay">0</stringProp>
|
||||
<boolProp name="ThreadGroup.scheduler">true</boolProp>
|
||||
</ThreadGroup>
|
||||
<hashTree>
|
||||
<HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="POWER Shelly status" enabled="true">
|
||||
<elementProp name="HTTPsampler.Arguments" elementType="Arguments">
|
||||
<collectionProp name="Arguments.arguments" />
|
||||
</elementProp>
|
||||
<stringProp name="HTTPSampler.domain">${__P(shelly_host,192.168.1.44)}</stringProp>
|
||||
<stringProp name="HTTPSampler.port">${__P(shelly_port,80)}</stringProp>
|
||||
<stringProp name="HTTPSampler.protocol">http</stringProp>
|
||||
<stringProp name="HTTPSampler.path">/rpc/Switch.GetStatus?id=${__P(shelly_switch_id,0)}</stringProp>
|
||||
<stringProp name="HTTPSampler.method">GET</stringProp>
|
||||
<stringProp name="HTTPSampler.implementation">HttpClient4</stringProp>
|
||||
<stringProp name="HTTPSampler.connect_timeout">3000</stringProp>
|
||||
<stringProp name="HTTPSampler.response_timeout">3000</stringProp>
|
||||
<boolProp name="HTTPSampler.follow_redirects">false</boolProp>
|
||||
<boolProp name="HTTPSampler.use_keepalive">true</boolProp>
|
||||
</HTTPSamplerProxy>
|
||||
<hashTree>
|
||||
<JSR223Timer guiclass="JSR223TimerGui" testclass="JSR223Timer" testname="Fixed meter cadence" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">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())</stringProp>
|
||||
</JSR223Timer>
|
||||
<hashTree />
|
||||
<JSR223PreProcessor guiclass="JSR223PreProcessorGui" testclass="JSR223PreProcessor" testname="Clear stale power values" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">['shelly_power_watts','shelly_voltage_volts','shelly_current_amps','shelly_energy_wh'].each { vars.put(it,'') }</stringProp>
|
||||
</JSR223PreProcessor>
|
||||
<hashTree />
|
||||
<JSR223Assertion guiclass="JSR223AssertionGui" testclass="JSR223Assertion" testname="Validate and extract plug readings" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">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)
|
||||
}
|
||||
</stringProp>
|
||||
</JSR223Assertion>
|
||||
<hashTree />
|
||||
</hashTree>
|
||||
<ResultCollector guiclass="SimpleDataWriter" testclass="ResultCollector" testname="Shelly measurements saved live" enabled="true">
|
||||
<stringProp name="filename">${__P(shelly_file,shelly.csv)}</stringProp>
|
||||
<boolProp name="ResultCollector.error_logging">false</boolProp>
|
||||
</ResultCollector>
|
||||
<hashTree />
|
||||
</hashTree>
|
||||
<kg.apc.jmeter.perfmon.PerfMonCollector guiclass="kg.apc.jmeter.vizualizers.PerfMonGui" testclass="kg.apc.jmeter.perfmon.PerfMonCollector" testname="NUC live CPU RAM disk and network" enabled="true">
|
||||
<stringProp name="filename">${__P(perfmon_file,perfmon.csv)}</stringProp>
|
||||
<boolProp name="ResultCollector.error_logging">false</boolProp>
|
||||
@@ -79,7 +149,7 @@
|
||||
</elementProp>
|
||||
<stringProp name="ThreadGroup.num_threads">${__P(users,1)}</stringProp>
|
||||
<stringProp name="ThreadGroup.ramp_time">${__P(ramp_seconds,60)}</stringProp>
|
||||
<stringProp name="ThreadGroup.duration">${__P(total_duration_seconds,16205)}</stringProp>
|
||||
<stringProp name="ThreadGroup.duration">${__P(total_duration_seconds,16210)}</stringProp>
|
||||
<stringProp name="ThreadGroup.delay">0</stringProp>
|
||||
<boolProp name="ThreadGroup.scheduler">true</boolProp>
|
||||
<boolProp name="ThreadGroup.same_user_on_next_iteration">true</boolProp>
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
<jmeterTestPlan version="1.2" properties="5.0" jmeter="5.6.3">
|
||||
<hashTree>
|
||||
<TestPlan guiclass="TestPlanGui" testclass="TestPlan" testname="HealthApp energy: recording" enabled="true">
|
||||
<stringProp name="TestPlan.comments">Synthetic closed-loop sessions; default duration four hours. Setup and energy-meter control are external.</stringProp>
|
||||
<stringProp name="TestPlan.comments">Synthetic closed-loop sessions; default duration four hours. Setup is external; Shelly power is collected live without changing the outlet.</stringProp>
|
||||
<boolProp name="TestPlan.functional_mode">false</boolProp>
|
||||
<boolProp name="TestPlan.serialize_threadgroups">false</boolProp>
|
||||
<elementProp name="TestPlan.user_defined_variables" elementType="Arguments" guiclass="ArgumentsPanel" testclass="Arguments" enabled="true">
|
||||
@@ -10,6 +10,76 @@
|
||||
</elementProp>
|
||||
</TestPlan>
|
||||
<hashTree>
|
||||
<ThreadGroup guiclass="ThreadGroupGui" testclass="ThreadGroup" testname="Shelly live power" enabled="true">
|
||||
<stringProp name="ThreadGroup.on_sample_error">continue</stringProp>
|
||||
<elementProp name="ThreadGroup.main_controller" elementType="LoopController" guiclass="LoopControlPanel" testclass="LoopController" enabled="true">
|
||||
<boolProp name="LoopController.continue_forever">false</boolProp>
|
||||
<stringProp name="LoopController.loops">-1</stringProp>
|
||||
</elementProp>
|
||||
<stringProp name="ThreadGroup.num_threads">1</stringProp>
|
||||
<stringProp name="ThreadGroup.ramp_time">0</stringProp>
|
||||
<stringProp name="ThreadGroup.duration">${__P(total_duration_seconds,16210)}</stringProp>
|
||||
<stringProp name="ThreadGroup.delay">0</stringProp>
|
||||
<boolProp name="ThreadGroup.scheduler">true</boolProp>
|
||||
</ThreadGroup>
|
||||
<hashTree>
|
||||
<HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="POWER Shelly status" enabled="true">
|
||||
<elementProp name="HTTPsampler.Arguments" elementType="Arguments">
|
||||
<collectionProp name="Arguments.arguments" />
|
||||
</elementProp>
|
||||
<stringProp name="HTTPSampler.domain">${__P(shelly_host,192.168.1.44)}</stringProp>
|
||||
<stringProp name="HTTPSampler.port">${__P(shelly_port,80)}</stringProp>
|
||||
<stringProp name="HTTPSampler.protocol">http</stringProp>
|
||||
<stringProp name="HTTPSampler.path">/rpc/Switch.GetStatus?id=${__P(shelly_switch_id,0)}</stringProp>
|
||||
<stringProp name="HTTPSampler.method">GET</stringProp>
|
||||
<stringProp name="HTTPSampler.implementation">HttpClient4</stringProp>
|
||||
<stringProp name="HTTPSampler.connect_timeout">3000</stringProp>
|
||||
<stringProp name="HTTPSampler.response_timeout">3000</stringProp>
|
||||
<boolProp name="HTTPSampler.follow_redirects">false</boolProp>
|
||||
<boolProp name="HTTPSampler.use_keepalive">true</boolProp>
|
||||
</HTTPSamplerProxy>
|
||||
<hashTree>
|
||||
<JSR223Timer guiclass="JSR223TimerGui" testclass="JSR223Timer" testname="Fixed meter cadence" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">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())</stringProp>
|
||||
</JSR223Timer>
|
||||
<hashTree />
|
||||
<JSR223PreProcessor guiclass="JSR223PreProcessorGui" testclass="JSR223PreProcessor" testname="Clear stale power values" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">['shelly_power_watts','shelly_voltage_volts','shelly_current_amps','shelly_energy_wh'].each { vars.put(it,'') }</stringProp>
|
||||
</JSR223PreProcessor>
|
||||
<hashTree />
|
||||
<JSR223Assertion guiclass="JSR223AssertionGui" testclass="JSR223Assertion" testname="Validate and extract plug readings" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">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)
|
||||
}
|
||||
</stringProp>
|
||||
</JSR223Assertion>
|
||||
<hashTree />
|
||||
</hashTree>
|
||||
<ResultCollector guiclass="SimpleDataWriter" testclass="ResultCollector" testname="Shelly measurements saved live" enabled="true">
|
||||
<stringProp name="filename">${__P(shelly_file,shelly.csv)}</stringProp>
|
||||
<boolProp name="ResultCollector.error_logging">false</boolProp>
|
||||
</ResultCollector>
|
||||
<hashTree />
|
||||
</hashTree>
|
||||
<kg.apc.jmeter.perfmon.PerfMonCollector guiclass="kg.apc.jmeter.vizualizers.PerfMonGui" testclass="kg.apc.jmeter.perfmon.PerfMonCollector" testname="NUC live CPU RAM disk and network" enabled="true">
|
||||
<stringProp name="filename">${__P(perfmon_file,perfmon.csv)}</stringProp>
|
||||
<boolProp name="ResultCollector.error_logging">false</boolProp>
|
||||
@@ -79,7 +149,7 @@
|
||||
</elementProp>
|
||||
<stringProp name="ThreadGroup.num_threads">${__P(users,1)}</stringProp>
|
||||
<stringProp name="ThreadGroup.ramp_time">${__P(ramp_seconds,60)}</stringProp>
|
||||
<stringProp name="ThreadGroup.duration">${__P(total_duration_seconds,16205)}</stringProp>
|
||||
<stringProp name="ThreadGroup.duration">${__P(total_duration_seconds,16210)}</stringProp>
|
||||
<stringProp name="ThreadGroup.delay">0</stringProp>
|
||||
<boolProp name="ThreadGroup.scheduler">true</boolProp>
|
||||
<boolProp name="ThreadGroup.same_user_on_next_iteration">true</boolProp>
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
<jmeterTestPlan version="1.2" properties="5.0" jmeter="5.6.3">
|
||||
<hashTree>
|
||||
<TestPlan guiclass="TestPlanGui" testclass="TestPlan" testname="HealthApp energy: review" enabled="true">
|
||||
<stringProp name="TestPlan.comments">Synthetic closed-loop sessions; default duration four hours. Setup and energy-meter control are external.</stringProp>
|
||||
<stringProp name="TestPlan.comments">Synthetic closed-loop sessions; default duration four hours. Setup is external; Shelly power is collected live without changing the outlet.</stringProp>
|
||||
<boolProp name="TestPlan.functional_mode">false</boolProp>
|
||||
<boolProp name="TestPlan.serialize_threadgroups">false</boolProp>
|
||||
<elementProp name="TestPlan.user_defined_variables" elementType="Arguments" guiclass="ArgumentsPanel" testclass="Arguments" enabled="true">
|
||||
@@ -10,6 +10,76 @@
|
||||
</elementProp>
|
||||
</TestPlan>
|
||||
<hashTree>
|
||||
<ThreadGroup guiclass="ThreadGroupGui" testclass="ThreadGroup" testname="Shelly live power" enabled="true">
|
||||
<stringProp name="ThreadGroup.on_sample_error">continue</stringProp>
|
||||
<elementProp name="ThreadGroup.main_controller" elementType="LoopController" guiclass="LoopControlPanel" testclass="LoopController" enabled="true">
|
||||
<boolProp name="LoopController.continue_forever">false</boolProp>
|
||||
<stringProp name="LoopController.loops">-1</stringProp>
|
||||
</elementProp>
|
||||
<stringProp name="ThreadGroup.num_threads">1</stringProp>
|
||||
<stringProp name="ThreadGroup.ramp_time">0</stringProp>
|
||||
<stringProp name="ThreadGroup.duration">${__P(total_duration_seconds,16210)}</stringProp>
|
||||
<stringProp name="ThreadGroup.delay">0</stringProp>
|
||||
<boolProp name="ThreadGroup.scheduler">true</boolProp>
|
||||
</ThreadGroup>
|
||||
<hashTree>
|
||||
<HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="POWER Shelly status" enabled="true">
|
||||
<elementProp name="HTTPsampler.Arguments" elementType="Arguments">
|
||||
<collectionProp name="Arguments.arguments" />
|
||||
</elementProp>
|
||||
<stringProp name="HTTPSampler.domain">${__P(shelly_host,192.168.1.44)}</stringProp>
|
||||
<stringProp name="HTTPSampler.port">${__P(shelly_port,80)}</stringProp>
|
||||
<stringProp name="HTTPSampler.protocol">http</stringProp>
|
||||
<stringProp name="HTTPSampler.path">/rpc/Switch.GetStatus?id=${__P(shelly_switch_id,0)}</stringProp>
|
||||
<stringProp name="HTTPSampler.method">GET</stringProp>
|
||||
<stringProp name="HTTPSampler.implementation">HttpClient4</stringProp>
|
||||
<stringProp name="HTTPSampler.connect_timeout">3000</stringProp>
|
||||
<stringProp name="HTTPSampler.response_timeout">3000</stringProp>
|
||||
<boolProp name="HTTPSampler.follow_redirects">false</boolProp>
|
||||
<boolProp name="HTTPSampler.use_keepalive">true</boolProp>
|
||||
</HTTPSamplerProxy>
|
||||
<hashTree>
|
||||
<JSR223Timer guiclass="JSR223TimerGui" testclass="JSR223Timer" testname="Fixed meter cadence" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">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())</stringProp>
|
||||
</JSR223Timer>
|
||||
<hashTree />
|
||||
<JSR223PreProcessor guiclass="JSR223PreProcessorGui" testclass="JSR223PreProcessor" testname="Clear stale power values" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">['shelly_power_watts','shelly_voltage_volts','shelly_current_amps','shelly_energy_wh'].each { vars.put(it,'') }</stringProp>
|
||||
</JSR223PreProcessor>
|
||||
<hashTree />
|
||||
<JSR223Assertion guiclass="JSR223AssertionGui" testclass="JSR223Assertion" testname="Validate and extract plug readings" enabled="true">
|
||||
<stringProp name="scriptLanguage">groovy</stringProp>
|
||||
<stringProp name="cacheKey">true</stringProp>
|
||||
<stringProp name="filename" />
|
||||
<stringProp name="parameters" />
|
||||
<stringProp name="script">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)
|
||||
}
|
||||
</stringProp>
|
||||
</JSR223Assertion>
|
||||
<hashTree />
|
||||
</hashTree>
|
||||
<ResultCollector guiclass="SimpleDataWriter" testclass="ResultCollector" testname="Shelly measurements saved live" enabled="true">
|
||||
<stringProp name="filename">${__P(shelly_file,shelly.csv)}</stringProp>
|
||||
<boolProp name="ResultCollector.error_logging">false</boolProp>
|
||||
</ResultCollector>
|
||||
<hashTree />
|
||||
</hashTree>
|
||||
<kg.apc.jmeter.perfmon.PerfMonCollector guiclass="kg.apc.jmeter.vizualizers.PerfMonGui" testclass="kg.apc.jmeter.perfmon.PerfMonCollector" testname="NUC live CPU RAM disk and network" enabled="true">
|
||||
<stringProp name="filename">${__P(perfmon_file,perfmon.csv)}</stringProp>
|
||||
<boolProp name="ResultCollector.error_logging">false</boolProp>
|
||||
@@ -79,7 +149,7 @@
|
||||
</elementProp>
|
||||
<stringProp name="ThreadGroup.num_threads">${__P(users,1)}</stringProp>
|
||||
<stringProp name="ThreadGroup.ramp_time">${__P(ramp_seconds,60)}</stringProp>
|
||||
<stringProp name="ThreadGroup.duration">${__P(total_duration_seconds,16205)}</stringProp>
|
||||
<stringProp name="ThreadGroup.duration">${__P(total_duration_seconds,16210)}</stringProp>
|
||||
<stringProp name="ThreadGroup.delay">0</stringProp>
|
||||
<boolProp name="ThreadGroup.scheduler">true</boolProp>
|
||||
<boolProp name="ThreadGroup.same_user_on_next_iteration">true</boolProp>
|
||||
|
||||
@@ -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)
|
||||
@@ -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]<end_ms:raise ValueError('Shelly samples do not bracket the full measured interval')
|
||||
if any(b[0]<=a[0] or b[0]-a[0]>interval_ms*3 or b[4]<a[4] for a,b in zip(points,points[1:])):raise ValueError('Shelly samples contain gaps, duplicate timestamps or an energy counter reset')
|
||||
def boundary(time):
|
||||
for a,b in zip(points,points[1:]):
|
||||
if a[0]<=time<=b[0]:return (time,*(a[i]+(b[i]-a[i])*(time-a[0])/(b[0]-a[0]) for i in range(1,5)))
|
||||
raise ValueError('Missing boundary')
|
||||
selected=[boundary(start_ms),*(p for p in points if start_ms<p[0]<end_ms),boundary(end_ms)]
|
||||
joules=sum((a[1]+b[1])/2*(b[0]-a[0])/1000 for a,b in zip(selected,selected[1:]))
|
||||
watt_hours=selected[-1][4]-selected[0][4]
|
||||
with measured.open('w') as f:
|
||||
w=csv.writer(f);w.writerow(['timestamp_ms','power_watts','voltage_volts','current_amps','energy_wh']);w.writerows(selected)
|
||||
return {'measurement_seconds':(end_ms-start_ms)/1000,'samples_including_interpolated_boundaries':len(selected),'integrated_joules':joules,'integrated_kWh':joules/3600000,'average_watts':joules/((end_ms-start_ms)/1000),'counter_delta_Wh':watt_hours,'counter_joules':watt_hours*3600,'counter_kWh':watt_hours/1000,'boundary_method':'Linear interpolation between polls; timestamps approximate HTTP request midpoint'}
|
||||
@@ -2,6 +2,7 @@
|
||||
"""Verify metric decoding; optionally verify a live JMeter-to-agent connection."""
|
||||
import argparse, csv, json, subprocess, tempfile, time
|
||||
from pathlib import Path
|
||||
import xml.etree.ElementTree as E
|
||||
from perfmon import METRICS, check_agent, summarize
|
||||
p=argparse.ArgumentParser();p.add_argument('--host');p.add_argument('--port',type=int,default=4444);p.add_argument('--output');a=p.parse_args()
|
||||
with tempfile.TemporaryDirectory(prefix='healthapp-perfmon-unit-') as name:
|
||||
@@ -26,7 +27,10 @@ if a.host:
|
||||
if not a.output:p.error('--output is required for a live check')
|
||||
check_agent(a.host,a.port)
|
||||
out=Path(a.output).resolve();out.mkdir(parents=True,mode=0o700,exist_ok=False)
|
||||
plan=Path(__file__).parent/'plans/idle.jmx'
|
||||
document=E.parse(Path(__file__).parent/'plans/idle.jmx')
|
||||
for group in document.iter('ThreadGroup'):
|
||||
if group.get('testname')=='Shelly live power':group.set('enabled','false')
|
||||
plan=out/'idle.jmx';document.write(plan)
|
||||
cmd=[str(Path.home()/'.local/bin/jmeter'),'-n','-t',str(plan),'-l',str(out/'samples.csv'),'-j',str(out/'jmeter.log'),'-Jperfmon_host='+a.host,'-Jperfmon_port='+str(a.port),'-Jperfmon_file='+str(out/'perfmon.csv'),'-JjmeterPlugin.perfmon.interval=5000','-JjmeterPlugin.perfmon.useUDP=false','-Jjmeter.save.saveservice.autoflush=true','-Jwarmup_seconds=5','-Jduration_seconds=20','-Jtotal_duration_seconds=30','-Jtimeline_file='+str(out/'timeline.json')]
|
||||
process=subprocess.Popen(cmd);saved_live=False
|
||||
while process.poll() is None:
|
||||
|
||||
@@ -69,7 +69,7 @@ with tempfile.TemporaryDirectory(prefix='healthapp-jmeter-verify-') as temp:
|
||||
# Professional runner preflight is intentionally separate: fixture credentials are patient roles.
|
||||
for scenario in ['recording','review','correction','mixed']:
|
||||
initial_logins=Handler.logins
|
||||
result=subprocess.run(['python3',str(HERE/'run.py'),scenario,'--no-perfmon','--host','127.0.0.1','--port',str(server.server_port),'--ca',str(cert),'--users-file',str(users),'--users','2','--warmup','1','--duration','6','--ramp','0','--think-mean-ms','10','--think-stddev-ms','5','--session-pause-ms','100','--session-stddev-ms','25','--output',str(root/scenario)],capture_output=True,text=True)
|
||||
result=subprocess.run(['python3',str(HERE/'run.py'),scenario,'--no-perfmon','--no-shelly','--host','127.0.0.1','--port',str(server.server_port),'--ca',str(cert),'--users-file',str(users),'--users','2','--warmup','1','--duration','6','--ramp','0','--think-mean-ms','10','--think-stddev-ms','5','--session-pause-ms','100','--session-stddev-ms','25','--output',str(root/scenario)],capture_output=True,text=True)
|
||||
if result.returncode:
|
||||
print(result.stdout,result.stderr)
|
||||
print((root/scenario/'jmeter.log').read_text()[-6000:])
|
||||
@@ -79,6 +79,8 @@ with tempfile.TemporaryDirectory(prefix='healthapp-jmeter-verify-') as temp:
|
||||
# Run the professional plan directly so its assigned-patient semantic assertion is exercised.
|
||||
professional=E.parse(HERE/'plans/professional.jmx')
|
||||
for collector in professional.iter('kg.apc.jmeter.perfmon.PerfMonCollector'):collector.set('enabled','false')
|
||||
for group in professional.iter('ThreadGroup'):
|
||||
if group.get('testname')=='Shelly live power':group.set('enabled','false')
|
||||
professional.write(root/'professional.jmx')
|
||||
result=subprocess.run([str(Path.home()/'.local/bin/jmeter'),'-n','-t',str(root/'professional.jmx'),'-l',str(root/'professional.csv'),'-j',str(root/'professional.log'),'-Jperfmon_enabled=false','-Jhost=127.0.0.1','-Jport='+str(server.server_port),'-Jusers_file='+str(users),'-Jusers=2','-Jtotal_duration_seconds=8','-Jramp_seconds=0','-Jthink_mean_ms=0','-Jthink_stddev_ms=0','-Jsession_pause_ms=100','-Jsession_stddev_ms=25','-Jperiod_from=2026-01-01T00:00:00Z','-Jperiod_to=2027-01-01T00:00:00Z'],capture_output=True,text=True)
|
||||
import csv
|
||||
@@ -86,7 +88,7 @@ with tempfile.TemporaryDirectory(prefix='healthapp-jmeter-verify-') as temp:
|
||||
assert result.returncode==0 and samples and all(r['success']=='true' for r in samples), result.stdout+result.stderr
|
||||
print('professional passed;',len(samples),'samples; token renewal exercised across all plans')
|
||||
Handler.break_insights=True
|
||||
failed=subprocess.run(['python3',str(HERE/'run.py'),'review','--no-perfmon','--host','127.0.0.1','--port',str(server.server_port),'--ca',str(cert),'--users-file',str(users),'--users','2','--warmup','0','--duration','5','--ramp','0','--think-mean-ms','0','--think-stddev-ms','0','--session-pause-ms','0','--session-stddev-ms','0','--output',str(root/'expected-failure')],capture_output=True,text=True)
|
||||
failed=subprocess.run(['python3',str(HERE/'run.py'),'review','--no-perfmon','--no-shelly','--host','127.0.0.1','--port',str(server.server_port),'--ca',str(cert),'--users-file',str(users),'--users','2','--warmup','0','--duration','5','--ramp','0','--think-mean-ms','0','--think-stddev-ms','0','--session-pause-ms','0','--session-stddev-ms','0','--output',str(root/'expected-failure')],capture_output=True,text=True)
|
||||
assert failed.returncode!=0
|
||||
assert json.loads((root/'expected-failure/run.json').read_text())['failed_http_samples']>0
|
||||
print('Unexpected upstream failure correctly invalidates the run')
|
||||
|
||||
@@ -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<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')
|
||||
Reference in new issue
Block a user