Ejemplo n.º 1
0
def connect_to_plc(indirizzo):
    client = Client(indirizzo)
    return client
 def __init__(self, endpoint):
     self.client = Client(endpoint)
from time import sleep
import json
from datetime import datetime

from opcua import Client
from opcua import ua

from elasticsearch import Elasticsearch
from elasticsearch import helpers
import os

es = Elasticsearch(http_auth=('elastic', 'changeme'))

client = Client("opc.tcp://10.101.100.39:4840")

parent_names = {
    'energy': 'ns=3;s="Data_From_Energy_PLC_DB"."DS142"',
    'fishtank': 'ns=3;s="Data_From_Fish_PLC_DB".Static',
    'security': 'ns=3;s="Data_From_Security_DB".Static'
}

connected = False

while True:
    try:
        client.connect()
        connected = True

        parents = {}
        data = {}
        for name in parent_names:
    Do not do expensive, slow or network operation there. Create another 
    thread if you need to do such a thing
    """
    def datachange_notification(self, node, val, data):
        print("Python: New data change event", node, val)

    def event_notification(self, event):
        print("Python: New event", event)


if __name__ == "__main__":
    logging.basicConfig(level=logging.WARN)
    #logger = logging.getLogger("KeepAlive")
    #logger.setLevel(logging.DEBUG)

    client = Client("opc.tcp://*****:*****@localhost:4840/freeopcua/server/") #connect using a user
    try:
        client.connect()
        client.load_type_definitions(
        )  # load definition of server specific structures/extension objects

        # Client has a few methods to get proxy to UA nodes that should always be in address space such as Root or Objects
        root = client.get_root_node()
        print("Root node is: ", root)
        objects = client.get_objects_node()
        print("Objects node is: ", objects)

        # Node objects have methods to read and write node attributes as well as browse or populate address space
        print("Children of root are: ", root.get_children())
Ejemplo n.º 5
0
    def __init__(self, gateway, config, connector_type):
        self._connector_type = connector_type
        self.statistics = {'MessagesReceived': 0, 'MessagesSent': 0}
        super().__init__()
        self.__gateway = gateway
        self.__server_conf = config.get("server")
        self.__interest_nodes = []
        self.__available_object_resources = {}
        self.__show_map = self.__server_conf.get("showMap", False)
        self.__previous_scan_time = 0
        for mapping in self.__server_conf["mapping"]:
            if mapping.get("deviceNodePattern") is not None:
                self.__interest_nodes.append(
                    {mapping["deviceNodePattern"]: mapping})
            else:
                log.error(
                    "deviceNodePattern in mapping: %s - not found, add property deviceNodePattern to processing this mapping",
                    dumps(mapping))
        if "opc.tcp" not in self.__server_conf.get("url"):
            self.__opcua_url = "opc.tcp://" + self.__server_conf.get("url")
        else:
            self.__opcua_url = self.__server_conf.get("url")
        self.client = Client(
            self.__opcua_url,
            timeout=self.__server_conf.get("timeoutInMillis", 4000) / 1000)
        if self.__server_conf["identity"].get("type") == "cert.PEM":
            try:
                ca_cert = self.__server_conf["identity"].get("caCert")
                private_key = self.__server_conf["identity"].get("privateKey")
                cert = self.__server_conf["identity"].get("cert")
                security_mode = self.__server_conf["identity"].get(
                    "mode", "SignAndEncrypt")
                policy = self.__server_conf["security"]
                if cert is None or private_key is None:
                    log.exception(
                        "Error in ssl configuration - cert or privateKey parameter not found"
                    )
                    raise RuntimeError(
                        "Error in ssl configuration - cert or privateKey parameter not found"
                    )
                security_string = policy + ',' + security_mode + ',' + cert + ',' + private_key
                if ca_cert is not None:
                    security_string = security_string + ',' + ca_cert
                self.client.set_security_string(security_string)

            except Exception as e:
                log.exception(e)
        if self.__server_conf["identity"].get("username"):
            self.client.set_user(
                self.__server_conf["identity"].get("username"))
            if self.__server_conf["identity"].get("password"):
                self.client.set_password(
                    self.__server_conf["identity"].get("password"))

        self.setName(
            self.__server_conf.get(
                "name", 'OPC-UA ' +
                ''.join(choice(ascii_lowercase)
                        for _ in range(5))) + " Connector")
        self.__opcua_nodes = {}
        self._subscribed = {}
        self.__sub = None
        self.__sub_handler = SubHandler(self)
        self.data_to_send = []
        self.__stopped = False
        self.__connected = False
        self.daemon = True
Ejemplo n.º 6
0
    def setUp(self):
        WebGatewayTestCase.setUp(self)

        self.opcua_client = Client(self.OPC_SERVER_URL)
        self.opcua_client.connect()
 def test_nocrypto_feil(self):
     clt = Client(self.uri_no_crypto)
     with self.assertRaises(ua.UaError):
         clt.set_security_string(
             "Basic256,Sign,examples/certificate-example.der,examples/private-key-example.pem"
         )
Ejemplo n.º 8
0
    Abonnement-Handler. Um Ereignisse vom Server für ein Abonnement zu erhalten
    Die Methoden data_change und event werden direkt vom empfangenden Thread aufgerufen.
    """
    def datachange_notification(self, node, val, data):
        print("Python: New data change event", node, val)

    def event_notification(self, event):
        print("Python: New event", event)


