-
Notifications
You must be signed in to change notification settings - Fork 5
/
main.go
105 lines (100 loc) · 2.48 KB
/
main.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
package main
import (
"log"
"time"
"github.com/huskar-t/opcda"
"github.com/huskar-t/opcda/com"
)
func main() {
com.Initialize()
defer com.Uninitialize()
host := "localhost"
progID := "Matrikon.OPC.Simulation.1"
tags := []string{
"Random.ArrayOfReal8",
"Random.ArrayOfString",
"Random.Boolean",
"Random.Int1",
"Random.Int2",
"Random.Int4",
"Random.Int8",
"Random.Qualities",
"Random.Real4",
"Random.Real8",
"Random.String",
"Random.Time",
"Random.UInt1",
"Random.UInt2",
"Random.UInt4",
"Random.UInt8",
}
server, err := opcda.Connect(progID, host)
if err != nil {
log.Fatalf("connect to opc server failed: %s\n", err)
}
defer server.Disconnect()
groups := server.GetOPCGroups()
group, err := groups.Add("group1")
if err != nil {
log.Fatalf("add group failed: %s\n", err)
}
items := group.OPCItems()
itemList, errs, err := items.AddItems(tags)
if err != nil {
log.Fatalf("add items failed: %s\n", err)
}
for i, err := range errs {
if err != nil {
log.Fatalf("add item %s failed: %s\n", tags[i], err)
}
}
// Wait for the OPC server to be ready
time.Sleep(time.Second * 2)
// group async read
log.Println("group sync read")
serverHandles := make([]uint32, len(itemList))
for i, item := range itemList {
serverHandles[i] = item.GetServerHandle()
}
ch := make(chan *opcda.ReadCompleteCallBackData, 100)
err = group.RegisterReadComplete(ch)
if err != nil {
log.Fatalf("register read complete callback failed: %s\n", err)
}
finishChan := make(chan struct{})
go func() {
loop(itemList, ch, finishChan)
}()
transID := uint32(1)
_, errs, err = group.AsyncRead(serverHandles, transID)
if err != nil {
log.Fatalf("sync read failed: %s\n", err)
}
for _, err := range errs {
if err != nil {
log.Fatalf("sync read failed: %s\n", err)
}
}
select {
case <-finishChan:
}
}
func loop(itemList []*opcda.OPCItem, ch chan *opcda.ReadCompleteCallBackData, finishChan chan struct{}) {
for {
select {
case data := <-ch:
log.Printf("read complete received, transaction id: %d, group handle: %d, masterQuality: %d, masterError: %v\n", data.TransID, data.GroupHandle, data.MasterQuality, data.MasterErr)
tag := ""
for i := 0; i < len(data.ItemClientHandles); i++ {
for _, item := range itemList {
if item.GetClientHandle() == data.ItemClientHandles[i] {
tag = item.GetItemID()
}
}
log.Printf("%s:\t%s\t%d\t%v\n", tag, data.TimeStamps[i], data.Qualities[i], data.Values[i])
}
close(finishChan)
return
}
}
}