/
container.go
259 lines (235 loc) · 6.9 KB
/
container.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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
package container
import (
"context"
"github.com/galenliu/gateway/pkg/addon/events"
"github.com/galenliu/gateway/pkg/bus"
"github.com/galenliu/gateway/pkg/bus/topic"
"github.com/galenliu/gateway/pkg/errors"
"github.com/galenliu/gateway/pkg/log"
"github.com/gofiber/fiber/v2"
"sync"
"time"
)
type Container interface {
SetThingPropertyValue(thingId, propertyName string, value any) (any, error)
GetThingPropertyValue(thingId, propertyName string) (any, error)
Publish(topic2 topic.Topic, args ...any)
Subscribe(topic2 topic.Topic, f any) error
Unsubscribe(topic2 topic.Topic, f any)
GetThing(thing string) *Thing
GetThings() []*Thing
}
type Manager interface {
SetPropertyValue(ctx context.Context, thingId, propertyName string, value any) (any, error)
GetPropertyValue(thingId, propertyName string) (any, error)
GetPropertiesValue(thingId string) (map[string]any, error)
Publish(topic2 topic.Topic, args ...any)
Subscribe(topic2 topic.Topic, f any) error
}
// ThingsStorage CRUD
type ThingsStorage interface {
DeleteThing(id string) error
CreateThing(id string, thing *Thing) error
UpdateThing(id string, thing *Thing) error
GetThings() map[string][]byte
}
// ThingsContainer 管理所有Thing Models
// 向外部发送ThingAdded,ThingRemoved,ThingModify,ThingConnected事件
type ThingsContainer struct {
things sync.Map
manager Manager
store ThingsStorage
bus.ThingsBus
}
// NewThingsContainerModel 管理所有Thing Models
func NewThingsContainerModel(manager Manager, store ThingsStorage) *ThingsContainer {
t := &ThingsContainer{}
t.store = store
t.manager = manager
t.ThingsBus = bus.NewBus()
t.updateThings()
_ = manager.Subscribe(topic.DeviceAdded, t.handleDeviceAdded)
_ = manager.Subscribe(topic.DeviceRemoved, t.handleDeviceRemoved)
_ = manager.Subscribe(topic.DeviceConnected, t.handleDeviceConnected)
_ = manager.Subscribe(topic.DevicePropertyChanged, t.handleDevicePropertyChanged)
_ = manager.Subscribe(topic.DeviceActionStatus, t.handleDeviceActionStatus)
_ = manager.Subscribe(topic.DeviceEvent, t.handleDeviceEvent)
return t
}
func (c *ThingsContainer) GetThing(id string) *Thing {
a, _ := c.things.Load(id)
t, ok := a.(*Thing)
if !ok {
return nil
}
return t
}
func (c *ThingsContainer) SetThingPropertyValue(thingId, propName string, value any) (any, error) {
thing := c.GetThing(thingId)
if thing == nil {
return nil, errors.NotFoundError("thing: %s not found", thing.GetId())
}
prop, ok := thing.Properties[propName]
if !ok {
return nil, errors.NotFoundError("thing property:%s not found", propName)
}
if prop.IsReadOnly() {
return nil, fiber.NewError(fiber.StatusBadRequest, "property read only")
}
ctx, cancelFunc := context.WithTimeout(context.Background(), 2*time.Second)
defer func() {
cancelFunc()
}()
v, err := c.manager.SetPropertyValue(ctx, thingId, propName, value)
if err != nil {
return nil, err
}
return v, nil
}
func (c *ThingsContainer) GetThings() (ts []*Thing) {
ts = make([]*Thing, 0)
c.things.Range(func(key, value any) bool {
t, ok := value.(*Thing)
if ok {
ts = append(ts, t)
}
return true
})
return
}
func (c *ThingsContainer) GetThingPropertyValue(thingId, propName string) (any, error) {
return c.manager.GetPropertyValue(thingId, propName)
}
func (c *ThingsContainer) GetMapOfThings() map[string]*Thing {
things := c.GetThings()
if things == nil {
return nil
}
var thingsMap = make(map[string]*Thing)
for _, th := range things {
thingsMap[th.GetId()] = th
}
return thingsMap
}
// CreateThing container和store中创建Thing
// ThingAdded事件
func (c *ThingsContainer) CreateThing(data []byte) (*Thing, error) {
thing, err := NewThing(data, c)
thing.Connected = true
if err != nil {
return nil, fiber.NewError(fiber.StatusBadRequest, err.Error())
}
err = c.store.CreateThing(thing.GetId(), thing)
if err != nil {
return nil, err
}
c.things.Store(thing.GetId(), thing)
c.Publish(topic.ThingAdded, topic.ThingAddedMessage{
ThingId: thing.GetId(),
Data: data,
})
return thing, nil
}
// RemoveThing 从container和store中删除Thing
// 向定阅发送ThingRemoved事件
func (c *ThingsContainer) RemoveThing(thingId string) error {
t := c.GetThing(thingId)
err := c.store.DeleteThing(thingId)
if err != nil {
log.Errorf(err.Error())
}
if t == nil {
return errors.NotFoundError("Thing Not Found")
}
c.things.Delete(thingId)
c.Publish(topic.ThingRemoved, topic.ThingRemovedMessage{ThingId: thingId})
return nil
}
// UpdateThing 在container和Store中更新Thing
func (c *ThingsContainer) UpdateThing(thing *Thing) error {
err := c.store.UpdateThing(thing.GetId(), thing)
if err != nil {
return err
}
c.things.Store(thing.GetId(), thing)
c.Publish(topic.ThingModify, topic.ThingModifyMessage{ThingId: thing.GetId()})
return nil
}
// 如果container为空,则从Store里加载所有的Things
func (c *ThingsContainer) updateThings() {
things := c.GetThings()
if len(things) == 0 {
for id, data := range c.store.GetThings() {
thing, err := NewThing(data, c)
if err != nil {
log.Errorf(err.Error())
continue
}
c.things.Store(id, thing)
}
}
}
// 当Manager中有设备移除,则更新Container中Thing中Connected为false
// 并且向定阅发达ThingConnected通知
func (c *ThingsContainer) handleDeviceRemoved(thingId string) {
t := c.GetThing(thingId)
if t != nil {
t.setConnected(false)
}
c.Publish(topic.ThingConnected, topic.ThingConnectedMessage{
ThingId: t.GetId(),
Connected: false,
})
}
// 当Manager中有新设备,则更新Container中Thing状态
// 并且向定阅发达ThingConnected通知
func (c *ThingsContainer) handleDeviceAdded(msg topic.DeviceAddedMessage) {
t := c.GetThing(msg.DeviceId)
if t != nil {
t.setConnected(true)
}
c.Publish(topic.ThingConnected, topic.ThingConnectedMessage{
ThingId: msg.Id,
Connected: true,
})
}
// 当Manager中有设备离线消息时,同步Thing的状态
// 并向Container中的定阅发送ThingConnected消息
func (c *ThingsContainer) handleDeviceConnected(msg topic.DeviceConnectedMessage) {
t := c.GetThing(msg.DeviceId)
if t != nil {
t.setConnected(msg.Connected)
}
c.Publish(topic.ThingConnected, topic.ThingConnectedMessage{
ThingId: t.GetId(),
Connected: msg.Connected,
})
}
func (c *ThingsContainer) handleDevicePropertyChanged(message topic.DevicePropertyChangedMessage) {
t := c.GetThing(message.DeviceId)
if t == nil {
return
}
if p := t.GetProperty(message.PropertyName); p == nil {
return
}
c.Publish(topic.ThingPropertyChanged, topic.ThingPropertyChangedMessage{
ThingId: t.GetId(),
PropertyName: message.Name,
Value: message.Value,
})
}
func (c *ThingsContainer) handleDeviceActionStatus(msg topic.DeviceActionStatusMessage) {
t := c.GetThing(msg.DeviceId)
if t == nil {
return
}
t.onActionStatus(msg.Action)
}
func (c *ThingsContainer) handleDeviceEvent(deviceId string, event *events.EventDescription) {
t := c.GetThing(deviceId)
if t == nil {
return
}
t.OnEvent(event)
}