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 = 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 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 myCallback(notification): print("Notification received!") changes = notification.fields[0] print("Changes:") for i in xrange(len(changes)): change = changes[i] print("- change %d:" %i) print(change) # check if we received indeed an ExtensionObject: assert isinstance(change, pyuaf.util.ExtensionObject) # OK, we can now check that the ExtensionObject represents a ModelChangeStructureDataType instance assert change.dataTypeId == NodeId(opcuaidentifiers.OpcUaId_ModelChangeStructureDataType, 0) print("The same object, converted to a ModelChangeStructureDataType:") modelChange = ModelChangeStructureDataType(change) print modelChange
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 = 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))
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()
) 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:
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))
# 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)
# 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
def connect( ): global client cs = ClientSettings("myClient", [server_address]) client = Client(cs) rootNode = Address( NodeId(opcuaidentifiers.OpcUaId_RootFolder, 0), server_uri ) result=client.browse ([ rootNode ])
def get_object(self, string_a, ns): n = NodeId(string_a, ns) a = Address(n, self.server_uri) return self.build_objects(a)
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)
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("===================================================")
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?)" )
"My/Unreliable/Device/Server/URI"] = SessionSettings() clientSettings.specificSessionSettings[ "My/Unreliable/Device/Server/URI"].sessionTimeoutSec = 200.0 clientSettings.specificSessionSettings[ "My/Unreliable/Device/Server/URI"].connectTimeoutSec = 5.0 # If the client connects to the server with ServerUri = "My/Unreliable/Device/Server/URI", # then it will use these settings instead of the defaultSessionSettings! # Now you can simply create a client that uses these settings: myClient = Client(clientSettings) # or alternatively: # myClient = Client() # myClient.setClientSettings(clientSettings) # let's read 2 nodes: address0 = Address(NodeId("Demo.SimulationSpeed", NAMESPACE_URI), SERVER_URI) address1 = Address(NodeId("Demo.SimulationActive", NAMESPACE_URI), SERVER_URI) # the next line will result in # - a session being created, with the defaultSessionSettings which we configured before # - the Read service being invoked, with the defaultReadSettings we configured before myClient.read([address0, address1]) # when the next line is executed, then: # - the session we created before will be reused (as we're requesting a session with the # defaultSessionSettings, but such a session exists already, so it can be reused!) # - the Write service will be invoked, with the defaultWriteSettings we configured before myClient.write([address0, address1], [UInt32(60), Boolean(True)]) # ================================================================================================== # 2) Overriding the defaults
) print( "# #" ) print( "# 2) How to read and write a scalar structure (i.e. a single structure, not an array) #" ) print( "# #" ) print( "#******************************************************************************************#" ) # define the address of the Structure which we would like to read address = Address(NodeId("Demo.Static.Scalar.Vector", demoNamespaceUri), demoServerUri) # try to read a structure result = myClient.read([address]) # we're expecting an ExtensionObject. Let's check this: if isinstance(result.targets[0].data, ExtensionObject): print("We received an ExtensionObject") print("") else: raise Exception( "Oops, we were expecting an ExtensionObject, but we received a: %s" % result.targets[0].data) extensionObject = result.targets[0].data
from pyuaf.client.settings import ClientSettings from pyuaf.client.requests import TranslateBrowsePathsToNodeIdsRequest from pyuaf.client.configs import TranslateBrowsePathsToNodeIdsConfig from pyuaf.util import Address, NodeId, RelativePathElement, QualifiedName, BrowsePath, ExpandedNodeId from pyuaf.util import primitives from pyuaf.util.errors import UafError from pyuaf.util.opcuaidentifiers import OpcUaId_RootFolder from pyuaf.util.constants import OPCUA_NAMESPACE_URI # define the namespace URI and server URI of the UaDemoServer demoNsUri = "http://www.unifiedautomation.com/DemoServer" demoServerUri = "urn:UnifiedAutomation:UaServerCpp" # define a browse path to the HeaterStatus node myStartingPoint = ExpandedNodeId( NodeId(OpcUaId_RootFolder, OPCUA_NAMESPACE_URI), demoServerUri ) myRelativePath = [ RelativePathElement(QualifiedName("Objects" , OPCUA_NAMESPACE_URI)), RelativePathElement(QualifiedName("Demo" , demoNsUri)), RelativePathElement(QualifiedName("BoilerDemo" , demoNsUri)), RelativePathElement(QualifiedName("Boiler1" , demoNsUri)), RelativePathElement(QualifiedName("HeaterStatus", demoNsUri)) ] myBrowsePath = BrowsePath(myStartingPoint, myRelativePath) # define the ClientSettings: settings = ClientSettings() settings.applicationName = "MyClient" settings.discoveryUrls.append("opc.tcp://localhost:48010") # settings.logToStdOutLevel = pyuaf.util.loglevels.Debug # uncomment for seeing debugging information # create the client myClient = Client(settings)
except UafError, e: print("Couldn't read the session information: %s" % e) print("Exiting...") sys.exit() # now use the server URI to read some variables try: print("") print("Now reading some variables") # define the namespace URI of the UaDemoServer: demoNsUri = "http://www.unifiedautomation.com/DemoServer" # define some addresses: someDoubleNode = Address(NodeId("Demo.Static.Scalar.Double", demoNsUri), info.serverUri) someUInt32Node = Address(NodeId("Demo.Static.Scalar.UInt32", demoNsUri), info.serverUri) # read the nodes of the addresses: result = myClient.read([someDoubleNode, someUInt32Node]) print("") print("ReadResult:") print(result) except UafError, e: print("Couldn't read some variables: %s" % e) print("Exiting...") sys.exit()
from pyuaf.util.constants import OPCUA_NAMESPACE_URI, OPCUA_NAMESPACE_ID #========================================================# # standard nodes # #========================================================# # First we define some standard OPC UA nodes. # Standard nodes have NodeIds that are fully defined by the OPC UA standard. # For instance, the Root node that is present on all servers, has a # - namespace URI "http://opcfoundation.org/UA/" --> defined as pyuaf.util.constants.OPCUA_NAMESPACE_URI # - namespace index 0 --> defined as pyuaf.util.constants.OPCUA_NAMESPACE_ID # (note that index 0 is ALWAYS reserved for the OPC UA namespace!) # - the numeric NodeId identifier 84 --> defined as pyuaf.util.opcuaidentifiers.OpcUaId_RootFolder # # So here are all valid ways to define the Root node: Root_NodeId = NodeId(84, 0) Root_NodeId = NodeId( OpcUaId_RootFolder, OPCUA_NAMESPACE_ID) # same as the previous, but with symbols 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
from pyuaf.client import Client from pyuaf.client.settings import ClientSettings from pyuaf.client.requests import TranslateBrowsePathsToNodeIdsRequest from pyuaf.util import Address, NodeId, RelativePathElement, QualifiedName, BrowsePath, ExpandedNodeId from pyuaf.util import primitives from pyuaf.util.errors import UafError from pyuaf.util.opcuaidentifiers import OpcUaId_RootFolder from pyuaf.util.constants import OPCUA_NAMESPACE_URI # define the namespace URI and server URI of the UaDemoServer demoNsUri = "http://www.unifiedautomation.com/DemoServer" demoServerUri = "urn:UnifiedAutomation:UaServerCpp" # define a browse path to the HeaterStatus node myStartingPoint = ExpandedNodeId( NodeId(OpcUaId_RootFolder, OPCUA_NAMESPACE_URI), demoServerUri) myRelativePath = [ RelativePathElement(QualifiedName("Objects", OPCUA_NAMESPACE_URI)), RelativePathElement(QualifiedName("Demo", demoNsUri)), RelativePathElement(QualifiedName("BoilerDemo", demoNsUri)), RelativePathElement(QualifiedName("Boiler1", demoNsUri)), RelativePathElement(QualifiedName("HeaterStatus", demoNsUri)) ] myBrowsePath = BrowsePath(myStartingPoint, myRelativePath) # define the ClientSettings: settings = ClientSettings() settings.applicationName = "MyClient" settings.discoveryUrls.append("opc.tcp://localhost:48010") # settings.logToStdOutLevel = pyuaf.util.loglevels.Debug # uncomment for seeing debugging information
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)
def get_object( string_a, ns ): n = NodeId( string_a, ns ) a = Address( n, server_uri ) return ObjectifiedNode(a)
# 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)
subSettings.publishingIntervalSec = 1.0 subSettings.maxKeepAliveCount = 5 # Explanation: # - The subscription will send at most one bunch of changed data samples per second, due to the # publishing interval of 1 second. # - If the sampled data does not change, then the server does not have to send notifications to # the client. However, when the sampled data does not change for 5 seconds in a row # (5 seconds = maxKeepAliveCount * publishingIntervalSec), then the server # will send a KeepAlive notification to the client, as a kind of "heartbeat". # 2) configure the monitored items # -------------------------------- target0 = CreateMonitoredDataRequestTarget() target0.address = Address( NodeId("Demo.Dynamic.Scalar.Float", demoNamespaceUri), demoServerUri) target0.queueSize = 5 target0.samplingIntervalSec = 0.2 target0.discardOldest = True filter = DataChangeFilter() filter.deadBandType = DataChangeFilter.DeadBandType_Absolute filter.deadBandValue = 0.1 target0.dataChangeFilter = filter # Explanation: # The variable we will monitor, must be sampled 5 times per second (see samplingIntervalSec of 0.2 seconds). # Note that this is 5 times faster than the publishing interval of the subscription! Indeed, to make # the data transmission more efficient, OPC UA will bundle (in this case) up to 5 data changes in one # transmission, every second. # Of course, it means that we need to instruct the server to reserve a queue, so it can store up to 5 samples
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("")
def addr(sa): return Address(NodeId(sa, server_ns), server_uri)
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)
settings.applicationName = "myClient" settings.logToStdOutLevel = loglevels.Debug settings.logToCallbackLevel = loglevels.Error # define the callback for the logging def myLoggingCallback(msg): print("************ CALLBACK SAYS: ************") if msg.level == loglevels.Error: print("Error message received: %s" % str(msg)) elif msg.level == loglevels.Warning: print("Warning message received: %s" % str(msg)) else: print("Info or debug message received: %s" % str(msg)) # create the client myClient = Client(settings, myLoggingCallback) # try to read the Value attribute of some non-existing node (so errors will be sent to the callback) try: nodeId = NodeId("NonExistingIdentifier", "NonExistingNameSpace") address = Address(nodeId, "NonExistingServerURI") myClient.read([address]) except pyuaf.util.errors.UafError, e: print("UAF error raised: %s" % e) # alternatively: myClient2 = Client() myClient2.registerLoggingCallback(myLoggingCallback) myClient2.setClientSettings(settings)