示例#1
0
    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)
示例#2
0
 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 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
示例#4
0
def connect(endpoint, server_uri):
    client_settings = ClientSettings("pnikiel:dump", [endpoint])
    client = Client(client_settings)
    connectionId = client.manuallyConnect(server_uri)
    sessionInfo = client.sessionInformation(connectionId)
    if sessionInfo.sessionState != pyuaf.client.sessionstates.Connected:
        raise Exception('Couldnt connect! TODO: reason')
    print 'Connected to ' + endpoint
    return (client, connectionId)
      - or simply a string (the name of the client)
      - or None (so default pyuaf.client.settings.ClientSettings() are used).
  - 'loggingCallback': optional: a callback function to catch log messages of type pyuaf.util.LogMessage.

See the PyUAF HTML documentation for more info.
"""

import time, os

import pyuaf
from pyuaf.client import Client
from pyuaf.client.settings import ClientSettings
from pyuaf.util import loglevels, Address, NodeId

# we can create some ClientSettings:
settings = ClientSettings()
settings.applicationName = "MyClient"
settings.discoveryUrls.append("opc.tcp://localhost:4841")
settings.logToStdOutLevel = loglevels.Info  # print Info, Warning and Error logging to the console
settings.logToCallbackLevel = loglevels.Debug  # send Debug, Info, Warning and Error logging to the callback

# And if you want to catch the logging output, you may also define a callback.
# In this case we define a callback to write the logging output to a file in the user's home directory.
# (but this callback is optional of course, only define one if you want to do something more with the
#  logging output than simply printing it to the console (i.e. sending it to the stdout))
f = open(os.path.expanduser("~/my_logging_output.txt"), "w")


def callback(msg):
    logDetailsString = ""
    logDetailsString += time.strftime("%a, %d %b %Y %H:%M:%S",
示例#6
0
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
示例#7
0
# Define the namespace URI and server URI of the UaServerCpp demo server
demoNsUri = "http://www.unifiedautomation.com/DemoServer"
demoServerUri = "urn:UnifiedAutomation:UaServerCpp"

print("")
print(
    "################################################################################################################"
)
print("Step 2: Configure and create the client")
print(
    "################################################################################################################"
)
print("")

# Define the ClientSettings:
settings = ClientSettings()
settings.applicationName = "MyClient"
settings.discoveryIntervalSec = 20.0  # try to re-discover the servers in the network every 20 seconds
# ... many more settings
settings.discoveryUrls.append("opc.tcp://localhost:48010")
# ... append as many Discovery URLs as you want.
#
# FYI: what are Discovery URLs?
#  -> A Discovery URL is the URL of a so-called "Discovery Endpoint".
#  -> Clients can use this Discovery Endpoint to learn ("discover") how they can connect to the server, by
#     learning the other endpoints of the server. For example, a server may expose (besides a Discovery Endpoint)
#     an unsecured endpoint and a secured one. The client can then choose to connect to the server via one
#     of these endpoints, and start reading/writing/monitoring/... data.
#  -> Discovery URLs are often of the form opc.tcp://<someIpAddressOrHostname>:4840 or :4841
#  -> The UAF makes it easy for you to deal with discovery: just specify the discovery URLs of the servers you may
#     want to use later on, and specify your favorite way of connecting to a server (e.g. without security). The UAF
# 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)
print("Step 1: Define some useful constants")
print("################################################################################################################")
print("")

# Define the namespace URI and server URI of the UaServerCpp demo server
demoNsUri     = "http://www.unifiedautomation.com/DemoServer"
demoServerUri = "urn:UnifiedAutomation:UaServerCpp"

print("")
print("################################################################################################################")
print("Step 2: Configure and create the client")
print("################################################################################################################")
print("")

# Define the ClientSettings:
settings = ClientSettings()
settings.applicationName = "MyClient"
settings.discoveryIntervalSec = 20.0 # try to re-discover the servers in the network every 20 seconds
# ... many more settings
settings.discoveryUrls.append("opc.tcp://localhost:48010")
# ... append as many Discovery URLs as you want. 
#
# FYI: what are Discovery URLs?
#  -> A Discovery URL is the URL of a so-called "Discovery Endpoint".
#  -> Clients can use this Discovery Endpoint to learn ("discover") how they can connect to the server, by
#     learning the other endpoints of the server. For example, a server may expose (besides a Discovery Endpoint)
#     an unsecured endpoint and a secured one. The client can then choose to connect to the server via one
#     of these endpoints, and start reading/writing/monitoring/... data.
#  -> Discovery URLs are often of the form opc.tcp://<someIpAddressOrHostname>:4840 or :4841
#  -> The UAF makes it easy for you to deal with discovery: just specify the discovery URLs of the servers you may
#     want to use later on, and specify your favorite way of connecting to a server (e.g. without security). The UAF
示例#10
0
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 ])
                             issuerPrivateKey)

# note: we will store the certificate and private key in STEP 3

print("")
print(
    "==========================================================================================="
)
print("STEP 2: Create a Client instance")
print(
    "==========================================================================================="
)
print("")

# define the clientSettings
clientSettings = ClientSettings()
clientSettings.applicationName = "MyClient"
clientSettings.applicationUri = info.uri  # Certificate info URI and application URI must be the same !!!
#clientSettings.logToStdOutLevel = pyuaf.util.loglevels.Debug # uncomment if needed
clientSettings.discoveryUrls.append(DISCOVERY_URL)

# We configure the PKI folder structure (set the PKI_FOLDER to 'PKI' and you get the defaults).
# Note that paths must ALWAYS be specified using '/', also on Windows!
# You cannot use os.path.join or similar, since these will introduce platform-dependent separators!
clientSettings.clientCertificate = PKI_FOLDER + '/client/certs/client.der'
clientSettings.clientPrivateKey = PKI_FOLDER + '/client/private/client.pem'
clientSettings.certificateTrustListLocation = PKI_FOLDER + '/trusted/certs/'
clientSettings.certificateRevocationListLocation = PKI_FOLDER + '/trusted/crl/'
clientSettings.issuersCertificatesLocation = PKI_FOLDER + '/issuers/certs/'
clientSettings.issuersRevocationListLocation = PKI_FOLDER + '/issuers/crl/'
示例#12
0
      - or simply a string (the name of the client)
      - or None (so default pyuaf.client.settings.ClientSettings() are used).
  - 'loggingCallback': optional: a callback function to catch log messages of type pyuaf.util.LogMessage.

See the PyUAF HTML documentation for more info.
"""

