forked from gopcua/opcua
-
Notifications
You must be signed in to change notification settings - Fork 0
/
subscription.go
422 lines (368 loc) · 12.2 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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
package opcua
import (
"context"
"fmt"
"sync"
"time"
"github.com/gopcua/opcua/debug"
"github.com/gopcua/opcua/errors"
"github.com/gopcua/opcua/id"
"github.com/gopcua/opcua/stats"
"github.com/gopcua/opcua/ua"
"github.com/gopcua/opcua/uasc"
)
const (
DefaultSubscriptionMaxNotificationsPerPublish = 10000
DefaultSubscriptionLifetimeCount = 10000
DefaultSubscriptionMaxKeepAliveCount = 3000
DefaultSubscriptionInterval = 100 * time.Millisecond
DefaultSubscriptionPriority = 0
)
const terminatedSubscriptionID uint32 = 0xC0CAC01B
type Subscription struct {
SubscriptionID uint32
RevisedPublishingInterval time.Duration
RevisedLifetimeCount uint32
RevisedMaxKeepAliveCount uint32
Notifs chan<- *PublishNotificationData
params *SubscriptionParameters
items map[uint32]*monitoredItem
itemsMu sync.Mutex
lastSeq uint32
nextSeq uint32
c *Client
}
type SubscriptionParameters struct {
Interval time.Duration
LifetimeCount uint32
MaxKeepAliveCount uint32
MaxNotificationsPerPublish uint32
Priority uint8
}
type monitoredItem struct {
req *ua.MonitoredItemCreateRequest
res *ua.MonitoredItemCreateResult
ts ua.TimestampsToReturn
}
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 stops the subscription and removes it
// from the client and the server.
func (s *Subscription) Cancel(ctx context.Context) error {
stats.Subscription().Add("Cancel", 1)
s.c.forgetSubscription(ctx, s.SubscriptionID)
return s.delete(ctx)
}
// delete removes the subscription from the server.
func (s *Subscription) delete(ctx context.Context) error {
req := &ua.DeleteSubscriptionsRequest{
SubscriptionIDs: []uint32{s.SubscriptionID},
}
var res *ua.DeleteSubscriptionsResponse
err := s.c.Send(ctx, req, func(v interface{}) error {
return safeAssign(v, &res)
})
switch {
case err != nil:
return err
case res.Results[0] == ua.StatusOK:
s.itemsMu.Lock()
s.items = make(map[uint32]*monitoredItem)
s.itemsMu.Unlock()
return nil
default:
return res.Results[0]
}
}
func (s *Subscription) Monitor(ctx context.Context, ts ua.TimestampsToReturn, items ...*ua.MonitoredItemCreateRequest) (*ua.CreateMonitoredItemsResponse, error) {
stats.Subscription().Add("Monitor", 1)
stats.Subscription().Add("MonitoredItems", int64(len(items)))
// 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(ctx, req, func(v interface{}) error {
return safeAssign(v, &res)
})
if err != nil {
return nil, err
}
// store monitored items
s.itemsMu.Lock()
for i, item := range items {
result := res.Results[i]
s.items[result.MonitoredItemID] = &monitoredItem{
req: item,
res: result,
ts: ts,
}
}
s.itemsMu.Unlock()
return res, err
}
func (s *Subscription) Unmonitor(ctx context.Context, monitoredItemIDs ...uint32) (*ua.DeleteMonitoredItemsResponse, error) {
stats.Subscription().Add("Unmonitor", 1)
stats.Subscription().Add("UnmonitoredItems", int64(len(monitoredItemIDs)))
req := &ua.DeleteMonitoredItemsRequest{
MonitoredItemIDs: monitoredItemIDs,
SubscriptionID: s.SubscriptionID,
}
var res *ua.DeleteMonitoredItemsResponse
err := s.c.Send(ctx, req, func(v interface{}) error {
return safeAssign(v, &res)
})
if err != nil {
return nil, err
}
// remove monitored items
s.itemsMu.Lock()
for _, id := range monitoredItemIDs {
delete(s.items, id)
}
s.itemsMu.Unlock()
return res, nil
}
func (s *Subscription) ModifyMonitoredItems(ctx context.Context, ts ua.TimestampsToReturn, items ...*ua.MonitoredItemModifyRequest) (*ua.ModifyMonitoredItemsResponse, error) {
stats.Subscription().Add("ModifyMonitoredItems", 1)
stats.Subscription().Add("ModifiedMonitoredItems", int64(len(items)))
s.itemsMu.Lock()
for _, item := range items {
id := item.MonitoredItemID
if _, exists := s.items[id]; !exists {
return nil, fmt.Errorf("sub %d: cannot modify unknown monitored item id: %d", s.SubscriptionID, id)
}
}
s.itemsMu.Unlock()
req := &ua.ModifyMonitoredItemsRequest{
SubscriptionID: s.SubscriptionID,
TimestampsToReturn: ts,
ItemsToModify: items,
}
var res *ua.ModifyMonitoredItemsResponse
err := s.c.Send(ctx, req, func(v interface{}) error {
return safeAssign(v, &res)
})
if err != nil {
return nil, err
}
// update monitored items
s.itemsMu.Lock()
for i, res := range res.Results {
if res.StatusCode != ua.StatusOK {
continue
}
id := req.ItemsToModify[i].MonitoredItemID
item := s.items[id]
item.ts = req.TimestampsToReturn
item.req.RequestedParameters = req.ItemsToModify[i].RequestedParameters
item.res.StatusCode = res.StatusCode
item.res.RevisedSamplingInterval = res.RevisedSamplingInterval
item.res.RevisedQueueSize = res.RevisedQueueSize
item.res.FilterResult = res.FilterResult
}
s.itemsMu.Unlock()
return res, nil
}
// SetTriggering sends a request to the server to add and/or remove triggering links from a triggering item.
// To add links from a triggering item to an item to report provide the server assigned ID(s) in the `add` argument.
// To remove links from a triggering item to an item to report provide the server assigned ID(s) in the `remove` argument.
func (s *Subscription) SetTriggering(ctx context.Context, triggeringItemID uint32, add, remove []uint32) (*ua.SetTriggeringResponse, error) {
stats.Subscription().Add("SetTriggering", 1)
// Part 4, 5.12.5.2 SetTriggering Service Parameters
req := &ua.SetTriggeringRequest{
SubscriptionID: s.SubscriptionID,
TriggeringItemID: triggeringItemID,
LinksToAdd: add,
LinksToRemove: remove,
}
var res *ua.SetTriggeringResponse
err := s.c.Send(ctx, req, 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.sechan.RequestTimeout {
return s.c.cfg.sechan.RequestTimeout
}
return timeout
}
func (s *Subscription) notify(ctx context.Context, data *PublishNotificationData) {
select {
case <-ctx.Done():
return
case s.Notifs <- data:
}
}
// Stats returns a diagnostic struct with metadata about the current subscription
func (s *Subscription) Stats(ctx context.Context) (*ua.SubscriptionDiagnosticsDataType, error) {
// TODO(kung-foo): once browsing feature is merged, attempt to get direct access to the
// diagnostics node. for example, Prosys lists them like:
// i=2290/ns=1;g=918ee6f4-2d25-4506-980d-e659441c166d
// maybe cache the nodeid to speed up future stats queries
node := s.c.Node(ua.NewNumericNodeID(0, id.Server_ServerDiagnostics_SubscriptionDiagnosticsArray))
v, err := node.Value(ctx)
if err != nil {
return nil, err
}
if v == nil {
return nil, errors.Errorf("empty SubscriptionDiagnostics for sub=%d", s.SubscriptionID)
}
eos, ok := v.Value().([]*ua.ExtensionObject)
if !ok {
return nil, errors.Errorf("invalid type for SubscriptionDiagnosticsArray. Want []*ua.ExtensionObject. subID=%d nodeID=%s type=%T", s.SubscriptionID, node.String(), v.Value())
}
for _, eo := range eos {
stat, ok := eo.Value.(*ua.SubscriptionDiagnosticsDataType)
if !ok {
continue
}
if stat.SubscriptionID == s.SubscriptionID {
return stat, nil
}
}
return nil, errors.Errorf("unable to find SubscriptionDiagnostics for sub=%d", s.SubscriptionID)
}
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
}
}
// recreate_NeedsSubMuxLock creates a new subscription based on the previous subscription
// parameters and monitored items.
func (s *Subscription) recreate_NeedsSubMuxLock(ctx context.Context) error {
dlog := debug.NewPrefixLogger("sub %d: recreate: ", s.SubscriptionID)
if s.SubscriptionID == terminatedSubscriptionID {
dlog.Printf("subscription is not in a valid state")
return nil
}
params := s.params
{
req := &ua.DeleteSubscriptionsRequest{
SubscriptionIDs: []uint32{s.SubscriptionID},
}
var res *ua.DeleteSubscriptionsResponse
_ = s.c.Send(ctx, req, func(v interface{}) error {
return safeAssign(v, &res)
})
dlog.Print("subscription deleted")
}
s.c.forgetSubscription_NeedsSubMuxLock(ctx, s.SubscriptionID)
dlog.Printf("subscription forgotton")
req := &ua.CreateSubscriptionRequest{
RequestedPublishingInterval: float64(params.Interval / time.Millisecond),
RequestedLifetimeCount: params.LifetimeCount,
RequestedMaxKeepAliveCount: params.MaxKeepAliveCount,
PublishingEnabled: true,
MaxNotificationsPerPublish: params.MaxNotificationsPerPublish,
Priority: params.Priority,
}
var res *ua.CreateSubscriptionResponse
err := s.c.Send(ctx, req, func(v interface{}) error {
return safeAssign(v, &res)
})
if err != nil {
dlog.Printf("failed to recreate subscription")
return err
}
// todo (unknownet): check if necessary
if status := res.ResponseHeader.ServiceResult; status != ua.StatusOK {
return status
}
dlog.Printf("recreated as subscription %d", res.SubscriptionID)
dlog.SetPrefix(fmt.Sprintf("sub %d: recreate: ", res.SubscriptionID))
s.SubscriptionID = res.SubscriptionID
s.RevisedPublishingInterval = time.Duration(res.RevisedPublishingInterval) * time.Millisecond
s.RevisedLifetimeCount = res.RevisedLifetimeCount
s.RevisedMaxKeepAliveCount = res.RevisedMaxKeepAliveCount
s.lastSeq = 0
s.nextSeq = 1
if err := s.c.registerSubscription_NeedsSubMuxLock(s); err != nil {
return err
}
dlog.Printf("subscription registered")
// Sort by timestamp to return
itemsByTimestamps := make(map[ua.TimestampsToReturn][]*ua.MonitoredItemCreateRequest)
s.itemsMu.Lock()
for _, mi := range s.items {
itemsByTimestamps[mi.ts] = append(itemsByTimestamps[mi.ts], mi.req)
}
s.items = make(map[uint32]*monitoredItem, len(s.items))
s.itemsMu.Unlock()
for ts, items := range itemsByTimestamps {
req := &ua.CreateMonitoredItemsRequest{
SubscriptionID: s.SubscriptionID,
TimestampsToReturn: ts,
ItemsToCreate: items,
}
var res *ua.CreateMonitoredItemsResponse
err := s.c.Send(ctx, req, func(v interface{}) error {
return safeAssign(v, &res)
})
if err != nil {
dlog.Printf("failed to create monitored items: %v", err)
return err
}
for _, result := range res.Results {
if status := result.StatusCode; status != ua.StatusOK {
return status
}
}
s.itemsMu.Lock()
for i, item := range items {
s.items[res.Results[i].MonitoredItemID] = &monitoredItem{
req: item,
res: res.Results[i],
ts: ts,
}
}
s.itemsMu.Unlock()
}
dlog.Printf("subscription successfully recreated")
return nil
}