def setUp(self): # create a new ClientSettings instance and add the localhost to the URLs to discover settings = pyuaf.client.settings.ClientSettings() settings.discoveryUrls.append(ARGS.demo_url) settings.applicationName = "client" settings.logToStdOutLevel = ARGS.loglevel self.client = pyuaf.client.Client(settings) serverUri = ARGS.demo_server_uri demoNsUri = ARGS.demo_ns_uri plcOpenNsUri = "http://PLCopen.org/OpcUa/IEC61131-3/" self.address_Scalar = Address( ExpandedNodeId("Demo.Static.Scalar", demoNsUri, serverUri)) self.address_Byte = Address( self.address_Scalar, [RelativePathElement(QualifiedName("Byte", demoNsUri))]) self.address_Int32 = Address( self.address_Scalar, [RelativePathElement(QualifiedName("Int32", demoNsUri))]) self.address_Float = Address( self.address_Scalar, [RelativePathElement(QualifiedName("Float", demoNsUri))])
def setUp(self): # create a new ClientSettings instance and add the localhost to the URLs to discover settings = ClientSettings() settings.discoveryUrls.append(ARGS.demo_url) settings.applicationName = "client" settings.logToStdOutLevel = ARGS.loglevel self.client = pyuaf.client.Client(settings) self.serverUri = ARGS.demo_server_uri demoNsUri = ARGS.demo_ns_uri plcOpenNsUri = "http://PLCopen.org/OpcUa/IEC61131-3/" # define some addresses self.addresses = [ Address(NodeId("Demo.SimulationSpeed", demoNsUri), self.serverUri), Address(NodeId("Demo.SimulationActive", demoNsUri), self.serverUri) ] self.address_Method = Address(ExpandedNodeId("Demo.Method", demoNsUri, self.serverUri)) self.address_Multiply = Address(ExpandedNodeId("Demo.Method.Multiply", demoNsUri, self.serverUri)) self.address_Alarms = Address(ExpandedNodeId("AlarmsWithNodes", demoNsUri, self.serverUri)) readResult = self.client.read(self.addresses) self.values = [readResult.targets[0].data, readResult.targets[1].data] del self.client self.client = pyuaf.client.Client(settings)
def setUp(self): # create a new ClientSettings instance and add the localhost to the URLs to discover settings = pyuaf.client.settings.ClientSettings() settings.discoveryUrls.append(ARGS.demo_url) settings.applicationName = "client" settings.logToStdOutLevel = ARGS.loglevel self.client = MyClient(settings) serverUri = ARGS.demo_server_uri demoNsUri = ARGS.demo_ns_uri self.address_Demo = Address( ExpandedNodeId("Demo", demoNsUri, serverUri)) self.address_Method = Address( self.address_Demo, [RelativePathElement(QualifiedName("Method", demoNsUri))]) self.address_Multiply = Address( self.address_Method, [RelativePathElement(QualifiedName("Multiply", demoNsUri))]) self.address_SetSimulationSpeed = Address(self.address_Demo, [ RelativePathElement(QualifiedName("SetSimulationSpeed", demoNsUri)) ]) self.request = AsyncMethodCallRequest(1) self.request.targets[0].objectAddress = self.address_Method self.request.targets[0].methodAddress = self.address_Multiply self.request.targets[0].inputArguments.append(Double(2.0)) self.request.targets[0].inputArguments.append(Double(3.0))
def setUp(self): # create a new ClientSettings instance and add the localhost to the URLs to discover settings = pyuaf.client.settings.ClientSettings() settings.discoveryUrls.append(ARGS.demo_url) settings.applicationName = "client" settings.logToStdOutLevel = ARGS.loglevel self.client = pyuaf.client.Client(settings) serverUri = ARGS.demo_server_uri demoNsUri = ARGS.demo_ns_uri plcOpenNsUri = "http://PLCopen.org/OpcUa/IEC61131-3/" self.address_Demo = Address(ExpandedNodeId("Demo", demoNsUri, serverUri)) self.address_StartSimulation = Address(self.address_Demo, [RelativePathElement(QualifiedName("StartSimulation", demoNsUri))]) self.address_StopSimulation = Address(self.address_Demo, [RelativePathElement(QualifiedName("StopSimulation", demoNsUri))]) self.address_Scalar = Address(self.address_Demo, [RelativePathElement(QualifiedName("Dynamic", demoNsUri)), RelativePathElement(QualifiedName("Scalar", demoNsUri))] ) self.address_Byte = Address(self.address_Scalar, [RelativePathElement(QualifiedName("Byte", demoNsUri))] ) self.address_Int32 = Address(self.address_Scalar, [RelativePathElement(QualifiedName("Int32", demoNsUri))] ) self.address_Int64 = Address(self.address_Scalar, [RelativePathElement(QualifiedName("Int64", demoNsUri))] ) self.address_Float = Address(self.address_Scalar, [RelativePathElement(QualifiedName("Float", demoNsUri))] ) self.address_Double = Address(self.address_Scalar, [RelativePathElement(QualifiedName("Double", demoNsUri))] ) # start the simulation (otherwise the dynamic variables won't change) self.client.call(self.address_Demo, self.address_StartSimulation)
def setUp(self): # create a new ClientSettings instance and add the localhost to the URLs to discover settings = pyuaf.client.settings.ClientSettings() settings.discoveryUrls.append(ARGS.demo_url) settings.applicationName = "client" settings.logToStdOutLevel = ARGS.loglevel self.client = pyuaf.client.Client(settings) serverUri = ARGS.demo_server_uri demoNsUri = ARGS.demo_ns_uri plcOpenNsUri = "http://PLCopen.org/OpcUa/IEC61131-3/" # define some nodeids self.id0 = NodeId(opcuaidentifiers.OpcUaId_Server_Auditing, 0) self.id1 = NodeId( opcuaidentifiers. OpcUaId_Server_ServerCapabilities_MaxHistoryContinuationPoints, 0) self.id2 = NodeId("Demo.SimulationSpeed", 2) self.id3 = NodeId("Demo.SimulationActive", demoNsUri) self.id4 = NodeId(opcuaidentifiers.OpcUaId_Server_ServerArray, 0) # define some nodeids self.address0 = Address(ExpandedNodeId(self.id0, serverUri)) self.address1 = Address(ExpandedNodeId(self.id1, serverUri)) self.address2 = Address(ExpandedNodeId(self.id2, serverUri)) self.address3 = Address(ExpandedNodeId(self.id3, serverUri)) self.address4 = Address(ExpandedNodeId(self.id4, serverUri)) # create some relative paths self.id5 = NodeId("Demo.BoilerDemo.Boiler1", demoNsUri) self.start5 = Address(ExpandedNodeId(self.id5, serverUri)) self.name5 = QualifiedName("TemperatureSetPoint", demoNsUri) self.elem5 = RelativePathElement(self.name5) self.path5 = [self.elem5] self.address5 = Address(self.start5, self.path5) self.start6 = Address(ExpandedNodeId("Demo", demoNsUri, serverUri)) self.elem6a = RelativePathElement( QualifiedName("BoilerDemo", demoNsUri)) self.elem6b = RelativePathElement(QualifiedName("Boiler1", demoNsUri)) self.path6 = [self.elem6a, self.elem6b] self.address6 = Address(self.start6, self.path6) self.elem7a = RelativePathElement( QualifiedName("TemperatureSensor", demoNsUri)) self.elem7b = RelativePathElement( QualifiedName("Temperature", demoNsUri)) self.path7 = [self.elem7a, self.elem7b] self.address7 = Address(self.address6, self.path7)
def setUp(self): # create a new ClientSettings instance and add the localhost to the URLs to discover settings = pyuaf.client.settings.ClientSettings() settings.discoveryUrls.append(ARGS.demo_url) settings.applicationName = "client" settings.logToStdOutLevel = ARGS.loglevel self.client = pyuaf.client.Client(settings) serverUri = ARGS.demo_server_uri demoNsUri = ARGS.demo_ns_uri self.address_demo = Address(NodeId("Demo" , demoNsUri), serverUri) self.address_startSim = Address(NodeId("Demo.StartSimulation" , demoNsUri), serverUri) self.address_stopSim = Address(NodeId("Demo.StopSimulation" , demoNsUri), serverUri) self.address_history = Address(NodeId("Demo.History" , demoNsUri), serverUri) self.address_startLog = Address(NodeId("Demo.History.StartLogging" , demoNsUri), serverUri) self.address_stopLog = Address(NodeId("Demo.History.StopLogging" , demoNsUri), serverUri) self.address_byte = Address(NodeId("Demo.History.ByteWithHistory" , demoNsUri), serverUri) self.address_double = Address(NodeId("Demo.History.DoubleWithHistory" , demoNsUri), serverUri) # start the simulation and the logging self.assertTrue( self.client.call(self.address_demo, self.address_startSim).overallStatus.isGood() ) self.client.call(self.address_history, self.address_startLog).overallStatus.isGood() self.startTime = time.time() # sleep a little more than a second, to make sure we have some historical data time.sleep(2)
def __init__(self,addr): self.a = addr self.contained = {} self.variables = {} # execute browse browse_result = client.browse([ self.a ]) for ri in xrange(len(browse_result.targets[0].references)): ref = browse_result.targets[0].references[ri] print ref.displayName # now we have information - node class if ref.nodeClass == nodeclasses.Variable: self.variables[str(ref.displayName.text())] = Address(ExpandedNodeId(ref.nodeId)) elif ref.nodeClass == nodeclasses.Object: if unfold: self.contained[str(ref.displayName.text())] = ObjectifiedNode( Address(ExpandedNodeId(ref.nodeId)) )
def connect(): global client cs = ClientSettings("myClient", [server_address]) # Uncomment below for session logging # cs.logToStdOutLevel = loglevels.Info max_attempts = 40 num_attempts = 0 while (True): print "Trying to connect to the OPC UA Server. Attempt #" + str( num_attempts) result = None try: client = Client(cs) rootNode = Address(NodeId(opcuaidentifiers.OpcUaId_RootFolder, 0), server_uri) result = client.browse([rootNode]) except Exception as e: print "Got exception: " + str(e) num_attempts = num_attempts + 1 if num_attempts > max_attempts: msg = 'Despite ' + str( max_attempts ) + ' attempts couldnt establish OPC UA connection: exception is ' + str( e) print msg dcs_test_utils.log_detail(False, msg, '') raise msg time.sleep(3) continue print 'Connected to OPC UA Server' return
def get_attribute(client, expanded_node_id, attribute, context): result = client.read([Address(expanded_node_id)], attribute) if result.targets[0].status.isGood(): data = result.targets[0].data if type(data) == LocalizedText: attribute_value = data.text() elif type(data) in [ primitives.Int32, primitives.Byte, primitives.Boolean ]: attribute_value = data.value elif type(data) == QualifiedName: attribute_value = data.name() elif type(data) == NodeId: attribute_value = stringify_nodeid(data) elif type(data) == type(None): attribute_value = 'WARNING_attribute_value_is_none' context['errors'] += 1 else: raise Exception("Don't know what to do when typs is {0}".format( str(type(data)))) else: context['errors'] += 1 attribute_value = "ERROR_attribute_not_readable" return attribute_value
def ADR(self): if isinstance(self.__opcua_parent__, Address): parentAddress = self.__opcua_parent__ else: parentAddress = self.__opcua_parent__.ADR() return Address(parentAddress, [RelativePathElement(QualifiedName(self.__opcua_name__, self.__opcua_ns__))])
def setUp(self): # create a new ClientSettings instance and add the localhost to the URLs to discover settings = pyuaf.client.settings.ClientSettings() settings.discoveryUrls.append(ARGS.demo_url) settings.applicationName = "client" settings.logToStdOutLevel = ARGS.loglevel self.client = pyuaf.client.Client(settings) serverUri = ARGS.demo_server_uri demoNsUri = ARGS.demo_ns_uri plcOpenNsUri = "http://PLCopen.org/OpcUa/IEC61131-3/" self.address_Demo = Address(ExpandedNodeId("Demo" , demoNsUri, serverUri)) self.address_StaticScalar = Address(ExpandedNodeId("Demo.Static.Scalar" , demoNsUri, serverUri)) self.address_DynamicScalar = Address(ExpandedNodeId("Demo.Dynamic.Scalar", demoNsUri, serverUri))
def build_objects(self, address): o = Object(Node(self, address)) browse_result = self.client.browse([address]) for ri in xrange(len(browse_result.targets[0].references)): ref = browse_result.targets[0].references[ri] print ref.displayName # now we have information - node class if ref.nodeClass == nodeclasses.Variable: o.variables[str(ref.displayName.text())] = Variable( Node(self, Address(ExpandedNodeId(ref.nodeId)))) elif ref.nodeClass == nodeclasses.Method: o.methods[str(ref.displayName.text())] = Method( Node(self, Address(ExpandedNodeId(ref.nodeId))), o) elif ref.nodeClass == nodeclasses.Object: o.children_objects[str( ref.displayName.text())] = self.build_objects( Address(ExpandedNodeId(ref.nodeId))) return o
def setUp(self): # create a new ClientSettings instance and add the localhost to the URLs to discover settings = pyuaf.client.settings.ClientSettings() settings.discoveryUrls.append(ARGS.demo_url) settings.applicationName = "client" settings.logToStdOutLevel = ARGS.loglevel self.client = pyuaf.client.Client(settings) serverUri = ARGS.demo_server_uri demoNsUri = ARGS.demo_ns_uri self.address_Demo = Address(ExpandedNodeId("Demo", demoNsUri, serverUri)) self.address_Method = Address(self.address_Demo, [RelativePathElement(QualifiedName("Method", demoNsUri))] ) self.address_Multiply = Address(self.address_Method, [RelativePathElement(QualifiedName("Multiply", demoNsUri))] ) self.address_SetSimulationSpeed = Address(self.address_Demo, [RelativePathElement(QualifiedName("SetSimulationSpeed", demoNsUri))] )
def setUp(self): # create a new ClientSettings instance and add the localhost to the URLs to discover settings = pyuaf.client.settings.ClientSettings() settings.discoveryUrls.append(ARGS.demo_url) settings.applicationName = "client" settings.logToStdOutLevel = ARGS.loglevel self.client = MyClient(settings) self.serverUri = ARGS.demo_server_uri demoNsUri = ARGS.demo_ns_uri plcOpenNsUri = "http://PLCopen.org/OpcUa/IEC61131-3/" # define some nodeids self.id = NodeId(opcuaidentifiers.OpcUaId_Server_Auditing, 0) # define some addresses self.address = Address(ExpandedNodeId(self.id, self.serverUri))
# define the namespace URI and server URI of the UaServerCPP demo server demoServerUri = "urn:UnifiedAutomation:UaServerCpp" demoNamespaceUri = "urn:UnifiedAutomation:CppDemoServer:BuildingAutomation" # define the ClientSettings: settings = ClientSettings() settings.applicationName = "MyClient" settings.discoveryUrls.append("opc.tcp://localhost:48010") # create the client myClient = Client(settings) # define the address of the Structure which we would like to read units_address = Address( NodeId("AirConditioner_1.Temperature.EngineeringUnits", demoNamespaceUri), demoServerUri ) range_address = Address( NodeId("AirConditioner_1.Temperature.EURange", demoNamespaceUri), demoServerUri ) # try to read a structure result = myClient.read( [units_address, range_address] ) # we're expecting ExtensionObjects. Let's check this: for i in xrange(2): if isinstance(result.targets[i].data, ExtensionObject): print("We received an ExtensionObject") else: raise Exception("Oops, we were expecting an ExtensionObject, but we received a: %s" %result.targets[0].data) units_extensionObject = result.targets[0].data range_extensionObject = result.targets[1].data
myClient.registerUntrustedServerCertificateCallback(myCallback) print("") print( "===========================================================================================" ) print("STEP 7: Read some variable using the configured secure session") print( "===========================================================================================" ) print("") # define the address of a node which we would like to read: someAddress = Address(NodeId("Demo.SimulationSpeed", DEMOSERVER_NS_URI), SERVER_URI) result = myClient.read([someAddress], sessionSettings=sessionSettings) # Note that instead of explicitly providing the sessionSettings **kwarg argument, we could also # have done the following: # clientSettings.defaultSessionSettings = sessionSettings # myClient.setClientSettings(clientSettings) # result = myClient.read( [someAddress] ) print("") print("Read result:") print(result) print("") # check the session that was used to read this address:
import pyuaf from pyuaf.client import Client from pyuaf.client.settings import ClientSettings from pyuaf.client.requests import BrowseRequest, BrowseRequestTarget from pyuaf.client.configs import BrowseConfig, SessionConfig from pyuaf.util import Address, NodeId from pyuaf.util import primitives from pyuaf.util import opcuaidentifiers from pyuaf.util.errors import UafError # define the namespace URI and server URI of the UaServerCPP demo server demoServerUri = "urn:UnifiedAutomation:UaServerCpp" # define the address of the Root node which we would like to start browsing rootNode = Address(NodeId(opcuaidentifiers.OpcUaId_RootFolder, 0), demoServerUri) # define the ClientSettings: settings = ClientSettings() settings.applicationName = "MyClient" settings.discoveryUrls.append("opc.tcp://localhost:48010") # create the client myClient = Client(settings) try: print("") print("First option: use the convenience function \"browse()\"") print("===================================================") # now browse the root node
# servers, they will be created according to the specified settings. # If sessions need to be created to other servers, they will be created according to the # defaultSessionSettings settings. # configure a client ... clientSettings = ClientSettings() clientSettings.applicationName = "MyClient" clientSettings.discoveryUrls.append("opc.tcp://10.133.78.42") clientSettings.discoveryUrls.append("opc.tcp://10.133.78.81") clientSettings.discoveryUrls.append("opc.tcp://10.134.25.16") # ... and create the client myClient = Client(clientSettings) # define some addresses temperature1 = Address(NodeId("temperature1", "MyCompanyNamespace"), "Some/OPCUA/Server") temperature2 = Address(NodeId("temperature2", "MyCompanyNamespace"), "Some/OPCUA/Server") pressure0005 = Address(NodeId("pressure0005", "MyCompanyNamespace"), "My/Unreliable/Device/Server") motorStatus3 = Address(NodeId("motorStatus3", "MyCompanyNamespace"), "My/Reliable/PLC/Server") # now we can read, write, ... any address(es) without worrying about the settings of the sessions! # read the Value attribute of the 4 nodes myReadResult = myClient.read( [temperature1, temperature2, pressure0005, motorStatus3], sessionConfig=cfg) # write a new motor status
from pyuaf.client.settings import ClientSettings from pyuaf.client.requests import ReadRequest, AsyncReadRequest, ReadRequestTarget from pyuaf.client.configs import ReadConfig, SessionConfig from pyuaf.util import Address, NodeId, RelativePathElement, QualifiedName, LocalizedText from pyuaf.util import primitives from pyuaf.util.errors import UafError # define the namespace URI and server URI of the UaDemoServer demoNsUri = "http://www.unifiedautomation.com/DemoServer" demoServerUri = "urn:UnifiedAutomation:UaServerCpp" # define some addresses of nodes of which we will read the Value attribute # (you could also define addresses as Relative Paths to other addresses, # see the example that shows you how to define addresses) someDoubleNode = Address( NodeId("Demo.Static.Scalar.Double" , demoNsUri), demoServerUri ) someUInt32Node = Address( NodeId("Demo.Static.Scalar.UInt32" , demoNsUri), demoServerUri ) someStringNode = Address( NodeId("Demo.Static.Scalar.String" , demoNsUri), demoServerUri ) someLocalizedTextNode = Address( NodeId("Demo.Static.Scalar.LocalizedText" , demoNsUri), demoServerUri ) someSByteArrayNode = Address( NodeId("Demo.Static.Arrays.SByte" , demoNsUri), demoServerUri ) # define a function to print the readResult (which is of type pyuaf.client.results.ReadResult) def printResult(readResult): # overall result print("The overall status is: %s" %str(readResult.overallStatus)) # target 0: status = readResult.targets[0].status # 'status' has type pyuaf.util.Status data = readResult.targets[0].data # 'data' has type pyuaf.util.primitives.Double if status.isGood() and isinstance(data, primitives.Double): print("The double is: %.3f" %data.value)
def addr(sa): return Address(NodeId(sa, server_ns), server_uri)
def setUp(self): # create a new ClientSettings instance and add the localhost to the URLs to discover settings = pyuaf.client.settings.ClientSettings() settings.discoveryUrls.append(ARGS.demo_url) settings.applicationName = "client" settings.logToStdOutLevel = ARGS.loglevel self.client = MyClient(settings) serverUri = ARGS.demo_server_uri demoNsUri = ARGS.demo_ns_uri opcUaNsIndex = 0 # the namespace index of nodes defined by the OPC UA specs is always 0 self.address_Demo = Address( ExpandedNodeId("Demo", demoNsUri, serverUri)) self.address_Events = Address( self.address_Demo, [RelativePathElement(QualifiedName("Events", demoNsUri))]) self.address_Alarms = Address( self.address_Events, [RelativePathElement(QualifiedName("AlarmsWithNodes", demoNsUri))]) self.address_Alarm = Address(self.address_Alarms, [ RelativePathElement(QualifiedName("ExclusiveLevelAlarm", demoNsUri)) ]) self.address_Trigger = Address(self.address_Alarms, [ RelativePathElement( QualifiedName("ExclusiveLevelAlarmTrigger", demoNsUri)) ]) self.address_LowLow = Address( self.address_Alarm, [RelativePathElement(QualifiedName("LowLowLimit", opcUaNsIndex))]) self.address_Low = Address( self.address_Alarm, [RelativePathElement(QualifiedName("LowLimit", opcUaNsIndex))]) self.address_High = Address( self.address_Alarm, [RelativePathElement(QualifiedName("HighLimit", opcUaNsIndex))]) self.address_HighHigh = Address(self.address_Alarm, [ RelativePathElement(QualifiedName("HighHighLimit", opcUaNsIndex)) ]) # start the simulation (otherwise the dynamic variables won't change) res = self.client.read([ self.address_LowLow, self.address_Low, self.address_High, self.address_HighHigh ]) self.assertTrue(res.overallStatus.isGood()) self.lowLowLimit = res.targets[0].data.value self.lowLimit = res.targets[1].data.value self.highLimit = res.targets[2].data.value self.highHighLimit = res.targets[3].data.value self.eventFilter = EventFilter() self.eventFilter.selectClauses.resize(3) self.eventFilter.selectClauses[0].attributeId = attributeids.Value self.eventFilter.selectClauses[0].browsePath.append( QualifiedName("Message", 0)) self.eventFilter.selectClauses[0].typeId = NodeId( opcuaidentifiers.OpcUaId_BaseEventType, 0) self.eventFilter.selectClauses[1].attributeId = attributeids.Value self.eventFilter.selectClauses[1].browsePath.append( QualifiedName("SourceName", 0)) self.eventFilter.selectClauses[1].typeId = NodeId( opcuaidentifiers.OpcUaId_BaseEventType, 0) self.eventFilter.selectClauses[2].attributeId = attributeids.Value self.eventFilter.selectClauses[2].browsePath.append( QualifiedName("Severity", 0)) self.eventFilter.selectClauses[2].typeId = NodeId( opcuaidentifiers.OpcUaId_BaseEventType, 0) # make sure the trigger has a default value result = self.client.write([self.address_Trigger], [Double(50.0)]) # Check if the write failed due to a BadUserAccessDenied failure # This appears to be the case for the UaServerCpp shipped with the Windows MSVS2008 demo SDK, # probably a bug in the UaServerCpp. if result.targets[0].status.opcUaStatusCode( ) == pyuaf.util.opcuastatuscodes.OpcUa_BadUserAccessDenied: self.skipTest( "Some old versions of the UaServerCpp have non-writeable triggers (bug in UaServerCpp?)" )
Root_NodeId = NodeId( OpcUaId_RootFolder, OPCUA_NAMESPACE_URI) # namespace URI instead of namespace index Root_NodeId = NodeId(OpcUaId_RootFolder, OPCUA_NAMESPACE_URI, OPCUA_NAMESPACE_ID) # redundant namespace info, but valid # NodeIds don't contain info about the server they are hosted by. # If you specifically want to refer to a NodeId within a particular server, you need to # use an ExpandedNodeId, which contains # - a NodeId # - and a serverUri # Assume from now on that the particular nodes we want to refer to, are hosted by a server defined # by the server URI "urn:UnifiedAutomation:UaDemoserver": serverUri = "urn:UnifiedAutomation:UaDemoserver" # Then we can refer to the Root node like this: Root_Node = Address(Root_NodeId, serverUri) # An absolute address can also be created directly from an ExpandedNodeId: Root_Node = Address( ExpandedNodeId(OpcUaId_RootFolder, OPCUA_NAMESPACE_ID, serverUri)) # within the Root folder, there is another standard node called the Objects folder: Objects_Node = Address(NodeId(OpcUaId_ObjectsFolder, OPCUA_NAMESPACE_ID), serverUri) # we could also refer to the Objects node via a relative path! # We can do this, since the standard Object node has a standard BrowseName. # The following are all valid ways to define the BrowseName of the Objects node Objects_BrowseName = QualifiedName("Objects", OPCUA_NAMESPACE_ID) Objects_BrowseName = QualifiedName( "Objects", OPCUA_NAMESPACE_URI) # namespace URI instead of index Objects_BrowseName = QualifiedName(
from pyuaf.util import Status from pyuaf.util import RelativePathElement from pyuaf.util import QualifiedName from pyuaf.util import primitives from pyuaf.util import opcuaidentifiers from pyuaf.util import opcuastatuscodes from pyuaf.util.errors import UafError # define the namespace URI and server URI of the UaDemoServer demoNsUri = "http://www.unifiedautomation.com/DemoServer" demoServerUri = "urn:UnifiedAutomation:UaServerCpp" # define the addresses of some useful nodes # (demoAddress is an absolute address, all the others are relative ones) demoAddress = Address( NodeId("Demo", demoNsUri), demoServerUri ) simulationActiveAddress = Address( demoAddress, [RelativePathElement(QualifiedName("SimulationActive", demoNsUri))] ) startSimulationAddress = Address( demoAddress, [RelativePathElement(QualifiedName("StartSimulation" , demoNsUri))] ) historyAddress = Address( demoAddress, [RelativePathElement(QualifiedName("History", demoNsUri))] ) loggingActiveAddress = Address( historyAddress, [RelativePathElement(QualifiedName("DataLoggerActive", demoNsUri))] ) startLoggingAddress = Address( historyAddress, [RelativePathElement(QualifiedName("StartLogging", demoNsUri))] ) doubleAddress = Address( historyAddress, [RelativePathElement(QualifiedName("DoubleWithHistory", demoNsUri))] ) # define the ClientSettings: settings = ClientSettings() settings.applicationName = "MyClient" settings.discoveryUrls.append("opc.tcp://localhost:48010") # create the client myClient = Client(settings)
# created according to the specified settings. # If subscriptions need to be created to other servers, they will be created according to the # defaultSubscriptionSettings settings. # First of all, configure a client ... clientSettings = ClientSettings() clientSettings.applicationName = "MyClient" clientSettings.discoveryUrls.append("opc.tcp://10.133.78.42") clientSettings.discoveryUrls.append("opc.tcp://10.133.78.81") clientSettings.discoveryUrls.append("opc.tcp://10.134.25.16") # ... and create the client myClient = Client(clientSettings) # define some node addresses temperature1 = Address(NodeId("temperature1", "MyCompanyNamespace"), "Some/OPCUA/Server") temperature2 = Address(NodeId("temperature2", "MyCompanyNamespace"), "Some/OPCUA/Server") pressure0005 = Address(NodeId("pressure0005", "MyCompanyNamespace"), "My/Slow/Device/Server") motorStatus3 = Address(NodeId("motorStatus3", "MyCompanyNamespace"), "My/Fast/PLC/Server") safetyValve5 = Address(NodeId("safetyValve5", "MyCompanyNamespace"), "My/Fast/PLC/Server") # now we can monitor any variables or events without worrying about the settings of the subscriptions! # monitor the 4 variables myCreateMonitoredDataResult = myClient.createMonitoredData( [temperature1, temperature2, pressure0005, motorStatus3], subscriptionConfig=cfg)
for line in msg.message.splitlines(): f.write("%s: %s\n" % (logDetailsString, line)) # Example 0: create a client with the default settings and no logging callback # -------------------------------------------------------------------------------------------------- client0 = Client() # Example 1: create a client by specifying the settings # -------------------------------------------------------------------------------------------------- client1 = Client(settings) # Example 2: create a client by specifying the settings # -------------------------------------------------------------------------------------------------- client2 = Client(settings, callback) # Example 3: create a client by specifying only the logging callback # -------------------------------------------------------------------------------------------------- client3 = Client(loggingCallback=callback) # you can still provide settings and register a logging callback afterwards, but you'll need to use: # client0.setClientSettings(settings) # client0.registerLoggingCallback(callback) # read the Value attribute of some non-existing node in order to have some Error output sent to the callback: client2.read([ Address(NodeId("InvalidIdentifier", "InvalidNamespace"), "InvalidServerURI") ]) f.close()
from pyuaf.client import Client from pyuaf.client.settings import ClientSettings, SessionSettings from pyuaf.util import Address, NodeId, opcuaidentifiers import uao server_uri = 'urn:CERN:QuasarOpcUaServer' # needs to match the factual server URI server_address = 'opc.tcp://127.0.0.1:4841' cs = ClientSettings("myClient", [server_address]) client = Client(cs) # next 2 lines are not necessary but help to ensure good state of OPC-UA connectivity rootNode = Address(NodeId(opcuaidentifiers.OpcUaId_RootFolder, 0), server_uri) result = client.browse([rootNode]) session = uao.Session(client, server_uri) obj = session.get_object('anObject', 2) # needs to match factuall existing object
print( "Step 3: Specify the addresses to some nodes which we would like to read/write/browse/monitor/call/..." ) print( "################################################################################################################" ) print("") # There are *many* ways how you can identify (address) a node, see the examples below: # 1) absolute address to the standard OPC UA "RootFolder" node (notice the standard OPC UA index 0) # 2) absolute address to the non-standard "Demo" node (notice the demo server namespace URI) # 3) absolute address to the non-standard "BoilerDemo" node (notice that we use an ExpandedNodeId this time) # 4) relative address to the "Boiler1" node (relative to the previous address) # 5) relative address to the "TemperatureSetpoint" Double variable (relative to the previous relative (!!!) address) # 6) relative address to the "HeaterStatus" node (relative to the standard "Root" folder) address_Root = Address(NodeId(OpcUaId_RootFolder, 0), demoServerUri) address_Demo = Address(NodeId("Demo", demoNsUri), demoServerUri) address_BoilerDemo = Address( ExpandedNodeId("Demo.BoilerDemo", demoNsUri, demoServerUri)) address_Boiler1 = Address( address_BoilerDemo, [RelativePathElement(QualifiedName("Boiler1", demoNsUri))]) address_TSetpoint = Address( address_Boiler1, [RelativePathElement(QualifiedName("TemperatureSetPoint", demoNsUri))]) address_HeaterStatus = Address(address_Root, [ RelativePathElement(QualifiedName("Objects", 0)), RelativePathElement(QualifiedName("Demo", demoNsUri)), RelativePathElement(QualifiedName("BoilerDemo", demoNsUri)), RelativePathElement(QualifiedName("Boiler1", demoNsUri)), RelativePathElement(QualifiedName("HeaterStatus", demoNsUri))
) print( "# #" ) print( "# 2) Read a matrix #" ) print( "# #" ) print( "#******************************************************************************#" ) # define the address of the matrix which we would like to read address = Address(NodeId("Demo.Static.Matrix.Int32", demoNamespaceUri), demoServerUri) # try to read it result = myClient.read([address]) if not result.overallStatus.isGood(): sys.exit("The matrix could not be read: %s" % result.targets[0].status) # ok we expect to have a matrix: matrix = result.targets[0].data if not type(matrix) == Matrix: sys.exit("Wrong type: %s" % type(matrix)) # print the matrix: printMatrix(matrix)
from pyuaf.client import Client from pyuaf.client.settings import ClientSettings from pyuaf.util import EventFilter from pyuaf.util import Address, NodeId, QualifiedName from pyuaf.util import ExtensionObject, ModelChangeStructureDataType from pyuaf.util import primitives from pyuaf.util.errors import UafError from pyuaf.util import opcuaidentifiers # define the namespace URI and server URI of the UaDemoServer demoNsUri = "http://www.unifiedautomation.com/DemoServer" demoServerUri = "urn:UnifiedAutomation:UaServerCpp" # define some addresses which will be used later on address_Server = Address( NodeId(opcuaidentifiers.OpcUaId_Server , 0), demoServerUri ) address_Dynamic = Address( NodeId("Demo.DynamicNodes" , demoNsUri), demoServerUri ) address_Create = Address( NodeId("Demo.DynamicNodes.CreateDynamicNode", demoNsUri), demoServerUri ) address_Delete = Address( NodeId("Demo.DynamicNodes.DeleteDynamicNode", demoNsUri), demoServerUri ) # define the ClientSettings: settings = ClientSettings() settings.applicationName = "MyClient" settings.discoveryUrls.append("opc.tcp://localhost:48010") # create the client myClient = Client(settings) # define the event filter to only receive the GeneralModelChangeEventType events eventFilter = EventFilter() eventFilter.selectClauses.resize(1)
# examples/pyuaf/client/easiest_client_example.py # Start the demo server ($SDK/bin/uaservercpp) of Unified Automation before running this script! import pyuaf from pyuaf.util import Address, NodeId from pyuaf.client import Client from pyuaf.client.settings import ClientSettings # create a client named "myClient", and provide the discovery URL of the server (uaservercpp): myClient = Client(ClientSettings("myClient", ["opc.tcp://localhost:48010"])) # specify the address of the node of which we would like to read its Value attribute: # (here we're using an absolute address, i.e. a NodeId(<identifier>, <namespace URI>) and a <server URI>) someAddress = Address( NodeId( "Demo.SimulationSpeed", # NodeId identifier "http://www.unifiedautomation.com/DemoServer"), # NodeId namespace URI "urn:UnifiedAutomation:UaServerCpp") # server URI # read the Value attribute of the node that we just addressed: result = myClient.read([someAddress]) print("The value is %d" % result.targets[0].data.value)