# 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()
python: opcua_server测试
最新推荐文章于 2024-08-20 15:35:42 发布