Skip to content

Commit

Permalink
Mqtt: allow nil/null/none/- as empty values (#17209)
Browse files Browse the repository at this point in the history
  • Loading branch information
andig authored Nov 13, 2024
1 parent d6f9e7a commit 3398312
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 10 deletions.
2 changes: 1 addition & 1 deletion server/mqtt.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
29 changes: 20 additions & 9 deletions server/mqtt_setter.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package server

import (
"slices"
"strconv"
"time"

Expand All @@ -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)
Expand All @@ -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 {
Expand Down

0 comments on commit 3398312

Please sign in to comment.