def __init__(self, shelffile=None, iserver=None): self.logger = logging.getLogger(__name__) self.endpoint = urlparse("opc.tcp://0.0.0.0:4840/freeopcua/server/") self._application_uri = "urn:freeopcua:python:server" self.product_uri = "urn:freeopcua.github.io:python:server" self.name = "FreeOpcUa Python Server" self.manufacturer_name = "FreeOpcUa" self.application_type = ua.ApplicationType.ClientAndServer self.default_timeout = 3600000 if iserver is not None: self.iserver = iserver else: self.iserver = InternalServer(shelffile = shelffile) self.bserver = None self._policies = [] self.nodes = Shortcuts(self.iserver.isession) # setup some expected values self.set_application_uri(self._application_uri) sa_node = self.get_node(ua.NodeId(ua.ObjectIds.Server_ServerArray)) sa_node.set_value([self._application_uri]) self.set_build_info(self.product_uri, self.manufacturer_name, self.name, "1.0pre", "0", datetime.now()) # enable all endpoints by default self.certificate = None self.private_key = None self.user_manager = UserManager(parent = self) self._security_policy = [ ua.SecurityPolicyType.NoSecurity, ua.SecurityPolicyType.Basic256Sha256_SignAndEncrypt, ua.SecurityPolicyType.Basic256Sha256_Sign ] self._policyIDs = ["Anonymous", "Basic256Sha256", "Username"]
def __init__(self, shelffile=None, iserver=None): self.logger = logging.getLogger(__name__) self.endpoint = urlparse("opc.tcp://0.0.0.0:4840/freeopcua/server/") self._application_uri = "urn:freeopcua:python:server" self.product_uri = "urn:freeopcua.github.no:python:server" self.name = "FreeOpcUa Python Server" self.application_type = ua.ApplicationType.ClientAndServer self.default_timeout = 3600000 if iserver is not None: self.iserver = iserver else: self.iserver = InternalServer(shelffile) self.bserver = None self._discovery_clients = {} self._discovery_period = 60 self.certificate = None self.private_key = None self._policies = [] self.nodes = Shortcuts(self.iserver.isession) # setup some expected values self.set_application_uri(self._application_uri) sa_node = self.get_node(ua.NodeId(ua.ObjectIds.Server_ServerArray)) sa_node.set_value([self._application_uri]) # enable all endpoints by default self._security_policy = [#"None", "Basic128Rsa15_Sign", # "Basic128Rsa15_SignAndEncrypt", "Basic256_Sign", "Basic256_SignAndEncrypt"] self._policyIDs = ["Anonymous", "Basic256", "Basic128", "Username"]
def setUpClass(cls): iserver = InternalServer(session_cls=CustomInternalSession) cls.srv = Server(iserver=iserver) iserver._parent = cls.srv cls.srv.set_endpoint('opc.tcp://127.0.0.1:{0:d}'.format(cls.PORT_NUM2)) cls.srv.start() # start admin client # short timeout since we want it to fail cls.clt = Client('opc.tcp://[email protected]:{0:d}'.format( cls.PORT_NUM2), timeout=1) cls.clt.connect() cls.opc = cls.clt
def __init__(self, shelffile=None, iserver=None): self.logger = logging.getLogger(__name__) self.endpoint = urlparse("opc.tcp://0.0.0.0:4840/freeopcua/server/") self._application_uri = "urn:freeopcua:python:server" self.product_uri = "urn:freeopcua.github.io:python:server" self.name = "FreeOpcUa Python Server" self.manufacturer_name = "FreeOpcUa" self.application_type = ua.ApplicationType.ClientAndServer self.default_timeout = 3600000 if iserver is not None: self.iserver = iserver else: self.iserver = InternalServer(shelffile) self.bserver = None self._discovery_clients = {} self._discovery_period = 60 self.certificate = None self.private_key = None self._policies = [] self.nodes = Shortcuts(self.iserver.isession) # setup some expected values self.set_application_uri(self._application_uri) sa_node = self.get_node(ua.NodeId(ua.ObjectIds.Server_ServerArray)) sa_node.set_value([self._application_uri]) status_node = self.get_node(ua.NodeId( ua.ObjectIds.Server_ServerStatus)) build_node = self.get_node( ua.NodeId(ua.ObjectIds.Server_ServerStatus_BuildInfo)) status = ua.ServerStatusDataType() status.BuildInfo.ProductUri = self.product_uri status.BuildInfo.ManufacturerName = self.manufacturer_name status.BuildInfo.ProductName = self.name status.BuildInfo.SoftwareVersion = "1.0pre" status.BuildInfo.BuildNumber = "0" status.BuildInfo.BuildDate = datetime.now() status.SecondsTillShutdown = 0 status_node.set_value(status) build_node.set_value(status.BuildInfo) # enable all endpoints by default self._security_policy = [ ua.SecurityPolicyType.NoSecurity, ua.SecurityPolicyType.Basic128Rsa15_SignAndEncrypt, ua.SecurityPolicyType.Basic128Rsa15_Sign, ua.SecurityPolicyType.Basic256_SignAndEncrypt, ua.SecurityPolicyType.Basic256_Sign ] self._policyIDs = ["Anonymous", "Basic256", "Basic128", "Username"]
def __init__(self): self.logger = logging.getLogger(__name__) self.endpoint = urlparse("opc.tcp://0.0.0.0:4840/freeopcua/server/") self.application_uri = "urn:freeopcua:python:server" self.product_uri = "urn:freeopcua.github.no:python:server" self.name = "FreeOpcUa Python Server" self.application_type = ua.ApplicationType.ClientAndServer self.default_timeout = 3600000 self.iserver = InternalServer() self.bserver = None self._discovery_clients = {} self._discovery_period = 60 self.certificate = None self.private_key = None self._policies = [] # setup some expected values self.register_namespace(self.application_uri) sa_node = self.get_node(ua.NodeId(ua.ObjectIds.Server_ServerArray)) sa_node.set_value([self.application_uri])
def __init__(self, shelffile=None, iserver=None): self.logger = logging.getLogger(__name__) self.endpoint = urlparse("opc.tcp://0.0.0.0:4840/freeopcua/server/") self._application_uri = "urn:freeopcua:python:server" self.product_uri = "urn:freeopcua.github.io:python:server" self.name = "FreeOpcUa Python Server" self.manufacturer_name = "FreeOpcUa" self.application_type = ua.ApplicationType.ClientAndServer self.default_timeout = 3600000 if iserver is not None: self.iserver = iserver else: self.iserver = InternalServer(shelffile) self.bserver = None self._discovery_clients = {} self._discovery_period = 60 self.certificate = None self.private_key = None self._policies = [] self.nodes = Shortcuts(self.iserver.isession) # setup some expected values self.set_application_uri(self._application_uri) sa_node = self.get_node(ua.NodeId(ua.ObjectIds.Server_ServerArray)) sa_node.set_value([self._application_uri]) status_node = self.get_node(ua.NodeId(ua.ObjectIds.Server_ServerStatus)) build_node = self.get_node(ua.NodeId(ua.ObjectIds.Server_ServerStatus_BuildInfo)) status = ua.ServerStatusDataType() status.BuildInfo.ProductUri = self.product_uri status.BuildInfo.ManufacturerName = self.manufacturer_name status.BuildInfo.ProductName = self.name status.BuildInfo.SoftwareVersion = "1.0pre" status.BuildInfo.BuildNumber = "0" status.BuildInfo.BuildDate = datetime.now() status.SecondsTillShutdown = 0 status_node.set_value(status) build_node.set_value(status.BuildInfo) # enable all endpoints by default self._security_policy = [ ua.SecurityPolicyType.NoSecurity, ua.SecurityPolicyType.Basic128Rsa15_SignAndEncrypt, ua.SecurityPolicyType.Basic128Rsa15_Sign, ua.SecurityPolicyType.Basic256_SignAndEncrypt, ua.SecurityPolicyType.Basic256_Sign ] self._policyIDs = ["Anonymous", "Basic256", "Basic128", "Username"]
def __init__(self): self.logger = logging.getLogger(__name__) self.endpoint = urlparse("opc.tcp://0.0.0.0:4841/freeopcua/server/") self.application_uri = "urn:freeopcua:python:server" self.product_uri = "urn:freeopcua.github.no:python:server" self.name = "FreeOpcUa Python Server" self.application_type = ua.ApplicationType.ClientAndServer self.default_timeout = 3600000 self.iserver = InternalServer() self.bserver = None self._discovery_clients = {} self._discovery_period = 60 self.certificate = None self.private_key = None self._policies = [] # setup some expected values self.register_namespace(self.application_uri) sa_node = self.get_node(ua.NodeId(ua.ObjectIds.Server_ServerArray)) sa_node.set_value([self.application_uri])
def is_running(self): return InternalServer.is_running(self)
def enable_history_event(self, source, period=timedelta(days=7), count=0): InternalServer.enable_history_event(self, source, period=period, count=count)
class Server(object): """ High level Server class This class creates an opcua server with default values Create your own namespace and then populate your server address space using use the get_root() or get_objects() to get Node objects. and get_event_object() to fire events. Then start server. See example_server.py All methods are threadsafe If you need more flexibility you call directly the Ua Service methods on the iserver or iserver.isession object members. During startup the standard address space will be constructed, which may be time-consuming when running a server on a less powerful device (e.g. a Raspberry Pi). In order to improve startup performance, a optional path to a cache file can be passed to the server constructor. If the parameter is defined, the address space will be loaded from the cache file or the file will be created if it does not exist yet. As a result the first startup will be even slower due to the cache file generation but all further start ups will be significantly faster. :ivar product_uri: :vartype product_uri: uri :ivar name: :vartype name: string :ivar default_timeout: timeout in milliseconds for sessions and secure channel :vartype default_timeout: int :ivar iserver: internal server object :vartype default_timeout: InternalServer :ivar bserver: binary protocol server :vartype bserver: BinaryServer :ivar nodes: shortcuts to common nodes :vartype nodes: Shortcuts """ def __init__(self, shelffile=None, iserver=None): self.logger = logging.getLogger(__name__) self.endpoint = urlparse("opc.tcp://0.0.0.0:4840/freeopcua/server/") self._application_uri = "urn:freeopcua:python:server" self.product_uri = "urn:freeopcua.github.no:python:server" self.name = "FreeOpcUa Python Server" self.application_type = ua.ApplicationType.ClientAndServer self.default_timeout = 3600000 if iserver is not None: self.iserver = iserver else: self.iserver = InternalServer(shelffile) self.bserver = None self._discovery_clients = {} self._discovery_period = 60 self.certificate = None self.private_key = None self._policies = [] self.nodes = Shortcuts(self.iserver.isession) # setup some expected values self.set_application_uri(self._application_uri) sa_node = self.get_node(ua.NodeId(ua.ObjectIds.Server_ServerArray)) sa_node.set_value([self._application_uri]) # enable all endpoints by default self._security_policy = [#"None", "Basic128Rsa15_Sign", # "Basic128Rsa15_SignAndEncrypt", "Basic256_Sign", "Basic256_SignAndEncrypt"] self._policyIDs = ["Anonymous", "Basic256", "Basic128", "Username"] def __enter__(self): self.start() return self def __exit__(self, exc_type, exc_value, traceback): self.stop() def load_certificate(self, path): """ load server certificate from file, either pem or der """ self.certificate = uacrypto.load_certificate(path) def load_private_key(self, path): self.private_key = uacrypto.load_private_key(path) def disable_clock(self, val=True): """ for debugging you may want to disable clock that write every second to address space """ self.iserver.disabled_clock = val def set_application_uri(self, uri): """ Set application/server URI. This uri is supposed to be unique. If you intent to register your server to a discovery server, it really should be unique in your system! default is : "urn:freeopcua:python:server" """ self._application_uri = uri ns_node = self.get_node(ua.NodeId(ua.ObjectIds.Server_NamespaceArray)) uries = ns_node.get_value() if len(uries) > 1: uries[1] = uri # application uri is always namespace 1 else: uries.append(uri) ns_node.set_value(uries) def find_servers(self, uris=None): """ find_servers. mainly implemented for symmetry with client """ if uris is None: uris = [] params = ua.FindServersParameters() params.EndpointUrl = self.endpoint.geturl() params.ServerUris = uris return self.iserver.find_servers(params) def register_to_discovery(self, url="opc.tcp://localhost:4840", period=60): """ Register to an OPC-UA Discovery server. Registering must be renewed at least every 10 minutes, so this method will use our asyncio thread to re-register every period seconds if period is 0 registration is not automatically renewed """ # FIXME: have a period per discovery if url in self._discovery_clients: self._discovery_clients[url].disconnect() self._discovery_clients[url] = Client(url) self._discovery_clients[url].connect() self._discovery_clients[url].register_server(self) self._discovery_period = period if period: self.iserver.loop.call_soon(self._renew_registration) def unregister_to_discovery(self, url="opc.tcp://localhost:4840"): """ stop registration thread """ # FIXME: is there really no way to deregister? self._discovery_clients[url].disconnect() def _renew_registration(self): for client in self._discovery_clients.values(): client.register_server(self) self.iserver.loop.call_later(self._discovery_period, self._renew_registration) def get_client_to_discovery(self, url="opc.tcp://localhost:4840"): """ Create a client to discovery server and return it """ client = Client(url) client.connect() return client def allow_remote_admin(self, allow): """ Enable or disable the builtin Admin user from network clients """ self.iserver.allow_remote_admin = allow def set_endpoint(self, url): self.endpoint = urlparse(url) def get_endpoints(self): return self.iserver.get_endpoints() def set_security_policy(self, security_policy): """ Method setting up the security policies for connections to the server. During server object initialization, all possible endpoints are enabled: security_policy = ["None", "Basic128Rsa15_Sign", "Basic128Rsa15_SignAndEncrypt", "Basic256_Sign", "Basic256_SignAndEncrypt"] where security_policy is a list of strings. "None" enables an endpoint without any security. E.g. to limit the number of endpoints and disable no encryption: set_security_policy(["Basic256_Sign", "Basic256_SignAndEncrypt"]) """ self._security_policy = security_policy def set_security_IDs(self, policyIDs): """ Method setting up the security endpoints for identification of clients. During server object initialization, all possible endpoints are enabled: self._policyIDs = ["Anonymous", "Basic256", "Basic128", "Username"] E.g. to limit the number of IDs and disable anonymous clients: set_security_policy(["Basic256"]) (Implementation for ID check is currently not finalized...) """ self._policyIDs = policyIDs def _setup_server_nodes(self): # to be called just before starting server since it needs all parameters to be setup if "None" in self._security_policy: self._set_endpoints() self._policies = [ua.SecurityPolicyFactory()] if (len(self._security_policy)>1) and self.private_key: self.logger.warning("Creating an open endpoint to the server, although encrypted endpoints are enabled.") if self.certificate and self.private_key: if "Basic128Rsa15_SignAndEncrypt" in self._security_policy: self._set_endpoints(security_policies.SecurityPolicyBasic128Rsa15, ua.MessageSecurityMode.SignAndEncrypt) self._policies.append(ua.SecurityPolicyFactory(security_policies.SecurityPolicyBasic128Rsa15, ua.MessageSecurityMode.SignAndEncrypt, self.certificate, self.private_key) ) if "Basic128Rsa15_Sign" in self._security_policy: self._set_endpoints(security_policies.SecurityPolicyBasic128Rsa15, ua.MessageSecurityMode.Sign) self._policies.append(ua.SecurityPolicyFactory(security_policies.SecurityPolicyBasic128Rsa15, ua.MessageSecurityMode.Sign, self.certificate, self.private_key) ) if "Basic256_SignAndEncrypt" in self._security_policy: self._set_endpoints(security_policies.SecurityPolicyBasic256, ua.MessageSecurityMode.SignAndEncrypt) self._policies.append(ua.SecurityPolicyFactory(security_policies.SecurityPolicyBasic256, ua.MessageSecurityMode.SignAndEncrypt, self.certificate, self.private_key) ) if "Basic256_Sign" in self._security_policy: self._set_endpoints(security_policies.SecurityPolicyBasic256, ua.MessageSecurityMode.Sign) self._policies.append(ua.SecurityPolicyFactory(security_policies.SecurityPolicyBasic256, ua.MessageSecurityMode.Sign, self.certificate, self.private_key) ) def _set_endpoints(self, policy=ua.SecurityPolicy, mode=ua.MessageSecurityMode.None_): idtokens = [] if "Anonymous" in self._policyIDs: idtoken = ua.UserTokenPolicy() idtoken.PolicyId = 'anonymous' idtoken.TokenType = ua.UserTokenType.Anonymous idtokens.append(idtoken) if "Basic256" in self._policyIDs: idtoken = ua.UserTokenPolicy() idtoken.PolicyId = 'certificate_basic256' idtoken.TokenType = ua.UserTokenType.Certificate idtokens.append(idtoken) if "Basic128" in self._policyIDs: idtoken = ua.UserTokenPolicy() idtoken.PolicyId = 'certificate_basic128' idtoken.TokenType = ua.UserTokenType.Certificate idtokens.append(idtoken) if "Username" in self._policyIDs: idtoken = ua.UserTokenPolicy() idtoken.PolicyId = 'username' idtoken.TokenType = ua.UserTokenType.UserName idtokens.append(idtoken) appdesc = ua.ApplicationDescription() appdesc.ApplicationName = ua.LocalizedText(self.name) appdesc.ApplicationUri = self._application_uri appdesc.ApplicationType = self.application_type appdesc.ProductUri = self.product_uri appdesc.DiscoveryUrls.append(self.endpoint.geturl()) edp = ua.EndpointDescription() edp.EndpointUrl = self.endpoint.geturl() edp.Server = appdesc if self.certificate: edp.ServerCertificate = uacrypto.der_from_x509(self.certificate) edp.SecurityMode = mode edp.SecurityPolicyUri = policy.URI edp.UserIdentityTokens = idtokens edp.TransportProfileUri = 'http://opcfoundation.org/UA-Profile/Transport/uatcp-uasc-uabinary' edp.SecurityLevel = 0 self.iserver.add_endpoint(edp) def set_server_name(self, name): self.name = name def start(self): """ Start to listen on network """ self._setup_server_nodes() self.iserver.start() try: self.bserver = BinaryServer(self.iserver, self.endpoint.hostname, self.endpoint.port) self.bserver.set_policies(self._policies) self.bserver.start() except Exception as exp: self.iserver.stop() raise exp def stop(self): """ Stop server """ for client in self._discovery_clients.values(): client.disconnect() self.bserver.stop() self.iserver.stop() def get_root_node(self): """ Get Root node of server. Returns a Node object. """ return self.get_node(ua.TwoByteNodeId(ua.ObjectIds.RootFolder)) def get_objects_node(self): """ Get Objects node of server. Returns a Node object. """ return self.get_node(ua.TwoByteNodeId(ua.ObjectIds.ObjectsFolder)) def get_server_node(self): """ Get Server node of server. Returns a Node object. """ return self.get_node(ua.TwoByteNodeId(ua.ObjectIds.Server)) def get_node(self, nodeid): """ Get a specific node using NodeId object or a string representing a NodeId """ return Node(self.iserver.isession, nodeid) def create_subscription(self, period, handler): """ Create a subscription. returns a Subscription object which allow to subscribe to events or data on server """ params = ua.CreateSubscriptionParameters() params.RequestedPublishingInterval = period params.RequestedLifetimeCount = 3000 params.RequestedMaxKeepAliveCount = 10000 params.MaxNotificationsPerPublish = 0 params.PublishingEnabled = True params.Priority = 0 return Subscription(self.iserver.isession, params, handler) def get_namespace_array(self): """ get all namespace defined in server """ ns_node = self.get_node(ua.NodeId(ua.ObjectIds.Server_NamespaceArray)) return ns_node.get_value() def register_namespace(self, uri): """ Register a new namespace. Nodes should in custom namespace, not 0. """ ns_node = self.get_node(ua.NodeId(ua.ObjectIds.Server_NamespaceArray)) uries = ns_node.get_value() if uri in uries: return uries.index(uri) uries.append(uri) ns_node.set_value(uries) return len(uries) - 1 def get_namespace_index(self, uri): """ get index of a namespace using its uri """ uries = self.get_namespace_array() return uries.index(uri) def get_event_generator(self, etype=None, source=ua.ObjectIds.Server): """ Returns an event object using an event type from address space. Use this object to fire events """ if not etype: etype = BaseEvent() return EventGenerator(self.iserver.isession, etype, source) def create_custom_data_type(self, idx, name, basetype=ua.ObjectIds.BaseDataType, properties=None): if properties is None: properties = [] return self._create_custom_type(idx, name, basetype, properties, [], []) def create_custom_event_type(self, idx, name, basetype=ua.ObjectIds.BaseEventType, properties=None): if properties is None: properties = [] return self._create_custom_type(idx, name, basetype, properties, [], []) def create_custom_object_type(self, idx, name, basetype=ua.ObjectIds.BaseObjectType, properties=None, variables=None, methods=None): if properties is None: properties = [] if variables is None: variables = [] if methods is None: methods = [] return self._create_custom_type(idx, name, basetype, properties, variables, methods) # def create_custom_reference_type(self, idx, name, basetype=ua.ObjectIds.BaseReferenceType, properties=[]): # return self._create_custom_type(idx, name, basetype, properties) def create_custom_variable_type(self, idx, name, basetype=ua.ObjectIds.BaseVariableType, properties=None, variables=None, methods=None): if properties is None: properties = [] if variables is None: variables = [] if methods is None: methods = [] return self._create_custom_type(idx, name, basetype, properties, variables, methods) def _create_custom_type(self, idx, name, basetype, properties, variables, methods): if isinstance(basetype, Node): base_t = basetype elif isinstance(basetype, ua.NodeId): base_t = Node(self.iserver.isession, basetype) else: base_t = Node(self.iserver.isession, ua.NodeId(basetype)) custom_t = base_t.add_object_type(idx, name) for prop in properties: datatype = None if len(prop) > 2: datatype = prop[2] custom_t.add_property(idx, prop[0], ua.get_default_value(prop[1]), varianttype=prop[1], datatype=datatype) for variable in variables: datatype = None if len(variable) > 2: datatype = variable[2] custom_t.add_variable(idx, variable[0], ua.get_default_value(variable[1]), varianttype=variable[1], datatype=datatype) for method in methods: custom_t.add_method(idx, method[0], method[1], method[2], method[3]) return custom_t def import_xml(self, path): """ Import nodes defined in xml """ importer = XmlImporter(self) return importer.import_xml(path) def export_xml(self, nodes, path): """ Export defined nodes to xml """ exp = XmlExporter(self) exp.build_etree(nodes) return exp.write_xml(path) def export_xml_by_ns(self, path, namespaces=None): """ Export nodes of one or more namespaces to an XML file. Namespaces used by nodes are always exported for consistency. Args: server: opc ua server to use path: name of the xml file to write namespaces: list of string uris or int indexes of the namespace to export, if not provide all ns are used except 0 Returns: """ if namespaces is None: namespaces = [] nodes = get_nodes_of_namespace(self, namespaces) self.export_xml(nodes, path) def delete_nodes(self, nodes, recursive=False): return delete_nodes(self.iserver.isession, nodes, recursive) def historize_node_data_change(self, node, period=timedelta(days=7), count=0): """ Start historizing supplied nodes; see history module Args: node: node or list of nodes that can be historized (variables/properties) period: time delta to store the history; older data will be deleted from the storage count: number of changes to store in the history Returns: """ nodes = node if isinstance(node, (list, tuple)) else [node] for node in nodes: self.iserver.enable_history_data_change(node, period, count) def dehistorize_node_data_change(self, node): """ Stop historizing supplied nodes; see history module Args: node: node or list of nodes that can be historized (UA variables/properties) Returns: """ nodes = node if isinstance(node, (list, tuple)) else [node] for node in nodes: self.iserver.disable_history_data_change(node) def historize_node_event(self, node, period=timedelta(days=7), count=0): """ Start historizing events from node (typically a UA object); see history module Args: node: node or list of nodes that can be historized (UA objects) period: time delta to store the history; older data will be deleted from the storage count: number of events to store in the history Returns: """ nodes = node if isinstance(node, (list, tuple)) else [node] for node in nodes: self.iserver.enable_history_event(node, period, count) def dehistorize_node_event(self, node): """ Stop historizing events from node (typically a UA object); see history module Args: node: node or list of nodes that can be historized (UA objects) Returns: """ nodes = node if isinstance(node, (list, tuple)) else [node] for node in nodes: self.iserver.disable_history_event(node) def subscribe_server_callback(self, event, handle): self.iserver.subscribe_server_callback(event, handle) def unsubscribe_server_callback(self, event, handle): self.iserver.unsubscribe_server_callback(event, handle) def link_method(self, node, callback): """ Link a python function to a UA method in the address space; required when a UA method has been imported to the address space via XML; the python executable must be linked manually Args: node: UA method node callback: python function that the UA method will call Returns: """ self.iserver.isession.add_method_callback(node.nodeid, callback) def load_type_definitions(self, nodes=None): return load_type_definitions(self, nodes)
class Server(object): """ High level Server class Create an opcua server with default values The class is very short. Users are adviced to read the code. Create your own namespace and then populate your server address space using use the get_root() or get_objects() to get Node objects. and get_event_object() to fire events. Then start server. See example_server.py All methods are threadsafe :ivar application_uri: :vartype application_uri: uri :ivar product_uri: :vartype product_uri: uri :ivar name: :vartype name: string :ivar default_timeout: timout in milliseconds for sessions and secure channel :vartype default_timeout: int :ivar iserver: internal server object :vartype default_timeout: InternalServer :ivar bserver: binary protocol server :vartype bserver: BinaryServer """ def __init__(self): self.logger = logging.getLogger(__name__) self.endpoint = urlparse("opc.tcp://0.0.0.0:4841/freeopcua/server/") self.application_uri = "urn:freeopcua:python:server" self.product_uri = "urn:freeopcua.github.no:python:server" self.name = "FreeOpcUa Python Server" self.application_type = ua.ApplicationType.ClientAndServer self.default_timeout = 3600000 self.iserver = InternalServer() self.bserver = None self._discovery_clients = {} self._discovery_period = 60 self.certificate = None self.private_key = None self._policies = [] # setup some expected values self.register_namespace(self.application_uri) sa_node = self.get_node(ua.NodeId(ua.ObjectIds.Server_ServerArray)) sa_node.set_value([self.application_uri]) def load_certificate(self, path): """ load server certificate from file, either pem or der """ self.certificate = uacrypto.load_certificate(path) def load_private_key(self, path): self.private_key = uacrypto.load_private_key(path) def disable_clock(self, val=True): """ for debugging you may want to disable clock that write every second to address space """ self.iserver.disabled_clock = val def set_application_uri(self, uri): """ Set application/server URI. This uri is supposed to be unique. If you intent to register your server to a discovery server, it really should be unique in your system! default is : "urn:freeopcua:python:server" """ self.application_uri = uri def find_servers(self, uris=None): """ find_servers. mainly implemented for simmetry with client """ if uris is None: uris = [] params = ua.FindServersParameters() params.EndpointUrl = self.endpoint.geturl() params.ServerUris = uris return self.iserver.find_servers(params) def register_to_discovery(self, url="opc.tcp://localhost:4840", period=60): """ Register to an OPC-UA Discovery server. Registering must be renewed at least every 10 minutes, so this method will use our asyncio thread to re-register every period seconds if period is 0 registration is not automatically renewed """ # FIXME: habe a period per discovery if url in self._discovery_clients: self._discovery_clients[url].disconnect() self._discovery_clients[url] = Client(url) self._discovery_clients[url].connect() self._discovery_clients[url].register_server(self) self._discovery_period = period if period: self.iserver.loop.call_soon(self._renew_registration) def unregister_to_discovery(self, url="opc.tcp://localhost:4840"): """ stop registration thread """ # FIXME: is there really no way to deregister? self._discovery_clients[url].disconnect() def _renew_registration(self): for client in self._discovery_clients.values(): client.register_server(self) self.iserver.loop.call_later(self._discovery_period, self._renew_registration) def get_client_to_discovery(self, url="opc.tcp://localhost:4840"): """ Create a client to discovery server and return it """ client = Client(url) client.connect() return client def allow_remote_admin(self, allow): """ Enable or disable the builtin Admin user from network clients """ self.iserver.allow_remote_admin = allow def set_endpoint(self, url): self.endpoint = urlparse(url) def get_endpoints(self): return self.iserver.get_endpoints() def _setup_server_nodes(self): # to be called just before starting server since it needs all parameters to be setup self._set_endpoints() self._policies = [ua.SecurityPolicyFactory()] if self.certificate and self.private_key: self._set_endpoints(security_policies.SecurityPolicyBasic128Rsa15, ua.MessageSecurityMode.SignAndEncrypt) self._policies.append(ua.SecurityPolicyFactory( security_policies.SecurityPolicyBasic128Rsa15, ua.MessageSecurityMode.SignAndEncrypt, self.certificate, self.private_key)) self._set_endpoints(security_policies.SecurityPolicyBasic128Rsa15, ua.MessageSecurityMode.Sign) self._policies.append(ua.SecurityPolicyFactory( security_policies.SecurityPolicyBasic128Rsa15, ua.MessageSecurityMode.Sign, self.certificate, self.private_key)) self._set_endpoints(security_policies.SecurityPolicyBasic256, ua.MessageSecurityMode.SignAndEncrypt) self._policies.append(ua.SecurityPolicyFactory( security_policies.SecurityPolicyBasic256, ua.MessageSecurityMode.SignAndEncrypt, self.certificate, self.private_key)) self._set_endpoints(security_policies.SecurityPolicyBasic256, ua.MessageSecurityMode.Sign) self._policies.append(ua.SecurityPolicyFactory( security_policies.SecurityPolicyBasic256, ua.MessageSecurityMode.Sign, self.certificate, self.private_key)) def _set_endpoints(self, policy=ua.SecurityPolicy, mode=ua.MessageSecurityMode.None_): idtoken = ua.UserTokenPolicy() idtoken.PolicyId = 'anonymous' idtoken.TokenType = ua.UserTokenType.Anonymous idtoken2 = ua.UserTokenPolicy() idtoken2.PolicyId = 'certificate_basic256' idtoken2.TokenType = ua.UserTokenType.Certificate idtoken3 = ua.UserTokenPolicy() idtoken3.PolicyId = 'certificate_basic128' idtoken3.TokenType = ua.UserTokenType.Certificate idtoken4 = ua.UserTokenPolicy() idtoken4.PolicyId = 'username' idtoken4.TokenType = ua.UserTokenType.UserName appdesc = ua.ApplicationDescription() appdesc.ApplicationName = ua.LocalizedText(self.name) appdesc.ApplicationUri = self.application_uri appdesc.ApplicationType = self.application_type appdesc.ProductUri = self.product_uri appdesc.DiscoveryUrls.append(self.endpoint.geturl()) edp = ua.EndpointDescription() edp.EndpointUrl = self.endpoint.geturl() edp.Server = appdesc if self.certificate: edp.ServerCertificate = uacrypto.der_from_x509(self.certificate) edp.SecurityMode = mode edp.SecurityPolicyUri = policy.URI edp.UserIdentityTokens = [idtoken, idtoken2, idtoken3] edp.TransportProfileUri = 'http://opcfoundation.org/UA-Profile/Transport/uatcp-uasc-uabinary' edp.SecurityLevel = 0 self.iserver.add_endpoint(edp) def set_server_name(self, name): self.name = name def start(self): """ Start to listen on network """ self._setup_server_nodes() self.iserver.start() self.bserver = BinaryServer(self.iserver, self.endpoint.hostname, self.endpoint.port) self.bserver.set_policies(self._policies) self.bserver.start() def stop(self): """ Stop server """ for client in self._discovery_clients.values(): client.disconnect() self.bserver.stop() self.iserver.stop() def get_root_node(self): """ Get Root node of server. Returns a Node object. """ return self.get_node(ua.TwoByteNodeId(ua.ObjectIds.RootFolder)) def get_objects_node(self): """ Get Objects node of server. Returns a Node object. """ return self.get_node(ua.TwoByteNodeId(ua.ObjectIds.ObjectsFolder)) def get_server_node(self): """ Get Server node of server. Returns a Node object. """ return self.get_node(ua.TwoByteNodeId(ua.ObjectIds.Server)) def get_node(self, nodeid): """ Get a specific node using NodeId object or a string representing a NodeId """ return Node(self.iserver.isession, nodeid) def create_subscription(self, period, handler): """ Create a subscription. returns a Subscription object which allow to subscribe to events or data on server """ params = ua.CreateSubscriptionParameters() params.RequestedPublishingInterval = period params.RequestedLifetimeCount = 3000 params.RequestedMaxKeepAliveCount = 10000 params.MaxNotificationsPerPublish = 0 params.PublishingEnabled = True params.Priority = 0 return Subscription(self.iserver.isession, params, handler) def get_namespace_array(self): """ get all namespace defined in server """ ns_node = self.get_node(ua.NodeId(ua.ObjectIds.Server_NamespaceArray)) return ns_node.get_value() def register_namespace(self, uri): """ Register a new namespace. Nodes should in custom namespace, not 0. """ ns_node = self.get_node(ua.NodeId(ua.ObjectIds.Server_NamespaceArray)) uries = ns_node.get_value() uries.append(uri) ns_node.set_value(uries) return (len(uries) - 1) def get_namespace_index(self, uri): """ get index of a namespace using its uri """ uries = self.get_namespace_array() return uries.index(uri) def get_event_object(self, etype=ua.ObjectIds.BaseEventType, source=ua.ObjectIds.Server): """ Returns an event object using an event type from address space. Use this object to fire events """ return Event(self.iserver.isession, etype, source) def import_xml(self, path): """ import nodes defined in xml """ importer = xmlimporter.XmlImporter(self.iserver.node_mgt_service) importer.import_xml(path)
def get_endpoints(self, params=None, sockname=None): return InternalServer.get_endpoints(self, params=params, sockname=sockname)
class Server(object): """ High level Server class This class creates an opcua server with default values Create your own namespace and then populate your server address space using use the get_root() or get_objects() to get Node objects. and get_event_object() to fire events. Then start server. See example_server.py All methods are threadsafe If you need more flexibility you call directly the Ua Service methods on the iserver or iserver.isesssion object members. :ivar application_uri: :vartype application_uri: uri :ivar product_uri: :vartype product_uri: uri :ivar name: :vartype name: string :ivar default_timeout: timout in milliseconds for sessions and secure channel :vartype default_timeout: int :ivar iserver: internal server object :vartype default_timeout: InternalServer :ivar bserver: binary protocol server :vartype bserver: BinaryServer """ def __init__(self): self.logger = logging.getLogger(__name__) self.endpoint = urlparse("opc.tcp://0.0.0.0:4840/freeopcua/server/") self.application_uri = "urn:freeopcua:python:server" self.product_uri = "urn:freeopcua.github.no:python:server" self.name = "FreeOpcUa Python Server" self.application_type = ua.ApplicationType.ClientAndServer self.default_timeout = 3600000 self.iserver = InternalServer() self.bserver = None self._discovery_clients = {} self._discovery_period = 60 self.certificate = None self.private_key = None self._policies = [] # setup some expected values self.register_namespace(self.application_uri) sa_node = self.get_node(ua.NodeId(ua.ObjectIds.Server_ServerArray)) sa_node.set_value([self.application_uri]) def load_certificate(self, path): """ load server certificate from file, either pem or der """ self.certificate = uacrypto.load_certificate(path) def load_private_key(self, path): self.private_key = uacrypto.load_private_key(path) def disable_clock(self, val=True): """ for debugging you may want to disable clock that write every second to address space """ self.iserver.disabled_clock = val def set_application_uri(self, uri): """ Set application/server URI. This uri is supposed to be unique. If you intent to register your server to a discovery server, it really should be unique in your system! default is : "urn:freeopcua:python:server" """ self.application_uri = uri def find_servers(self, uris=None): """ find_servers. mainly implemented for simmetry with client """ if uris is None: uris = [] params = ua.FindServersParameters() params.EndpointUrl = self.endpoint.geturl() params.ServerUris = uris return self.iserver.find_servers(params) def register_to_discovery(self, url="opc.tcp://localhost:4840", period=60): """ Register to an OPC-UA Discovery server. Registering must be renewed at least every 10 minutes, so this method will use our asyncio thread to re-register every period seconds if period is 0 registration is not automatically renewed """ # FIXME: habe a period per discovery if url in self._discovery_clients: self._discovery_clients[url].disconnect() self._discovery_clients[url] = Client(url) self._discovery_clients[url].connect() self._discovery_clients[url].register_server(self) self._discovery_period = period if period: self.iserver.loop.call_soon(self._renew_registration) def unregister_to_discovery(self, url="opc.tcp://localhost:4840"): """ stop registration thread """ # FIXME: is there really no way to deregister? self._discovery_clients[url].disconnect() def _renew_registration(self): for client in self._discovery_clients.values(): client.register_server(self) self.iserver.loop.call_later(self._discovery_period, self._renew_registration) def get_client_to_discovery(self, url="opc.tcp://localhost:4840"): """ Create a client to discovery server and return it """ client = Client(url) client.connect() return client def allow_remote_admin(self, allow): """ Enable or disable the builtin Admin user from network clients """ self.iserver.allow_remote_admin = allow def set_endpoint(self, url): self.endpoint = urlparse(url) def get_endpoints(self): return self.iserver.get_endpoints() def _setup_server_nodes(self): # to be called just before starting server since it needs all parameters to be setup self._set_endpoints() self._policies = [ua.SecurityPolicyFactory()] if self.certificate and self.private_key: self._set_endpoints(security_policies.SecurityPolicyBasic128Rsa15, ua.MessageSecurityMode.SignAndEncrypt) self._policies.append(ua.SecurityPolicyFactory(security_policies.SecurityPolicyBasic128Rsa15, ua.MessageSecurityMode.SignAndEncrypt, self.certificate, self.private_key) ) self._set_endpoints(security_policies.SecurityPolicyBasic128Rsa15, ua.MessageSecurityMode.Sign) self._policies.append(ua.SecurityPolicyFactory(security_policies.SecurityPolicyBasic128Rsa15, ua.MessageSecurityMode.Sign, self.certificate, self.private_key) ) self._set_endpoints(security_policies.SecurityPolicyBasic256, ua.MessageSecurityMode.SignAndEncrypt) self._policies.append(ua.SecurityPolicyFactory(security_policies.SecurityPolicyBasic256, ua.MessageSecurityMode.SignAndEncrypt, self.certificate, self.private_key) ) self._set_endpoints(security_policies.SecurityPolicyBasic256, ua.MessageSecurityMode.Sign) self._policies.append(ua.SecurityPolicyFactory(security_policies.SecurityPolicyBasic256, ua.MessageSecurityMode.Sign, self.certificate, self.private_key) ) def _set_endpoints(self, policy=ua.SecurityPolicy, mode=ua.MessageSecurityMode.None_): idtoken = ua.UserTokenPolicy() idtoken.PolicyId = 'anonymous' idtoken.TokenType = ua.UserTokenType.Anonymous idtoken2 = ua.UserTokenPolicy() idtoken2.PolicyId = 'certificate_basic256' idtoken2.TokenType = ua.UserTokenType.Certificate idtoken3 = ua.UserTokenPolicy() idtoken3.PolicyId = 'certificate_basic128' idtoken3.TokenType = ua.UserTokenType.Certificate idtoken4 = ua.UserTokenPolicy() idtoken4.PolicyId = 'username' idtoken4.TokenType = ua.UserTokenType.UserName appdesc = ua.ApplicationDescription() appdesc.ApplicationName = ua.LocalizedText(self.name) appdesc.ApplicationUri = self.application_uri appdesc.ApplicationType = self.application_type appdesc.ProductUri = self.product_uri appdesc.DiscoveryUrls.append(self.endpoint.geturl()) edp = ua.EndpointDescription() edp.EndpointUrl = self.endpoint.geturl() edp.Server = appdesc if self.certificate: edp.ServerCertificate = uacrypto.der_from_x509(self.certificate) edp.SecurityMode = mode edp.SecurityPolicyUri = policy.URI edp.UserIdentityTokens = [idtoken, idtoken2, idtoken3, idtoken4] edp.TransportProfileUri = 'http://opcfoundation.org/UA-Profile/Transport/uatcp-uasc-uabinary' edp.SecurityLevel = 0 self.iserver.add_endpoint(edp) def set_server_name(self, name): self.name = name def start(self): """ Start to listen on network """ self._setup_server_nodes() self.iserver.start() self.bserver = BinaryServer(self.iserver, self.endpoint.hostname, self.endpoint.port) self.bserver.set_policies(self._policies) self.bserver.start() def stop(self): """ Stop server """ for client in self._discovery_clients.values(): client.disconnect() self.bserver.stop() self.iserver.stop() def get_root_node(self): """ Get Root node of server. Returns a Node object. """ return self.get_node(ua.TwoByteNodeId(ua.ObjectIds.RootFolder)) def get_objects_node(self): """ Get Objects node of server. Returns a Node object. """ return self.get_node(ua.TwoByteNodeId(ua.ObjectIds.ObjectsFolder)) def get_server_node(self): """ Get Server node of server. Returns a Node object. """ return self.get_node(ua.TwoByteNodeId(ua.ObjectIds.Server)) def get_node(self, nodeid): """ Get a specific node using NodeId object or a string representing a NodeId """ return Node(self.iserver.isession, nodeid) def create_subscription(self, period, handler): """ Create a subscription. returns a Subscription object which allow to subscribe to events or data on server """ params = ua.CreateSubscriptionParameters() params.RequestedPublishingInterval = period params.RequestedLifetimeCount = 3000 params.RequestedMaxKeepAliveCount = 10000 params.MaxNotificationsPerPublish = 0 params.PublishingEnabled = True params.Priority = 0 return Subscription(self.iserver.isession, params, handler) def get_namespace_array(self): """ get all namespace defined in server """ ns_node = self.get_node(ua.NodeId(ua.ObjectIds.Server_NamespaceArray)) return ns_node.get_value() def register_namespace(self, uri): """ Register a new namespace. Nodes should in custom namespace, not 0. """ ns_node = self.get_node(ua.NodeId(ua.ObjectIds.Server_NamespaceArray)) uries = ns_node.get_value() uries.append(uri) ns_node.set_value(uries) return len(uries) - 1 def get_namespace_index(self, uri): """ get index of a namespace using its uri """ uries = self.get_namespace_array() return uries.index(uri) def get_event_object(self, etype=ua.ObjectIds.BaseEventType, source=ua.ObjectIds.Server): """ Returns an event object using an event type from address space. Use this object to fire events """ return Event(self.iserver.isession, etype, source) def import_xml(self, path): """ import nodes defined in xml """ importer = xmlimporter.XmlImporter(self.iserver.node_mgt_service) importer.import_xml(path) def delete_nodes(self, nodes, recursive=False): return delete_nodes(self.iserver.isession, nodes, recursive) def historize_node(self, node): self.iserver.enable_history(node) def dehistorize_node(self, node): self.iserver.disable_history(node)
class Server(object): """ High level Server class This class creates an opcua server with default values Create your own namespace and then populate your server address space using use the get_root() or get_objects() to get Node objects. and get_event_object() to fire events. Then start server. See example_server.py All methods are threadsafe If you need more flexibility you call directly the Ua Service methods on the iserver or iserver.isesssion object members. During startup the standard address space will be constructed, which may be time-consuming when running a server on a less powerful device (e.g. a Raspberry Pi). In order to improve startup performance, a optional path to a cache file can be passed to the server constructor. If the parameter is defined, the address space will be loaded from the cache file or the file will be created if it does not exist yet. As a result the first startup will be even slower due to the cache file generation but all further startups will be significantly faster. :ivar application_uri: :vartype application_uri: uri :ivar product_uri: :vartype product_uri: uri :ivar name: :vartype name: string :ivar default_timeout: timout in milliseconds for sessions and secure channel :vartype default_timeout: int :ivar iserver: internal server object :vartype default_timeout: InternalServer :ivar bserver: binary protocol server :vartype bserver: BinaryServer :ivar nodes: shortcuts to common nodes :vartype nodes: Shortcuts """ def __init__(self, cacheFile = None, iserver = None): self.logger = logging.getLogger(__name__) self.endpoint = urlparse("opc.tcp://0.0.0.0:4840/freeopcua/server/") self.application_uri = "urn:freeopcua:python:server" self.product_uri = "urn:freeopcua.github.no:python:server" self.name = "FreeOpcUa Python Server" self.application_type = ua.ApplicationType.ClientAndServer self.default_timeout = 3600000 if iserver is not None : self.iserver = iserver else : self.iserver = InternalServer(cacheFile) self.bserver = None self._discovery_clients = {} self._discovery_period = 60 self.certificate = None self.private_key = None self._policies = [] self.nodes = Shortcuts(self.iserver.isession) # setup some expected values self.register_namespace(self.application_uri) sa_node = self.get_node(ua.NodeId(ua.ObjectIds.Server_ServerArray)) sa_node.set_value([self.application_uri]) def __enter__(self): self.start() return self def __exit__(self, exc_type, exc_value, traceback): self.stop() def load_certificate(self, path): """ load server certificate from file, either pem or der """ self.certificate = uacrypto.load_certificate(path) def load_private_key(self, path): self.private_key = uacrypto.load_private_key(path) def disable_clock(self, val=True): """ for debugging you may want to disable clock that write every second to address space """ self.iserver.disabled_clock = val def set_application_uri(self, uri): """ Set application/server URI. This uri is supposed to be unique. If you intent to register your server to a discovery server, it really should be unique in your system! default is : "urn:freeopcua:python:server" """ self.application_uri = uri def find_servers(self, uris=None): """ find_servers. mainly implemented for simmetry with client """ if uris is None: uris = [] params = ua.FindServersParameters() params.EndpointUrl = self.endpoint.geturl() params.ServerUris = uris return self.iserver.find_servers(params) def register_to_discovery(self, url="opc.tcp://localhost:4840", period=60): """ Register to an OPC-UA Discovery server. Registering must be renewed at least every 10 minutes, so this method will use our asyncio thread to re-register every period seconds if period is 0 registration is not automatically renewed """ # FIXME: habe a period per discovery if url in self._discovery_clients: self._discovery_clients[url].disconnect() self._discovery_clients[url] = Client(url) self._discovery_clients[url].connect() self._discovery_clients[url].register_server(self) self._discovery_period = period if period: self.iserver.loop.call_soon(self._renew_registration) def unregister_to_discovery(self, url="opc.tcp://localhost:4840"): """ stop registration thread """ # FIXME: is there really no way to deregister? self._discovery_clients[url].disconnect() def _renew_registration(self): for client in self._discovery_clients.values(): client.register_server(self) self.iserver.loop.call_later(self._discovery_period, self._renew_registration) def get_client_to_discovery(self, url="opc.tcp://localhost:4840"): """ Create a client to discovery server and return it """ client = Client(url) client.connect() return client def allow_remote_admin(self, allow): """ Enable or disable the builtin Admin user from network clients """ self.iserver.allow_remote_admin = allow def set_endpoint(self, url): self.endpoint = urlparse(url) def get_endpoints(self): return self.iserver.get_endpoints() def _setup_server_nodes(self): # to be called just before starting server since it needs all parameters to be setup self._set_endpoints() self._policies = [ua.SecurityPolicyFactory()] if self.certificate and self.private_key: self._set_endpoints(security_policies.SecurityPolicyBasic128Rsa15, ua.MessageSecurityMode.SignAndEncrypt) self._policies.append(ua.SecurityPolicyFactory(security_policies.SecurityPolicyBasic128Rsa15, ua.MessageSecurityMode.SignAndEncrypt, self.certificate, self.private_key) ) self._set_endpoints(security_policies.SecurityPolicyBasic128Rsa15, ua.MessageSecurityMode.Sign) self._policies.append(ua.SecurityPolicyFactory(security_policies.SecurityPolicyBasic128Rsa15, ua.MessageSecurityMode.Sign, self.certificate, self.private_key) ) self._set_endpoints(security_policies.SecurityPolicyBasic256, ua.MessageSecurityMode.SignAndEncrypt) self._policies.append(ua.SecurityPolicyFactory(security_policies.SecurityPolicyBasic256, ua.MessageSecurityMode.SignAndEncrypt, self.certificate, self.private_key) ) self._set_endpoints(security_policies.SecurityPolicyBasic256, ua.MessageSecurityMode.Sign) self._policies.append(ua.SecurityPolicyFactory(security_policies.SecurityPolicyBasic256, ua.MessageSecurityMode.Sign, self.certificate, self.private_key) ) def _set_endpoints(self, policy=ua.SecurityPolicy, mode=ua.MessageSecurityMode.None_): idtoken = ua.UserTokenPolicy() idtoken.PolicyId = 'anonymous' idtoken.TokenType = ua.UserTokenType.Anonymous idtoken2 = ua.UserTokenPolicy() idtoken2.PolicyId = 'certificate_basic256' idtoken2.TokenType = ua.UserTokenType.Certificate idtoken3 = ua.UserTokenPolicy() idtoken3.PolicyId = 'certificate_basic128' idtoken3.TokenType = ua.UserTokenType.Certificate idtoken4 = ua.UserTokenPolicy() idtoken4.PolicyId = 'username' idtoken4.TokenType = ua.UserTokenType.UserName appdesc = ua.ApplicationDescription() appdesc.ApplicationName = ua.LocalizedText(self.name) appdesc.ApplicationUri = self.application_uri appdesc.ApplicationType = self.application_type appdesc.ProductUri = self.product_uri appdesc.DiscoveryUrls.append(self.endpoint.geturl()) edp = ua.EndpointDescription() edp.EndpointUrl = self.endpoint.geturl() edp.Server = appdesc if self.certificate: edp.ServerCertificate = uacrypto.der_from_x509(self.certificate) edp.SecurityMode = mode edp.SecurityPolicyUri = policy.URI edp.UserIdentityTokens = [idtoken, idtoken2, idtoken3, idtoken4] edp.TransportProfileUri = 'http://opcfoundation.org/UA-Profile/Transport/uatcp-uasc-uabinary' edp.SecurityLevel = 0 self.iserver.add_endpoint(edp) def set_server_name(self, name): self.name = name def start(self): """ Start to listen on network """ self._setup_server_nodes() self.iserver.start() self.bserver = BinaryServer(self.iserver, self.endpoint.hostname, self.endpoint.port) self.bserver.set_policies(self._policies) self.bserver.start() def stop(self): """ Stop server """ for client in self._discovery_clients.values(): client.disconnect() self.bserver.stop() self.iserver.stop() def get_root_node(self): """ Get Root node of server. Returns a Node object. """ return self.get_node(ua.TwoByteNodeId(ua.ObjectIds.RootFolder)) def get_objects_node(self): """ Get Objects node of server. Returns a Node object. """ return self.get_node(ua.TwoByteNodeId(ua.ObjectIds.ObjectsFolder)) def get_server_node(self): """ Get Server node of server. Returns a Node object. """ return self.get_node(ua.TwoByteNodeId(ua.ObjectIds.Server)) def get_node(self, nodeid): """ Get a specific node using NodeId object or a string representing a NodeId """ return Node(self.iserver.isession, nodeid) def create_subscription(self, period, handler): """ Create a subscription. returns a Subscription object which allow to subscribe to events or data on server """ params = ua.CreateSubscriptionParameters() params.RequestedPublishingInterval = period params.RequestedLifetimeCount = 3000 params.RequestedMaxKeepAliveCount = 10000 params.MaxNotificationsPerPublish = 0 params.PublishingEnabled = True params.Priority = 0 return Subscription(self.iserver.isession, params, handler) def get_namespace_array(self): """ get all namespace defined in server """ ns_node = self.get_node(ua.NodeId(ua.ObjectIds.Server_NamespaceArray)) return ns_node.get_value() def register_namespace(self, uri): """ Register a new namespace. Nodes should in custom namespace, not 0. """ ns_node = self.get_node(ua.NodeId(ua.ObjectIds.Server_NamespaceArray)) uries = ns_node.get_value() if uri in uries: return uries.index(uri) uries.append(uri) ns_node.set_value(uries) return len(uries) - 1 def get_namespace_index(self, uri): """ get index of a namespace using its uri """ uries = self.get_namespace_array() return uries.index(uri) def get_event_generator(self, etype=None, source=ua.ObjectIds.Server): """ Returns an event object using an event type from address space. Use this object to fire events """ if not etype: etype = BaseEvent() return EventGenerator(self.iserver.isession, etype, source) def create_custom_data_type(self, idx, name, basetype=ua.ObjectIds.BaseDataType, properties=[]): return self._create_custom_type(idx, name, basetype, properties, [], []) def create_custom_event_type(self, idx, name, basetype=ua.ObjectIds.BaseEventType, properties=[]): return self._create_custom_type(idx, name, basetype, properties, [], []) def create_custom_object_type(self, idx, name, basetype=ua.ObjectIds.BaseObjectType, properties=[], variables=[], methods=[]): return self._create_custom_type(idx, name, basetype, properties, variables, methods) #def create_custom_reference_type(self, idx, name, basetype=ua.ObjectIds.BaseReferenceType, properties=[]): #return self._create_custom_type(idx, name, basetype, properties) def create_custom_variable_type(self, idx, name, basetype=ua.ObjectIds.BaseVariableType, properties=[], variables=[], methods=[]): return self._create_custom_type(idx, name, basetype, properties, variables, methods) def _create_custom_type(self, idx, name, basetype, properties, variables, methods): if isinstance(basetype, Node): base_t = basetype elif isinstance(basetype, ua.NodeId): base_t = Node(self.iserver.isession, basetype) else: base_t = Node(self.iserver.isession, ua.NodeId(basetype)) custom_t = base_t.add_object_type(idx, name) for property in properties: datatype = None if len(property) > 2: datatype = property[2] custom_t.add_property(idx, property[0], None, varianttype=property[1], datatype=datatype) for variable in variables: datatype = None if len(variable) > 2: datatype = variable[2] custom_t.add_variable(idx, variable[0], None, varianttype=variable[1], datatype=datatype) for method in methods: custom_t.add_method(idx, method[0], method[1], method[2], method[3]) return custom_t def import_xml(self, path): """ import nodes defined in xml """ importer = xmlimporter.XmlImporter(self.iserver.node_mgt_service) importer.import_xml(path, self) def delete_nodes(self, nodes, recursive=False): return delete_nodes(self.iserver.isession, nodes, recursive) def historize_node(self, node): self.iserver.enable_history(node) def dehistorize_node(self, node): self.iserver.disable_history(node) def subscribe_server_callback(self, event, handle): self.iserver.subscribe_server_callback(event, handle) def unsubscribe_server_callback(self, event, handle): self.iserver.unsubscribe_server_callback(event, handle)
def setup_nodes(self): InternalServer.setup_nodes(self)
def local_discovery_service(self): return InternalServer.local_discovery_service(self)
def thread_loop(self): return InternalServer.thread_loop(self)
def user_manager(self): return InternalServer.user_manager(self)
def set_attribute_value(self, nodeid, datavalue, attr=ua.AttributeIds.Value): InternalServer.set_attribute_value(self, nodeid, datavalue, attr=attr)
def unsubscribe_server_callback(self, event, handle): InternalServer.unsubscribe_server_callback(self, event, handle)
def disable_history_event(self, source): InternalServer.disable_history_event(self, source)
def _set_current_time(self): InternalServer._set_current_time(self)
def get_new_channel_id(self): return InternalServer.get_new_channel_id(self)
def load_standard_address_space(self, shelffile=None): InternalServer.load_standard_address_space(self, shelffile=shelffile)
def __init__(self, name, shared): super().__init__(name, shared) self.logger = logging.getLogger(self.name) self.logger.info("init") self.shared.config.set_hidden_value(self.name, "user") self.shared.config.set_hidden_value(self.name, "password") self.shared.config.set_hidden_value(self.name, "password_hash") def config(key, val): return self.shared.config.config(self.name, key, val) endpoint = config("endpoint", "no_endpoint") certificate = config("certificate", "") private_key = config("private_key", "") name = config("name", "FreeOpcUa Python Server") uri = config("uri", "http://examples.freeopcua.github.io") root_object_name = config("root_object_name", "TEST") separator = config("separator", ".") namespace = config("namespace", 2) auto_build_folders = config("auto_build_folders", 0) self.oldnew = config("oldnew_comparision", 0) self.debug_statistics = config("debug_statistics", 0) admin_username = config("user", "admin") admin_password = config("password", "admin") admin_password_hash = config("password_hash", "").replace("$$", "$") security_ids = [] anonymous_on = config("anonymous_on", 0) username_on = config("username_on", 1) certificate_on = config("certificate_basic256sha256_on", 0) if anonymous_on: security_ids.append("Anonymous") if username_on: security_ids.append("Username") if certificate_on: security_ids.append("Basic256Sha256") security_policy = [] if config("nosecurity_on", 1): security_policy.append(ua.SecurityPolicyType.NoSecurity) if config("basic128rsa15_sign_on", 0): security_policy.append(ua.SecurityPolicyType.Basic128Rsa15_Sign) if config("basic128rsa15_signandencrypt_on", 0): security_policy.append( ua.SecurityPolicyType.Basic128Rsa15_SignAndEncrypt) if config("basic256_sign_on", 0): security_policy.append(ua.SecurityPolicyType.Basic256_Sign) if config("basic256_signandencrypt_on", 0): security_policy.append( ua.SecurityPolicyType.Basic256_SignAndEncrypt) if config("basic256sha256_sign_on", 1): security_policy.append(ua.SecurityPolicyType.Basic256Sha256_Sign) if config("basic256sha256_signandencrypt_on", 1): security_policy.append( ua.SecurityPolicyType.Basic256Sha256_SignAndEncrypt) initial_values_is_quality_good = config( "initial_values_is_quality_good", 0) if anonymous_on: server = CustomServer(iserver=InternalServer( session_cls=CustomAnonInternalSession)) else: server = CustomServer(iserver=InternalServer( session_cls=CustomInternalSession)) server.iserver._parent = server server.set_application_uri(uri) server.name = name server.set_endpoint(endpoint) server.allow_remote_admin(False) if certificate and private_key: server.load_certificate(str(certificate)) server.load_private_key(str(private_key)) if security_ids: server.set_security_IDs(security_ids) if security_policy: server.set_security_policy(security_policy) def custom_user_manager(isession, userName, password): if userName != admin_username: return False if admin_password_hash: if werkzeug.security.check_password_hash( admin_password_hash, password): return True else: # fallback to plaintext if password == admin_password: return True return False if username_on: server.user_manager.set_user_manager(custom_user_manager) idx = server.register_namespace(uri) objects = server.get_objects_node() root = objects.add_object(idx, root_object_name) self.server = server self.objects = objects self.root = root self.sep = separator self.ns = namespace self.auto_build_folders = auto_build_folders self.items = [] self.subscription = None if initial_values_is_quality_good: self.initial_status_code = ua.StatusCodes.Good else: self.initial_status_code = ua.StatusCodes.BadWaitingForInitialData self.initial_timestamp = datetime.datetime.utcnow()
def _address_space_fixes(self): InternalServer._address_space_fixes(self)
def enable_history_data_change(self, node, period=timedelta(days=7), count=0): InternalServer.enable_history_data_change(self, node, period=period, count=count)
class Server(object): """ High level Server class This class creates an opcua server with default values Create your own namespace and then populate your server address space using use the get_root() or get_objects() to get Node objects. and get_event_object() to fire events. Then start server. See example_server.py All methods are threadsafe If you need more flexibility you call directly the Ua Service methods on the iserver or iserver.isession object members. During startup the standard address space will be constructed, which may be time-consuming when running a server on a less powerful device (e.g. a Raspberry Pi). In order to improve startup performance, a optional path to a cache file can be passed to the server constructor. If the parameter is defined, the address space will be loaded from the cache file or the file will be created if it does not exist yet. As a result the first startup will be even slower due to the cache file generation but all further start ups will be significantly faster. :ivar product_uri: :vartype product_uri: uri :ivar name: :vartype name: string :ivar default_timeout: timeout in milliseconds for sessions and secure channel :vartype default_timeout: int :ivar iserver: internal server object :vartype default_timeout: InternalServer :ivar bserver: binary protocol server :vartype bserver: BinaryServer :ivar nodes: shortcuts to common nodes :vartype nodes: Shortcuts """ def __init__(self, shelffile=None, iserver=None): self.logger = logging.getLogger(__name__) self.endpoint = urlparse("opc.tcp://0.0.0.0:4840/freeopcua/server/") self._application_uri = "urn:freeopcua:python:server" self.product_uri = "urn:freeopcua.github.io:python:server" self.name = "FreeOpcUa Python Server" self.manufacturer_name = "FreeOpcUa" self.application_type = ua.ApplicationType.ClientAndServer self.default_timeout = 3600000 if iserver is not None: self.iserver = iserver else: self.iserver = InternalServer(shelffile = shelffile, parent = self) self.bserver = None self._policies = [] self.nodes = Shortcuts(self.iserver.isession) # setup some expected values self.set_application_uri(self._application_uri) sa_node = self.get_node(ua.NodeId(ua.ObjectIds.Server_ServerArray)) sa_node.set_value([self._application_uri]) status_node = self.get_node(ua.NodeId(ua.ObjectIds.Server_ServerStatus)) build_node = self.get_node(ua.NodeId(ua.ObjectIds.Server_ServerStatus_BuildInfo)) status = ua.ServerStatusDataType() status.BuildInfo.ProductUri = self.product_uri status.BuildInfo.ManufacturerName = self.manufacturer_name status.BuildInfo.ProductName = self.name status.BuildInfo.SoftwareVersion = "1.0pre" status.BuildInfo.BuildNumber = "0" status.BuildInfo.BuildDate = datetime.now() status.SecondsTillShutdown = 0 status_node.set_value(status) build_node.set_value(status.BuildInfo) # enable all endpoints by default self.certificate = None self.private_key = None self.user_manager = UserManager(parent = self) self._security_policy = [ ua.SecurityPolicyType.NoSecurity, ua.SecurityPolicyType.Basic256Sha256_SignAndEncrypt, ua.SecurityPolicyType.Basic256Sha256_Sign ] self._policyIDs = ["Anonymous", "Basic256Sha256", "Username"] def __enter__(self): self.start() return self def __exit__(self, exc_type, exc_value, traceback): self.stop() @property def local_discovery_service(self): return self.iserver.local_discovery_service def load_certificate(self, path): """ load server certificate from file, either pem or der """ self.certificate = uacrypto.load_certificate(path) def load_private_key(self, path): self.private_key = uacrypto.load_private_key(path) def disable_clock(self, val=True): """ for debugging you may want to disable clock that write every second to address space """ self.iserver.disabled_clock = val def set_application_uri(self, uri): """ Set application/server URI. This uri is supposed to be unique. If you intent to register your server to a discovery server, it really should be unique in your system! default is : "urn:freeopcua:python:server" """ self._application_uri = uri ns_node = self.get_node(ua.NodeId(ua.ObjectIds.Server_NamespaceArray)) uries = ns_node.get_value() if len(uries) > 1: uries[1] = uri # application uri is always namespace 1 else: uries.append(uri) ns_node.set_value(uries) def find_servers(self, uris=None): """ find_servers. mainly implemented for symmetry with client """ if uris is None: uris = [] params = ua.FindServersParameters() params.EndpointUrl = self.endpoint.geturl() params.ServerUris = uris return self.local_discovery_service.find_servers(params) def allow_remote_admin(self, allow): """ Enable or disable the builtin Admin user from network clients """ self.user_manager.allow_remote_admin = allow def set_endpoint(self, url): self.endpoint = urlparse(url) def get_endpoints(self): return self.iserver.get_endpoints() def set_security_policy(self, security_policy): """ Method setting up the security policies for connections to the server, where security_policy is a list of integers. During server initialization, all endpoints are enabled: security_policy = [ ua.SecurityPolicyType.NoSecurity, ua.SecurityPolicyType.Basic256Sha256_SignAndEncrypt, ua.SecurityPolicyType.Basic256Sha256_Sign ] E.g. to limit the number of endpoints and disable no encryption: set_security_policy([ ua.SecurityPolicyType.Basic256Sha256_SignAndEncrypt]) """ self._security_policy = security_policy def set_security_IDs(self, policyIDs): """ Method setting up the security endpoints for identification of clients. During server object initialization, all possible endpoints are enabled: self._policyIDs = ["Anonymous", "Basic256Sha256", "Username"] E.g. to limit the number of IDs and disable anonymous clients: set_security_policy(["Basic256Sha256"]) (Implementation for ID check is currently not finalized...) """ self._policyIDs = policyIDs def _setup_server_nodes(self): # to be called just before starting server since it needs all parameters to be setup if ua.SecurityPolicyType.NoSecurity in self._security_policy: self._set_endpoints() self._policies = [ua.SecurityPolicyFactory()] if self._security_policy != [ua.SecurityPolicyType.NoSecurity]: if not (self.certificate and self.private_key): self.logger.warning("Endpoints other than open requested but private key and certificate are not set.") return if ua.SecurityPolicyType.NoSecurity in self._security_policy: self.logger.warning("Creating an open endpoint to the server, although encrypted endpoints are enabled.") if ua.SecurityPolicyType.Basic256Sha256_SignAndEncrypt in self._security_policy: self._set_endpoints(security_policies.SecurityPolicyBasic256Sha256, ua.MessageSecurityMode.SignAndEncrypt) self._policies.append(ua.SecurityPolicyFactory(security_policies.SecurityPolicyBasic256Sha256, ua.MessageSecurityMode.SignAndEncrypt, self.certificate, self.private_key) ) if ua.SecurityPolicyType.Basic256Sha256_Sign in self._security_policy: self._set_endpoints(security_policies.SecurityPolicyBasic256Sha256, ua.MessageSecurityMode.Sign) self._policies.append(ua.SecurityPolicyFactory(security_policies.SecurityPolicyBasic256Sha256, ua.MessageSecurityMode.Sign, self.certificate, self.private_key) ) def _set_endpoints(self, policy=ua.SecurityPolicy, mode=ua.MessageSecurityMode.None_): idtokens = [] if "Anonymous" in self._policyIDs: idtoken = ua.UserTokenPolicy() idtoken.PolicyId = 'anonymous' idtoken.TokenType = ua.UserTokenType.Anonymous idtokens.append(idtoken) if "Basic256Sha256" in self._policyIDs: idtoken = ua.UserTokenPolicy() idtoken.PolicyId = 'certificate_basic256sha256' idtoken.TokenType = ua.UserTokenType.Certificate idtokens.append(idtoken) if "Username" in self._policyIDs: idtoken = ua.UserTokenPolicy() idtoken.PolicyId = 'username' idtoken.TokenType = ua.UserTokenType.UserName idtokens.append(idtoken) appdesc = ua.ApplicationDescription() appdesc.ApplicationName = ua.LocalizedText(self.name) appdesc.ApplicationUri = self._application_uri appdesc.ApplicationType = self.application_type appdesc.ProductUri = self.product_uri appdesc.DiscoveryUrls.append(self.endpoint.geturl()) edp = ua.EndpointDescription() edp.EndpointUrl = self.endpoint.geturl() edp.Server = appdesc if self.certificate: edp.ServerCertificate = uacrypto.der_from_x509(self.certificate) edp.SecurityMode = mode edp.SecurityPolicyUri = policy.URI edp.UserIdentityTokens = idtokens edp.TransportProfileUri = 'http://opcfoundation.org/UA-Profile/Transport/uatcp-uasc-uabinary' edp.SecurityLevel = 0 self.iserver.add_endpoint(edp) def set_server_name(self, name): self.name = name def start(self): """ Start to listen on network """ self._setup_server_nodes() self.iserver.start() try: if not self.bserver: self.bserver = BinaryServer(self.iserver, self.endpoint.hostname, self.endpoint.port) self.bserver.set_policies(self._policies) self.bserver.set_loop(self.iserver.loop) self.bserver.start() except Exception as exp: self.iserver.stop() raise exp def stop(self): """ Stop server """ self.bserver.stop() self.iserver.stop() def get_root_node(self): """ Get Root node of server. Returns a Node object. """ return self.get_node(ua.TwoByteNodeId(ua.ObjectIds.RootFolder)) def get_objects_node(self): """ Get Objects node of server. Returns a Node object. """ return self.get_node(ua.TwoByteNodeId(ua.ObjectIds.ObjectsFolder)) def get_server_node(self): """ Get Server node of server. Returns a Node object. """ return self.get_node(ua.TwoByteNodeId(ua.ObjectIds.Server)) def get_node(self, nodeid): """ Get a specific node using NodeId object or a string representing a NodeId """ return Node(self.iserver.isession, nodeid) def create_subscription(self, period, handler): """ Create a subscription. returns a Subscription object which allow to subscribe to events or data on server period is in milliseconds handler is a python object with following methods: def datachange_notification(self, node, val, data): def event_notification(self, event): def status_change_notification(self, status): """ params = ua.CreateSubscriptionParameters() params.RequestedPublishingInterval = period params.RequestedLifetimeCount = 3000 params.RequestedMaxKeepAliveCount = 10000 params.MaxNotificationsPerPublish = 0 params.PublishingEnabled = True params.Priority = 0 return Subscription(self.iserver.isession, params, handler) def get_namespace_array(self): """ get all namespace defined in server """ ns_node = self.get_node(ua.NodeId(ua.ObjectIds.Server_NamespaceArray)) return ns_node.get_value() def register_namespace(self, uri): """ Register a new namespace. Nodes should in custom namespace, not 0. """ ns_node = self.get_node(ua.NodeId(ua.ObjectIds.Server_NamespaceArray)) uries = ns_node.get_value() if uri in uries: return uries.index(uri) uries.append(uri) ns_node.set_value(uries) return len(uries) - 1 def get_namespace_index(self, uri): """ get index of a namespace using its uri """ uries = self.get_namespace_array() return uries.index(uri) def get_event_generator(self, etype=None, emitting_node=ua.ObjectIds.Server): """ Returns an event object using an event type from address space. Use this object to fire events """ if not etype: etype = BaseEvent() return EventGenerator(self.iserver.isession, etype, emitting_node=emitting_node) def create_custom_data_type(self, idx, name, basetype=ua.ObjectIds.BaseDataType, properties=None): if properties is None: properties = [] return self._create_custom_type(idx, name, basetype, properties, [], []) def create_custom_event_type(self, idx, name, basetype=ua.ObjectIds.BaseEventType, properties=None): if properties is None: properties = [] return self._create_custom_type(idx, name, basetype, properties, [], []) def create_custom_object_type(self, idx, name, basetype=ua.ObjectIds.BaseObjectType, properties=None, variables=None, methods=None): if properties is None: properties = [] if variables is None: variables = [] if methods is None: methods = [] return self._create_custom_type(idx, name, basetype, properties, variables, methods) # def create_custom_reference_type(self, idx, name, basetype=ua.ObjectIds.BaseReferenceType, properties=[]): # return self._create_custom_type(idx, name, basetype, properties) def create_custom_variable_type(self, idx, name, basetype=ua.ObjectIds.BaseVariableType, properties=None, variables=None, methods=None): if properties is None: properties = [] if variables is None: variables = [] if methods is None: methods = [] return self._create_custom_type(idx, name, basetype, properties, variables, methods) def _create_custom_type(self, idx, name, basetype, properties, variables, methods): if isinstance(basetype, Node): base_t = basetype elif isinstance(basetype, ua.NodeId): base_t = Node(self.iserver.isession, basetype) else: base_t = Node(self.iserver.isession, ua.NodeId(basetype)) custom_t = base_t.add_object_type(idx, name) for prop in properties: datatype = None if len(prop) > 2: datatype = prop[2] custom_t.add_property(idx, prop[0], ua.get_default_value(prop[1]), varianttype=prop[1], datatype=datatype) for variable in variables: datatype = None if len(variable) > 2: datatype = variable[2] custom_t.add_variable(idx, variable[0], ua.get_default_value(variable[1]), varianttype=variable[1], datatype=datatype) for method in methods: custom_t.add_method(idx, method[0], method[1], method[2], method[3]) return custom_t def import_xml(self, path=None, xmlstring=None): """ Import nodes defined in xml """ importer = XmlImporter(self) return importer.import_xml(path, xmlstring) def export_xml(self, nodes, path): """ Export defined nodes to xml """ exp = XmlExporter(self) exp.build_etree(nodes) return exp.write_xml(path) def export_xml_by_ns(self, path, namespaces=None): """ Export nodes of one or more namespaces to an XML file. Namespaces used by nodes are always exported for consistency. Args: server: opc ua server to use path: name of the xml file to write namespaces: list of string uris or int indexes of the namespace to export, if not provide all ns are used except 0 Returns: """ if namespaces is None: namespaces = [] nodes = get_nodes_of_namespace(self, namespaces) self.export_xml(nodes, path) def delete_nodes(self, nodes, recursive=False): return delete_nodes(self.iserver.isession, nodes, recursive) def historize_node_data_change(self, node, period=timedelta(days=7), count=0): """ Start historizing supplied nodes; see history module Args: node: node or list of nodes that can be historized (variables/properties) period: time delta to store the history; older data will be deleted from the storage count: number of changes to store in the history Returns: """ nodes = node if isinstance(node, (list, tuple)) else [node] for node in nodes: self.iserver.enable_history_data_change(node, period, count) def dehistorize_node_data_change(self, node): """ Stop historizing supplied nodes; see history module Args: node: node or list of nodes that can be historized (UA variables/properties) Returns: """ nodes = node if isinstance(node, (list, tuple)) else [node] for node in nodes: self.iserver.disable_history_data_change(node) def historize_node_event(self, node, period=timedelta(days=7), count=0): """ Start historizing events from node (typically a UA object); see history module Args: node: node or list of nodes that can be historized (UA objects) period: time delta to store the history; older data will be deleted from the storage count: number of events to store in the history Returns: """ nodes = node if isinstance(node, (list, tuple)) else [node] for node in nodes: self.iserver.enable_history_event(node, period, count) def dehistorize_node_event(self, node): """ Stop historizing events from node (typically a UA object); see history module Args: node: node or list of nodes that can be historized (UA objects) Returns: """ nodes = node if isinstance(node, (list, tuple)) else [node] for node in nodes: self.iserver.disable_history_event(node) def subscribe_server_callback(self, event, handle): self.iserver.subscribe_server_callback(event, handle) def unsubscribe_server_callback(self, event, handle): self.iserver.unsubscribe_server_callback(event, handle) def link_method(self, node, callback): """ Link a python function to a UA method in the address space; required when a UA method has been imported to the address space via XML; the python executable must be linked manually Args: node: UA method node callback: python function that the UA method will call Returns: """ self.iserver.isession.add_method_callback(node.nodeid, callback) def load_type_definitions(self, nodes=None): """ load custom structures from our server. Server side this can be used to create python objects from custom structures imported through xml into server """ return load_type_definitions(self, nodes) def load_enums(self): """ load UA structures and generate python Enums in ua module for custom enums in server """ return load_enums(self) def set_attribute_value(self, nodeid, datavalue, attr=ua.AttributeIds.Value): """ directly write datavalue to the Attribute, bypasing some checks and structure creation so it is a little faster """ return self.iserver.set_attribute_value(nodeid, datavalue, attr)
def add_endpoint(self, endpoint): InternalServer.add_endpoint(self, endpoint)
def dump_address_space(self, path): InternalServer.dump_address_space(self, path)
def start(self): InternalServer.start(self)
def stop(self): InternalServer.stop(self)
def load_address_space(self, path): InternalServer.load_address_space(self, path)
def disable_history_data_change(self, node): InternalServer.disable_history_data_change(self, node)