forked from gopcua/opcua
-
Notifications
You must be signed in to change notification settings - Fork 0
/
monitor.go
154 lines (126 loc) · 4.04 KB
/
monitor.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
package main
import (
"context"
"flag"
"log"
"os"
"os/signal"
"sync"
"time"
"github.com/barisvelioglu/opcua"
"github.com/barisvelioglu/opcua/debug"
"github.com/barisvelioglu/opcua/monitor"
"github.com/barisvelioglu/opcua/ua"
)
func main() {
var (
endpoint = flag.String("endpoint", "opc.tcp://localhost:4840", "OPC UA Endpoint URL")
policy = flag.String("policy", "", "Security policy: None, Basic128Rsa15, Basic256, Basic256Sha256. Default: auto")
mode = flag.String("mode", "", "Security mode: None, Sign, SignAndEncrypt. Default: auto")
certFile = flag.String("cert", "", "Path to cert.pem. Required for security mode/policy != None")
keyFile = flag.String("key", "", "Path to private key.pem. Required for security mode/policy != None")
nodeID = flag.String("node", "", "node id to subscribe to")
interval = flag.String("interval", opcua.DefaultSubscriptionInterval.String(), "subscription interval")
)
flag.BoolVar(&debug.Enable, "debug", false, "enable debug logging")
flag.Parse()
// log.SetFlags(0)
subInterval, err := time.ParseDuration(*interval)
if err != nil {
log.Fatal(err)
}
signalCh := make(chan os.Signal, 1)
signal.Notify(signalCh, os.Interrupt)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go func() {
<-signalCh
println()
cancel()
}()
endpoints, err := opcua.GetEndpoints(ctx, *endpoint)
if err != nil {
log.Fatal(err)
}
ep := opcua.SelectEndpoint(endpoints, *policy, ua.MessageSecurityModeFromString(*mode))
if ep == nil {
log.Fatal("Failed to find suitable endpoint")
}
log.Print("*", ep.SecurityPolicyURI, ep.SecurityMode)
opts := []opcua.Option{
opcua.SecurityPolicy(*policy),
opcua.SecurityModeString(*mode),
opcua.CertificateFile(*certFile),
opcua.PrivateKeyFile(*keyFile),
opcua.AuthAnonymous(),
opcua.SecurityFromEndpoint(ep, ua.UserTokenTypeAnonymous),
}
c := opcua.NewClient(ep.EndpointURL, opts...)
if err := c.Connect(ctx); err != nil {
log.Fatal(err)
}
defer c.Close()
m, err := monitor.NewNodeMonitor(c)
if err != nil {
log.Fatal(err)
}
m.SetErrorHandler(func(_ *opcua.Client, sub *monitor.Subscription, err error) {
log.Printf("error: sub=%d err=%s", sub.SubscriptionID(), err.Error())
})
wg := &sync.WaitGroup{}
// start callback-based subscription
wg.Add(1)
go startCallbackSub(ctx, m, subInterval, 0, wg, *nodeID)
// start channel-based subscription
wg.Add(1)
go startChanSub(ctx, m, subInterval, 0, wg, *nodeID)
<-ctx.Done()
wg.Wait()
}
func startCallbackSub(ctx context.Context, m *monitor.NodeMonitor, interval, lag time.Duration, wg *sync.WaitGroup, nodes ...string) {
sub, err := m.Subscribe(
ctx,
&opcua.SubscriptionParameters{
Interval: interval,
},
func(s *monitor.Subscription, msg *monitor.DataChangeMessage) {
if msg.Error != nil {
log.Printf("[callback] sub=%d error=%s", s.SubscriptionID(), msg.Error)
} else {
log.Printf("[callback] sub=%d ts=%s node=%s value=%v", s.SubscriptionID(), msg.SourceTimestamp.UTC().Format(time.RFC3339), msg.NodeID, msg.Value.Value())
}
time.Sleep(lag)
},
nodes...)
if err != nil {
log.Fatal(err)
}
defer cleanup(sub, wg)
<-ctx.Done()
}
func startChanSub(ctx context.Context, m *monitor.NodeMonitor, interval, lag time.Duration, wg *sync.WaitGroup, nodes ...string) {
ch := make(chan *monitor.DataChangeMessage, 16)
sub, err := m.ChanSubscribe(ctx, &opcua.SubscriptionParameters{Interval: interval}, ch, nodes...)
if err != nil {
log.Fatal(err)
}
defer cleanup(sub, wg)
for {
select {
case <-ctx.Done():
return
case msg := <-ch:
if msg.Error != nil {
log.Printf("[channel ] sub=%d error=%s", sub.SubscriptionID(), msg.Error)
} else {
log.Printf("[channel ] sub=%d ts=%s node=%s value=%v", sub.SubscriptionID(), msg.SourceTimestamp.UTC().Format(time.RFC3339), msg.NodeID, msg.Value.Value())
}
time.Sleep(lag)
}
}
}
func cleanup(sub *monitor.Subscription, wg *sync.WaitGroup) {
log.Printf("stats: sub=%d delivered=%d dropped=%d", sub.SubscriptionID(), sub.Delivered(), sub.Dropped())
sub.Unsubscribe()
wg.Done()
}