/
state.go
79 lines (65 loc) · 1.46 KB
/
state.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
package main
import (
"sync"
"github.com/stampzilla/stampzilla-go/nodes/basenode"
"github.com/stampzilla/stampzilla-go/protocol"
"github.com/stampzilla/stampzilla-go/protocol/devices"
)
type State struct {
Devices map[string]*Chromecast
connection basenode.Connection
node *protocol.Node
sync.RWMutex
}
func (s *State) Publish() {
if s.node != nil {
s.connection.Send(s.node.Node())
}
}
func (s *State) GetByUUID(uuid string) *Chromecast {
s.RLock()
defer s.RUnlock()
if val, ok := s.Devices[uuid]; ok {
return val
}
return nil
}
func (s *State) Add(c *Chromecast) {
c.publish = s.Publish
if s.Devices == nil {
s.Devices = make(map[string]*Chromecast, 0)
}
s.Lock()
s.Devices[c.Uuid()] = c
s.Unlock()
s.node.Devices_.Add(&devices.Device{
Type: "chromecast",
Name: c.Name_,
Id: c.Id,
Online: true,
Node: s.node.Uuid(),
StateMap: map[string]string{
"Playing": c.Id + ".Playing",
"PrimaryApp": c.Id + ".PrimaryApp",
"Title": c.Id + ".Media.Title",
"SubTitle": c.Id + ".Media.SubTitle",
"Thumb": c.Id + ".Media.Thumb",
"Url": c.Id + ".Media.Url",
"Duration": c.Id + ".Media.Duration",
},
})
s.Publish()
}
// Remove removes a chromecast from the state
func (s *State) Remove(c *Chromecast) {
_, ok := s.Devices[c.Uuid()]
if ok {
s.Lock()
delete(s.Devices, c.Uuid())
s.Unlock()
}
if dev := s.node.Devices_.ByID(c.Id); dev != nil {
dev.SetOnline(false)
}
s.Publish()
}