コード例 #1
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 = MyClient(settings)

        self.serverUri = ARGS.demo_server_uri
        demoNsUri = ARGS.demo_ns_uri
        plcOpenNsUri = "http://PLCopen.org/OpcUa/IEC61131-3/"

        # define some nodeids
        self.node_id = NodeId(opcuaidentifiers.OpcUaId_Server_Auditing, 0)

        # define some addresses
        self.address = Address(ExpandedNodeId(self.node_id, self.serverUri))
コード例 #2
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

        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)
コード例 #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 = MyClient(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_Float = Address(
            self.address_Scalar,
            [RelativePathElement(QualifiedName("Float", demoNsUri))])

        # start the simulation (otherwise the dynamic variables won't change)
        self.client.call(self.address_Demo, self.address_StartSimulation)
コード例 #4
0
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)
コード例 #5
0

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:
コード例 #6
0
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)
コード例 #7
0
    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()
コード例 #8
0
ファイル: example1.py プロジェクト: quasar-team/UaoForQuasar
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
コード例 #9
0
)
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)
コード例 #10
0
subSettings = SubscriptionSettings()
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
コード例 #11
0
        
        print("")
        print("Full translation result:")
        print(result)
    else:
        print("Problem when translating the target: %s" %result.targets[0].status)

except UafError, e:
    print("Some error occurred!")
    raise


# As mentioned in the top description of this example, in most cases you don't need to translate
# browsepaths manually. You can simply read/write/monitor/... the node directly:
try:
    readResult = myClient.read( Address(myBrowsePath) )
    print("")
    print("Full read result:")
    print(readResult)
except UafError, e:
    print("Some error occurred!")
    raise

# Note: in fact, during the above myClient.read() call, no translation request is being sent 
# to the server, because the UAF had already internally cached the translation results during 
# the myClient.processRequest() invocation. 
# Of course, if the browsepath wouldn't have been cached, the UAF *would* have automatically
# sent a translation request to the server prior to reading the data. So the UAF takes care
# of translating browsepaths in the most efficient way, all done automatically for you!

コード例 #12
0
    "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
コード例 #13
0
ファイル: main.py プロジェクト: quasar-team/UaoForQuasar
def get_object( string_a, ns ):
    n = NodeId( string_a, ns )
    a = Address( n, server_uri )
    return ObjectifiedNode(a)
コード例 #14
0
ファイル: main.py プロジェクト: quasar-team/UaoForQuasar
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 ])
コード例 #15
0
# 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)
コード例 #16
0
ファイル: uao.py プロジェクト: quasar-team/UaoForQuasar
 def get_object(self, string_a, ns):
     n = NodeId(string_a, ns)
     a = Address(n, self.server_uri)
     return self.build_objects(a)
コード例 #17
0

# 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
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()
コード例 #19
0
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))
コード例 #20
0
)
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
コード例 #21
0
# 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)
コード例 #22
0
def recurse(client, expanded_node_id, document, parent, refTypeFromParent,
            context):
    global added_nodes
    print 'recurse at: ' + str(expanded_node_id)
    results = client.browse([Address(expanded_node_id)])
    references = results.targets[
        0].references  #  asked to browse only one address, that's why targets[0]

    if expanded_node_id.nodeId().nameSpaceIndex(
    ) != constants.OPCUA_NAMESPACE_ID:

        stringified_id = stringify_nodeid(expanded_node_id.nodeId())
        if not stringified_id in added_nodes:

            nodeclass = get_attribute(client, expanded_node_id,
                                      attributeids.NodeClass, context)
            display_name = get_attribute(client, expanded_node_id,
                                         attributeids.DisplayName, context)
            browse_name = get_attribute(client, expanded_node_id,
                                        attributeids.BrowseName, context)

            if nodeclass == nodeclasses.Object:
                opcua_attributes = {
                    'NodeId': stringified_id,
                    'BrowseName': browse_name,
                    'DisplayName': display_name
                }
                document.append(
                    nodeset_xml.make_element_for_uaobject(
                        stringified_id, opcua_attributes, references, parent,
                        refTypeFromParent))

            elif nodeclass == nodeclasses.Variable:
                data_type = get_attribute(client, expanded_node_id,
                                          attributeids.DataType, context)
                access_level = get_attribute(client, expanded_node_id,
                                             attributeids.AccessLevel, context)
                opcua_attributes = {
                    'NodeId': stringified_id,
                    'BrowseName': browse_name,
                    'DisplayName': display_name,
                    'DataType': data_type,
                    'AccessLevel': access_level
                }
                document.append(
                    nodeset_xml.make_element_for_uavariable(
                        stringified_id, opcua_attributes, references, parent,
                        refTypeFromParent))

            elif nodeclass == nodeclasses.Method:
                executable = get_attribute(client, expanded_node_id,
                                           attributeids.Executable, context)
                opcua_attributes = {
                    'NodeId': stringified_id,
                    'BrowseName': browse_name,
                    'DisplayName': display_name,
                    'Executable': executable
                }
                document.append(
                    nodeset_xml.make_element_for_uamethod(
                        stringified_id, opcua_attributes, references, parent,
                        refTypeFromParent))

            else:
                print 'nodeclass not supported'
                context['errors'] += 1
            added_nodes.append(stringified_id)

    for ref_i in xrange(0, len(references)):
        target = references[ref_i]
        print target
        #pdb.set_trace()
        if target.nodeId.nodeId().nameSpaceIndex(
        ) != constants.OPCUA_NAMESPACE_ID:
            recurse(client, target.nodeId, document, expanded_node_id,
                    target.referenceTypeId, context)
        else:
            print 'Note: skipping this because both source and target are in the namespace 0 (probably coming from the UA standard). '
コード例 #23
0
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(
コード例 #24
0
ファイル: client_monitorevents.py プロジェクト: juhuawong/uaf
    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?)"
            )
コード例 #25
0
# 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
コード例 #26
0
def addr(sa):
    return Address(NodeId(sa, server_ns), server_uri)
コード例 #27
0
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)
コード例 #28
0
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)
コード例 #29
0
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
コード例 #30
0
myClient = Client(ClientSettings("myClient", ["opc.tcp://localhost:48010"]))

# The client now discovers the "opc.tcp://localhost:48010", and fetches the application description
# of the UaServerCpp demo server.
# Let's print out what the client discovered:
listOfApplicationDescriptions = myClient.serversFound()
print(listOfApplicationDescriptions)

# It's a list of one server description (the demo server). It tells us the application URI, or in
# this case, the server uri:
SERVER_URI = listOfApplicationDescriptions[0].applicationUri

# Okay now that we know the server URI of the demo server, we can connect to it.
# We'll just dynamically browse the address space, and let the UAF do the connection for us:

rootNode = Address(NodeId(opcuaidentifiers.OpcUaId_RootFolder, 0), SERVER_URI)
firstLevelBrowseResult = myClient.browse([rootNode])
print("BROWSE RESULT:")
print(firstLevelBrowseResult)

# Note that the 0 is the namespace index for the OPC UA standard. It always corresponds to the
# OPC UA standard URI 'http://opcfoundation.org/UA/'
# Instead of the above, we therefore could have also specified the namespace URI:
#rootNode = Address(NodeId(opcuaidentifiers.OpcUaId_RootFolder,
#                          'http://opcfoundation.org/UA/'),
#                   SERVER_URI)
# It woulnd't make a difference, as the UAF will automatically "translate" the namespace URI
# 'http://opcfoundation.org/UA/' to the namespace index 0 for you.
# The mapping between namespace URIs and namespace indexes is called the NamespaceArray.
# Let's print this mapping:
result = myClient.read(