python: opcua_server测试

# encoding=utf-8
import time
from opcua import Server
import threading


class OpcServer:
    def __init__(self, js):
        self.ip = js["address"]
        self.server = None
        self.objects = None
        self.myobj = None
        self.NoErr = True
        self.TagNames = js
        self.vars = {}

    def Start(self):
        self.server = Server()
        self.server.set_endpoint(self.ip)
        self.objects = self.server.get_objects_node()
        self.myobj = self.objects.add_object(0, "TagNames")
        self.AddVars()
        self.server.start()

    def AddVars(self):
        for name in self.TagNames:
            if name == "address":
                continue
            v = self.myobj.add_variable("ns=2;s=" + name, name, 0)
            v.set_writable()
            self.vars[name] = v

    def Stop(self):
        self.NoErr = False

    def __Run(self):
        self.NoErr = True
        while self.NoErr:
            try:
                self.Start()
                print("OPCUA_Server," + self.ip + ",Start。")
            except:
                print("OPCUA_Server," + self.ip + ",Start发生错误,30秒后重新连接。")
                time.sleep(30)  # 休眠30秒
                continue
            while self.NoErr:
                time.sleep(1)
                try:
                    for key in self.vars.keys():
                        v = self.vars[key]
                        v.set_value(self.TagNames[key])
                except:
                    print("OPCUA_Server," + self.ip + ",set_value发生错误,30秒后重新连接。")
                    time.sleep(30)  # 休眠30秒
                    break
            try:
                self.server.stop()
            except:
                print("OPCUA_Server," + self.ip + ",Stop发生错误,30秒后重新连接。")
                time.sleep(30)  # 休眠30秒

        self.NoErr = False

    def ThreadRun(self):
        threading.Thread(target=self.__Run).start()


if __name__ == "__main__":
    write_TagNames = {"w1": 0, "w2": 0}
    t = OpcServer("opc.tcp://192.168.10.233:8020")
    t.ThreadRun()


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值