Files
HealthAppRepository/tools/energy-jmeter/shelly.py
T

41 lines
3.7 KiB
Python

"""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)]
# Each recorded power reading represents one nominal polling interval.
# Do not interpolate power or invent readings at the window boundaries.
measured_points=[p for p in points if start_ms<=p[0]<end_ms]
if not measured_points:raise ValueError('No Shelly power readings inside the measured interval')
joules=sum(p[1] for p in measured_points)*(interval_ms/1000)
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),'power_sample_count':len(measured_points),'nominal_sample_interval_ms':interval_ms,'nominal_sample_coverage_seconds':len(measured_points)*interval_ms/1000,'energy_method':'sum of recorded power readings multiplied by nominal polling interval; assumes each reading represents that interval','integrated_joules':joules,'integrated_kWh':joules/3600000,'average_watts':sum(p[1] for p in measured_points)/len(measured_points),'counter_delta_Wh':watt_hours,'counter_joules':watt_hours*3600,'counter_kWh':watt_hours/1000,'boundary_method':'Energy counter and exported plot boundaries interpolated; power sum uses only recorded in-window samples; timestamps approximate HTTP request midpoint'}