if __name__ == "__main__":
    logging.basicConfig(level=logging.WARN)
    #logger = logging.getLogger("KeepAlive")
    #logger.setLevel(logging.DEBUG)

    client = Client("opc.tcp://192.168.1.112:50840/freeopcua/server/")
    # client = Client("opc.tcp://admin@localhost:4840/freeopcua/server/") #connect using a user
    try:
        client.connect()
        client.load_type_definitions(
        )  # Ladet Definition von serverspezifischen Strukturen / Erweiterungsobjekten

        # Der Client verfügt über einige Methoden, um einen Proxy für UA-Knoten abzurufen,
        # die sich immer im Adressraum befinden sollten, z. B. Root oder Objects

        root = client.get_root_node()
        print("Root node is: ", root)
        objects = client.get_objects_node()
        print("Objects node is: ", objects)

        # Knotenobjekte verfügen über Methoden zum Lesen und Schreiben von Knotenattributen
Ejemplo n.º 9
0
# encoding=utf-8

import sys, time

sys.path.insert(0, "..")
from opcua import Client

if __name__ == "__main__":

    # client = Client("opc.tcp://127.0.0.1:4840")
    # client = Client("opc.tcp://127.0.0.1:4840/freeopcua/server/")
    client = Client("opc.tcp://127.0.0.1:7766")  #connect using a user
    try:
        res = client.connect()

        # Client has a few methods to get proxy to UA nodes that should always be in address space such as Root or Objects
        root = client.get_root_node()
        print("Objects node is: ", root)
        children = root.get_children()

        # Node objects have methods to read and write node attributes as well as browse or populate address space
        print("Children of root are: ", root.get_children())

        # get a specific node knowing its node id
        # var = client.get_node(ua.NodeId(1002, 2))
        # var = client.get_node("ns=3;i=2002")
        # print(var)
        # var.get_data_value() # get value of node as a DataValue object
        # var.get_value() # get value of node as a python builtin
        # var.set_value(ua.Variant([23], ua.VariantType.Int64)) #set node value using explicit data type
        # var.set_value(3.9) # set node value using implicit data type
