modbus_MediaPipe/OPCUA_test.py

46 lines
1.4 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from opcua import ua, Server
import time
import random
if __name__ == "__main__":
server = Server()
# 設定端點本機4840
server.set_endpoint("opc.tcp://0.0.0.0:4840")
server.set_server_name("MyUA Server")
# 新增命名空間(回傳 nsIndex
idx = server.register_namespace("urn:mycompany:demo")
# 建立地址空間:一個 Object底下放一個 Variable
objects = server.get_objects_node()
myobj = objects.add_object(idx, "DemoObject")
#空間建好,可以設變數了
temp_var = myobj.add_variable(idx, "Temperature", 25.0) # 初值 25.0
A = myobj.add_variable(idx, "A_value", 1)
#變數設好打開Client寫入功能
temp_var.set_writable() # 允許 Client 寫入
A.set_writable() # 允許 Client 寫入
# 啟動 Server
server.start()
print("Server started at opc.tcp://localhost:4840")
x=0
try:
while True:
# 模擬溫度改變
new_value = 20.0 + random.random() * 10.0
temp_var.set_value(ua.Variant(new_value, ua.VariantType.Float))
x=x+1
A.set_value(ua.Variant(x, ua.VariantType.Int64))
print(A.get_value())
print(temp_var.get_value())
time.sleep(1)
except KeyboardInterrupt:
print("Server stopped by user")
finally:
server.stop()
print("Resources released, server closed")