Python基于OPC-UA的Push-pull消息传输案例。

OPC UA  Server侧Push代码

--------------------------------------------------------------

import logging
import random
from opcua import ua, Server
if __name__ == "__main__":
    logging.basicConfig(level=logging.WARN)
    logger = logging.getLogger("opcua.server.internal_subscription")
    logger.setLevel(logging.DEBUG)#logging level of this logger: 10
    server = Server()
    server.set_endpoint("opc.tcp://127.0.0.1:4841/freeopcua/server/")
    # setup  namespace
    uri = "http://examples.io"# this can be any
    idx = server.register_namespace(uri) #register the uri name space in the server
    objs = server.get_objects_node()
    myobj = objs.add_object(idx, "OT_Object")    # populating our address space
    custom_etype = server.nodes.base_event_type.add_object_type(1, 'VALUE_MSG')
    server.start()
    try:
        import time
        count=0
        while True:
            time.sleep(3)
            value=random.randint(100,1000)
            print("Push Value: ",value)
            custom_etype.add_property(0, 'MyRadomProperty', ua.Variant(value, ua.VariantType.Int16))
            event_obj = server.get_event_generator(custom_etype, myobj)
            event_obj.trigger(message="VALUE_MSG %d" % count)
            count += 1
    finally:
        server.stop()

 

------------------------------------------------

OPC-UA client 端代码

import pickle
from IPython import embed
from opcua import Client
class SubHandler(object):
    def event_notification(self, event):
        print("************************************")
        print("Value: ",event.MyRadomProperty)
if __name__ == "__main__":
    server_url="opc.tcp://127.0.0.1:4841/freeopcua/server/"
    client = Client(server_url)
    try:
        client.connect()
        root = client.get_root_node()
        obj = root.get_child(["0:Objects", "2:OT_Object"])
        myevent_tss = root.get_child(["0:Types", "0:EventTypes","0:BaseEventType",  "1:VALUE_MSG"])
        print("event is: ",myevent_tss)
        msclt_tss = SubHandler()
        sub_tss = client.create_subscription(100, msclt_tss)
        handle_tss = sub_tss.subscribe_events(obj, myevent_tss)
        embed()
        sub_tss.unsubscribe(handle_tss)
        sub_tss.delete()
    finally:
        client.disconnect()

 

-----------------------------------

参考资源:https://github.com/FreeOpcUa/python-opcua

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值