Ejemplo n.º 10
0
    thread if you need to do such a thing
    """
    def datachange_notification(self, node, val, var):
        print("Python: New data change event", node, val)

    def event_notification(self, event):
        print("Python: New event", event)


if __name__ == "__main__":
    time.sleep(1)  # Time must be set here, so you can run server first
    logging.basicConfig(level=logging.WARN)
    # logger = logging.getLogger("KeepAlive")
    # logger.setLevel(logging.DEBUG)

    client = Client("opc.tcp://*****:*****@localhost:4840/freeopcua/server/") #connect using a user
    try:
        client.connect()

        ns = client.get_namespace_array()
        uax = str(ns.index("http://opcfoundation.org/UA/"))
        dix = str(ns.index("http://opcfoundation.org/UA/DI/"))
        fdix = str(ns.index("http://fdi-cooperation.com/OPCUA/FDI5/"))
        i4ox = str(ns.index("http://juandavid.univalle/i4o/"))
        m1x = str(ns.index("http://juandavid.univalle/i4o/Mixer1/"))
        m2x = str(ns.index("http://juandavid.univalle/i4o/Mixer2/"))

        # Get a specific node knowing its node id
        st_actions = client.get_node("ns=" + i4ox + ";s=D.ST.O.ActionSet")
        mx1_actions = client.get_node("ns=" + m1x + ";s=D.Mx1.O.ActionSet")
Ejemplo n.º 11
0
    parser.add_argument(
        '--path',
        type=str,
        help='path for storing tool data. Default is in ./tools',
        default="./tools")

    args = parser.parse_args()

    if args.verbose:
        logger.setLevel(level=logging.DEBUG)

    try:
        url = re.sub(r"\/\/",
                     "//" + args.opcua_user + ":" + args.opcua_password + "@",
                     args.opcua_connection)
        opcua_client = Client(url)  #connect using a user
        opcua_client.connect()
        logger.info('Successfully connceted to OPC UA server: %s',
                    [args.opcua_connection])
    except Exception as e:
        logger.error('Failed connecting to OPC UA server: %s',
                     [args.opcua_connection])
        logger.debug(traceback.format_exc())
        sys.exit(str(e))

    try:
        #get max number of tools
        TnumWZV = opcua_client.get_node(ua.NodeId("/Tool/Catalogue/TnumWZV",
                                                  2)).get_value()
        logger.info('Number of available tools: {}'.format(TnumWZV))
        numCuttEdgeParams = args.numCuttEdgeParams
Ejemplo n.º 12
0
class SubHandler(object):
    """
    Client to subscription. It will receive events from server
    """
    def datachange_notification(self, node, val, data):
        print("Python: New data change event", node, val)

    def event_notification(self, event):
        print("Python: New event", event)


if __name__ == "__main__":
    #from IPython import embed
    logging.basicConfig(level=logging.WARN)
    client = Client("opc.tcp://192.168.56.100:49320/OPCUA/SimulationServer/")
    #client = Client("opc.tcp://192.168.56.100:4840/OPCUA/SimulationServer/")
    #client = Client("opc.tcp://*****:*****@localhost:53530/OPCUA/SimulationServer/")
    try:
        client.connect()
        root = client.get_root_node()
        print("Root is", root)
        print("childs of root are: ", root.get_children())
        print("name of root is", root.get_browse_name())
        objects = client.get_objects_node()
        print("childs og objects are: ", objects.get_children())

        tag1 = client.get_node("ns=2;s=Channel1.Device1.Tag1")
        print("tag1 is: {0} with value {1} ".format(tag1, tag1.get_value()))
        tag2 = client.get_node("ns=2;s=Channel1.Device1.Tag2")
        print("tag2 is: {0} with value {1} ".format(tag2, tag2.get_value()))
Ejemplo n.º 13
0
 def test_get_endpointr(self):
     client = Client("opc.tcp://" + os.environ['TEST_IP'] + ":" + os.environ['TEST_PORT'])
     client.connect()
     endpoints = client.get_endpoints()
     self.assertEqual(len(endpoints), 4)
     client.disconnect()
Ejemplo n.º 14
0
 def __init__(self, address):
     print "initializing OPC UA Client"
     client = Client(address)
     self.client = client
Ejemplo n.º 15
0
def run():
    logger.debug("Modular Input mi_opcua_event command: %s" % sys.argv)
    if len(sys.argv) > 1:
        try:
            if sys.argv[1] == "--scheme":
                do_scheme()
            elif sys.argv[1] == "--validate-arguments":
                validate_arguments()
            elif sys.argv[1] == "--test":
                test()
            else:
                usage()
        except Exception as ex:
            logger.critical(ex)
    else:
        logger.debug("Modular Input mi_opcua_event Starts data collection.")
        
        configs = get_config()
        logger.debug("Configuration: %s" % configs)
        stanza = configs["name"]
        # server_uri = configs["server_uri"]
        # sessionKey = configs["session_key"]
        # userName = "******"   # make this modular input as application context only.

        """
        wevts = configs["events"].strip()
        if len(wevts) <= 0:
            wevts = ["Objects", "Server"]
        else:
            wevts = wevts.split(":")
            
        patterns = configs["event_types"].strip()
        if len(patterns) <= 0:
            patterns = ["*"]
        else:
            patterns = patterns.split(":")
        """
            
        tout = configs["connection_timeout"].strip()
        timeout = 1 if len(tout) <= 0 else int(tout)

        cdur = configs["collect_duration"].strip()
        duration = 1000 if len(cdur) <= 0 else int(cdur)
        
        conn = configs["connection"]   ## "opc.tcp://ec2-54-190-162-94.us-west-2.compute.amazonaws.com:49320"
        if configs.has_key("username"):
            username = configs["username"].strip()
            if len(username)>0:
                password = configs["password"].strip()
                conn = "%s?username=%s&password=%s" % (conn, username, password)
    
        client = Client(conn, timeout=timeout)
        
        try:
            client.connect()
            #root = client.get_root_node()
            #m = node.get_child(root, wevts)
            #measures = []
            #node.collect_measures(measures, wevts, root)
                    
            handler = SubHandler(stanza)
            sub = client.create_subscription(duration, handler)
            h = sub.subscribe_events()
        
            """
            handles = []
            
            for evt in measures:
                try:
                    h = sub.subscribe_events(evt[len(evt)-1])
                    handles.append(h)
                except Exception as ex:
                    logger.warn(ex)
            """    
       
            def signal_handler(signal, frame):
                logger.info('Press Ctrl+C')
                
                if signal in [signal.SIGABRT, signal.SIGINT, signal.SIGQUIT, signal.SIGTERM]:
                    #[sub.unsubscribe(h) for h in handles]
                    sub.unsubscribe(h)
                    sub.delete()
                    client.disconnect()

            signal.signal(signal.SIGINT, signal_handler)
            signal.signal(signal.SIGABRT, signal_handler)
            signal.signal(signal.SIGTERM, signal_handler)
#            signal.signal(signal.SIGQUIT, signal_handler)

#            signal.pause()
                            
        except Exception as ex:
            logger.critical(ex)
        finally:
            logger.info("---- end of sub opc ua event ----")
Ejemplo n.º 16
0
from IPython import embed
from opcua import Client


class SubHandler(object):
    def datachange_notification(self, node, val, data):
        print("Python: New data change event:{}".format(val))


if __name__ == "__main__":
    server_url = "opc.tcp://10.6.0.75:4840"
    client = Client(server_url)  #连接服务器

    # try:
    client.connect()
    root = client.get_root_node()  #获取根节点
    # obj2 = root.get_children()    #获取所有节点列表
    struct = client.get_node("ns=2;i=2")
    struct_array = client.get_node("ns=2;i=3")
    print("struct:{}".format(struct))
    print("struct_array:{}".format(struct_array))
    msclt_tss = SubHandler()  #订阅信息回调类

    before = struct.get_value()
    before_array = struct_array.get_value()
    print("before:{}".format(before))
    print("before_array:{}".format(before_array))

    #订阅节点
    handler = SubHandler()
    sub = client.create_subscription(500, handler)
    Do not do expensive, slow or network operation there. Create another
    thread if you need to do such a thing
    """
    def datachange_notification(self, node, val, data):
        print("Python: New data change event", node, val)

    def event_notification(self, event):
        print("Python: New event", event)


