-
Notifications
You must be signed in to change notification settings - Fork 272
/
Copy pathsubscribe.go
220 lines (194 loc) · 6.23 KB
/
subscribe.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
// 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/gopcua/opcua"
"github.com/gopcua/opcua/debug"
"github.com/gopcua/opcua/id"
"github.com/gopcua/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")
event = flag.Bool("event", false, "subscribe to node event changes (Default: node value changes)")
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()
log.Printf("Subscription will stop after %s for demonstration purposes", d)
endpoints, err := opcua.GetEndpoints(ctx, *endpoint)
if err != nil {
log.Fatal(err)
}
ep, err := opcua.SelectEndpoint(endpoints, *policy, ua.MessageSecurityModeFromString(*mode))
if err != nil {
log.Fatal(err)
}
ep.EndpointURL = *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)
id, err := ua.ParseNodeID(*nodeID)
if err != nil {
log.Fatal(err)
}
var miCreateRequest *ua.MonitoredItemCreateRequest
var eventFieldNames []string
if *event {
miCreateRequest, eventFieldNames = eventRequest(id)
} else {
miCreateRequest = valueRequest(id)
}
res, err := sub.Monitor(ctx, ua.TimestampsToReturnBoth, miCreateRequest)
if err != nil || res.Results[0].StatusCode != ua.StatusOK {
log.Fatal(err)
}
// Uncomment the following to try modifying the subscription
//
// var params opcua.SubscriptionParameters
// params.Interval = time.Millisecond * 2000
// if _, err := sub.ModifySubscription(ctx, params); err != nil {
// log.Fatal(err)
// }
// 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)
}
case *ua.EventNotificationList:
for _, item := range x.Events {
log.Printf("Event for client handle: %v\n", item.ClientHandle)
for i, field := range item.EventFields {
log.Printf("%v: %v of Type: %T", eventFieldNames[i], field.Value(), field.Value())
}
log.Println()
}
default:
log.Printf("what's this publish result? %T", res.Value)
}
}
}
}
func valueRequest(nodeID *ua.NodeID) *ua.MonitoredItemCreateRequest {
handle := uint32(42)
return opcua.NewMonitoredItemCreateRequestWithDefaults(nodeID, ua.AttributeIDValue, handle)
}
func eventRequest(nodeID *ua.NodeID) (*ua.MonitoredItemCreateRequest, []string) {
fieldNames := []string{"EventId", "EventType", "Severity", "Time", "Message"}
selects := make([]*ua.SimpleAttributeOperand, len(fieldNames))
for i, name := range fieldNames {
selects[i] = &ua.SimpleAttributeOperand{
TypeDefinitionID: ua.NewNumericNodeID(0, id.BaseEventType),
BrowsePath: []*ua.QualifiedName{{NamespaceIndex: 0, Name: name}},
AttributeID: ua.AttributeIDValue,
}
}
wheres := &ua.ContentFilter{
Elements: []*ua.ContentFilterElement{
{
FilterOperator: ua.FilterOperatorGreaterThanOrEqual,
FilterOperands: []*ua.ExtensionObject{
{
EncodingMask: 1,
TypeID: &ua.ExpandedNodeID{
NodeID: ua.NewNumericNodeID(0, id.SimpleAttributeOperand_Encoding_DefaultBinary),
},
Value: ua.SimpleAttributeOperand{
TypeDefinitionID: ua.NewNumericNodeID(0, id.BaseEventType),
BrowsePath: []*ua.QualifiedName{{NamespaceIndex: 0, Name: "Severity"}},
AttributeID: ua.AttributeIDValue,
},
},
{
EncodingMask: 1,
TypeID: &ua.ExpandedNodeID{
NodeID: ua.NewNumericNodeID(0, id.LiteralOperand_Encoding_DefaultBinary),
},
Value: ua.LiteralOperand{
Value: ua.MustVariant(uint16(0)),
},
},
},
},
},
}
filter := ua.EventFilter{
SelectClauses: selects,
WhereClause: wheres,
}
filterExtObj := ua.ExtensionObject{
EncodingMask: ua.ExtensionObjectBinary,
TypeID: &ua.ExpandedNodeID{
NodeID: ua.NewNumericNodeID(0, id.EventFilter_Encoding_DefaultBinary),
},
Value: filter,
}
handle := uint32(42)
req := &ua.MonitoredItemCreateRequest{
ItemToMonitor: &ua.ReadValueID{
NodeID: nodeID,
AttributeID: ua.AttributeIDEventNotifier,
DataEncoding: &ua.QualifiedName{},
},
MonitoringMode: ua.MonitoringModeReporting,
RequestedParameters: &ua.MonitoringParameters{
ClientHandle: handle,
DiscardOldest: true,
Filter: &filterExtObj,
QueueSize: 10,
SamplingInterval: 1.0,
},
}
return req, fieldNames
}