Ejemplo n.º 1
0
class OPCUAClient:
    """
    定义opcuaclient
    """
    def __init__(self, url, username='', password=''):
        try:
            self.client = Client(url)  # 初始化OPCUA客户端
            if username != '' and password != '':  # 初始化时如果提供用户名密码则配置
                self.client.activate_session("username", "password")  # 配置用户名密码
            self.client.connect()
        except Exception as e:
            print("OPCUAClient INIT ERROR", e)

    def subscribeTag(self, stringNodeID):
        """
        通过StringNodeID订阅Tag
        """
        tag = self.client.get_node(stringNodeID)  # 获取需要读取的节点tag值
        print('tag节点值:', tag)
        handler = SubHandler()
        subobj = self.client.create_subscription(
            100, handler)  # 返回一个订阅对象第一个参数为发布间隔(毫秒)
        handle = subobj.subscribe_data_change(tag)  # 返回可用于退订的句柄
        return subobj, handle, stringNodeID  # 返回的三个参数可用于取消订阅

    def unsubscribeTag(self, subobj, handle):
        """
        取消订阅
        """
        subobj.unsubscribe(handle)

    def getNodeValue(self, stringNodeID, type=1):
        """
        通过StringNodeID读取节点tag值
        type = 1 获取值
        type = 2 获取DataValue object
        """
        tag = self.client.get_node(stringNodeID)
        return tag.get_value()

    def setNodeValue(self, stringNodeID, value):
        """
        通过StringNodeID设置节点tag值
        """
        tag = self.client.get_node(stringNodeID)
        tag.set_value(value)  # 使用隐含变量类型设置节点值

    def disconnect(self, client):
        """
        断开连接
        """
        return client.disconnect()