def server(): s = Server() s.set_endpoint('opc.tcp://0.0.0.0:8840/freeopcua/server/') uri = "http://examples.freeopcua.github.io" idx = s.register_namespace(uri) myobj = s.nodes.objects.add_object(idx, "MyObject") myvar = myobj.add_variable(idx, "MyVariable", 6.7) mysin = myobj.add_variable(idx, "MySin", 0, ua.VariantType.Float) s.start() yield s s.stop()
class ServerPython(object): def __init__(self): self._server = None self.nodes = None self.get_node = None self.get_namespace_array = None def get_server(self): return self._server def start_server(self, endpoint): logger.info("Starting python-opcua server") self._server = Server() self._server.set_endpoint(endpoint) self._server.set_server_name("OpcUa Modeler Server") self.nodes = self._server.nodes self.get_node = self._server.get_node self.get_namespace_array = self._server.get_namespace_array self.load_type_definitions = self._server.load_type_definitions self.load_enums = self._server.load_enums # now remove freeopcua namespace, not necessary when modeling and # ensures correct idx for exported nodesets ns_node = self._server.get_node( ua.NodeId(ua.ObjectIds.Server_NamespaceArray)) nss = ns_node.read_value() ns_node.write_value(nss[:1]) self._server.start() def stop_server(self): if self._server is not None: self._server.stop() self._server = None self.get_node = None self.get_namespace_array = None def import_xml(self, path): return self._server.import_xml(path) def export_xml(self, nodes, uris, path): exp = XmlExporter(self._server) exp.build_etree(nodes, uris=uris) exp.write_xml(path)
# creating a default event object # The event object automatically will have members for all events properties # you probably want to create a custom event type, see other examples myevgen = server.get_event_generator() myevgen.event.Severity = 300 # starting! server.start() print("Available loggers are: ", logging.Logger.manager.loggerDict.keys()) vup = VarUpdater(mysin) # just a stupide class update a variable vup.start() try: # enable following if you want to subscribe to nodes on server side #handler = SubHandler() #sub = server.create_subscription(500, handler) #handle = sub.subscribe_data_change(myvar) # trigger event, all subscribed clients wil receive it var = myarrayvar.get_value() # return a ref to value in db server side! not a copy! var = copy.copy(var) # WARNING: we need to copy before writting again otherwise no data change event will be generated var.append(9.3) myarrayvar.set_value(var) mydevice_var.set_value("Running") myevgen.trigger(message="This is BaseEvent") server.set_attribute_value(myvar.nodeid, ua.DataValue(9.9)) # Server side write method which is a but faster than using set_value embed() finally: vup.stop() server.stop() stop_thread_loop()
def server(): s = Server() s.set_endpoint('opc.tcp://*:8840/freeopcua/server/') s.start() yield s s.stop()