forked from evcc-io/evcc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmqtt_handler.go
81 lines (64 loc) · 1.43 KB
/
mqtt_handler.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package provider
import (
"fmt"
"math"
"strconv"
"time"
"github.com/evcc-io/evcc/provider/pipeline"
"github.com/evcc-io/evcc/util"
)
type msgHandler struct {
mux *util.Waiter
scale float64
topic string
pipeline *pipeline.Pipeline
payload string
}
func (h *msgHandler) receive(payload string) {
h.mux.Lock()
defer h.mux.Unlock()
h.payload = payload
h.mux.Update()
}
// hasValue returned the received and processed payload as string
func (h *msgHandler) hasValue() (string, error) {
h.mux.Lock()
defer h.mux.Unlock()
if late := h.mux.Overdue(); late > 0 {
return "", fmt.Errorf("%s outdated: %v", h.topic, late.Truncate(time.Second))
}
if h.pipeline != nil {
b, err := h.pipeline.Process([]byte(h.payload))
return string(b), err
}
return h.payload, nil
}
func (h *msgHandler) floatGetter() (float64, error) {
v, err := h.hasValue()
if err != nil {
return 0, err
}
f, err := strconv.ParseFloat(v, 64)
if err != nil {
return 0, fmt.Errorf("%s invalid: '%s'", h.topic, v)
}
return f * h.scale, nil
}
func (h *msgHandler) intGetter() (int64, error) {
f, err := h.floatGetter()
return int64(math.Round(f)), err
}
func (h *msgHandler) stringGetter() (string, error) {
v, err := h.hasValue()
if err != nil {
return "", err
}
return string(v), nil
}
func (h *msgHandler) boolGetter() (bool, error) {
v, err := h.hasValue()
if err != nil {
return false, err
}
return util.Truish(v), nil
}