import time, os

import pyuaf
from pyuaf.client          import Client
from pyuaf.client.settings import ClientSettings
from pyuaf.util            import loglevels, Address, NodeId

# we can create some ClientSettings:
settings = ClientSettings()
settings.applicationName = "MyClient"
settings.discoveryUrls.append("opc.tcp://localhost:4841")
settings.logToStdOutLevel   = loglevels.Info   # print Info, Warning and Error logging to the console 
settings.logToCallbackLevel = loglevels.Debug  # send Debug, Info, Warning and Error logging to the callback

# And if you want to catch the logging output, you may also define a callback.
# In this case we define a callback to write the logging output to a file in the user's home directory.
# (but this callback is optional of course, only define one if you want to do something more with the
#  logging output than simply printing it to the console (i.e. sending it to the stdout))
f = open(os.path.expanduser("~/my_logging_output.txt"), "w")
def callback(msg):
    logDetailsString = ""
    logDetailsString += time.strftime("%a, %d %b %Y %H:%M:%S", time.localtime(msg.ctime))
    logDetailsString += ".%.3d " %msg.msec
    logDetailsString += "%-10s " %msg.applicationName
"""
Example: how to setup logging for a client
====================================================================================================

See the HTML documentation of PyUAF for more info!
""" 
import pyuaf
from pyuaf.util            import loglevels
from pyuaf.client          import Client
from pyuaf.client.settings import ClientSettings
from pyuaf.util            import Address, NodeId

# create a client that
#  - logs everything to the standard out ("stdout", i.e. the Windows DOS Prompt or the Linux shell)
#  - only logs warnings and errors to an external callback function
settings = ClientSettings()
settings.discoveryUrls.append("opc.tcp://localhost:4841")
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))
from pyuaf.util import Address, NodeId
from pyuaf.util.primitives import UInt32, Boolean
from pyuaf.client import Client
from pyuaf.client.settings  import ClientSettings, SessionSettings, SubscriptionSettings, \
                                   ReadSettings

# Some constants needed during the rest of this example:
NAMESPACE_URI = "http://www.unifiedautomation.com/DemoServer"
SERVER_URI = "urn:UnifiedAutomation:UaServerCpp"

# ==================================================================================================
# 1) Setting the defaults
# ==================================================================================================

# using ClientSettings, you can configure all default session/subscription and service settings:
clientSettings = ClientSettings()

# first configure some general client settings:
clientSettings.applicationName = "MyClient"
clientSettings.discoveryUrls.append("opc.tcp://localhost:48010")
# etc. ...

# now configure the default session settings:
clientSettings.defaultSessionSettings.sessionTimeoutSec = 100.0
clientSettings.defaultSessionSettings.connectTimeoutSec = 2.0
# etc. ...

