Mqtt: allow nil/null/none/- as empty values (#17209)

This commit is contained in:
andig 2024-11-13 10:40:28 +01:00 • committed by GitHub
parent d6f9e7a0c8
commit 3398312e77
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 21 additions and 10 deletions

View file

@ -220,7 +220,7 @@ func (m *MQTT) listenLoadpointSetters(topic string, site site.API, lp loadpoint.
}},
{"vehicle", func(payload string) error {
// https://github.com/evcc-io/evcc/issues/11184 empty payload is swallowed by listener
if payload == "-" {
if isEmpty(payload) {
lp.SetVehicle(nil)
return nil
}

View file

@ -1,6 +1,7 @@
package server
import (
"slices"
"strconv"
"time"
@ -13,6 +14,10 @@ type setter struct {
fun func(string) error
}
func isEmpty(payload string) bool {
return slices.Contains([]string{"-", "nil", "null", "none"}, payload)
}
func setterFunc[T any](conv func(string) (T, error), set func(T) error) func(string) error {
return func(payload string) error {
val, err := conv(payload)
@ -23,20 +28,26 @@ func setterFunc[T any](conv func(string) (T, error), set func(T) error) func(str
}
}
// ptrSetter updates pointer api
func ptrSetter[T any](conv func(string) (T, error), set func(*T) error) func(string) error {
return func(payload string) error {
var val *T
v, err := conv(payload)
if err == nil {
val = &v
} else if !isEmpty(payload) {
return err
}
return set(val)
}
}
func floatSetter(set func(float64) error) func(string) error {
return setterFunc(parseFloat, set)
}
func floatPtrSetter(set func(*float64) error) func(string) error {
return func(s string) error {
var val *float64
if f, err := parseFloat(s); err == nil {
val = &f
} else if s != "" {
return err
}
return set(val)
}
return ptrSetter(parseFloat, set)
}
func intSetter(set func(int) error) func(string) error {