Calculate energy from recorded power samples

This commit is contained in:
Steffen committed 2026-11-23 00:01:07 +01:00
1 parent 2117236366
commit b76897d8f8
4 files changed
+24 -13

No files matched your search

+6 -2
View File
@@ -29,8 +29,12 @@ def summarize(raw,measured,start_ms,end_ms,interval_ms):
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:]))
# 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),'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'}
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'}