-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconnection.go
190 lines (150 loc) · 4.91 KB
/
connection.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
package hal
import (
"fmt"
"log/slog"
"sync"
"time"
"github.com/dansimau/hal/hassws"
"github.com/dansimau/hal/perf"
"github.com/dansimau/hal/store"
"github.com/davecgh/go-spew/spew"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
// Connection is a new instance of the HAL framework. It connects to Home Assistant,
// listens for state updates and invokes automations when state changes are detected.
// TODO: Rename "Connection" to something more descriptive.
type Connection struct {
config Config
db *gorm.DB
automations map[string][]Automation
entities map[string]EntityInterface
// Lock to serialize state updates and ensure automations fire in order.
mutex sync.RWMutex
homeAssistant *hassws.Client
*SunTimes
}
// ConnectionBinder is an interface that can be implemented by entities to bind
// them to a connection.
type ConnectionBinder interface {
BindConnection(connection *Connection)
}
func NewConnection(cfg Config) *Connection {
db, err := store.Open("sqlite.db")
if err != nil {
panic(err)
}
api := hassws.NewClient(hassws.ClientConfig{
Host: cfg.HomeAssistant.Host,
Token: cfg.HomeAssistant.Token,
})
return &Connection{
config: cfg,
db: db,
homeAssistant: api,
automations: make(map[string][]Automation),
entities: make(map[string]EntityInterface),
SunTimes: NewSunTimes(cfg.Location),
}
}
func (h *Connection) CallService(msg hassws.CallServiceRequest) (hassws.CallServiceResponse, error) {
return h.homeAssistant.CallService(msg)
}
// FindEntities recursively finds and registers all entities in a struct, map, or slice.
func (h *Connection) FindEntities(v any) {
h.RegisterEntities(findEntities(v)...)
}
// RegisterAutomations registers automations and binds them to the relevant entities.
func (h *Connection) RegisterAutomations(automations ...Automation) {
for _, automation := range automations {
slog.Info("Registering automation", "Name", automation.Name())
for _, entity := range automation.Entities() {
h.automations[entity.GetID()] = append(h.automations[entity.GetID()], automation)
}
}
}
// RegisterEntities registers entities and binds them to the connection.
func (h *Connection) RegisterEntities(entities ...EntityInterface) {
for _, entity := range entities {
slog.Info("Registering entity", "EntityID", entity.GetID())
entity.BindConnection(h)
h.entities[entity.GetID()] = entity
// Entities can also be automations
if automation, ok := entity.(Automation); ok {
h.RegisterAutomations(automation)
}
}
}
// Start connects to the Home Assistant websocket and starts listening for events.
func (h *Connection) Start() error {
if err := h.homeAssistant.Connect(); err != nil {
return err
}
if err := h.homeAssistant.SubscribeEvents(string(hassws.MessageTypeStateChanged), h.StateChangeEvent); err != nil {
return fmt.Errorf("failed to subscribe to state changed events: %w", err)
}
if err := h.syncStates(); err != nil {
return fmt.Errorf("failed to sync initial states: %w", err)
}
return nil
}
func (h *Connection) Close() {
h.homeAssistant.Close()
}
func (h *Connection) syncStates() error {
defer perf.Timer(func(timeTaken time.Duration) {
slog.Info("Initial state sync complete", "duration", timeTaken)
})()
states, err := h.homeAssistant.GetStates()
if err != nil {
return err
}
for _, state := range states {
entity, ok := h.entities[state.EntityID]
if !ok {
continue
}
slog.Debug("Setting initial state", "EntityID", state.EntityID, "State", state)
entity.SetState(state)
}
return nil
}
// Process incoming state change events. Dispatch state change to the relevant
// entity and fire any automations listening for state changes to this entity.
func (h *Connection) StateChangeEvent(event hassws.EventMessage) {
defer perf.Timer(func(timeTaken time.Duration) {
slog.Debug("Tick processing time", "duration", timeTaken)
})()
h.mutex.Lock()
defer h.mutex.Unlock()
entity, ok := h.entities[event.Event.EventData.EntityID]
if !ok {
slog.Debug("Entity not registered", "EntityID", event.Event.EventData.EntityID)
return
}
slog.Debug("State changed for",
"EntityID", event.Event.EventData.EntityID,
"NewState", spew.Sdump(event.Event.EventData.NewState),
)
if event.Event.EventData.NewState != nil {
entity.SetState(*event.Event.EventData.NewState)
}
// Update database
h.db.Clauses(clause.OnConflict{
UpdateAll: true,
}).Create(&store.Entity{
ID: event.Event.EventData.EntityID,
Type: entity.GetID(),
State: event.Event.EventData.NewState,
})
// Prevent loops by not running automations that originate from hal
if event.Event.Context.UserID == h.config.HomeAssistant.UserID {
slog.Debug("Skipping automation from own action", "EntityID", event.Event.EventData.EntityID)
return
}
// Dispatch automations
for _, automation := range h.automations[event.Event.EventData.EntityID] {
slog.Info("Running automation", "name", automation.Name())
automation.Action(entity)
}
}