Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Merged
merged 1 commit into from
Nov 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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