# now configure the default subscription settings:
clientSettings.defaultSubscriptionSettings.publishingIntervalSec = 0.5
clientSettings.defaultSubscriptionSettings.lifeTimeCount = 600
# etc. ...
from pyuaf.util.primitives  import UInt32, Boolean
from pyuaf.client           import Client
from pyuaf.client.settings  import ClientSettings, SessionSettings, SubscriptionSettings, \
                                   ReadSettings


# Some constants needed during the rest of this example:
NAMESPACE_URI = "http://www.unifiedautomation.com/DemoServer"
SERVER_URI = "urn:UnifiedAutomation:UaServerCpp"

# ==================================================================================================
# 1) Setting the defaults
# ==================================================================================================

# using ClientSettings, you can configure all default session/subscription and service settings:
clientSettings = ClientSettings()

# first configure some general client settings:
clientSettings.applicationName = "MyClient";
clientSettings.discoveryUrls.append("opc.tcp://localhost:48010")
# etc. ...

# now configure the default session settings:
clientSettings.defaultSessionSettings.sessionTimeoutSec = 100.0
clientSettings.defaultSessionSettings.connectTimeoutSec = 2.0
# etc. ...

# now configure the default subscription settings:
clientSettings.defaultSubscriptionSettings.publishingIntervalSec = 0.5
clientSettings.defaultSubscriptionSettings.lifeTimeCount         = 600
# etc. ...
示例#16
0
    status = readResult.targets[3].status                         # 'status' has type pyuaf.util.Status
    data   = readResult.targets[3].data                           # 'data' has type pyuaf.util.LocalizedText
    if status.isGood() and isinstance(data, LocalizedText):
        print("The locale is: '%s', the text is: '%s'" %(data.locale(), data.text()))
    
    # target 4:
    status = readResult.targets[4].status                         # 'status' has type pyuaf.util.Status
    data   = readResult.targets[4].data                           # 'data' is a list of pyuaf.util.primitives.SByte
    if status.isGood() and isinstance(data, list):
        print("The array is:")
        for i in xrange(len(data)):
            print(" - array[%d] = %d" %(i, data[i].value))


# define the ClientSettings:
settings = ClientSettings()
settings.applicationName = "MyClient"
settings.discoveryUrls.append("opc.tcp://localhost:4841")

# create the client
myClient = Client(settings)



# read the node attributes all at once
try:
    print("")
    print("First option: use the convenience function \"read()\"")
    print("===================================================")
    
    # OPTIONAL: You could also provide a ReadConfig to configure a call timeout, 
info.eMail = "*****@*****.**"
info.validTime = 60 * 60 * 24 * 365 * 5  # 5 years

certificate = PkiCertificate(info, identity, subjectPublicKey, identity, issuerPrivateKey)

# note: we will store the certificate and private key in STEP 3

print("")
print("===========================================================================================")
print("STEP 2: Create a Client instance")
print("===========================================================================================")
print("")


# define the clientSettings
clientSettings = ClientSettings()
clientSettings.applicationName = "MyClient"
clientSettings.applicationUri = info.uri  # Certificate info URI and application URI must be the same !!!
# clientSettings.logToStdOutLevel = pyuaf.util.loglevels.Debug # uncomment if needed
clientSettings.discoveryUrls.append(DISCOVERY_URL)

# We configure the PKI folder structure (set the PKI_FOLDER to 'PKI' and you get the defaults).
# Note that paths must ALWAYS be specified using '/', also on Windows!
# You cannot use os.path.join or similar, since these will introduce platform-dependent separators!
clientSettings.clientCertificate = PKI_FOLDER + "/client/certs/client.der"
clientSettings.clientPrivateKey = PKI_FOLDER + "/client/private/client.pem"
clientSettings.certificateTrustListLocation = PKI_FOLDER + "/trusted/certs/"
clientSettings.certificateRevocationListLocation = PKI_FOLDER + "/trusted/crl/"
clientSettings.issuersCertificatesLocation = PKI_FOLDER + "/issuers/certs/"
clientSettings.issuersRevocationListLocation = PKI_FOLDER + "/issuers/crl/"
示例#18
0
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
    # (notice that there is also an argument called 'maxAutoBrowseNext', which we don't mention
    #  here because we can leave it at the default value (100), to make sure that BrowseNext is
    # automatically being called for us as much as needed!)
"""
Example: how to setup logging for a client
====================================================================================================

See the HTML documentation of PyUAF for more info!
"""
import pyuaf
from pyuaf.util import loglevels
from pyuaf.client import Client
from pyuaf.client.settings import ClientSettings
from pyuaf.util import Address, NodeId

# create a client that
#  - logs everything to the standard out ("stdout", i.e. the Windows DOS Prompt or the Linux shell)
#  - only logs warnings and errors to an external callback function
settings = ClientSettings()
settings.discoveryUrls.append("opc.tcp://localhost:4841")
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))