if __name__ == "__main__":
    logging.basicConfig(level=logging.WARN)
    #logger = logging.getLogger("KeepAlive")
    # logger.setLevel(logging.DEBUG)

    client = Client("opc.tcp://localhost:4840")
    uasecurity = UaSecurity()
    if uasecurity.get_securitytype() == 'tls':
        server_cert, client_cert, private_key = uasecurity.get_certificates()
        if server_cert is None:
            print(
                'tls is enabled, but server cert is missing with current configuration'
            )
            sys.exit(-1)
        if private_key is None:
            print(
                'tls is enabled, but private key is missing with current configuration'
            )
            sys.exit(-1)
        client.load_client_certificate(server_cert)
        client.load_private_key(private_key)
            nodeConvBelt_mgate.set_value(False)



    def event_notification(self, event):
        print("Python: New event", event)


if __name__ == "__main__":
    logging.basicConfig(level=logging.WARN)
    #logger = logging.getLogger("KeepAlive")
    #logger.setLevel(logging.DEBUG)

    #Set according to the OPC UA network
    #client = Client("opc.tcp://127.0.0.1:12686/AI4.0-Ontology-Example")
    client = Client("opc.tcp://192.168.1.7:12686/AI4.0-Ontology-Example")
    try:
        client.connect()
        client.load_type_definitions()  # load definition of server specific structures/extension objects

        # Client has a few methods to get proxy to UA nodes that should always be in address space such as Root or Objects
        root = client.get_root_node()
        print("Root node is: ", root)
        objects = client.get_objects_node()
        print("Objects node is: ", objects)

        # Node objects have methods to read and write node attributes as well as browse or populate address space
        print("Children of root are: ", root.get_children())

        ###States
        state0Node = client.get_node("ns=2;s=A-I4.0-Ontology/Metal-Separation-Process/States/State 0")
