-
Notifications
You must be signed in to change notification settings - Fork 85
/
datamodel.go
83 lines (69 loc) · 1.47 KB
/
datamodel.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
package opc
import (
"io"
"sync"
"time"
)
//Collector interface
type Collector interface {
Get(string) (interface{}, bool)
Sync(Connection, time.Duration) io.Closer
}
//data holds the data structure that is refreshed with OPC data.
type data struct {
tags map[string]interface{}
mu sync.RWMutex
}
//Get is the thread-safe getter for the tags.
func (d *data) Get(key string) (interface{}, bool) {
d.mu.RLock()
value, ok := d.tags[key]
d.mu.RUnlock()
return value, ok
}
//update is a helper function to update map
func (d *data) update(conn Connection) {
update := conn.Read()
d.mu.Lock()
for key, item := range update {
d.tags[key] = item.Value
}
d.mu.Unlock()
}
//Sync synchronizes the opc server and stores the data into the data model.
func (d *data) Sync(conn Connection, refreshRate time.Duration) io.Closer {
control := newControl()
ticker := time.NewTicker(refreshRate)
d.update(conn)
go func() {
for {
select {
case <-ticker.C:
d.update(conn)
case <-control.close:
ticker.Stop()
control.done <- true
return
}
}
}()
return control
}
//NewDataModel returns an OPC Data struct.
func NewDataModel() Collector {
return &data{tags: make(map[string]interface{})}
}
type control struct {
close chan bool
done chan bool
}
func (c *control) Close() error {
if c.close != nil && c.done != nil {
c.close <- true
<-c.done
}
return nil
}
func newControl() *control {
return &control{close: make(chan bool), done: make(chan bool)}
}