-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
221 lines (188 loc) · 4.56 KB
/
main.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
//go:build js && wasm
package main
import (
_ "embed"
"fmt"
"slices"
"strconv"
"strings"
"time"
"github.com/glasslabs/client-go"
"github.com/pawal/go-hass"
)
var (
//go:embed assets/style.css
css []byte
//go:embed assets/index.html
html []byte
)
// Config is the module configuration.
type Config struct {
URL string `yaml:"url"`
Token string `yaml:"token"`
SensorIDs struct {
GeyserPct string `yaml:"geyserPct"`
TankPct string `yaml:"tankPct"`
WaterConnected string `yaml:"waterConnected"`
} `yaml:"sensorIds"`
Geyser struct {
Warning int `yaml:"warning"`
Low int `yaml:"low"`
} `yaml:"geyser"`
Tank struct {
Warning int `yaml:"warning"`
Low int `yaml:"low"`
} `yaml:"tank"`
}
// NewConfig creates a default configuration for the module.
func NewConfig() *Config {
return &Config{}
}
func main() {
log := client.NewLogger()
mod, err := client.NewModule()
if err != nil {
log.Error("Could not create module", "error", err.Error())
return
}
cfg := NewConfig()
if err = mod.ParseConfig(&cfg); err != nil {
log.Error("Could not parse config", "error", err.Error())
return
}
log.Info("Loading Module", "module", mod.Name())
m := &Module{
mod: mod,
cfg: cfg,
log: log,
}
if err = m.setup(); err != nil {
log.Error("Could not setup module", "error", err.Error())
return
}
first := true
for {
if !first {
time.Sleep(10 * time.Second)
}
first = false
if err = m.syncStates(); err != nil {
log.Error("Could not sync states", "error", err.Error())
continue
}
if err = m.listenStates(); err != nil {
log.Error("Could not listen to states", "error", err.Error())
continue
}
}
}
// Module runs the module.
type Module struct {
mod *client.Module
cfg *Config
ha *hass.Access
log *client.Logger
}
func (m *Module) setup() error {
if err := m.mod.LoadCSS(string(css)); err != nil {
return fmt.Errorf("loading css: %w", err)
}
m.mod.Element().SetInnerHTML(string(html))
ha := hass.NewAccess(m.cfg.URL, "")
ha.SetBearerToken(m.cfg.Token)
if err := ha.CheckAPI(); err != nil {
return fmt.Errorf("could not connect to home assistant: %w", err)
}
m.ha = ha
return nil
}
func (m *Module) syncStates() error {
states, err := m.ha.FilterStates("sensor", "binary_sensor")
if err != nil {
return fmt.Errorf("getting states: %w", err)
}
for _, state := range states {
m.updateState(state.EntityID, state.State)
}
return nil
}
func (m *Module) listenStates() error {
l, err := m.ha.ListenEvents()
if err != nil {
return fmt.Errorf("calling listen: %w", err)
}
defer func() { _ = l.Close() }()
for {
event, err := l.NextStateChanged()
if err != nil {
return fmt.Errorf("listening for event: %w", err)
}
if event.EventType != "state_changed" {
continue
}
prefix := strings.TrimSuffix(strings.SplitAfter(event.Data.EntityID, ".")[0], ".")
if !slices.Contains([]string{"sensor", "binary_sensor"}, prefix) {
continue
}
m.updateState(event.Data.EntityID, event.Data.NewState.State)
}
}
const percentageVar = "--percentage: "
func (m *Module) updateState(id, state string) {
switch id {
case m.cfg.SensorIDs.GeyserPct:
per, err := strconv.ParseFloat(state, 64)
if err != nil {
return
}
if per > 100 {
per = 100
}
perStr := strconv.FormatFloat(per, 'f', 0, 64)
var class string
if per <= float64(m.cfg.Geyser.Low) {
class = "low"
} else if per <= float64(m.cfg.Geyser.Warning) {
class = "warning"
}
if elem := m.mod.Element().QuerySelector("#heat"); elem != nil {
elem.SetAttribute("style", percentageVar+perStr)
elem.Class().Remove("low")
elem.Class().Remove("warning")
if class != "" {
elem.Class().Add(class)
}
}
if elem := m.mod.Element().QuerySelector("#geyserText .super"); elem != nil {
elem.SetTextContent(strconv.Itoa(int(per)))
}
case m.cfg.SensorIDs.TankPct:
per, err := strconv.ParseFloat(state, 64)
if err != nil {
return
}
perStr := strconv.FormatFloat(per, 'f', 2, 64)
var class string
if per <= float64(m.cfg.Tank.Low) {
class = "low"
} else if per <= float64(m.cfg.Tank.Warning) {
class = "warning"
}
if elem := m.mod.Element().QuerySelector("#water"); elem != nil {
elem.SetAttribute("style", percentageVar+perStr)
elem.Class().Remove("low")
elem.Class().Remove("warning")
if class != "" {
elem.Class().Add(class)
}
}
case m.cfg.SensorIDs.WaterConnected:
connected := state == "on"
if elem := m.mod.Element().QuerySelector("#water-disconnect"); elem != nil {
elem.Class().Remove("off")
if connected {
elem.Class().Add("off")
}
}
}
}