/
handler.go
85 lines (66 loc) · 1.53 KB
/
handler.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
package config
import (
"errors"
"fmt"
"sync"
)
type handler[T any] struct {
mu sync.RWMutex
topic string
devices []Device[T]
}
type Operation string
const (
OpAdd Operation = "add"
OpDelete Operation = "del"
)
func (cp *handler[T]) Subscribe(fn func(Operation, Device[T])) {
if err := bus.Subscribe(cp.topic, fn); err != nil {
panic(err)
}
}
// Devices returns the handlers devices
func (cp *handler[T]) Devices() []Device[T] {
cp.mu.RLock()
defer cp.mu.RUnlock()
return cp.devices
}
// Add adds device and config
func (cp *handler[T]) Add(dev Device[T]) error {
conf := dev.Config()
if conf.Name == "" {
return errors.New("missing name")
}
if _, err := cp.ByName(conf.Name); err == nil {
return fmt.Errorf("duplicate name: %s already defined and must be unique", conf.Name)
}
cp.mu.Lock()
cp.devices = append(cp.devices, dev)
cp.mu.Unlock()
bus.Publish(cp.topic, OpAdd, dev)
return nil
}
// Delete deletes device
func (cp *handler[T]) Delete(name string) error {
cp.mu.RLock()
defer cp.mu.RUnlock()
for i, dev := range cp.devices {
if name == dev.Config().Name {
cp.devices = append(cp.devices[:i], cp.devices[i+1:]...)
bus.Publish(cp.topic, OpDelete, dev)
return nil
}
}
return fmt.Errorf("not found: %s", name)
}
// ByName provides device by name
func (cp *handler[T]) ByName(name string) (Device[T], error) {
cp.mu.RLock()
defer cp.mu.RUnlock()
for _, dev := range cp.devices {
if name == dev.Config().Name {
return dev, nil
}
}
return nil, fmt.Errorf("not found: %s", name)
}