def create_session(self): """ send a CreateSessionRequest to server with reasonable parameters. If you want o modify settings look at code of this methods and make your own """ desc = ua.ApplicationDescription() desc.ApplicationUri = self.application_uri desc.ProductUri = self.product_uri desc.ApplicationName = ua.LocalizedText(self.name) desc.ApplicationType = ua.ApplicationType.Client params = ua.CreateSessionParameters() # at least 32 random bytes for server to prove possession of private key (specs part 4, 5.6.2.2) nonce = utils.create_nonce(32) params.ClientNonce = nonce params.ClientCertificate = self.security_policy.client_certificate params.ClientDescription = desc params.EndpointUrl = self.server_url.geturl() params.SessionName = self.description + " Session" + str(self._session_counter) params.RequestedSessionTimeout = 3600000 params.MaxResponseMessageSize = 0 # means no max size response = self.uaclient.create_session(params) if self.security_policy.client_certificate is None: data = nonce else: data = self.security_policy.client_certificate + nonce self.security_policy.asymmetric_cryptography.verify(data, response.ServerSignature.Signature) self._server_nonce = response.ServerNonce if not self.security_policy.server_certificate: self.security_policy.server_certificate = response.ServerCertificate elif self.security_policy.server_certificate != response.ServerCertificate: raise ua.UaError("Server certificate mismatch") # remember PolicyId's: we will use them in activate_session() ep = Client.find_endpoint(response.ServerEndpoints, self.security_policy.Mode, self.security_policy.URI) self._policy_ids = ep.UserIdentityTokens self.session_timeout = response.RevisedSessionTimeout self.keepalive = KeepAlive( self, min(self.session_timeout, self.secure_channel_timeout) * 0.7) # 0.7 is from spec self.keepalive.start() return response
def string_to_val(string, vtype): """ Convert back a string to a python or python-opcua object """ string = string.strip() if string.startswith("["): string = string[1:-1] var = [] for s in string.split(","): s = s.strip() val = string_to_val(s, vtype) var.append(val) return var if vtype == ua.VariantType.Null: val = None elif vtype == ua.VariantType.Boolean: val = bool(string) elif 4 <= vtype.value < 9: val = int(string) elif vtype in (ua.VariantType.Float, ua.VariantType.Double): val = float(string) elif vtype in (ua.VariantType.String, ua.VariantType.XmlElement): val = string elif vtype in (ua.VariantType.SByte, ua.VariantType.Guid, ua.VariantType.ByteString): val = bytes(string) elif vtype in (ua.VariantType.NodeId, ua.VariantType.ExpandedNodeId): val = ua.NodeId.from_string(string) elif vtype == ua.VariantType.QualifiedName: val = ua.QualifiedName.from_string(string) elif vtype == ua.VariantType.DateTime: val = parser.parse(string) elif vtype == ua.VariantType.LocalizedText: val = ua.LocalizedText(string) elif vtype == ua.VariantType.StatusCode: val = ua.StatusCode(string) else: # FIXME: Some types are probably missing! raise NotImplementedError return val
def _register_server(serverToRegister, registrationClient, uaDiscoveryConfiguration=None): """ Register serverToRegister to discovery server if uaDiscoveryConfiguration is provided, the newer register_server2 service call is used """ uaRegSrv = ua.RegisteredServer() uaRegSrv.ServerUri = serverToRegister.get_application_uri() uaRegSrv.ProductUri = serverToRegister.product_uri uaRegSrv.DiscoveryUrls = [serverToRegister.endpoint.geturl()] uaRegSrv.ServerType = serverToRegister.application_type uaRegSrv.ServerNames = [ua.LocalizedText(serverToRegister.name)] uaRegSrv.IsOnline = serverToRegister.iserver.is_running() if uaDiscoveryConfiguration: params = ua.RegisterServer2Parameters() params.Server = uaRegSrv params.DiscoveryConfiguration = uaDiscoveryConfiguration return registrationClient.uaclient.register_server2(params) else: return registrationClient.uaclient.register_server(uaRegSrv)
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_endpoints(self): idtoken = ua.UserTokenPolicy() idtoken.PolicyId = 'anonymous' idtoken.TokenType = ua.UserTokenType.Anonymous appdesc = ua.ApplicationDescription() appdesc.ApplicationName = ua.LocalizedText(self.name) appdesc.ApplicationUri = self.server_uri appdesc.ApplicationType = ua.ApplicationType.Server appdesc.ProductUri = self.product_uri appdesc.DiscoveryUrls.append(self.endpoint.geturl()) edp = ua.EndpointDescription() edp.EndpointUrl = self.endpoint.geturl() edp.Server = appdesc edp.SecurityMode = ua.MessageSecurityMode.None_ edp.SecurityPolicyUri = 'http://opcfoundation.org/UA/SecurityPolicy#None' edp.UserIdentityTokens = [idtoken] edp.TransportProfileUri = 'http://opcfoundation.org/UA-Profile/Transport/uatcp-uasc-uabinary' edp.SecurityLevel = 0 self.iserver.add_endpoint(edp)
def create_object(parent, nodeid, bname, objecttype=None): """ create a child node object arguments are nodeid, browsename, [objecttype] or namespace index, name, [objecttype] if objectype is given (a NodeId) then the type node is instantiated inclusive its child nodes """ nodeid, qname = _parse_nodeid_qname(nodeid, bname) if objecttype is not None: objecttype = node.Node(parent.server, objecttype) dname = ua.LocalizedText(bname) nodes = instantiate(parent, objecttype, nodeid, bname=qname, dname=dname)[0] return nodes else: return node.Node( parent.server, _create_object(parent.server, parent.nodeid, nodeid, qname, ua.ObjectIds.BaseObjectType))
def _add_variable_value(self, obj): """ Returns the value for a Variable based on the objects value type. """ self.logger.debug("Setting value with type %s and value %s", obj.valuetype, obj.value) if obj.valuetype == 'ListOfExtensionObject': values = [] for ext in obj.value: extobj = self._make_ext_obj(ext) values.append(extobj) return ua.Variant(values, ua.VariantType.ExtensionObject) elif obj.valuetype == 'ListOfGuid': return ua.Variant([ uuid.UUID(guid) for guid in obj.value ], getattr(ua.VariantType, obj.valuetype[6:])) elif obj.valuetype.startswith("ListOf"): vtype = obj.valuetype[6:] if hasattr(ua.ua_binary.Primitives, vtype): return ua.Variant(obj.value, getattr(ua.VariantType, vtype)) else: return ua.Variant([getattr(ua, vtype)(v) for v in obj.value]) elif obj.valuetype == 'ExtensionObject': extobj = self._make_ext_obj(obj.value) return ua.Variant(extobj, getattr(ua.VariantType, obj.valuetype)) elif obj.valuetype == 'Guid': return ua.Variant(uuid.UUID(obj.value), getattr(ua.VariantType, obj.valuetype)) elif obj.valuetype == 'LocalizedText': ltext = ua.LocalizedText() for name, val in obj.value: if name == "Text": ltext.Text = val else: self.logger.warning("While parsing localizedText value, unkown element: %s with val: %s", name, val) return ua.Variant(ltext, ua.VariantType.LocalizedText) elif obj.valuetype == 'NodeId': return ua.Variant(ua.NodeId.from_string(obj.value)) else: return ua.Variant(obj.value, getattr(ua.VariantType, obj.valuetype))
def __init__(self): self.BooleanDataType = True self.SByteDataType = 0 self.ByteDataType = 0 self.Int16DataType = 0 self.UInt16DataType = 0 self.Int32DataType = 0 self.UInt32DataType = 0 self.Int64DataType = 0 self.UInt64DataType = 0 self.FloatDataType = 0 self.DoubleDataType = 0 self.StringDataType = '' self.DateTimeDataType = datetime.utcnow() self.GuidDataType = uuid.uuid4() self.ByteStringDataType = b'' self.XmlElementDataType = ua.XmlElement() self.NodeIdDataType = ua.NodeId() self.ExpandedNodeIdDataType = ua.ExpandedNodeId() self.QualifiedNameDataType = ua.QualifiedName() self.LocalizedTextDataType = ua.LocalizedText() self.StatusCodeDataType = ua.StatusCode() self.VariantDataType = ua.Variant()
def __init__(self, isession, etype=ua.ObjectIds.BaseEventType, source=ua.ObjectIds.Server): self.isession = isession if isinstance(etype, Node): self.node = etype elif isinstance(etype, ua.NodeId): self.node = Node(self.isession, etype) else: self.node = Node(self.isession, ua.NodeId(etype)) self.set_members_from_node(self.node) if isinstance(source, Node): self.SourceNode = source.NodeId elif isinstance(etype, ua.NodeId): self.SourceNode = source.NodeId else: self.SourceNode = ua.NodeId(source) # set some default values for attributes from BaseEventType, thus that all event must have self.EventId = uuid.uuid4().bytes self.EventType = self.node.nodeid self.LocaleTime = datetime.utcnow() self.ReceiveTime = datetime.utcnow() self.Time = datetime.utcnow() self.Message = ua.LocalizedText() self.Severity = ua.Variant(1, ua.VariantType.UInt16) self.SourceName = "Server" # og set some node attributed we also are expected to have self.BrowseName = self.node.get_browse_name() self.DisplayName = self.node.get_display_name() self.NodeId = self.node.nodeid self.NodeClass = self.node.get_node_class() self.Description = self.node.get_description()
return ua.StatusCode(0) elif manualoperation.get_value() == False: manualoperation.set_value(True) return ua.StatusCode(0) else: return ua.StatusCode(0x80000000) # Status code for Bad error #Define arguments for Irrigate Control and Irrigate Fuzzy Methods # Define mm_control as an argument to the Irrigate Control Method mm_control = ua.Argument() mm_control.Name = "mm_control" mm_control.DataType = ua.NodeId(ua.ObjectIds.Float) mm_control.ValueRank = -1 mm_control.ArrayDemisions = [] mm_control.Description = ua.LocalizedText( "Irrigation recommendation mm control") # Define mm_fuzzy as an argument to the Irrigate Fuzzy Method mm_fuzzy = ua.Argument() mm_fuzzy.Name = "mm_fuzzy" mm_fuzzy.DataType = ua.NodeId(ua.ObjectIds.Float) mm_fuzzy.ValueRank = -1 mm_fuzzy.ArrayDemisions = [] mm_fuzzy.Description = ua.LocalizedText("Irrigation recommendation mm fuzzy") # Define two folders automatic (to control irrigation by the IoT platform calculations) and manual (to control irrigation based on the farmers need) automatic = server.nodes.objects.add_folder(idx, "Automatic") manual = server.nodes.objects.add_folder(idx, "Manual") # Define Automatic irrigation methods automatic.add_method(idx, "irrigatecontrol", irrigate_control, [mm_control])
def test_xml_localizedtext_array(self): o = self.opc.nodes.objects.add_variable(2, "xmlltext_array", [ua.LocalizedText("erert"), ua.LocalizedText("erert33")]) self._test_xml_var_type(o, "localized_text_array")
def test_xml_localizedtext(self): o = self.opc.nodes.objects.add_variable(2, "xmlltext", ua.LocalizedText("mytext")) self._test_xml_var_type(o, "localized_text")
def create_standard_address_space_Part13(server): node = ua.AddNodesItem() node.RequestedNewNodeId = ua.NodeId.from_string("i=11187") node.BrowseName = ua.QualifiedName.from_string( "AggregateConfigurationType") node.NodeClass = ua.NodeClass.ObjectType node.ParentNodeId = ua.NodeId.from_string("i=58") node.ReferenceTypeId = ua.NodeId.from_string("i=45") attrs = ua.ObjectTypeAttributes() attrs.DisplayName = ua.LocalizedText("AggregateConfigurationType") attrs.IsAbstract = false node.NodeAttributes = attrs server.add_nodes([node]) refs = [] ref = ua.AddReferencesItem() ref.IsForward = true ref.ReferenceTypeId = ua.NodeId.from_string("i=46") ref.SourceNodeId = ua.NodeId.from_string("i=11187") ref.TargetNodeClass = ua.NodeClass.DataType ref.TargetNodeId = ua.NodeId.from_string("i=11188") refs.append(ref) ref = ua.AddReferencesItem() ref.IsForward = true ref.ReferenceTypeId = ua.NodeId.from_string("i=46") ref.SourceNodeId = ua.NodeId.from_string("i=11187") ref.TargetNodeClass = ua.NodeClass.DataType ref.TargetNodeId = ua.NodeId.from_string("i=11189") refs.append(ref) ref = ua.AddReferencesItem() ref.IsForward = true ref.ReferenceTypeId = ua.NodeId.from_string("i=46") ref.SourceNodeId = ua.NodeId.from_string("i=11187") ref.TargetNodeClass = ua.NodeClass.DataType ref.TargetNodeId = ua.NodeId.from_string("i=11190") refs.append(ref) ref = ua.AddReferencesItem() ref.IsForward = true ref.ReferenceTypeId = ua.NodeId.from_string("i=46") ref.SourceNodeId = ua.NodeId.from_string("i=11187") ref.TargetNodeClass = ua.NodeClass.DataType ref.TargetNodeId = ua.NodeId.from_string("i=11191") refs.append(ref) server.add_references(refs) node = ua.AddNodesItem() node.RequestedNewNodeId = ua.NodeId.from_string("i=11188") node.BrowseName = ua.QualifiedName.from_string("TreatUncertainAsBad") node.NodeClass = ua.NodeClass.Variable node.ParentNodeId = ua.NodeId.from_string("i=11187") node.ReferenceTypeId = ua.NodeId.from_string("i=46") node.TypeDefinition = ua.NodeId.from_string("i=68") attrs = ua.VariableAttributes() attrs.DisplayName = ua.LocalizedText("TreatUncertainAsBad") attrs.DataType = ua.NodeId(ua.ObjectIds.Boolean) attrs.ValueRank = -1 node.NodeAttributes = attrs server.add_nodes([node]) refs = [] ref = ua.AddReferencesItem() ref.IsForward = true ref.ReferenceTypeId = ua.NodeId.from_string("i=37") ref.SourceNodeId = ua.NodeId.from_string("i=11188") ref.TargetNodeClass = ua.NodeClass.DataType ref.TargetNodeId = ua.NodeId.from_string("i=78") refs.append(ref) server.add_references(refs) node = ua.AddNodesItem() node.RequestedNewNodeId = ua.NodeId.from_string("i=11189") node.BrowseName = ua.QualifiedName.from_string("PercentDataBad") node.NodeClass = ua.NodeClass.Variable node.ParentNodeId = ua.NodeId.from_string("i=11187") node.ReferenceTypeId = ua.NodeId.from_string("i=46") node.TypeDefinition = ua.NodeId.from_string("i=68") attrs = ua.VariableAttributes() attrs.DisplayName = ua.LocalizedText("PercentDataBad") attrs.DataType = ua.NodeId(ua.ObjectIds.Byte) attrs.ValueRank = -1 node.NodeAttributes = attrs server.add_nodes([node]) refs = [] ref = ua.AddReferencesItem() ref.IsForward = true ref.ReferenceTypeId = ua.NodeId.from_string("i=37") ref.SourceNodeId = ua.NodeId.from_string("i=11189") ref.TargetNodeClass = ua.NodeClass.DataType ref.TargetNodeId = ua.NodeId.from_string("i=78") refs.append(ref) server.add_references(refs) node = ua.AddNodesItem() node.RequestedNewNodeId = ua.NodeId.from_string("i=11190") node.BrowseName = ua.QualifiedName.from_string("PercentDataGood") node.NodeClass = ua.NodeClass.Variable node.ParentNodeId = ua.NodeId.from_string("i=11187") node.ReferenceTypeId = ua.NodeId.from_string("i=46") node.TypeDefinition = ua.NodeId.from_string("i=68") attrs = ua.VariableAttributes() attrs.DisplayName = ua.LocalizedText("PercentDataGood") attrs.DataType = ua.NodeId(ua.ObjectIds.Byte) attrs.ValueRank = -1 node.NodeAttributes = attrs server.add_nodes([node]) refs = [] ref = ua.AddReferencesItem() ref.IsForward = true ref.ReferenceTypeId = ua.NodeId.from_string("i=37") ref.SourceNodeId = ua.NodeId.from_string("i=11190") ref.TargetNodeClass = ua.NodeClass.DataType ref.TargetNodeId = ua.NodeId.from_string("i=78") refs.append(ref) server.add_references(refs) node = ua.AddNodesItem() node.RequestedNewNodeId = ua.NodeId.from_string("i=11191") node.BrowseName = ua.QualifiedName.from_string("UseSlopedExtrapolation") node.NodeClass = ua.NodeClass.Variable node.ParentNodeId = ua.NodeId.from_string("i=11187") node.ReferenceTypeId = ua.NodeId.from_string("i=46") node.TypeDefinition = ua.NodeId.from_string("i=68") attrs = ua.VariableAttributes() attrs.DisplayName = ua.LocalizedText("UseSlopedExtrapolation") attrs.DataType = ua.NodeId(ua.ObjectIds.Boolean) attrs.ValueRank = -1 node.NodeAttributes = attrs server.add_nodes([node]) refs = [] ref = ua.AddReferencesItem() ref.IsForward = true ref.ReferenceTypeId = ua.NodeId.from_string("i=37") ref.SourceNodeId = ua.NodeId.from_string("i=11191") ref.TargetNodeClass = ua.NodeClass.DataType ref.TargetNodeId = ua.NodeId.from_string("i=78") refs.append(ref) server.add_references(refs) node = ua.AddNodesItem() node.RequestedNewNodeId = ua.NodeId.from_string("i=2341") node.BrowseName = ua.QualifiedName.from_string("Interpolative") node.NodeClass = ua.NodeClass.Object node.TypeDefinition = ua.NodeId.from_string("i=2340") attrs = ua.ObjectAttributes() attrs.Description = ua.LocalizedText( "At the beginning of each interval, retrieve the calculated value from the data points on either side of the requested timestamp." ) attrs.DisplayName = ua.LocalizedText("Interpolative") attrs.EventNotifier = 0 node.NodeAttributes = attrs server.add_nodes([node]) node = ua.AddNodesItem() node.RequestedNewNodeId = ua.NodeId.from_string("i=2342") node.BrowseName = ua.QualifiedName.from_string("Average") node.NodeClass = ua.NodeClass.Object node.TypeDefinition = ua.NodeId.from_string("i=2340") attrs = ua.ObjectAttributes() attrs.Description = ua.LocalizedText( "Retrieve the average value of the data over the interval.") attrs.DisplayName = ua.LocalizedText("Average") attrs.EventNotifier = 0 node.NodeAttributes = attrs server.add_nodes([node]) node = ua.AddNodesItem() node.RequestedNewNodeId = ua.NodeId.from_string("i=2343") node.BrowseName = ua.QualifiedName.from_string("TimeAverage") node.NodeClass = ua.NodeClass.Object node.TypeDefinition = ua.NodeId.from_string("i=2340") attrs = ua.ObjectAttributes() attrs.Description = ua.LocalizedText( "Retrieve the time weighted average data over the interval using Interpolated Bounding Values." ) attrs.DisplayName = ua.LocalizedText("TimeAverage") attrs.EventNotifier = 0 node.NodeAttributes = attrs server.add_nodes([node]) node = ua.AddNodesItem() node.RequestedNewNodeId = ua.NodeId.from_string("i=11285") node.BrowseName = ua.QualifiedName.from_string("TimeAverage2") node.NodeClass = ua.NodeClass.Object node.TypeDefinition = ua.NodeId.from_string("i=2340") attrs = ua.ObjectAttributes() attrs.Description = ua.LocalizedText( "Retrieve the time weighted average data over the interval using Simple Bounding Values." ) attrs.DisplayName = ua.LocalizedText("TimeAverage2") attrs.EventNotifier = 0 node.NodeAttributes = attrs server.add_nodes([node]) node = ua.AddNodesItem() node.RequestedNewNodeId = ua.NodeId.from_string("i=2344") node.BrowseName = ua.QualifiedName.from_string("Total") node.NodeClass = ua.NodeClass.Object node.TypeDefinition = ua.NodeId.from_string("i=2340") attrs = ua.ObjectAttributes() attrs.Description = ua.LocalizedText( "Retrieve the total (time integral) of the data over the interval using Interpolated Bounding Values." ) attrs.DisplayName = ua.LocalizedText("Total") attrs.EventNotifier = 0 node.NodeAttributes = attrs server.add_nodes([node]) node = ua.AddNodesItem() node.RequestedNewNodeId = ua.NodeId.from_string("i=11304") node.BrowseName = ua.QualifiedName.from_string("Total2") node.NodeClass = ua.NodeClass.Object node.TypeDefinition = ua.NodeId.from_string("i=2340") attrs = ua.ObjectAttributes() attrs.Description = ua.LocalizedText( "Retrieve the total (time integral) of the data over the interval using Simple Bounding Values." ) attrs.DisplayName = ua.LocalizedText("Total2") attrs.EventNotifier = 0 node.NodeAttributes = attrs server.add_nodes([node]) node = ua.AddNodesItem() node.RequestedNewNodeId = ua.NodeId.from_string("i=2346") node.BrowseName = ua.QualifiedName.from_string("Minimum") node.NodeClass = ua.NodeClass.Object node.TypeDefinition = ua.NodeId.from_string("i=2340") attrs = ua.ObjectAttributes() attrs.Description = ua.LocalizedText( "Retrieve the minimum raw value in the interval with the timestamp of the start of the interval." ) attrs.DisplayName = ua.LocalizedText("Minimum") attrs.EventNotifier = 0 node.NodeAttributes = attrs server.add_nodes([node]) node = ua.AddNodesItem() node.RequestedNewNodeId = ua.NodeId.from_string("i=2347") node.BrowseName = ua.QualifiedName.from_string("Maximum") node.NodeClass = ua.NodeClass.Object node.TypeDefinition = ua.NodeId.from_string("i=2340") attrs = ua.ObjectAttributes() attrs.Description = ua.LocalizedText( "Retrieve the maximum raw value in the interval with the timestamp of the start of the interval." ) attrs.DisplayName = ua.LocalizedText("Maximum") attrs.EventNotifier = 0 node.NodeAttributes = attrs server.add_nodes([node]) node = ua.AddNodesItem() node.RequestedNewNodeId = ua.NodeId.from_string("i=2348") node.BrowseName = ua.QualifiedName.from_string("MinimumActualTime") node.NodeClass = ua.NodeClass.Object node.TypeDefinition = ua.NodeId.from_string("i=2340") attrs = ua.ObjectAttributes() attrs.Description = ua.LocalizedText( "Retrieve the minimum value in the interval and the Timestamp of the minimum value." ) attrs.DisplayName = ua.LocalizedText("MinimumActualTime") attrs.EventNotifier = 0 node.NodeAttributes = attrs server.add_nodes([node]) node = ua.AddNodesItem() node.RequestedNewNodeId = ua.NodeId.from_string("i=2349") node.BrowseName = ua.QualifiedName.from_string("MaximumActualTime") node.NodeClass = ua.NodeClass.Object node.TypeDefinition = ua.NodeId.from_string("i=2340") attrs = ua.ObjectAttributes() attrs.Description = ua.LocalizedText( "Retrieve the maximum value in the interval and the Timestamp of the maximum value." ) attrs.DisplayName = ua.LocalizedText("MaximumActualTime") attrs.EventNotifier = 0 node.NodeAttributes = attrs server.add_nodes([node]) node = ua.AddNodesItem() node.RequestedNewNodeId = ua.NodeId.from_string("i=2350") node.BrowseName = ua.QualifiedName.from_string("Range") node.NodeClass = ua.NodeClass.Object node.TypeDefinition = ua.NodeId.from_string("i=2340") attrs = ua.ObjectAttributes() attrs.Description = ua.LocalizedText( "Retrieve the difference between the minimum and maximum Value over the interval." ) attrs.DisplayName = ua.LocalizedText("Range") attrs.EventNotifier = 0 node.NodeAttributes = attrs server.add_nodes([node]) node = ua.AddNodesItem() node.RequestedNewNodeId = ua.NodeId.from_string("i=11286") node.BrowseName = ua.QualifiedName.from_string("Minimum2") node.NodeClass = ua.NodeClass.Object node.TypeDefinition = ua.NodeId.from_string("i=2340") attrs = ua.ObjectAttributes() attrs.Description = ua.LocalizedText( "Retrieve the minimum value in the interval including the Simple Bounding Values." ) attrs.DisplayName = ua.LocalizedText("Minimum2") attrs.EventNotifier = 0 node.NodeAttributes = attrs server.add_nodes([node]) node = ua.AddNodesItem() node.RequestedNewNodeId = ua.NodeId.from_string("i=11287") node.BrowseName = ua.QualifiedName.from_string("Maximum2") node.NodeClass = ua.NodeClass.Object node.TypeDefinition = ua.NodeId.from_string("i=2340") attrs = ua.ObjectAttributes() attrs.Description = ua.LocalizedText( "Retrieve the maximum value in the interval including the Simple Bounding Values." ) attrs.DisplayName = ua.LocalizedText("Maximum2") attrs.EventNotifier = 0 node.NodeAttributes = attrs server.add_nodes([node]) node = ua.AddNodesItem() node.RequestedNewNodeId = ua.NodeId.from_string("i=11305") node.BrowseName = ua.QualifiedName.from_string("MinimumActualTime2") node.NodeClass = ua.NodeClass.Object node.TypeDefinition = ua.NodeId.from_string("i=2340") attrs = ua.ObjectAttributes() attrs.Description = ua.LocalizedText( "Retrieve the minimum value with the actual timestamp including the Simple Bounding Values." ) attrs.DisplayName = ua.LocalizedText("MinimumActualTime2") attrs.EventNotifier = 0 node.NodeAttributes = attrs server.add_nodes([node]) node = ua.AddNodesItem() node.RequestedNewNodeId = ua.NodeId.from_string("i=11306") node.BrowseName = ua.QualifiedName.from_string("MaximumActualTime2") node.NodeClass = ua.NodeClass.Object node.TypeDefinition = ua.NodeId.from_string("i=2340") attrs = ua.ObjectAttributes() attrs.Description = ua.LocalizedText( "Retrieve the maximum value with the actual timestamp including the Simple Bounding Values." ) attrs.DisplayName = ua.LocalizedText("MaximumActualTime2") attrs.EventNotifier = 0 node.NodeAttributes = attrs server.add_nodes([node]) node = ua.AddNodesItem() node.RequestedNewNodeId = ua.NodeId.from_string("i=11288") node.BrowseName = ua.QualifiedName.from_string("Range2") node.NodeClass = ua.NodeClass.Object node.TypeDefinition = ua.NodeId.from_string("i=2340") attrs = ua.ObjectAttributes() attrs.Description = ua.LocalizedText( "Retrieve the difference between the Minimum2 and Maximum2 value over the interval." ) attrs.DisplayName = ua.LocalizedText("Range2") attrs.EventNotifier = 0 node.NodeAttributes = attrs server.add_nodes([node]) node = ua.AddNodesItem() node.RequestedNewNodeId = ua.NodeId.from_string("i=2351") node.BrowseName = ua.QualifiedName.from_string("AnnotationCount") node.NodeClass = ua.NodeClass.Object node.TypeDefinition = ua.NodeId.from_string("i=2340") attrs = ua.ObjectAttributes() attrs.Description = ua.LocalizedText( "Retrieve the number of Annotations in the interval.") attrs.DisplayName = ua.LocalizedText("AnnotationCount") attrs.EventNotifier = 0 node.NodeAttributes = attrs server.add_nodes([node]) node = ua.AddNodesItem() node.RequestedNewNodeId = ua.NodeId.from_string("i=2352") node.BrowseName = ua.QualifiedName.from_string("Count") node.NodeClass = ua.NodeClass.Object node.TypeDefinition = ua.NodeId.from_string("i=2340") attrs = ua.ObjectAttributes() attrs.Description = ua.LocalizedText( "Retrieve the number of raw values over the interval.") attrs.DisplayName = ua.LocalizedText("Count") attrs.EventNotifier = 0 node.NodeAttributes = attrs server.add_nodes([node]) node = ua.AddNodesItem() node.RequestedNewNodeId = ua.NodeId.from_string("i=11307") node.BrowseName = ua.QualifiedName.from_string("DurationInStateZero") node.NodeClass = ua.NodeClass.Object node.TypeDefinition = ua.NodeId.from_string("i=2340") attrs = ua.ObjectAttributes() attrs.Description = ua.LocalizedText( "Retrieve the time a Boolean or numeric was in a zero state using Simple Bounding Values." ) attrs.DisplayName = ua.LocalizedText("DurationInStateZero") attrs.EventNotifier = 0 node.NodeAttributes = attrs server.add_nodes([node]) node = ua.AddNodesItem() node.RequestedNewNodeId = ua.NodeId.from_string("i=11308") node.BrowseName = ua.QualifiedName.from_string("DurationInStateNonZero") node.NodeClass = ua.NodeClass.Object node.TypeDefinition = ua.NodeId.from_string("i=2340") attrs = ua.ObjectAttributes() attrs.Description = ua.LocalizedText( "Retrieve the time a Boolean or numeric was in a non-zero state using Simple Bounding Values." ) attrs.DisplayName = ua.LocalizedText("DurationInStateNonZero") attrs.EventNotifier = 0 node.NodeAttributes = attrs server.add_nodes([node]) node = ua.AddNodesItem() node.RequestedNewNodeId = ua.NodeId.from_string("i=2355") node.BrowseName = ua.QualifiedName.from_string("NumberOfTransitions") node.NodeClass = ua.NodeClass.Object node.TypeDefinition = ua.NodeId.from_string("i=2340") attrs = ua.ObjectAttributes() attrs.Description = ua.LocalizedText( "Retrieve the number of changes between zero and non-zero that a Boolean or Numeric value experienced in the interval." ) attrs.DisplayName = ua.LocalizedText("NumberOfTransitions") attrs.EventNotifier = 0 node.NodeAttributes = attrs server.add_nodes([node]) node = ua.AddNodesItem() node.RequestedNewNodeId = ua.NodeId.from_string("i=2357") node.BrowseName = ua.QualifiedName.from_string("Start") node.NodeClass = ua.NodeClass.Object node.TypeDefinition = ua.NodeId.from_string("i=2340") attrs = ua.ObjectAttributes() attrs.Description = ua.LocalizedText( "Retrieve the value at the beginning of the interval using Interpolated Bounding Values." ) attrs.DisplayName = ua.LocalizedText("Start") attrs.EventNotifier = 0 node.NodeAttributes = attrs server.add_nodes([node]) node = ua.AddNodesItem() node.RequestedNewNodeId = ua.NodeId.from_string("i=2358") node.BrowseName = ua.QualifiedName.from_string("End") node.NodeClass = ua.NodeClass.Object node.TypeDefinition = ua.NodeId.from_string("i=2340") attrs = ua.ObjectAttributes() attrs.Description = ua.LocalizedText( "Retrieve the value at the end of the interval using Interpolated Bounding Values." ) attrs.DisplayName = ua.LocalizedText("End") attrs.EventNotifier = 0 node.NodeAttributes = attrs server.add_nodes([node]) node = ua.AddNodesItem() node.RequestedNewNodeId = ua.NodeId.from_string("i=2359") node.BrowseName = ua.QualifiedName.from_string("Delta") node.NodeClass = ua.NodeClass.Object node.TypeDefinition = ua.NodeId.from_string("i=2340") attrs = ua.ObjectAttributes() attrs.Description = ua.LocalizedText( "Retrieve the difference between the Start and End value in the interval." ) attrs.DisplayName = ua.LocalizedText("Delta") attrs.EventNotifier = 0 node.NodeAttributes = attrs server.add_nodes([node]) node = ua.AddNodesItem() node.RequestedNewNodeId = ua.NodeId.from_string("i=11505") node.BrowseName = ua.QualifiedName.from_string("StartBound") node.NodeClass = ua.NodeClass.Object node.TypeDefinition = ua.NodeId.from_string("i=2340") attrs = ua.ObjectAttributes() attrs.Description = ua.LocalizedText( "Retrieve the value at the beginning of the interval using Simple Bounding Values." ) attrs.DisplayName = ua.LocalizedText("StartBound") attrs.EventNotifier = 0 node.NodeAttributes = attrs server.add_nodes([node]) node = ua.AddNodesItem() node.RequestedNewNodeId = ua.NodeId.from_string("i=11506") node.BrowseName = ua.QualifiedName.from_string("EndBound") node.NodeClass = ua.NodeClass.Object node.TypeDefinition = ua.NodeId.from_string("i=2340") attrs = ua.ObjectAttributes() attrs.Description = ua.LocalizedText( "Retrieve the value at the end of the interval using Simple Bounding Values." ) attrs.DisplayName = ua.LocalizedText("EndBound") attrs.EventNotifier = 0 node.NodeAttributes = attrs server.add_nodes([node]) node = ua.AddNodesItem() node.RequestedNewNodeId = ua.NodeId.from_string("i=11507") node.BrowseName = ua.QualifiedName.from_string("DeltaBounds") node.NodeClass = ua.NodeClass.Object node.TypeDefinition = ua.NodeId.from_string("i=2340") attrs = ua.ObjectAttributes() attrs.Description = ua.LocalizedText( "Retrieve the difference between the StartBound and EndBound value in the interval." ) attrs.DisplayName = ua.LocalizedText("DeltaBounds") attrs.EventNotifier = 0 node.NodeAttributes = attrs server.add_nodes([node]) node = ua.AddNodesItem() node.RequestedNewNodeId = ua.NodeId.from_string("i=2360") node.BrowseName = ua.QualifiedName.from_string("DurationGood") node.NodeClass = ua.NodeClass.Object node.TypeDefinition = ua.NodeId.from_string("i=2340") attrs = ua.ObjectAttributes() attrs.Description = ua.LocalizedText( "Retrieve the total duration of time in the interval during which the data is good." ) attrs.DisplayName = ua.LocalizedText("DurationGood") attrs.EventNotifier = 0 node.NodeAttributes = attrs server.add_nodes([node]) node = ua.AddNodesItem() node.RequestedNewNodeId = ua.NodeId.from_string("i=2361") node.BrowseName = ua.QualifiedName.from_string("DurationBad") node.NodeClass = ua.NodeClass.Object node.TypeDefinition = ua.NodeId.from_string("i=2340") attrs = ua.ObjectAttributes() attrs.Description = ua.LocalizedText( "Retrieve the total duration of time in the interval during which the data is bad." ) attrs.DisplayName = ua.LocalizedText("DurationBad") attrs.EventNotifier = 0 node.NodeAttributes = attrs server.add_nodes([node]) node = ua.AddNodesItem() node.RequestedNewNodeId = ua.NodeId.from_string("i=2362") node.BrowseName = ua.QualifiedName.from_string("PercentGood") node.NodeClass = ua.NodeClass.Object node.TypeDefinition = ua.NodeId.from_string("i=2340") attrs = ua.ObjectAttributes() attrs.Description = ua.LocalizedText( "Retrieve the percent of data (0 to 100) in the interval which has a good StatusCode." ) attrs.DisplayName = ua.LocalizedText("PercentGood") attrs.EventNotifier = 0 node.NodeAttributes = attrs server.add_nodes([node]) node = ua.AddNodesItem() node.RequestedNewNodeId = ua.NodeId.from_string("i=2363") node.BrowseName = ua.QualifiedName.from_string("PercentBad") node.NodeClass = ua.NodeClass.Object node.TypeDefinition = ua.NodeId.from_string("i=2340") attrs = ua.ObjectAttributes() attrs.Description = ua.LocalizedText( "Retrieve the percent of data (0 to 100) in the interval which has a bad StatusCode." ) attrs.DisplayName = ua.LocalizedText("PercentBad") attrs.EventNotifier = 0 node.NodeAttributes = attrs server.add_nodes([node]) node = ua.AddNodesItem() node.RequestedNewNodeId = ua.NodeId.from_string("i=2364") node.BrowseName = ua.QualifiedName.from_string("WorstQuality") node.NodeClass = ua.NodeClass.Object node.TypeDefinition = ua.NodeId.from_string("i=2340") attrs = ua.ObjectAttributes() attrs.Description = ua.LocalizedText( "Retrieve the worst StatusCode of data in the interval.") attrs.DisplayName = ua.LocalizedText("WorstQuality") attrs.EventNotifier = 0 node.NodeAttributes = attrs server.add_nodes([node]) node = ua.AddNodesItem() node.RequestedNewNodeId = ua.NodeId.from_string("i=11292") node.BrowseName = ua.QualifiedName.from_string("WorstQuality2") node.NodeClass = ua.NodeClass.Object node.TypeDefinition = ua.NodeId.from_string("i=2340") attrs = ua.ObjectAttributes() attrs.Description = ua.LocalizedText( "Retrieve the worst StatusCode of data in the interval including the Simple Bounding Values." ) attrs.DisplayName = ua.LocalizedText("WorstQuality2") attrs.EventNotifier = 0 node.NodeAttributes = attrs server.add_nodes([node]) node = ua.AddNodesItem() node.RequestedNewNodeId = ua.NodeId.from_string("i=11426") node.BrowseName = ua.QualifiedName.from_string("StandardDeviationSample") node.NodeClass = ua.NodeClass.Object node.TypeDefinition = ua.NodeId.from_string("i=2340") attrs = ua.ObjectAttributes() attrs.Description = ua.LocalizedText( "Retrieve the standard deviation for the interval for a sample of the population (n-1)." ) attrs.DisplayName = ua.LocalizedText("StandardDeviationSample") attrs.EventNotifier = 0 node.NodeAttributes = attrs server.add_nodes([node]) node = ua.AddNodesItem() node.RequestedNewNodeId = ua.NodeId.from_string("i=11427") node.BrowseName = ua.QualifiedName.from_string( "StandardDeviationPopulation") node.NodeClass = ua.NodeClass.Object node.TypeDefinition = ua.NodeId.from_string("i=2340") attrs = ua.ObjectAttributes() attrs.Description = ua.LocalizedText( "Retrieve the standard deviation for the interval for a complete population (n) which includes Simple Bounding Values." ) attrs.DisplayName = ua.LocalizedText("StandardDeviationPopulation") attrs.EventNotifier = 0 node.NodeAttributes = attrs server.add_nodes([node]) node = ua.AddNodesItem() node.RequestedNewNodeId = ua.NodeId.from_string("i=11428") node.BrowseName = ua.QualifiedName.from_string("VarianceSample") node.NodeClass = ua.NodeClass.Object node.TypeDefinition = ua.NodeId.from_string("i=2340") attrs = ua.ObjectAttributes() attrs.Description = ua.LocalizedText( "Retrieve the variance for the interval as calculated by the StandardDeviationSample." ) attrs.DisplayName = ua.LocalizedText("VarianceSample") attrs.EventNotifier = 0 node.NodeAttributes = attrs server.add_nodes([node]) node = ua.AddNodesItem() node.RequestedNewNodeId = ua.NodeId.from_string("i=11429") node.BrowseName = ua.QualifiedName.from_string("VariancePopulation") node.NodeClass = ua.NodeClass.Object node.TypeDefinition = ua.NodeId.from_string("i=2340") attrs = ua.ObjectAttributes() attrs.Description = ua.LocalizedText( "Retrieve the variance for the interval as calculated by the StandardDeviationPopulation which includes Simple Bounding Values." ) attrs.DisplayName = ua.LocalizedText("VariancePopulation") attrs.EventNotifier = 0 node.NodeAttributes = attrs server.add_nodes([node])
def enum_to_stringlist(a_enum): items = [] for value in a_enum: items.append(ua.LocalizedText(value.name)) return items
def _create_data_type(self, type_name, nodeid=None, init=True): #name = _to_camel_case(type_name) name = type_name if nodeid is None: # create data type node dt_node = ua.AddNodesItem() dt_node.RequestedNewNodeId = ua.NodeId(0, self._idx) dt_node.BrowseName = ua.QualifiedName(name, self._idx) dt_node.NodeClass = ua.NodeClass.DataType dt_node.ParentNodeId = ua.NodeId(ua.ObjectIds.Structure, 0) dt_node.ReferenceTypeId = ua.NodeId(ua.ObjectIds.HasSubtype, 0) dt_attributes = ua.DataTypeAttributes() dt_attributes.DisplayName = ua.LocalizedText(type_name) dt_node.NodeAttributes = dt_attributes res = self._session_server.add_nodes([dt_node]) data_type_node_id = res[0].AddedNodeId else: data_type_node_id = nodeid added = [data_type_node_id] if init: # create description node desc_node = ua.AddNodesItem() desc_node.RequestedNewNodeId = ua.NodeId(0, self._idx) desc_node.BrowseName = ua.QualifiedName(name, self._idx) desc_node.NodeClass = ua.NodeClass.Variable desc_node.ParentNodeId = self.dict_id desc_node.ReferenceTypeId = ua.NodeId(ua.ObjectIds.HasComponent, 0) desc_node.TypeDefinition = ua.NodeId( ua.ObjectIds.DataTypeDescriptionType, 0) desc_attributes = ua.VariableAttributes() desc_attributes.DisplayName = ua.LocalizedText(type_name) desc_attributes.DataType = ua.NodeId(ua.ObjectIds.String) desc_attributes.Value = ua.Variant(name, ua.VariantType.String) desc_attributes.ValueRank = -1 desc_node.NodeAttributes = desc_attributes res = self._session_server.add_nodes([desc_node]) description_node_id = res[0].AddedNodeId added.append(description_node_id) # create object node which the loaded python class should link to obj_node = ua.AddNodesItem() obj_node.RequestedNewNodeId = ua.NodeId(0, self._idx) obj_node.BrowseName = ua.QualifiedName('Default Binary', 0) obj_node.NodeClass = ua.NodeClass.Object obj_node.ParentNodeId = data_type_node_id obj_node.ReferenceTypeId = ua.NodeId(ua.ObjectIds.HasEncoding, 0) obj_node.TypeDefinition = ua.NodeId( ua.ObjectIds.DataTypeEncodingType, 0) obj_attributes = ua.ObjectAttributes() obj_attributes.DisplayName = ua.LocalizedText('Default Binary') obj_attributes.EventNotifier = 0 obj_node.NodeAttributes = obj_attributes res = self._session_server.add_nodes([obj_node]) bind_obj_node_id = res[0].AddedNodeId added.append(bind_obj_node_id) self._link_nodes(bind_obj_node_id, data_type_node_id, description_node_id) self._type_dictionary.append_struct(type_name) return StructNode(self, data_type_node_id, type_name, added)
def init_methods(self): # method: ADD_OBJECTS_DIR inarg1 = ua.Argument() inarg1.Name = "objects folder" inarg1.DataType = ua.NodeId(ua.ObjectIds.String) # String inarg1.ValueRank = -1 inarg1.ArrayDimensions = [] inarg1.Description = ua.LocalizedText("Name the new objects folder") method_node = self.obj.add_method(self.idx, "ADD_NEW_OBJECTS_FOLDER", self.add_objects_subfolder, [inarg1]) # method: ADD_OPC_TAG inarg1 = ua.Argument() inarg1.Name = "opctag" inarg1.DataType = ua.NodeId(ua.ObjectIds.String) # String inarg1.ValueRank = -1 inarg1.ArrayDimensions = [] inarg1.Description = ua.LocalizedText("Name new OPC variable") inarg2 = ua.Argument() inarg2.Name = "variant_type" inarg2.DataType = ua.NodeId(ua.ObjectIds.String) # String inarg2.ValueRank = -1 inarg2.ArrayDimensions = [] inarg2.Description = ua.LocalizedText("Type of variable") inarg3 = ua.Argument() inarg3.Name = "parent_node" inarg3.DataType = ua.NodeId(ua.ObjectIds.String) # String inarg3.ValueRank = -1 inarg3.ArrayDimensions = [] inarg3.Description = ua.LocalizedText( "Type in the name of the parent node the new variable should assigned to" ) method_node = self.obj.add_method(self.idx, "ADD_OPC_TAG", self.register_opc_tag, [inarg1, inarg2, inarg3]) # method: SET_PV_LIMIT inarg1 = ua.Argument() inarg1.Name = "active_power_setpoint" inarg1.DataType = ua.NodeId(ua.ObjectIds.Int32) # Integer inarg1.ValueRank = -1 inarg1.ArrayDimensions = [] inarg1.Description = ua.LocalizedText( "Type in active power setpoint in percent [0 ... 100]") inarg2 = ua.Argument() inarg2.Name = "parent_node" inarg2.DataType = ua.NodeId(ua.ObjectIds.String) # String inarg2.ValueRank = -1 inarg2.ArrayDimensions = [] inarg2.Description = ua.LocalizedText( "Type in the name of the parent node") method_node = self.obj.add_method(self.idx, "SET_PV_LIMIT", self.set_pv_active_power_setpoint, [inarg1, inarg2]) # method: RUN_ONLINE_GRID_PROTECTION inarg1 = ua.Argument() inarg1.Name = "On/Off" inarg1.DataType = ua.NodeId(ua.ObjectIds.Int32) # Integer inarg1.ValueRank = -1 inarg1.ArrayDimensions = [] inarg1.Description = ua.LocalizedText( "Type in 1 to RUN or 0 to STOP ONLINE_GRID_PROTECTION") inarg2 = ua.Argument() inarg2.Name = "parent_node" inarg2.DataType = ua.NodeId(ua.ObjectIds.String) # String inarg2.ValueRank = -1 inarg2.ArrayDimensions = [] inarg2.Description = ua.LocalizedText( "Type in the name of the parent node") method_node = self.obj.add_method(self.idx, "RUN_ONLINE_GRID_PROTECTION", self.run_online_grid_protection, [inarg1, inarg2])
myObj = objects.add_object(idx, "RaspberryPi") editableVar = myObj.add_variable(idx, "ModifyMe", 1, ua.VariantType.Int64) sinFunc = myObj.add_variable(idx, "SinExample", 0, ua.VariantType.Float) core0temp = myObj.add_variable(idx, "Core0Temperature", 0) sensorTemp = myObj.add_variable(idx, "SensorTemperature", 0) sensorHum = myObj.add_variable(idx, "SensorHumidity", 0) myObj.add_method(idx, "BlinkLed", BlinkLed, [ua.VariantType.Int64, ua.VariantType.Int64], []) editableVar.set_writable() temp = ua.Argument() temp.Name = "Temperature" temp.DataType = ua.NodeId(ua.ObjectIds.Int64) temp.ValueRank = -1 temp.ArrayDimensions = [] temp.Description = ua.LocalizedText("Output of sensor") hum = ua.Argument() hum.Name = "Humidity" hum.DataType = ua.NodeId(ua.ObjectIds.Int64) hum.ValueRank = -1 hum.ArrayDimensions = [] hum.Description = ua.LocalizedText("Output of sensor") myObj.add_method(idx, "ReadHumidityTemperature", ReadHumidityTemperature, [], [temp, hum]) # Start Server server.start() sinUp = SinUpdater(sinFunc)
def test_data_type_dict_create_data_type(self): type_name = 'CustomizedStruct2' created_type = self.dict_builder.create_data_type(type_name) self.assertTrue(isinstance(created_type, StructNode)) # Test data type node type_node = self.srv.get_node(created_type.data_type) self.assertEqual(type_node.get_browse_name(), ua.QualifiedName(type_name, self.idx)) self.assertEqual(type_node.get_node_class(), ua.NodeClass.DataType) self.assertEqual(type_node.get_parent().nodeid, ua.NodeId(ua.ObjectIds.Structure, 0)) self.assertEqual( ua.NodeId(ua.ObjectIds.HasSubtype, 0), type_node.get_references( refs=ua.ObjectIds.HasSubtype)[0].ReferenceTypeId) self.assertEqual(type_node.get_display_name(), ua.LocalizedText(type_name)) # Test description node desc_node = self.srv.get_node(self.dict_builder.dict_id).get_child( "2:{}".format(type_name)) self.assertEqual(desc_node.get_browse_name(), ua.QualifiedName(type_name, self.idx)) self.assertEqual(desc_node.get_node_class(), ua.NodeClass.Variable) self.assertEqual(desc_node.get_parent().nodeid, self.dict_builder.dict_id) self.assertEqual( ua.NodeId(ua.ObjectIds.HasComponent, 0), desc_node.get_references( refs=ua.ObjectIds.HasComponent)[0].ReferenceTypeId) self.assertEqual(desc_node.get_type_definition(), ua.NodeId(ua.ObjectIds.DataTypeDescriptionType, 0)) self.assertEqual(desc_node.get_display_name(), ua.LocalizedText(type_name)) self.assertEqual(desc_node.get_data_type(), ua.NodeId(ua.ObjectIds.String)) self.assertEqual(desc_node.get_value(), type_name) self.assertEqual(desc_node.get_value_rank(), -1) # Test object node obj_node = type_node.get_children(refs=ua.ObjectIds.HasEncoding)[0] self.assertEqual(obj_node.get_browse_name(), ua.QualifiedName('Default Binary', 0)) self.assertEqual(obj_node.get_node_class(), ua.NodeClass.Object) self.assertEqual( obj_node.get_references(refs=ua.ObjectIds.HasEncoding)[0].NodeId, type_node.nodeid) self.assertEqual( ua.NodeId(ua.ObjectIds.HasEncoding, 0), obj_node.get_references( refs=ua.ObjectIds.HasEncoding)[0].ReferenceTypeId) self.assertEqual(obj_node.get_type_definition(), ua.NodeId(ua.ObjectIds.DataTypeEncodingType, 0)) self.assertEqual(obj_node.get_display_name(), ua.LocalizedText('Default Binary')) self.assertEqual(len(obj_node.get_event_notifier()), 0) # Test links, three were tested above struct_node = self.srv.get_node(ua.NodeId(ua.ObjectIds.Structure, 0)) struct_children = struct_node.get_children( refs=ua.ObjectIds.HasSubtype) self.assertTrue(type_node in struct_children) dict_node = self.srv.get_node(self.dict_builder.dict_id) dict_children = dict_node.get_children(refs=ua.ObjectIds.HasComponent) self.assertTrue(desc_node in dict_children) self.assertTrue( obj_node in type_node.get_children(ua.ObjectIds.HasEncoding)) self.assertTrue(desc_node in obj_node.get_children( refs=ua.ObjectIds.HasDescription)) self.assertEqual( obj_node.nodeid, desc_node.get_references( refs=ua.ObjectIds.HasDescription, direction=ua.BrowseDirection.Inverse)[0].NodeId)
myobj = objects.add_object(idx, "MyObject") myvar = myobj.add_variable(idx, "MyVariable", 6.7) myvar.set_writable() # Set MyVariable to be writable by clients myarrayvar = myobj.add_variable(idx, "myarrayvar", [6.7, 7.9]) myarrayvar = myobj.add_variable(idx, "myStronglytTypedVariable", ua.Variant([], ua.VariantType.UInt32)) myprop = myobj.add_property(idx, "myproperty", "I am a property") mymethod = myobj.add_method(idx, "mymethod", func, [ua.VariantType.Int64], [ua.VariantType.Boolean]) inargx = ua.Argument() inargx.Name = "x" inargx.DataType = ua.NodeId(ObjectIds.Int64) inargx.ValueRank = -1 inargx.ArrayDimensions = [] inargx.Description = ua.LocalizedText("First number x") inargy = ua.Argument() inargy.Name = "y" inargy.DataType = ua.NodeId(ObjectIds.Int64) inargy.ValueRank = -1 inargy.ArrayDimensions = [] inargy.Description = ua.LocalizedText("Second number y") outarg = ua.Argument() outarg.Name = "Result" outarg.DataType = ua.NodeId(ObjectIds.Int64) outarg.ValueRank = -1 outarg.ArrayDimensions = [] outarg.Description = ua.LocalizedText("Multiplication result") multiply_node = myobj.add_method(idx, "multiply", multiply, [inargx, inargy], [outarg])
def _add_node(self, item, user): result = ua.AddNodesResult() if item.RequestedNewNodeId in self._aspace: self.logger.warning("AddNodesItem: node already exists") result.StatusCode = ua.StatusCode(ua.StatusCodes.BadNodeIdExists) return result nodedata = NodeData(item.RequestedNewNodeId) # add common attrs nodedata.attributes[ua.AttributeIds.NodeId] = AttributeValue( ua.DataValue( ua.Variant(item.RequestedNewNodeId, ua.VariantType.NodeId))) nodedata.attributes[ua.AttributeIds.BrowseName] = AttributeValue( ua.DataValue( ua.Variant(item.BrowseName, ua.VariantType.QualifiedName))) nodedata.attributes[ua.AttributeIds.NodeClass] = AttributeValue( ua.DataValue(ua.Variant(item.NodeClass, ua.VariantType.Int32))) # add requested attrs self._add_nodeattributes(item.NodeAttributes, nodedata) # add parent if item.ParentNodeId == ua.NodeId(): #self.logger.warning("add_node: creating node %s without parent", item.RequestedNewNodeId) pass elif item.ParentNodeId not in self._aspace: #self.logger.warning("add_node: while adding node %s, requested parent node %s does not exists", item.RequestedNewNodeId, item.ParentNodeId) result.StatusCode = ua.StatusCode( ua.StatusCodes.BadParentNodeIdInvalid) return result else: if not user == User.Admin: result.StatusCode = ua.StatusCode( ua.StatusCodes.BadUserAccessDenied) return result desc = ua.ReferenceDescription() desc.ReferenceTypeId = item.ReferenceTypeId desc.NodeId = item.RequestedNewNodeId desc.NodeClass = item.NodeClass desc.BrowseName = item.BrowseName desc.DisplayName = ua.LocalizedText(item.BrowseName.Name) desc.TypeDefinition = item.TypeDefinition desc.IsForward = True self._aspace[item.ParentNodeId].references.append(desc) # now add our node to db self._aspace[item.RequestedNewNodeId] = nodedata # add type definition if item.TypeDefinition != ua.NodeId(): addref = ua.AddReferencesItem() addref.SourceNodeId = item.RequestedNewNodeId addref.IsForward = True addref.ReferenceTypeId = ua.NodeId(ua.ObjectIds.HasTypeDefinition) addref.TargetNodeId = item.TypeDefinition addref.TargetNodeClass = ua.NodeClass.DataType self._add_reference(addref, user) result.StatusCode = ua.StatusCode() result.AddedNodeId = item.RequestedNewNodeId return result
def _add_node(self, item, user): result = ua.AddNodesResult() # If Identifier of requested NodeId is null we generate a new NodeId using # the namespace of the nodeid, this is an extention of the spec to allow # to requests the server to generate a new nodeid in a specified namespace if item.RequestedNewNodeId.has_null_identifier(): self.logger.debug( "RequestedNewNodeId has null identifier, generating Identifier" ) nodedata = NodeData( self._aspace.generate_nodeid( item.RequestedNewNodeId.NamespaceIndex)) else: nodedata = NodeData(item.RequestedNewNodeId) if nodedata.nodeid in self._aspace: self.logger.warning("AddNodesItem: node already exists") result.StatusCode = ua.StatusCode(ua.StatusCodes.BadNodeIdExists) return result if item.ParentNodeId.is_null(): # self.logger.warning("add_node: creating node %s without parent", nodedata.nodeid) # We should return Error here, but the standard namespace seems to define many nodes # without parents, so ignore... pass elif item.ParentNodeId not in self._aspace: self.logger.warning( "add_node: while adding node %s, requested parent node %s does not exists", nodedata.nodeid, item.ParentNodeId) result.StatusCode = ua.StatusCode( ua.StatusCodes.BadParentNodeIdInvalid) return result if not user == User.Admin: result.StatusCode = ua.StatusCode( ua.StatusCodes.BadUserAccessDenied) return result # add common attrs nodedata.attributes[ua.AttributeIds.NodeId] = AttributeValue( ua.DataValue(ua.Variant(nodedata.nodeid, ua.VariantType.NodeId))) nodedata.attributes[ua.AttributeIds.BrowseName] = AttributeValue( ua.DataValue( ua.Variant(item.BrowseName, ua.VariantType.QualifiedName))) nodedata.attributes[ua.AttributeIds.NodeClass] = AttributeValue( ua.DataValue(ua.Variant(item.NodeClass, ua.VariantType.Int32))) # add requested attrs self._add_nodeattributes(item.NodeAttributes, nodedata) if not item.ParentNodeId.is_null(): desc = ua.ReferenceDescription() desc.ReferenceTypeId = item.ReferenceTypeId desc.NodeId = nodedata.nodeid desc.NodeClass = item.NodeClass desc.BrowseName = item.BrowseName desc.DisplayName = ua.LocalizedText(item.BrowseName.Name) desc.TypeDefinition = item.TypeDefinition desc.IsForward = True self._aspace[item.ParentNodeId].references.append(desc) # now add our node to db self._aspace[nodedata.nodeid] = nodedata # add type definition if item.TypeDefinition != ua.NodeId(): addref = ua.AddReferencesItem() addref.SourceNodeId = nodedata.nodeid addref.IsForward = True addref.ReferenceTypeId = ua.NodeId(ua.ObjectIds.HasTypeDefinition) addref.TargetNodeId = item.TypeDefinition addref.TargetNodeClass = ua.NodeClass.DataType self._add_reference(addref, user) result.StatusCode = ua.StatusCode() result.AddedNodeId = nodedata.nodeid return result
test_value.Timestamp = datetime.datetime.now() test_value.User = "******" test_value.EngineeringUnit = "lol" test_var.set_value(test_value) objects = ua_server.server.get_objects_node() mymachine = objects.add_object(2, "MyCoolMachine") myservice = mymachine.add_object(2, "MESServices") mymethods = myservice.add_object(2, "Methods") batchidarg = ua.Argument() batchidarg.Name = "BatchId" batchidarg.DataType = parameter_struct.data_type batchidarg.ValueRank = -1 batchidarg.ArrayDimensions = [] batchidarg.Description = ua.LocalizedText( "The BatchID of the batch associated with this cleaning run") wateramountarg = ua.Argument() wateramountarg.Name = "WaterAmount" wateramountarg.DataType = parameter_struct.data_type wateramountarg.ValueRank = -1 wateramountarg.ArrayDimensions = [] wateramountarg.Description = ua.LocalizedText( "The amount of water used for this cleaning run") start_cleaning_method = mymethods.add_method( 2, "StartCleaning", start_cleaning, [batchidarg, wateramountarg], [ua.VariantType.Boolean]) start_production_param_descs = start_cleaning_method.add_folder( 2, "ParameterDescriptions") batchid_desc = start_production_param_descs.add_object(2, "BatchId") batchid_desc.add_property(2, "Optional", False) batchid_desc.add_property(2, "StandardEUInformation", None)
def test_string_to_variant_localized_text(self): string = "_This is my string" # string = "_This is my nøåæ"FIXME: does not work with python2 ?!?! obj = ua.LocalizedText(string) self.assertEqual(string_to_val(string, ua.VariantType.LocalizedText), obj) self.assertEqual(val_to_string(obj), string)
def test_root(self): root = self.opc.get_root_node() self.assertEqual(ua.QualifiedName('Root', 0), root.get_browse_name()) self.assertEqual(ua.LocalizedText('Root'), root.get_display_name()) nid = ua.NodeId(84, 0) self.assertEqual(nid, root.nodeid)
server = Server() server.set_endpoint("opc.tcp://0.0.0.0:4840/freeopcua/server/") server.set_security_policy([ua.SecurityPolicyType.NoSecurity]) obj = server.get_objects_node() idx = server.register_namespace("http://examples.freeopcua.github.io") server.load_type_definitions() inarg_extobj = ua.Argument() inarg_extobj.Name = "In" inarg_extobj.DataType = ua.NodeId(12079, 0) inarg_extobj.ValueRank = -1 inarg_extobj.ArrayDimensions = [] inarg_extobj.Description = ua.LocalizedText("Wanted AxisInformation") outarg_extobj = ua.Argument() outarg_extobj.Name = "Out" outarg_extobj.DataType = ua.NodeId(12079, 0) outarg_extobj.ValueRank = -1 outarg_extobj.ArrayDimensions = [] outarg_extobj.Description = ua.LocalizedText("Actual AxisInformation") status = ua.Argument() status.Name = "Status" status.DataType = ua.NodeId(12, 0) status.ValueRank = -1 status.ArrayDimensions = [] status.Description = ua.LocalizedText("MSG")
myevgen = server.get_event_generator(etype, myobj) # Creating a custom event: Approach 2 custom_etype = server.nodes.base_event_type.add_object_type(2, 'MySecondEvent') custom_etype.add_property(2, 'MyIntProperty', ua.Variant(0, ua.VariantType.Int32)) custom_etype.add_property(2, 'MyBoolProperty', ua.Variant(True, ua.VariantType.Boolean)) mysecondevgen = server.get_event_generator(custom_etype, myobj) # starting! server.start() try: # time.sleep is here just because we want to see events in UaExpert import time count = 0 while True: time.sleep(5) myevgen.event.Message = ua.LocalizedText("MyFirstEvent %d" % count) myevgen.event.Severity = count myevgen.event.MyNumericProperty = count myevgen.event.MyStringProperty = "Property " + str(count) myevgen.trigger() mysecondevgen.trigger(message="MySecondEvent %d" % count) count += 1 embed() finally: # close connection, remove subcsriptions, etc server.stop()
def main(): logging.basicConfig(level=logging.WARN) logger = logging.getLogger("opcua.server.internal_subscription") logger.setLevel(logging.DEBUG) # setup our server server = Server() server.set_endpoint( Commons.OPC_ENDPOINT ) # setup our own namespace, not really necessary but should as spec server_namespace = Commons.OPC_NAMESPACE address_space = server.register_namespace( server_namespace ) # get Objects node, this is where we should put our custom stuff objects_node = server.get_objects_node() # populating our address space ChargeControllerObject = objects_node.add_object(address_space, Commons.MY_OBJECT_NAME) RelayBoxObject = objects_node.add_object(address_space, "RelayBox") panelVoltage = ChargeControllerObject.add_variable( address_space, "panelVoltage", 0.0 ) panelCurrent = ChargeControllerObject.add_variable( address_space, "panelCurrent", 0.0 ) batteryVoltage = ChargeControllerObject.add_variable( address_space, "batteryVoltage", 0.0 ) batteryCurrent = ChargeControllerObject.add_variable( address_space, "batteryCurrent", 0.0 ) loadVoltage = ChargeControllerObject.add_variable( address_space, "loadVoltage", 0.0 ) loadCurrent = ChargeControllerObject.add_variable( address_space, "loadCurrent", 0.0 ) inPower = ChargeControllerObject.add_variable( address_space, "inPower", 0.0 ) outPower = ChargeControllerObject.add_variable( address_space, "outPower", 0.0 ) batteryStatus = ChargeControllerObject.add_variable( address_space, "batteryStatus", "" ) batteryCapacity = ChargeControllerObject.add_variable( address_space, "batteryCapacity", 0.0 ) batteryTemperature = ChargeControllerObject.add_variable( address_space, "batteryTemperature", 0.0 ) ## To make them writable by the clients """ panelVoltage.set_writable() panelCurrent.set_writable() batteryCurrent.set_writable() batteryVoltage.set_writable() loadVoltage.set_writable() loadCurrent.set_writable() inPower.set_writable() outPower.set_writable() batteryStatus.set_writable() batteryCapacity.set_writable() batteryTemperature.set_writable() """ ### Creating a custom EVENT eventType = server.create_custom_event_type( address_space, Commons.MY_FIRST_EVENT_NAME, ua.ObjectIds.BaseEventType, [ ('batteryVoltage', ua.VariantType.Float), ('outputsEnabled', ua.VariantType.Boolean), ] ) myEventGenerator = server.get_event_generator(eventType, ChargeControllerObject) ##creating an array plug_A_current_array = ChargeControllerObject.add_variable(address_space, "plug_A_current_array", [6.7, 7.9]) # the variable could be hard typed plug_B_current_array = ChargeControllerObject.add_variable(address_space, "plug_B_current_array", ua.Variant([], ua.VariantType.Float)) ## creating a property prop_charge_controller_producer = ChargeControllerObject.add_property(address_space, "charge_controller_producer", "Epever") prop_charge_controller_model = ChargeControllerObject.add_property(address_space, "charge_controller_model", "Tracer 2210A MPPT") prop_panel = ChargeControllerObject.add_property(address_space, "panel_info", "12V 100 W") prop_battery = ChargeControllerObject.add_property(address_space, "battery_info", "Bosch 12V") ## Two different methods definitions # First plugs_control_node = RelayBoxObject.add_method(address_space, "set_plug_state", set_plug_state, [ua.VariantType.Boolean], [ua.VariantType.Boolean]) # Second inarg = ua.Argument() inarg.Name = "inverter_state" inarg.DataType = ua.NodeId(ua.ObjectIds.Boolean) inarg.ValueRank = -1 inarg.ArrayDimensions = [] inarg.Description = ua.LocalizedText("Boolean inverter state") outarg = ua.Argument() outarg.Name = "Result" outarg.DataType = ua.NodeId(ua.ObjectIds.Boolean) outarg.ValueRank = -1 outarg.ArrayDimensions = [] outarg.Description = ua.LocalizedText("Final Inverter State") inverter_control_node = RelayBoxObject.add_method(address_space, "set_inverter_state", set_inverter_state, [inarg], [outarg]) # starting! server.start() print( "Server starting ...") # creating my machinery objects chargeController = cc.EpeverChargeController(produce_dummy_data = DUMMY_DATA) outputsEnabled = True try: while True: time.sleep(1) data = chargeController.readAllData() panelVoltage.set_value( data['panelVoltage'] ) panelCurrent.set_value( data['panelCurrent'] ) batteryVoltage.set_value( data['batteryVoltage'] ) batteryCurrent.set_value( data['batteryCurrent'] ) loadVoltage.set_value( data['loadVoltage'] ) loadCurrent.set_value( data['loadCurrent'] ) inPower.set_value( data['inPower'] ) outPower.set_value( data['outPower'] ) batteryStatus.set_value( data['batteryStatus'] ) batteryCapacity.set_value( data['batteryCapacity'] ) batteryTemperature.set_value( data['batteryTemperature'] ) if data['batteryVoltage'] < LOW_BATTERY_VOLTAGE and outputsEnabled: outputsEnabled = False; myEventGenerator.event.Message = ua.LocalizedText("Battery Voltage is too low. Outputs will be disconnected") myEventGenerator.event.batteryVoltage = ua.Variant(float(data['panelVoltage']), ua.VariantType.Float) myEventGenerator.event.outputsEnabled = ua.Variant( outputsEnabled , ua.VariantType.Boolean) myEventGenerator.event.Severity = ua.Variant( 1 , ua.VariantType.Int32) myEventGenerator.trigger() elif data['batteryVoltage'] > LOW_BATTERY_VOLTAGE and not outputsEnabled: outputsEnabled = True; myEventGenerator.event.Message = ua.LocalizedText("Battery Voltage is normal. Outputs will be activated") myEventGenerator.event.batteryVoltage = ua.Variant(float(data['panelVoltage']), ua.VariantType.Float) myEventGenerator.event.outputsEnabled = ua.Variant( outputsEnabled , ua.VariantType.Boolean) myEventGenerator.event.Severity = ua.Variant( 1 , ua.VariantType.Int32) myEventGenerator.trigger() ## update array variables burst = [random.random() for _ in range(1024)] plug_A_current_array.set_value(burst) plug_B_current_array.set_value(burst) embed() finally: # close connection, remove subcsriptions, etc server.stop()