Target charge: don't allow timestamps in the past

This commit is contained in:
andig 2022-12-16 08:34:35 +01:00
parent d062adb689
commit 8be06fbb9d
4 changed files with 16 additions and 5 deletions

View file

@ -49,7 +49,7 @@ type API interface {
SetPhases(int) error
// SetTargetCharge sets the charge targetSoC
SetTargetCharge(time.Time, int)
SetTargetCharge(time.Time, int) error
// RemoteControl sets remote status demand
RemoteControl(string, RemoteDemand)

View file

@ -1,6 +1,7 @@
package core
import (
"errors"
"fmt"
"time"
@ -185,10 +186,14 @@ func (lp *LoadPoint) SetPhases(phases int) error {
}
// SetTargetCharge sets loadpoint charge targetSoC
func (lp *LoadPoint) SetTargetCharge(finishAt time.Time, soc int) {
func (lp *LoadPoint) SetTargetCharge(finishAt time.Time, soc int) error {
lp.Lock()
defer lp.Unlock()
if !finishAt.IsZero() && finishAt.Before(time.Now()) {
return errors.New("timestamp is in the past")
}
lp.log.DEBUG.Printf("set target charge: %d @ %v", soc, finishAt)
// apply immediately
@ -201,6 +206,8 @@ func (lp *LoadPoint) SetTargetCharge(finishAt time.Time, soc int) {
lp.requestUpdate()
}
}
return nil
}
// RemoteControl sets remote status demand

View file

@ -294,7 +294,10 @@ func targetChargeHandler(loadpoint targetCharger) http.HandlerFunc {
return
}
loadpoint.SetTargetCharge(timeV, socV)
if err := loadpoint.SetTargetCharge(timeV, socV); err != nil {
jsonError(w, http.StatusBadRequest, err)
return
}
res := struct {
SoC int `json:"soc"`
@ -371,5 +374,5 @@ func socketHandler(hub *SocketHub) http.HandlerFunc {
// TargetCharger defines target charge related loadpoint operations
type targetCharger interface {
// SetTargetCharge sets the charge targetSoC
SetTargetCharge(time.Time, int)
SetTargetCharge(time.Time, int) error
}

View file

@ -15,9 +15,10 @@ type mockLoadpoint struct {
TargetTime time.Time
}
func (lp *mockLoadpoint) SetTargetCharge(time time.Time, soc int) {
func (lp *mockLoadpoint) SetTargetCharge(time time.Time, soc int) error {
lp.SoC = soc
lp.TargetTime = time
return nil
}
func TestTargetChargeHandler(t *testing.T) {