This page is for development purposes only. Gives insights into the upcoming
optimization algorithm.
@@ -81,19 +81,44 @@
:dimmed-battery-colors="dimmedBatteryColors"
/>
-
-
-
- Show Raw Data
-
-
-
-
Request:
-
{{ JSON.stringify(evopt.req, null, 2) }}
-
Response:
-
{{ JSON.stringify(evopt.res, null, 2) }}
+
Raw Data
+
+
+
+
+
Request:
+
+
{{ formattedRequest }}
+
+
+
+
+
+
Response:
+
+
{{ formattedResponse }}
+
+
+
@@ -112,6 +137,8 @@ import SocChart from "../components/Optimize/SocChart.vue";
import ChargeChart from "../components/Optimize/ChargeChart.vue";
import PriceChart from "../components/Optimize/PriceChart.vue";
import TimeSeriesDataTable from "../components/Optimize/TimeSeriesDataTable.vue";
+import CopyButton from "../components/Optimize/CopyButton.vue";
+import { formatCompactJson } from "../components/Optimize/compactJson";
import store from "../store";
import formatter from "../mixins/formatter";
import colors from "../colors";
@@ -126,10 +153,11 @@ export default defineComponent({
ChargeChart,
PriceChart,
TimeSeriesDataTable,
+ CopyButton,
},
mixins: [formatter],
head() {
- return { title: this.$t("energy.title") };
+ return { title: "Optimize Debug" };
},
computed: {
evopt() {
@@ -162,6 +190,12 @@ export default defineComponent({
dimmedBatteryColors() {
return this.batteryColors.map((color) => this.dimColorBy25Percent(color));
},
+ formattedRequest() {
+ return this.evopt?.req ? formatCompactJson(this.evopt.req) : "";
+ },
+ formattedResponse() {
+ return this.evopt?.res ? formatCompactJson(this.evopt.res) : "";
+ },
},
methods: {
dimColorBy25Percent(color: string): string {
diff --git a/core/site_optimizer.go b/core/site_optimizer.go
index 92a7c929d..b7bebc300 100644
--- a/core/site_optimizer.go
+++ b/core/site_optimizer.go
@@ -17,12 +17,12 @@ import (
"github.com/evcc-io/evcc/util/sponsor"
"github.com/jinzhu/now"
"github.com/samber/lo"
+ "moul.io/http2curl"
)
var (
- eta = float32(0.9) // efficiency of the battery charging/discharging
- batteryPower = float32(6000) // power of the battery in W
- pa = float32(0.3 / 1e3) // Value per Wh at end of time horizon
+ eta = float32(0.9) // efficiency of the battery charging/discharging
+ batteryPower = float32(6000) // power of the battery in W
updated time.Time
)
@@ -48,9 +48,25 @@ type responseDetails struct {
}
func (site *Site) optimizerUpdateAsync(battery []measurement) {
- if err := site.optimizerUpdate(battery); err != nil {
- site.log.ERROR.Println("optimizer:", err)
+ if time.Since(updated) < 5*time.Minute {
+ return
}
+
+ var err error
+
+ defer func() {
+ if r := recover(); r != nil {
+ err = fmt.Errorf("panic %v", r)
+ }
+
+ if err != nil {
+ site.log.ERROR.Println("optimizer:", err)
+ }
+ }()
+
+ err = site.optimizerUpdate(battery)
+
+ updated = time.Now()
}
func (site *Site) optimizerUpdate(battery []measurement) error {
@@ -59,14 +75,6 @@ func (site *Site) optimizerUpdate(battery []measurement) error {
return nil
}
- if time.Since(updated) < time.Minute {
- return nil
- }
-
- defer func() {
- updated = time.Now()
- }()
-
solarTariff := site.GetTariff(api.TariffUsageSolar)
solarRates, err := solarTariff.Rates()
if err != nil {
@@ -100,6 +108,9 @@ func (site *Site) optimizerUpdate(battery []measurement) error {
}
req := evopt.OptimizationInput{
+ Strategy: &evopt.OptimizerStrategy{
+ ChargingStrategy: lo.ToPtr(evopt.ChargeBeforeExport),
+ },
EtaC: &eta,
EtaD: &eta,
TimeSeries: evopt.TimeSeries{
@@ -111,6 +122,9 @@ func (site *Site) optimizerUpdate(battery []measurement) error {
},
}
+ // end of horizon Wh value
+ pa := lo.Min(req.TimeSeries.PN)
+
details := responseDetails{
Timestamps: asTimestamps(dt),
}
@@ -202,12 +216,12 @@ func (site *Site) optimizerUpdate(battery []measurement) error {
return err
}
+ var curl *http2curl.CurlCommand
resp, err := apiClient.PostOptimizeChargeScheduleWithResponse(context.TODO(), req, func(_ context.Context, req *http.Request) error {
if sponsor.IsAuthorized() {
req.Header.Set("Authorization", "Bearer "+sponsor.Token)
}
- // command, _ := http2curl.GetCurlCommand(req)
- // log.TRACE.Println("\n" + command.String())
+ curl, _ = http2curl.GetCurlCommand(req)
return nil
})
if err != nil {
@@ -229,16 +243,19 @@ func (site *Site) optimizerUpdate(battery []measurement) error {
site.publish("evopt", struct {
Req evopt.OptimizationInput `json:"req"`
Res evopt.OptimizationResult `json:"res"`
+ Curl string `json:"curl"`
Details responseDetails `json:"details"`
}{
Req: req,
Res: *resp.JSON200,
+ Curl: curl.String(),
Details: details,
})
return nil
}
+// loadpointProfile returns the loadpoint's charging profile in Wh
// TODO consider charging efficiency
func loadpointProfile(lp loadpoint.API, firstSlotDuration time.Duration, minLen int) []float64 {
mode := lp.GetMode()
@@ -275,86 +292,75 @@ func loadpointProfile(lp loadpoint.API, firstSlotDuration time.Duration, minLen
return res
}
+// homeProfile returns the home base load in Wh
func (site *Site) homeProfile(minLen int) []float64 {
- now := time.Now().Truncate(time.Hour)
-
- profile, err := metrics.Profile(now.AddDate(0, 0, -30))
+ // kWh over last 30 days
+ profile, err := metrics.Profile(now.BeginningOfDay().AddDate(0, 0, -30))
if err != nil {
- site.log.ERROR.Printf("household metrics profile: %v", err)
+ site.log.WARN.Println("optimizer:", err)
return lo.RepeatBy(minLen, func(_ int) float64 {
return 0
})
}
- res := slotsToHours(now, profile)
- for len(res) < minLen {
- res = append(res, profile[:]...)
+ // max 4 days
+ hours := make([]float64, 0, minLen+1)
+
+ combined := combineSlots(profile[:])
+ for len(hours) <= minLen+24 { // allow for prorating first day
+ hours = append(hours, combined...)
+ }
+
+ res := prorateFirstHour(time.Now(), hours)
+ if len(res) < minLen {
+ panic("minimum home profile length failed")
}
if len(res) > minLen {
res = res[:minLen]
}
- return res
+ // convert to Wh
+ return lo.Map(res, func(v float64, i int) float64 {
+ return v * 1e3
+ })
}
-// slotsToHours converts a daily consumption profile consisting of 96 15min slots
-// to an hourly profile by totaling the values per hour and returning the first minLen values.
-// the first value is fractional part of the the current hour, prorated.
-func slotsToHours(now time.Time, profile *[96]float64) []float64 {
+// combineSlots combines 15-minute slots into hourly values
+func combineSlots(profile []float64) []float64 {
if profile == nil {
return []float64{}
}
- // Calculate current 15-minute slot within the day (0-95)
- currentMinute := now.Hour()*60 + now.Minute()
- currentSlot := currentMinute / 15
+ result := make([]float64, 0, 24)
- // Calculate remaining minutes in current hour for prorating
- minutesIntoHour := now.Minute()
- remainingMinutesInHour := 60 - minutesIntoHour
-
- var result []float64
-
- // Handle the partial current hour first
- if remainingMinutesInHour > 0 && currentSlot < 96 {
- var partialHourValue float64
- slotsInCurrentHour := remainingMinutesInHour / 15
- if remainingMinutesInHour%15 != 0 {
- slotsInCurrentHour++
+ // Process complete hours starting from the start slot
+ for hour := range 24 {
+ var sum float64
+ for i := range 4 {
+ sum += profile[4*hour+i]
}
- // Sum the remaining slots in the current hour
- for i := 0; i < slotsInCurrentHour && currentSlot+i < 96; i++ {
- if currentSlot+i >= 0 {
- partialHourValue += profile[currentSlot+i]
- }
- }
-
- // Prorate based on the fraction of the hour remaining
- fractionOfHour := float64(remainingMinutesInHour) / 60.0
- partialHourValue *= fractionOfHour
-
- result = append(result, float64(partialHourValue))
- }
-
- // Process complete hours starting from the next hour
- nextHourSlot := (currentSlot/4 + 1) * 4
-
- // Don't wrap around at end of day - only process remaining hours
- for hourSlot := nextHourSlot; len(result) < 24 && hourSlot < 96; hourSlot += 4 {
- var hourValue float64
-
- // Sum 4 slots (4 × 15min = 60min = 1 hour)
- for i := 0; i < 4 && hourSlot+i < 96; i++ {
- hourValue += profile[hourSlot+i]
- }
-
- result = append(result, float64(hourValue))
+ result = append(result, sum)
}
return result
}
+// prorateFirstHour strips away any slots before "now" and prorates the first remaining hour
+// based on remaining time in current hour. The profile contains hourly slots (0-23) that repeat for multiple days.
+func prorateFirstHour(now time.Time, profile []float64) []float64 {
+ // Take only slots from current hour onwards
+ res := profile[now.Hour():]
+
+ // Prorate the first hour based on remaining time in current hour
+ if minutesIntoHour := now.Minute(); minutesIntoHour > 0 {
+ fractionOfHour := float64(60-minutesIntoHour) / 60.0
+ res[0] *= fractionOfHour
+ }
+
+ return res
+}
+
func ratesToEnergy(rr api.Rates, firstSlot time.Duration) (api.Rates, error) {
res := make(api.Rates, 0, len(rr))
diff --git a/core/site_optimizer_test.go b/core/site_optimizer_test.go
index f27fc4826..04c8639ae 100644
--- a/core/site_optimizer_test.go
+++ b/core/site_optimizer_test.go
@@ -95,111 +95,112 @@ func TestUpdateHouseholdProfile(t *testing.T) {
}
}
-func TestSlotsToHours(t *testing.T) {
- // Create a test profile with known values
- // Slots 0-3: hour 0 (00:00-01:00), values 1,2,3,4 -> sum = 10
- // Slots 4-7: hour 1 (01:00-02:00), values 5,6,7,8 -> sum = 26
- // etc.
- var profile [96]float64
+func TestCombineSlots(t *testing.T) {
+ // Create test profile with known values
+ // Slots 0-3: hour 0, values 1,2,3,4 -> sum = 10
+ // Slots 4-7: hour 1, values 5,6,7,8 -> sum = 26
+ // Slots 8-11: hour 2, values 9,10,11,12 -> sum = 42
+ profile := make([]float64, 96)
for i := range 96 {
profile[i] = float64(i + 1)
}
+ t.Run("standard profile", func(t *testing.T) {
+ result := combineSlots(profile)
+ require.Equal(t, 24, len(result), "should return 24 hours")
+ require.InDelta(t, 10, result[0], 0.01, "hour 0: slots 0-3 (1+2+3+4)")
+ require.InDelta(t, 26, result[1], 0.01, "hour 1: slots 4-7 (5+6+7+8)")
+ require.InDelta(t, 42, result[2], 0.01, "hour 2: slots 8-11 (9+10+11+12)")
+ require.InDelta(t, 378, result[23], 0.01, "hour 23: slots 92-95 (93+94+95+96)")
+ })
+
+ t.Run("nil profile", func(t *testing.T) {
+ result := combineSlots(nil)
+ require.Empty(t, result)
+ })
+}
+
+func TestProrateFirstHour(t *testing.T) {
+ // Create test hourly profile with known values
+ // Hour 0: 10, Hour 1: 20, Hour 2: 30, etc.
+ profile := make([]float64, 24)
+ for i := range 24 {
+ profile[i] = float64((i + 1) * 10)
+ }
+
tests := []struct {
- name string
- now time.Time
- expected []float32
+ name string
+ now time.Time
+ expectedFirstHour float64
+ expectedLength int
+ expectedSecond float64
}{
{
- name: "start of hour",
- now: time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC), // 00:00
- expected: []float32{
- 10, // hour 0: slots 0-3 (1+2+3+4)
- 26, // hour 1: slots 4-7 (5+6+7+8)
- 42, // hour 2: slots 8-11 (9+10+11+12)
- },
+ name: "start of hour 0 - no proration",
+ now: time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC),
+ expectedFirstHour: 10.0, // full hour: no proration applied
+ expectedLength: 24, // all 24 hours remain
+ expectedSecond: 20.0, // hour 1 value
},
{
- name: "middle of hour",
- now: time.Date(2024, 1, 1, 0, 30, 0, 0, time.UTC), // 00:30
- expected: []float32{
- 3.5, // remaining 30min of hour 0: slots 2-3 (3+4) * 0.5 = 7 * 0.5 = 3.5
- 26, // hour 1: slots 4-7 (5+6+7+8)
- 42, // hour 2: slots 8-11 (9+10+11+12)
- },
+ name: "30 minutes into hour 0",
+ now: time.Date(2024, 1, 1, 0, 30, 0, 0, time.UTC),
+ expectedFirstHour: 5.0, // 30min remaining: 10 * 0.5 = 5
+ expectedLength: 24, // all 24 hours remain
+ expectedSecond: 20.0, // hour 1 value unchanged
},
{
- name: "quarter past hour",
- now: time.Date(2024, 1, 1, 0, 15, 0, 0, time.UTC), // 00:15
- expected: []float32{
- 6.75, // remaining 45min of hour 0: slots 1-3 (2+3+4) * 0.75 = 9 * 0.75 = 6.75
- 26, // hour 1: slots 4-7 (5+6+7+8)
- 42, // hour 2: slots 8-11 (9+10+11+12)
- },
+ name: "start of hour 2 - no proration",
+ now: time.Date(2024, 1, 1, 2, 0, 0, 0, time.UTC),
+ expectedFirstHour: 30.0, // hour 2 value: 30
+ expectedLength: 22, // hours 2-23 remain (22 hours)
+ expectedSecond: 40.0, // hour 3 value
},
{
- name: "middle of slot early",
- now: time.Date(2024, 1, 1, 0, 10, 0, 0, time.UTC), // 00:10 (middle of slot 0)
- expected: []float32{
- 8.33, // remaining 50min of hour 0: slots 0-3 (1+2+3+4) * (50/60) = 10 * 0.833 = 8.33
- 26, // hour 1: slots 4-7 (5+6+7+8)
- 42, // hour 2: slots 8-11 (9+10+11+12)
- },
+ name: "15 minutes into hour 2",
+ now: time.Date(2024, 1, 1, 2, 15, 0, 0, time.UTC),
+ expectedFirstHour: 22.5, // 45min remaining: 30 * 0.75 = 22.5
+ expectedLength: 22, // hours 2-23 remain (22 hours)
+ expectedSecond: 40.0, // hour 3 value unchanged
},
{
- name: "middle of slot late",
- now: time.Date(2024, 1, 1, 0, 50, 0, 0, time.UTC), // 00:50 (middle of slot 3)
- expected: []float32{
- 0.67, // remaining 10min of hour 0: slot 3 (4) * (10/60) = 4 * 0.167 = 0.67
- 26, // hour 1: slots 4-7 (5+6+7+8)
- 42, // hour 2: slots 8-11 (9+10+11+12)
- },
+ name: "45 minutes into hour 5",
+ now: time.Date(2024, 1, 1, 5, 45, 0, 0, time.UTC),
+ expectedFirstHour: 15.0, // 15min remaining: 60 * 0.25 = 15.0
+ expectedLength: 19, // hours 5-23 remain (19 hours)
+ expectedSecond: 70.0, // hour 6 value unchanged
+ },
+ {
+ name: "10 minutes into hour 10",
+ now: time.Date(2024, 1, 1, 10, 10, 0, 0, time.UTC),
+ expectedFirstHour: 91.67, // 50min remaining: 110 * (50/60) = 91.67
+ expectedLength: 14, // hours 10-23 remain (14 hours)
+ expectedSecond: 120.0, // hour 11 value unchanged
+ },
+ {
+ name: "near end of day - hour 23",
+ now: time.Date(2024, 1, 1, 23, 30, 0, 0, time.UTC),
+ expectedFirstHour: 120.0, // 30min remaining: 240 * 0.5 = 120
+ expectedLength: 1, // only hour 23 remains
+ expectedSecond: 0.0, // no second hour
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- result := slotsToHours(tt.now, &profile)
- require.GreaterOrEqual(t, len(result), len(tt.expected), "insufficient result length")
-
- for i, expected := range tt.expected {
- require.InDelta(t, expected, result[i], 0.01, "mismatch at index %d", i)
+ result := prorateFirstHour(tt.now, profile)
+ require.Equal(t, tt.expectedLength, len(result), "length mismatch")
+ if len(result) > 0 {
+ require.InDelta(t, tt.expectedFirstHour, result[0], 0.01, "first hour value mismatch")
+ // Verify second hour is unchanged (if exists)
+ if len(result) > 1 {
+ require.Equal(t, tt.expectedSecond, result[1], "second hour should be unchanged")
+ }
}
})
}
}
-func TestSlotsToHoursEdgeCases(t *testing.T) {
- var profile [96]float64
- for i := range 96 {
- profile[i] = float64(i + 1)
- }
-
- t.Run("nil profile", func(t *testing.T) {
- result := slotsToHours(time.Now(), nil)
- require.Empty(t, result)
- })
-
- t.Run("end of day", func(t *testing.T) {
- now := time.Date(2024, 1, 1, 23, 45, 0, 0, time.UTC) // 23:45
- result := slotsToHours(now, &profile)
-
- // Should only return the remaining 15min of the current hour
- expected := []float32{24} // slot 95 (value 96) * 0.25 (15min/60min)
- require.Equal(t, len(expected), len(result))
- require.InDelta(t, expected[0], result[0], 0.01)
- })
-
- t.Run("exact hour boundary", func(t *testing.T) {
- now := time.Date(2024, 1, 1, 1, 0, 0, 0, time.UTC) // 01:00
- result := slotsToHours(now, &profile)
-
- // Should start from hour 1 (slots 4-7)
- require.GreaterOrEqual(t, len(result), 1)
- require.InDelta(t, float32(26), result[0], 0.01) // 5+6+7+8 = 26
- })
-}
-
func TestLoadpointProfile(t *testing.T) {
ctrl := gomock.NewController(t)
diff --git a/go.mod b/go.mod
index 5419c81de..9f5191baa 100644
--- a/go.mod
+++ b/go.mod
@@ -9,7 +9,7 @@ require (
github.com/Masterminds/sprig/v3 v3.3.0
github.com/PuerkitoBio/goquery v1.10.3
github.com/WulfgarW/sensonet v0.0.4
- github.com/andig/evopt v0.0.0-20250806061439-fc50d99582e9
+ github.com/andig/evopt v0.0.0-20250820184747-c28617953a3c
github.com/andig/go-powerwall v0.2.1-0.20230808194509-dd70cdb6e140
github.com/andig/gosunspec v0.0.0-20240918203654-860ce51d602b
github.com/andig/mbserver v0.0.0-20230310211055-1d29cbb5820e
@@ -114,6 +114,7 @@ require (
google.golang.org/grpc v1.74.2
google.golang.org/protobuf v1.36.6
gorm.io/gorm v1.30.1
+ moul.io/http2curl v1.0.0
)
require (
diff --git a/go.sum b/go.sum
index d32d66ddf..257b589ca 100644
--- a/go.sum
+++ b/go.sum
@@ -33,8 +33,8 @@ github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuy
github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=
github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=
github.com/alecthomas/units v0.0.0-20190924025748-f65c72e2690d/go.mod h1:rBZYJk541a8SKzHPHnH3zbiI+7dagKZ0cgpgrD7Fyho=
-github.com/andig/evopt v0.0.0-20250806061439-fc50d99582e9 h1:tWGkO2RipG162BGfxuLj3TbxA2BiI/oHH7ftQGUJ/VI=
-github.com/andig/evopt v0.0.0-20250806061439-fc50d99582e9/go.mod h1:TE4sjD3Fxu4Jn49ecE6H6EdHliJA5KnkRfY6WGdHBu0=
+github.com/andig/evopt v0.0.0-20250820184747-c28617953a3c h1:tEJUsri5R7OP/Zs9P1eh1uASs6oStsZJIrKFF3bofV0=
+github.com/andig/evopt v0.0.0-20250820184747-c28617953a3c/go.mod h1:TE4sjD3Fxu4Jn49ecE6H6EdHliJA5KnkRfY6WGdHBu0=
github.com/andig/go-powerwall v0.2.1-0.20230808194509-dd70cdb6e140 h1:C93T8vg7CN4Q4BBDbBMOvBoTYBA+CaBEvlY2SZF8aa0=
github.com/andig/go-powerwall v0.2.1-0.20230808194509-dd70cdb6e140/go.mod h1:Xk09mD+7RTCuuHMX5RxlqgEUeh9oZdIX0rL0qiY6l/4=
github.com/andig/gosunspec v0.0.0-20240918203654-860ce51d602b h1:81UMfM949I7StrRay7YDUZazY8M1u/JHkzwcFEjiilQ=
@@ -1077,6 +1077,8 @@ modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=
modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=
modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=
+moul.io/http2curl v1.0.0 h1:6XwpyZOYsgZJrU8exnG87ncVkU1FVCcTRpwzOkTDUi8=
+moul.io/http2curl v1.0.0/go.mod h1:f6cULg+e4Md/oW1cYmwW4IWQOVl2lGbmCNGOHvzX2kE=
pgregory.net/rapid v1.1.0 h1:CMa0sjHSru3puNx+J0MIAuiiEV4N0qj8/cMWGBBCsjw=
pgregory.net/rapid v1.1.0/go.mod h1:PY5XlDGj0+V1FCq0o192FdRhpKHGTRIWBgqjDBTrq04=
sigs.k8s.io/yaml v1.1.0/go.mod h1:UJmg0vDUVViEyp3mgSv9WPwZCDxu4rQW1olrI1uml+o=