-
Notifications
You must be signed in to change notification settings - Fork 250
/
history-read.go
106 lines (89 loc) · 2.42 KB
/
history-read.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
// 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"
"log"
"time"
"github.com/gopcua/opcua"
"github.com/gopcua/opcua/debug"
"github.com/gopcua/opcua/ua"
)
func main() {
endpoint := flag.String("endpoint", "opc.tcp://localhost:4840", "OPC UA Endpoint URL")
nodeID := flag.String("node", "", "NodeID to read")
flag.BoolVar(&debug.Enable, "debug", false, "enable debug logging")
flag.Parse()
log.SetFlags(0)
ctx := context.Background()
c, err := opcua.NewClient(*endpoint)
if err != nil {
log.Fatal(err)
}
if err := c.Connect(ctx); err != nil {
log.Fatal(err)
}
defer c.Close(ctx)
id, err := ua.ParseNodeID(*nodeID)
if err != nil {
log.Fatalf("invalid node id: %v", err)
}
// HistoryRead with ContinuationPoint use
nodesToRequest := []*ua.HistoryReadValueID{
{
NodeID: id,
DataEncoding: &ua.QualifiedName{},
},
}
for {
if len(nodesToRequest) == 0 {
break
}
// For ContinuationPoint usage
// Get current nodes
nodes := nodesToRequest
// Reset old nodes
nodesToRequest = make([]*ua.HistoryReadValueID, 0)
data, err := c.HistoryReadRawModified(ctx, nodes, &ua.ReadRawModifiedDetails{
IsReadModified: false,
StartTime: time.Now().UTC().AddDate(0, -1, 0),
EndTime: time.Now().UTC().AddDate(0, 1, 0),
})
if err != nil {
log.Printf("HistoryReadRequest error: %s", err)
break
}
if data == nil || len(data.Results) == 0 {
break
}
for nodeNum, result := range data.Results {
if result.StatusCode != ua.StatusOK {
log.Printf("result.StatusCode not StatusOK: %d", result.StatusCode)
continue
}
// If this is not the end of the data - continue requesting
if len(result.ContinuationPoint) > 0 {
nodeNew := nodes[nodeNum]
nodeNew.ContinuationPoint = result.ContinuationPoint
nodesToRequest = append(nodesToRequest, nodeNew)
}
if result.HistoryData == nil || result.HistoryData.Value == nil {
continue
}
historyData, ok := result.HistoryData.Value.(*ua.HistoryData)
if !ok || historyData == nil || len(historyData.DataValues) == 0 {
continue
}
for _, value := range historyData.DataValues {
log.Printf(
"%s - %s - %v \n",
nodes[nodeNum].NodeID.String(),
value.SourceTimestamp.Format(time.RFC3339),
value.Value.Value(),
)
}
}
}
}