实现功能
package mainimport ("fmt""log""opcuaclient/util/plugin/client/opcclient""os""os/signal""syscall" )func main() {OPCUATest()// 监听操作系统信号,阻塞直到接收到信号quit := make(chan os.Signal, 1)signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)<-quit }func OPCUATest() {endpoint := "opc.tcp://127.0.0.1:49320" // KepServerusername := "admin"password := "123456"nodeID := "ns=2;s=Channel1.Device1.400101"// 创建 OPC UA 客户端opcClient, err := opcclient.NewOpcUaClient("Anonymous", endpoint, username, password) // Anonymous | Accountif err != nil {log.Fatalf("Error creating client: %v", err)}defer opcClient.Close()// 连接到服务器if err := opcClient.Connect(); err != nil {fmt.Println("连接失败", err)} else {fmt.Println("连接成功")// 写入值nodeValue := uint16(333)opcClient.WriteNodeValue(nodeID, nodeValue)// 读取值status, value := opcClient.ReadNodeValue(nodeID)if status {fmt.Println("读取单个节点:", nodeID, value)}// 订阅节点opcClient.NodeIDs = append(opcClient.NodeIDs, "ns=2;s=Channel1.Device1.400101")opcClient.NodeIDs = append(opcClient.NodeIDs, "ns=2;s=Channel1.Device1.400102")opcClient.NodeIDs = append(opcClient.NodeIDs, "ns=2;s=Channel1.Device1.400103")opcClient.BatchNodeIdDatasSubscription(opcClient.NodeIDs, func(uaTag string, uaValueStr string) {log.Printf("DataChange %v = %v", uaTag, uaValueStr)})} }
测试输出: