-
Notifications
You must be signed in to change notification settings - Fork 0
/
goscript.go
200 lines (165 loc) · 4.23 KB
/
goscript.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
package goscript
import (
"context"
"errors"
"fmt"
"github.com/go-logr/logr"
"github.com/go-logr/logr/funcr"
"github.com/google/uuid"
hassmqtt "github.com/kjbreil/hass-mqtt"
hassws "github.com/kjbreil/hass-ws"
"github.com/kjbreil/hass-ws/model"
"github.com/kjbreil/hass-ws/services"
"sync"
"time"
)
// GoScript is the base type for GoScript holding all the state and functionality for interacting with Home Assistant
type GoScript struct {
config *Config
mqtt *hassmqtt.Client
ws *hassws.Client
// maps holding state based triggers
periodic map[string][]*Trigger
nextPeriodic time.Time
triggers map[string][]*Trigger
domainTrigger map[string][]*Trigger
triggerRunning triggerRunning
devices map[string]*Device
areaRegistry map[string][]model.Result
taskToRun taskMap
// Context for the GoScript
ctx context.Context
cancel context.CancelFunc
ServiceChan ServiceChan
// states store
states States
logger logr.Logger
}
// New creates a new GoScript instance
func New(c *Config, logger logr.Logger) (*GoScript, error) {
var err error
gs := &GoScript{
config: c,
logger: logger,
}
gs.mqtt, err = hassmqtt.NewClientWithLogger(*gs.config.MQTT, gs.logger)
if err != nil {
return nil, err
}
gs.ws, err = hassws.NewClientWithLogger(gs.config.Websocket, gs.logger)
if err != nil {
return nil, err
}
gs.ws.Logger()
gs.triggers = make(map[string][]*Trigger)
gs.domainTrigger = make(map[string][]*Trigger)
gs.periodic = make(map[string][]*Trigger)
gs.ServiceChan = make(chan services.Service, 100)
gs.taskToRun = taskMap{
tasks: make(map[uuid.UUID][]*Task),
m: &sync.Mutex{},
}
gs.triggerRunning = triggerRunning{
m: make(map[uuid.UUID]*bool),
s: &sync.Mutex{},
}
gs.states = States{
s: make(map[string]*State),
m: &sync.Mutex{},
}
gs.devices = make(map[string]*Device)
return gs, nil
}
// Connect connects to the WebSocket server and MQTT server as setup
// all options need to be passed before firing connect, anything added after will have odd effects
func (gs *GoScript) Connect() error {
var err error
gs.ctx, gs.cancel = context.WithCancel(context.Background())
if gs.mqtt != nil {
err = gs.mqtt.Connect()
if err != nil {
if !errors.Is(err, hassmqtt.ErrNoDeviceFound) {
return err
}
}
gs.logger.Info("MQTT connected")
}
// Add a subscription for the websocket on all events
gs.ws.AddSubscription(model.EventTypeAll)
// Handle all messages
gs.ws.OnMessage = gs.handleMessage
// handle running get States
gs.ws.OnGetState = gs.handleGetStates
// setup hass_ws to initialize all States at connect. This is run through the triggers.
gs.ws.InitStates = true
err = gs.ws.Connect()
if err != nil {
return err
}
gs.logger.Info("Websocket connected")
gs.fillAreaRegistry()
time.Sleep(100 * time.Millisecond)
go gs.runFunctions()
go gs.runService()
go gs.runPeriodic()
gs.logger.Info("GoScript started")
return nil
}
// Logger returns the logr to create your own logs
func (gs *GoScript) Logger() logr.Logger {
return gs.logger
}
func (gs *GoScript) runFunctions() {
defer func() {
gs.logger.Info("runFunctions exited")
}()
timer := time.NewTicker(10 * time.Millisecond)
for {
select {
case <-gs.ctx.Done():
return
case <-timer.C:
var ran []uuid.UUID
gs.taskToRun.m.Lock()
for u, tasks := range gs.taskToRun.tasks {
if len(tasks) > 0 {
t := tasks[0]
if !*t.running {
go gs.runTask(t)
gs.taskToRun.tasks[u] = tasks[1:]
}
}
if len(tasks) == 0 {
ran = append(ran, u)
}
}
for _, u := range ran {
delete(gs.taskToRun.tasks, u)
}
gs.taskToRun.m.Unlock()
}
}
}
// Close the connections to WebSocket and MQTT
func (gs *GoScript) Close() {
gs.cancel()
err := gs.ws.Close()
gs.mqtt.Disconnect()
if err != nil {
gs.logger.Error(err, "error closing websocket")
}
}
// GetModule returns the config module in interface{} form, must be cast to module type
func (gs *GoScript) GetModule(key string) (interface{}, error) {
return gs.config.GetModule(key)
}
func DefaultLogger() logr.Logger {
log := funcr.New(
func(pfx, args string) { fmt.Println(pfx, args) },
funcr.Options{
LogCaller: funcr.None,
LogTimestamp: true,
Verbosity: 1,
})
return log.WithName("goscript")
}