forked from gopcua/opcua
-
Notifications
You must be signed in to change notification settings - Fork 0
/
trigger.go
173 lines (149 loc) · 4.97 KB
/
trigger.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
// Copyright 2018-2020 opcua authors. All rights reserved.
// Use of this source code is governed by a MIT-style license that can be
// found in the LICENSE file.
package main
import (
"context"
"flag"
"fmt"
"log"
"time"
"github.com/mvandergrift/opcua"
"github.com/mvandergrift/opcua/debug"
"github.com/mvandergrift/opcua/id"
"github.com/mvandergrift/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")
triggerNodeID = flag.String("trigger", "", "node id to trigger with")
reportNodeID = flag.String("report", "", "node id value to report on trigger")
filter = flag.String("filter", "timestamp", "DataFilter: status, value, timestamp.")
interval = flag.Duration("interval", opcua.DefaultSubscriptionInterval, "subscription interval")
)
flag.BoolVar(&debug.Enable, "debug", false, "enable debug logging")
flag.Parse()
log.SetFlags(0)
// add an arbitrary timeout to demonstrate how to stop a subscription
// with a context.
d := 60 * time.Second
ctx, cancel := context.WithTimeout(context.Background(), d)
defer 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")
}
fmt.Println("*", 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, err := opcua.NewClient(ep.EndpointURL, opts...)
if err != nil {
log.Fatal(err)
}
if err := c.Connect(ctx); err != nil {
log.Fatal(err)
}
defer c.Close(ctx)
notifyCh := make(chan *opcua.PublishNotificationData)
sub, err := c.Subscribe(ctx, &opcua.SubscriptionParameters{
Interval: *interval,
}, notifyCh)
if err != nil {
log.Fatal(err)
}
defer sub.Cancel(ctx)
log.Printf("Created subscription with id %v", sub.SubscriptionID)
triggeringNode, err := ua.ParseNodeID(*triggerNodeID)
if err != nil {
log.Fatal(err)
}
triggeredNode, err := ua.ParseNodeID(*reportNodeID)
if err != nil {
log.Fatal(err)
}
miCreateRequests := []*ua.MonitoredItemCreateRequest{
opcua.NewMonitoredItemCreateRequestWithDefaults(triggeringNode, ua.AttributeIDValue, 42),
{
ItemToMonitor: &ua.ReadValueID{
NodeID: triggeredNode,
AttributeID: ua.AttributeIDValue,
DataEncoding: &ua.QualifiedName{},
},
MonitoringMode: ua.MonitoringModeSampling,
RequestedParameters: &ua.MonitoringParameters{
ClientHandle: 43,
DiscardOldest: true,
Filter: getFilter(*filter),
QueueSize: 10,
SamplingInterval: 0.0,
},
},
}
subRes, err := sub.Monitor(ctx, ua.TimestampsToReturnBoth, miCreateRequests...)
if err != nil || subRes.Results[0].StatusCode != ua.StatusOK {
log.Fatal(err)
}
triggeringServerID, triggeredServerID := subRes.Results[0].MonitoredItemID, subRes.Results[1].MonitoredItemID
tRes, err := sub.SetTriggering(ctx, triggeringServerID, []uint32{triggeredServerID}, nil)
if err != nil {
log.Fatal(err)
}
if tRes.AddResults[0] != ua.StatusOK {
log.Fatal(tRes.AddResults[0].Error())
}
// read from subscription's notification channel until ctx is cancelled
for {
select {
case <-ctx.Done():
return
case res := <-notifyCh:
if res.Error != nil {
log.Print(res.Error)
continue
}
switch x := res.Value.(type) {
case *ua.DataChangeNotification:
for _, item := range x.MonitoredItems {
data := item.Value.Value.Value()
log.Printf("MonitoredItem with client handle %v = %v", item.ClientHandle, data)
}
default:
log.Printf("what's this publish result? %T", res.Value)
}
}
}
}
func getFilter(filterStr string) *ua.ExtensionObject {
var filter ua.DataChangeFilter
switch filterStr {
case "status":
filter = ua.DataChangeFilter{Trigger: ua.DataChangeTriggerStatus}
case "value":
filter = ua.DataChangeFilter{Trigger: ua.DataChangeTriggerStatusValue}
case "timestamp":
filter = ua.DataChangeFilter{Trigger: ua.DataChangeTriggerStatusValueTimestamp}
default:
log.Fatalf("Unable to match to a valid filter type: %v\nShould be status, value, or timestamp", filterStr)
}
return &ua.ExtensionObject{
EncodingMask: ua.ExtensionObjectBinary,
TypeID: &ua.ExpandedNodeID{
NodeID: ua.NewNumericNodeID(0, id.DataChangeFilter_Encoding_DefaultBinary),
},
Value: filter,
}
}