服务端代码, 来自官方
import sys
import time
sys.path.insert(0, "..")
from opcua import ua, Server
if __name__ == "__main__":
# setup our server
server = Server()
server.set_endpoint("opc.tcp://0.0.0.0:4840/freeopcua/server/")
server.set_security_policy([ua.SecurityPolicyType.Basic256Sha256_SignAndEncrypt])
# load server certificate and private key. This enables endpoints
# with signing and encryption.
server.load_certificate(r"C:\Users\42082\Desktop\certificate-example.der")
server.load_private_key(r"C:\Users\42082\Desktop\private-key-example.pem")
# setup our own namespace, not really necessary but should as spec
uri = "http://examples.freeopcua.github.io"
idx = server.register_namespace(uri)
print(idx)
# get Objects node, this is where we should put our custom stuff
objects = server.get_objects_node()
# populating our address space
myobj = objects.add_object(idx, "MyObject")
myvar = myobj.add_variable(idx, "MyVariable", 6.7)
myvar.set_writable() # Set MyVariable to be writable by clients
# starting!
server.start()
try:
count = 0
while True:
time.sleep(1)
count += 0.1
myvar.set_value(count)
finally:
#close connection, remove subcsriptions, etc
server.stop()
代码中的公私钥可以从https://github.com/FreeOpcUa/python-opcua/tree/master/examples中进行获取
客户端代码
import time
from opcua import Client, ua
from opcua.crypto import uacrypto
class SubHandler(object):
def datachange_notification(self, node, val, data):
print("Python: New data change event", node, val, data)
client = Client('opc.tcp://127.0.0.1:4840/', timeout=10)
client.set_user('will')
client.set_password('123456')
client.set_security_string(r"Basic256Sha256,SignAndEncrypt,C:\Users\42082\Desktop\certificate-example.der,C:\Users\42082\Desktop\private-key-example.pem")
# client.activate_session('will', '123456', cer)
client.connect()
objects = client.get_objects_node()
print(objects)
print(objects.get_variables())
root = client.get_root_node()
print(root.get_children())
namespaces = client.get_namespace_array()
print(namespaces)
endpoints = client.get_endpoints()
snode = client.get_server_node()
print(snode)
try:
node = objects.get_child(["2:MyObject"])
print(node.get_variables()[0].get_value())
time.sleep(1000)
except Exception as e:
print(e)
finally:
client.disconnect()
此处没有采用root获取节点的方法, 是因为通过root我没有找到那个节点, 而通过objects可以通过变量名去找, 这也是两种找节点的不一样的地方