Skip to content

Commit

Permalink
Guard soc against invalid values (#9532)
Browse files Browse the repository at this point in the history
  • Loading branch information
andig authored Aug 25, 2023
1 parent 7154fb9 commit 697bc88
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 4 deletions.
3 changes: 2 additions & 1 deletion core/loadpoint_charger.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"slices"

"github.com/evcc-io/evcc/api"
"github.com/evcc-io/evcc/core/soc"
)

// chargerHasFeature checks availability of charger feature
Expand All @@ -27,7 +28,7 @@ func (lp *Loadpoint) publishChargerFeature(f api.Feature) {
// chargerSoc returns charger soc if available
func (lp *Loadpoint) chargerSoc() (float64, error) {
if c, ok := lp.charger.(api.Battery); ok {
return c.Soc()
return soc.Guard(c.Soc())
}
return 0, api.ErrNotAvailable
}
3 changes: 2 additions & 1 deletion core/site.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import (
"github.com/evcc-io/evcc/core/planner"
"github.com/evcc-io/evcc/core/prioritizer"
"github.com/evcc-io/evcc/core/session"
"github.com/evcc-io/evcc/core/soc"
"github.com/evcc-io/evcc/push"
"github.com/evcc-io/evcc/server/db"
"github.com/evcc-io/evcc/server/db/settings"
Expand Down Expand Up @@ -483,7 +484,7 @@ func (site *Site) updateMeters() error {

// battery soc and capacity
var capacity float64
soc, err := meter.(api.Battery).Soc()
soc, err := soc.Guard(meter.(api.Battery).Soc())

if err == nil {
// weigh soc by capacity and accumulate total capacity
Expand Down
4 changes: 2 additions & 2 deletions core/soc/estimator.go
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ func (s *Estimator) Soc(chargedEnergy float64) (float64, error) {
var fetchedSoc *float64

if charger, ok := s.charger.(api.Battery); ok {
f, err := charger.Soc()
f, err := Guard(charger.Soc())

// if the charger does or could provide Soc, we always use it instead of using the vehicle API
if err == nil || !errors.Is(err, api.ErrNotAvailable) {
Expand All @@ -128,7 +128,7 @@ func (s *Estimator) Soc(chargedEnergy float64) (float64, error) {
}

if fetchedSoc == nil {
f, err := s.vehicle.Soc()
f, err := Guard(s.vehicle.Soc())
if err != nil {
// required for online APIs with refreshkey
if errors.Is(err, api.ErrMustRetry) {
Expand Down
20 changes: 20 additions & 0 deletions core/soc/helper.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package soc

import "fmt"

// Guard checks soc value for validity
func Guard(soc float64, err error) (float64, error) {
switch {
case err != nil:
return soc, err

case soc < 0:
return 0, fmt.Errorf("invalid soc: %.1f", soc)

case soc > 100:
return 100, fmt.Errorf("invalid soc: %.1f", soc)

default:
return soc, nil
}
}

0 comments on commit 697bc88

Please sign in to comment.