diff --git a/core/site_tariffs.go b/core/site_tariffs.go index fca040df6..537b5924e 100644 --- a/core/site_tariffs.go +++ b/core/site_tariffs.go @@ -72,17 +72,21 @@ func accumulatedEnergy(rr timeseries, from, to time.Time) float64 { continue } - start := last.Timestamp - if start.Before(from) { - start = from + x1 := last.Timestamp + y1 := last.Value + if x1.Before(from) { + x1 = from + y1 += float64(from.Sub(last.Timestamp)) * (r.Value - last.Value) / float64(r.Timestamp.Sub(last.Timestamp)) } - end := r.Timestamp - if end.After(to) { - end = to + x2 := r.Timestamp + y2 := r.Value + if x2.After(to) { + x2 = to + y2 += float64(to.Sub(r.Timestamp)) * (r.Value - last.Value) / float64(r.Timestamp.Sub(last.Timestamp)) } - energy += (r.Value + last.Value) / 2 * end.Sub(start).Hours() + energy += (y1 + y2) / 2 * x2.Sub(x1).Hours() if !r.Timestamp.Before(to) { break diff --git a/core/site_tariffs_test.go b/core/site_tariffs_test.go index 52b621da6..6a4a78c6a 100644 --- a/core/site_tariffs_test.go +++ b/core/site_tariffs_test.go @@ -27,10 +27,14 @@ func TestAccumulatedEnergy(t *testing.T) { expected float64 }{ {0, 0, 0}, - {0, 0.5, 0.25}, + {0, 0.5, 0.125}, {0, 1, 0.5}, - {1, 2, 1.5}, + {0, 1.5, 1.125}, {0, 2, 2}, + {1, 2, 1.5}, + {0.25, 0.75, 0.25}, + {0.5, 1, 0.375}, + {0.5, 3.5, 6}, } { t.Logf("%d. %+v", i+1, tc) @@ -38,6 +42,6 @@ func TestAccumulatedEnergy(t *testing.T) { to := clock.Now().Add(time.Duration(float64(time.Hour) * tc.to)) res := accumulatedEnergy(rr, from, to) - assert.Equal(t, tc.expected, res, "test case %d", i) + assert.Equal(t, tc.expected, res, "test case %d", i+1) } }