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
Example #2
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)
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!)
    # (notice too that you can optionally provide a BrowseConfig and a SessionConfig for
    #  more detailed configuration)
    firstLevelBrowseResult = myClient.browse([rootNode])

    # print the result
# 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/'

# make sure the above directories are created
clientSettings.createSecurityLocations()

# create the client
myClient = Client(clientSettings)

print("")
print(
    "==========================================================================================="
)
print("STEP 3: Store the client certificate and private key")
print(
    "==========================================================================================="
)
print("")

# store the certificate
result = certificate.toDERFile(clientSettings.clientCertificate)
if result == -1:
    raise Exception("Could not save the client certificate!")
    logDetailsString = ""
    logDetailsString += time.strftime("%a, %d %b %Y %H:%M:%S",
                                      time.localtime(msg.ctime))
    logDetailsString += ".%.3d " % msg.msec
    logDetailsString += "%-10s " % msg.applicationName
    logDetailsString += "%-20s " % msg.loggerName
    logDetailsString += "%-8s " % loglevels.toString(msg.level)
    # msg.message may contain multiple lines, so we prepend the other logging details in
    # front of each line:
    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)
Example #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
# 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)
#     every 20 seconds (configurable, see above) the URLs you provided, and keep an inventory of all discovered 
#     endpoints. If at some point the UAF thinks it's necessary to connect to one of these servers (e.g. because
#     you want to read a variable on a particular server), it will automatically create the necessary session
#     for you. 
#  -> Bottomline: just provide the discovery URLs to the UAF, and afterwards you can directly start
#     reading data or monitoring events or calling methods or whatever. No need to manage connections yourself! 
#  -> All OPC UA servers have such a Discovery endpoint, but additionally there are also "dedicated" discovery servers
#     that do nothing more than provide endpoints to other servers. Most people will never have to deal with such a 
#     server, however. 
#  -> In the (advanced!) scenario where a hierarchy of dedicated discovery servers is used, you only need to specify
#     the top discovery server. The UAF will automatically discover the discovery servers that are lower in the 
#     hierarchy.


# create the client
myClient = Client(myClientSettings)



print("")
print("################################################################################################################")
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)
Example #9
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 ])
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)