forked from gopcua/opcua
-
Notifications
You must be signed in to change notification settings - Fork 0
/
subscription.go
221 lines (198 loc) · 6.34 KB
/
subscription.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
package opcua
import (
"context"
"time"
"github.com/gopcua/opcua/ua"
"github.com/gopcua/opcua/uasc"
)
const (
DefaultSubscriptionMaxNotificationsPerPublish = 10000
DefaultSubscriptionLifetimeCount = 10000
DefaultSubscriptionMaxKeepAliveCount = 3000
DefaultSubscriptionInterval = 100 * time.Millisecond
DefaultSubscriptionPriority = 0
)
type Subscription struct {
SubscriptionID uint32
RevisedPublishingInterval time.Duration
RevisedLifetimeCount uint32
RevisedMaxKeepAliveCount uint32
Notifs chan *PublishNotificationData
c *Client
}
type SubscriptionParameters struct {
Interval time.Duration
LifetimeCount uint32
MaxKeepAliveCount uint32
MaxNotificationsPerPublish uint32
Priority uint8
Notifs chan *PublishNotificationData
}
func NewMonitoredItemCreateRequestWithDefaults(nodeID *ua.NodeID, attributeID ua.AttributeID, clientHandle uint32) *ua.MonitoredItemCreateRequest {
if attributeID == 0 {
attributeID = ua.AttributeIDValue
}
return &ua.MonitoredItemCreateRequest{
ItemToMonitor: &ua.ReadValueID{
NodeID: nodeID,
AttributeID: attributeID,
DataEncoding: &ua.QualifiedName{},
},
MonitoringMode: ua.MonitoringModeReporting,
RequestedParameters: &ua.MonitoringParameters{
ClientHandle: clientHandle,
DiscardOldest: true,
Filter: nil,
QueueSize: 10,
SamplingInterval: 0.0,
},
}
}
type PublishNotificationData struct {
SubscriptionID uint32
Error error
Value interface{}
}
// Cancel() deletes the Subscription from Server and makes the Client forget it so that publishing
// loops cannot deliver notifications to it anymore
func (s *Subscription) Cancel() error {
s.c.forgetSubscription(s.SubscriptionID)
req := &ua.DeleteSubscriptionsRequest{
SubscriptionIDs: []uint32{s.SubscriptionID},
}
var res *ua.DeleteSubscriptionsResponse
err := s.c.Send(req, func(v interface{}) error {
return safeAssign(v, &res)
})
if err != nil {
return err
}
if res.ResponseHeader.ServiceResult != ua.StatusOK {
return res.ResponseHeader.ServiceResult
}
return nil
}
func (s *Subscription) Monitor(ts ua.TimestampsToReturn, items ...*ua.MonitoredItemCreateRequest) (*ua.CreateMonitoredItemsResponse, error) {
// Part 4, 5.12.2.2 CreateMonitoredItems Service Parameters
req := &ua.CreateMonitoredItemsRequest{
SubscriptionID: s.SubscriptionID,
TimestampsToReturn: ts,
ItemsToCreate: items,
}
var res *ua.CreateMonitoredItemsResponse
err := s.c.Send(req, func(v interface{}) error {
return safeAssign(v, &res)
})
return res, err
}
func (s *Subscription) Unmonitor(monitoredItemIDs ...uint32) (*ua.DeleteMonitoredItemsResponse, error) {
req := &ua.DeleteMonitoredItemsRequest{
MonitoredItemIDs: monitoredItemIDs,
SubscriptionID: s.SubscriptionID,
}
var res *ua.DeleteMonitoredItemsResponse
err := s.c.Send(req, func(v interface{}) error {
return safeAssign(v, &res)
})
return res, err
}
func (s *Subscription) publish(acks []*ua.SubscriptionAcknowledgement) (*ua.PublishResponse, error) {
if acks == nil {
acks = []*ua.SubscriptionAcknowledgement{}
}
req := &ua.PublishRequest{
SubscriptionAcknowledgements: acks,
}
var res *ua.PublishResponse
err := s.c.sendWithTimeout(req, s.publishTimeout(), func(v interface{}) error {
return safeAssign(v, &res)
})
return res, err
}
func (s *Subscription) publishTimeout() time.Duration {
timeout := time.Duration(s.RevisedMaxKeepAliveCount) * s.RevisedPublishingInterval // expected keepalive interval
if timeout > uasc.MaxTimeout {
return uasc.MaxTimeout
}
if timeout < s.c.cfg.RequestTimeout {
return s.c.cfg.RequestTimeout
}
return timeout
}
// Run() starts an infinite loop that sends PublishRequests and delivers received
// notifications to registered Subscriptions.
// It is the responsibility of the user to stop no longer needed Run() loops by cancelling ctx
// Note that Run() may return before ctx is cancelled in case of an irrecoverable communication error
func (s *Subscription) Run(ctx context.Context) {
var acks []*ua.SubscriptionAcknowledgement
for {
select {
case <-ctx.Done():
return
default:
// send the next publish request
// note that res contains data even if an error was returned
res, err := s.publish(acks)
switch {
case err == ua.StatusBadSequenceNumberUnknown:
// At least one ack has been submitted repeatedly
// Ignore the error. Acks will be cleared below
case err == ua.StatusBadTimeout:
// ignore and continue the loop
case err == ua.StatusBadNoSubscription:
// All subscriptions have been deleted, but the publishing loop is still running
// The user will stop the loop or create subscriptions at his discretion
case err != nil:
// irrecoverable error
s.c.notifySubscriptionsOfError(ctx, res, err)
return
}
if res != nil {
// Prepare SubscriptionAcknowledgement for next PublishRequest
acks = make([]*ua.SubscriptionAcknowledgement, 0)
if res.AvailableSequenceNumbers != nil {
for _, i := range res.AvailableSequenceNumbers {
ack := &ua.SubscriptionAcknowledgement{
SubscriptionID: res.SubscriptionID,
SequenceNumber: i,
}
acks = append(acks, ack)
}
}
}
if err == nil {
s.c.notifySubscription(ctx, res)
}
}
}
}
func (s *Subscription) sendNotification(ctx context.Context, data *PublishNotificationData) {
select {
case <-ctx.Done():
return
case s.Notifs <- data:
}
}
func (p *SubscriptionParameters) setDefaults() {
if p.MaxNotificationsPerPublish == 0 {
p.MaxNotificationsPerPublish = DefaultSubscriptionMaxNotificationsPerPublish
}
if p.LifetimeCount == 0 {
p.LifetimeCount = DefaultSubscriptionLifetimeCount
}
if p.MaxKeepAliveCount == 0 {
p.MaxKeepAliveCount = DefaultSubscriptionMaxKeepAliveCount
}
if p.Interval == 0 {
p.Interval = DefaultSubscriptionInterval
}
if p.Priority == 0 {
// DefaultSubscriptionPriority is 0 at the time of writing, so this redundant assignment is
// made only to allow for a one-liner change of default priority should a need arise
// and to explicitly expose the default priority as a constant
p.Priority = DefaultSubscriptionPriority
}
if p.Notifs == nil {
p.Notifs = make(chan *PublishNotificationData)
}
}