Ejemplo n.º 19
0
from opcua import Client
import py
import time
import pytest
import Tags
import OPC as server

#///////////////////Initialize///////////////////
calibTag_struct = Tags.CalibTags
tag_struct = Tags.TestTags
varpath = Tags.Testpath

client = Client("opc.tcp://DESKTOP-G25O981:4840")

delay_time = 0.05

#///////////////////////////////////////////////////
"""
TAGS tag_struct

                  "AnalogSignal",    #0
                  "ScaledValue" ,    #1 
                  "UpperLimitWarn" , #2 
                  "LowerLimitWarn"   #3  
                 
CALIB calibTag_struct
                 
                 'Gain'       :  0.076 ,  #0 
                 'UpperLimit' :  40 ,      #1 
                 'LowerLimit' :  10        #2 
Ejemplo n.º 20
0
from opcua import Client

path = "opc.tcp://192.168.10.141:49320/OPCUA/Kepware.KEPServerEX.V5/"
client = Client(path)
#client.server_url = "POWERTOWER", path

client.connect()
print(client.get_namespace_array())
print("Server node = " + str(client.get_server_node()) + "\n")
objects = client.get_objects_node()
print("Objects: " + str(objects))
print("Children of objects are: ", objects.get_children())

var = objects.get_child(["3:Channel1.Device1", "tag1"])
print(var)
print("Value of variable is: ", str(var.get_value()))
print(client.get_node(2))

client.disconnect()
"""
Children of objects are:  [Node(FourByteNodeId(i=2253)), Node(StringNodeId(ns=2;s=_AdvancedTags)), 
Node(StringNodeId(ns=2;s=_CustomAlarms)), Node(StringNodeId(ns=2;s=_DataLogger)), Node(StringNodeId(ns=2;s=_OracleConnector)), 
Node(StringNodeId(ns=2;s=_Redundancy)), Node(StringNodeId(ns=2;s=_SNMP Agent)), Node(StringNodeId(ns=2;s=_System)), 
Node(StringNodeId(ns=2;s=Channel1))]

