Guard soc against invalid values (#9532)

This commit is contained in:
andig 2023-08-25 17:41:42 +02:00 • committed by GitHub
parent 7154fb9b08
commit 697bc88a62
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 26 additions and 4 deletions

View file

@ -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
@ -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
}

View file

@ -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"
@ -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

View file

@ -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) {
@ -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) {

20
core/soc/helper.go Normal file
View file

@ -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
}
}