Meter (Home Assistant): grid charging via switch entities (#30191)
Some checks failed
Release / Hassio Addon (push) Has been cancelled
Release / call-build-workflow (push) Has been cancelled
Release / Publish Docker :release (push) Has been cancelled
Release / Github & APT (push) Has been cancelled
Release / Demo (push) Has been cancelled

This commit is contained in:
andig 2026-05-25 08:00:09 +02:00 • committed by GitHub
parent 4d80489986
commit 070e27fc21
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 78 additions and 0 deletions

View file

@ -3,6 +3,7 @@ package meter
import (
"errors"
"fmt"
"strings"
"github.com/evcc-io/evcc/api"
"github.com/evcc-io/evcc/api/implement"
@ -34,6 +35,11 @@ func NewHomeAssistantFromConfig(other map[string]any) (api.Meter, error) {
batteryCapacity `mapstructure:",squash"`
batterySocLimits `mapstructure:",squash"`
batteryPowerLimits `mapstructure:",squash"`
// battery mode control - optional switch-like entities per mode
ModeNormal string
ModeHold string
ModeCharge string
}{
batterySocLimits: batterySocLimits{
MinSoc: 20,
@ -98,6 +104,26 @@ func NewHomeAssistantFromConfig(other map[string]any) (api.Meter, error) {
implement.May(m, implement.BatteryCapacity(cc.batteryCapacity.Decorator()))
implement.May(m, implement.BatterySocLimiter(cc.batterySocLimits.Decorator()))
implement.May(m, implement.BatteryPowerLimiter(cc.batteryPowerLimits.Decorator()))
if cc.ModeHold != "" || cc.ModeCharge != "" {
if cc.ModeNormal == "" {
return nil, errors.New("modeNormal is required when modeHold or modeCharge is configured")
}
modes := map[api.BatteryMode]string{
api.BatteryNormal: cc.ModeNormal,
api.BatteryHold: cc.ModeHold,
api.BatteryCharge: cc.ModeCharge,
}
for _, entity := range modes {
if entity != "" && !strings.HasPrefix(entity, "script.") {
return nil, fmt.Errorf("battery mode entity must be a script: %s", entity)
}
}
implement.Has(m, implement.BatteryController(batteryModeController(conn, modes)))
} else if cc.ModeNormal != "" {
return nil, errors.New("modeNormal alone has no effect; configure modeHold and/or modeCharge")
}
return m, nil
}
@ -108,3 +134,19 @@ func NewHomeAssistantFromConfig(other map[string]any) (api.Meter, error) {
return m, nil
}
// batteryModeController returns a BatteryController function that activates
// the switch-like Home Assistant entity configured for the requested evcc
// battery mode. Each mode is self-contained: evcc only triggers the matching
// entity and never deactivates others - any mutual exclusion is the HA side's
// responsibility. modeHold and modeCharge are optional and return
// api.ErrNotAvailable when requested without a backing entity.
func batteryModeController(conn *homeassistant.Connection, modes map[api.BatteryMode]string) func(api.BatteryMode) error {
return func(mode api.BatteryMode) error {
target, ok := modes[mode]
if !ok || target == "" {
return api.ErrNotAvailable
}
return conn.CallSwitchService(target, true)
}
}