"""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]