forked from evcc-io/evcc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhub.go
57 lines (47 loc) · 1.25 KB
/
hub.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
package push
import "github.com/andig/evcc/util"
// Event is a notification event
type Event struct {
Event string
Attributes map[string]interface{}
}
// apply applies the event template to the content to produce the actual message
func (e Event) apply(template string) (string, error) {
return util.ReplaceFormatted(template, e.Attributes)
}
// Hub subscribes to event notifications and sends them to client devices
type Hub struct {
definitions map[string]EventTemplate
sender []Sender
}
// NewHub creates push hub with definitions and receiver
func NewHub(definitions map[string]EventTemplate) *Hub {
h := &Hub{
definitions: definitions,
}
return h
}
// Add adds a sender to the list of senders
func (h *Hub) Add(sender Sender) {
h.sender = append(h.sender, sender)
}
// Run is the Hub's main publishing loop
func (h *Hub) Run(events <-chan Event) {
for ev := range events {
if len(h.sender) == 0 {
continue
}
definition, ok := h.definitions[ev.Event]
if !ok {
log.ERROR.Printf("invalid event %v", ev.Event)
break
}
msg, err := ev.apply(definition.Msg)
if err != nil {
log.ERROR.Printf("invalid message template: %v", err)
}
for _, sender := range h.sender {
go sender.Send(ev, definition.Title, msg)
}
}
}