"""
Ejemplo n.º 21
0
 def connect(self, uri):
     self.disconnect()
     print("Connecting to ", uri)
     self.client = Client(uri)
     self.client.connect()
     self._connected = True
Ejemplo n.º 22
0
import sys
sys.path.insert(0, "..")
import logging

from IPython import embed

from opcua import Client

if __name__ == "__main__":
    logging.basicConfig(level=logging.DEBUG)
    client = Client("opc.tcp://localhost:53530/OPCUA/SimulationServer/")
    client.set_security_string(
        "Basic256,Sign,certificate-example.der,private-key-example.pem")
    try:
        client.connect()
        root = client.get_root_node()
        objects = client.get_objects_node()
        print("childs og objects are: ", objects.get_children())

        embed()
    finally:
        client.disconnect()
Ejemplo n.º 23
0
 def run(self):
     while not self.__connected:
         try:
             self.client.connect()
             try:
                 self.client.load_type_definitions()
             except Exception as e:
                 log.debug(e)
                 log.debug("Error on loading type definitions.")
             log.debug(self.client.get_namespace_array()[-1])
             log.debug(
                 self.client.get_namespace_index(
                     self.client.get_namespace_array()[-1]))
         except ConnectionRefusedError:
             log.error(
                 "Connection refused on connection to OPC-UA server with url %s",
                 self.__server_conf.get("url"))
             time.sleep(10)
         except OSError:
             log.error(
                 "Connection refused on connection to OPC-UA server with url %s",
                 self.__server_conf.get("url"))
             time.sleep(10)
         except Exception as e:
             log.debug("error on connection to OPC-UA server.")
             log.error(e)
             time.sleep(10)
         else:
             self.__connected = True
             log.info("OPC-UA connector %s connected to server %s",
                      self.get_name(), self.__server_conf.get("url"))
     self.__initialize_client()
     while not self.__stopped:
         try:
             time.sleep(.1)
             self.__check_connection()
             if not self.__connected and not self.__stopped:
                 self.client.connect()
                 self.__initialize_client()
                 log.info("Reconnected to the OPC-UA server - %s",
                          self.__server_conf.get("url"))
             elif not self.__stopped:
                 if self.__server_conf.get(
                         "disableSubscriptions", False
                 ) and time.time(
                 ) * 1000 - self.__previous_scan_time > self.__server_conf.get(
                         "scanPeriodInMillis", 60000):
                     self.scan_nodes_from_config()
                     self.__previous_scan_time = time.time() * 1000
                 # giusguerrini, 2020-09-24: Fix: flush event set and send all data to platform,
                 # so data_to_send doesn't grow indefinitely in case of more than one value change
                 # per cycle, and platform doesn't lose events.
                 # NOTE: possible performance improvement: use a map to store only one event per
                 # variable to reduce frequency of messages to platform.
                 while self.data_to_send:
                     self.__gateway.send_to_storage(self.get_name(),
                                                    self.data_to_send.pop())
             if self.__stopped:
                 self.close()
                 break
         except (KeyboardInterrupt, SystemExit):
             self.close()
             raise
         except FuturesTimeoutError:
             self.__check_connection()
         except Exception as e:
             log.error(
                 "Connection failed on connection to OPC-UA server with url %s",
                 self.__server_conf.get("url"))
             log.exception(e)
             self.client = Client(
                 self.__opcua_url,
                 timeout=self.__server_conf.get("timeoutInMillis", 4000) /
                 1000)
             self._subscribed = {}
             self.__available_object_resources = {}
             time.sleep(10)
Ejemplo n.º 24
0
 def __init__(self, serverUrl):
     self._logger = logging.getLogger(self.__class__.__name__)
     self._client = Client(serverUrl.geturl(), timeout=self.CONNECT_TIMEOUT)
Ejemplo n.º 25
0

from opcua import Client
import time


url = "opc.tcp://192.168.8.109:4840"
client = Client(url)
# client = Client("opc.tcp://admin@localhost:4840/freeopcua/server/") #connect using a user

client.connect()
print ("Client connected")

while True:
    # Client has a few methods to get proxy to UA nodes that should always be in address space such as Root or Objects
    Temp = client.get_node("ns=2; i=2")
    Temperatura = Temp.get_value()
    print(Temperatura)

    Press = client.get_node("ns=2; i=3")
    Presion = Press.get_value()
    print(Presion)

    TIME = client.get_node("ns=2; i=4")
    Time_value = TIME.get_value()
    print(Time_value)

    # get a specific node knowing its node id
    #var = client.get_node(ua.NodeId(1002, 2))
    #var = client.get_node("ns=3;i=2002")
    #print(var)
Ejemplo n.º 26
0
__author__ = 'tangjiashan'
import time
from opcua import ua, Client


class SubHandler(object):
    def data_change(self, handle, node, val, attr):
        print("Python: New data change event", handle, node, val, attr)


if __name__ == "__main__":
    # client = Client("opc.tcp://localhost:4881/ua/server/")
    client = Client("opc.tcp://10.9.192.199:4881/ua/server/", timeout=10)
    client.connect()

    root = client.get_root_node()

    # obj = root.get_child(["0:Objects", "0:SSRobot"])
    # res = obj.call_method("0:MovingStart", 2, 1)

    # obj = root.get_child(["0:Objects", "0:SSRobot"])
    # res = obj.call_method("0:WeldingStart", 2)

    # obj = root.get_child(["0:Objects", "0:MJGrooveRobot"])
    # res = obj.call_method("0:Start", 2, 2)

    # obj = root.get_child(["0:Objects", "0:MJMoveRobot"])
    # res = obj.call_method("0:Start", 1)

    obj = root.get_child(["0:Objects", "0:SSAgv"])
    res = obj.call_method("0:SendOrder", 4, 10, 1)
Ejemplo n.º 27
0
def startLogging(ip, username, password, rate, path):

    print("Starting")
    print(ip)
    print(username)
    print(password)
    print(rate)
    print(path)
    url = "opc.tcp://192.168.1.20:4840"

    client = Client(url)

    #KUKA_OPC_UA_Logger_GUI.gui.setEntry("Logging Status","Logging Started")
    #KUKA_OPC_UA_Logger_GUI.startbutton = "Logging Active"

    print("try session connect")

    client.set_user("opcuaoperator")

    client.set_password("kuka")

    print("session success")

    client.connect()

    print("Client Connected to KUKA OPC Server")

    lograte = 0.1

    while True:

        now = time.strftime('%d-%m-%Y %H:%M:%S')

        # Force in X Direction

        variablename = "ForceinX"
        variableid = client.get_node(
            "ns=5;s=MotionDeviceSystem.ProcessData.R1.System.$config.FX_FT")
        variabledata = variableid.get_value()
        print(variablename)
        print(variabledata)

        myFile = open("E:/test.csv", 'w')

        with myFile:
            writer = csv.writer(myFile)
            writer.writerows([now, now])
            with open("E:/" + variablename + ".csv", "a") as log:
                log.write("{0},{1}\n".format(now, str(variabledata)))

            # Force in Y Direction

            variablename = "ForceinY"
        variableid = client.get_node(
            "ns=5;s=MotionDeviceSystem.ProcessData.R1.System.$config.FY_FT")
        variabledata = variableid.get_value()
        print(variablename)
        print(variabledata)

        myFile = open("E:/test.csv", 'w')

        with myFile:
            writer = csv.writer(myFile)
            writer.writerows([now, now])
            with open("E:/" + variablename + ".csv", "a") as log:
                log.write("{0},{1}\n".format(now, str(variabledata)))

            # Force in Z Direction

            variablename = "ForceinZ"
        variableid = client.get_node(
            "ns=5;s=MotionDeviceSystem.ProcessData.R1.System.$config.FZ_FT")
        variabledata = variableid.get_value()
        print(variablename)
        print(variabledata)

        myFile = open("E:/test.csv", 'w')

        with myFile:
            writer = csv.writer(myFile)
            writer.writerows([now, now])
            with open("E:/" + variablename + ".csv", "a") as log:
                log.write("{0},{1}\n".format(now, str(variabledata)))

            # Torque in X Direction

            variablename = "TorqueinX"
        variableid = client.get_node(
            "ns=5;s=MotionDeviceSystem.ProcessData.R1.System.$config.TX_FT")
        variabledata = variableid.get_value()

        print(variablename)
        print(variabledata)

        myFile = open("E:/test.csv", 'w')

        with myFile:
            writer = csv.writer(myFile)
            writer.writerows([now, now])
            with open("E:/" + variablename + ".csv", "a") as log:
                log.write("{0},{1}\n".format(now, str(variabledata)))

                # Torque in X Direction

            variablename = "TorqueinY"
        variableid = client.get_node(
            "ns=5;s=MotionDeviceSystem.ProcessData.R1.System.$config.TY_FT")
        variabledata = variableid.get_value()
        print(variablename)
        print(variabledata)

        myFile = open("E:/test.csv", 'w')

        with myFile:
            writer = csv.writer(myFile)
            writer.writerows([now, now])
            with open("E:/" + variablename + ".csv", "a") as log:
                log.write("{0},{1}\n".format(now, str(variabledata)))

                # Torque in X Direction

            variablename = "TorqueinZ"
        variableid = client.get_node(
            "ns=5;s=MotionDeviceSystem.ProcessData.R1.System.$config.TZ_FT")
        variabledata = variableid.get_value()
        print(variablename)
        print(variabledata)

        myFile = open("E:/test.csv", 'w')

        with myFile:
            writer = csv.writer(myFile)
            writer.writerows([now, now])
            with open("E:/" + variablename + ".csv", "a") as log:
                log.write("{0},{1}\n".format(now, str(variabledata)))

        time.sleep(lograte)
Ejemplo n.º 28
0
from time import sleep

from opcua import Client

client = Client('opc.tcp://localhost:4840')
client.connect()
root = client.get_root_node()
print("Root node is: {:s} ".format(str(root)))
print(root)
object_node = client.get_objects_node()
for node in object_node.get_children():
    print(node.get_display_name())
print(object_node.get_children()[1].get_children()[0])
print(object_node.get_children()[1].get_children()[0].get_display_name())
while True:
    print(object_node.get_children()[1].get_children()[0].get_value())
    sleep(2)

Ejemplo n.º 29
0

import ConfigParser

# -----------------------------------------------------------------------------
# Read configuration parameter:
# -----------------------------------------------------------------------------
cfg_file = os.path.expanduser('../openerp.cfg')

config = ConfigParser.ConfigParser()
config.read([cfg_file])
dbname = config.get('dbaccess', 'dbname')

uri = "opc.tcp://192.168.1.186:4840"

client = Client(uri)
client.connect()

# -----------------------------------------------------------------------------
# A. Fast information:
# -----------------------------------------------------------------------------
check_is_allarm = client.get_node("ns=6;s=::AsGlobalPV:Allarmi.Presente")
print('Is Allarm', check_is_allarm.get_data_value().Value._value)
check_is_working = client.get_node(
    "ns=6;s=::AsGlobalPV:PezzoPLC_InLavoro.CaricaInLavoroOK")
print('Is Working', check_is_working.get_data_value().Value._value)
pdb.set_trace()
sys.exit()

# -----------------------------------------------------------------------------
# Browse node:
Ejemplo n.º 30
0
    def __init__(self, address="opc.tcp://192.168.42.20:4840"):
        # self.client = Client("opc.tcp://100.102.7.5:4840")
        self.address = address
        self.client = Client(self.address)

        self.nodes = {}