def __init__(self, name, shared): super().__init__(name, shared) self.logger = logging.getLogger(name) self.logger.info("init") self.shared.config.set_hidden_value(self.name, "user") self.shared.config.set_hidden_value(self.name, "password") self.oldnew = self.config("oldnew_comparision", 0) self.disable = self.config("disable", 0) endpoint = self.config("endpoint", "") certificate = self.config("certificate", "") private_key = self.config("private_key", "") connection_timeout = self.config("connection_timeout", 4) username = self.config("user", "") password = self.config("password", "") self.security_string = "" # format: Policy,Mode,certificate,private_key if self.config("basic128rsa15_sign_on", 0): self.security_string = "Basic128Rsa15,Sign,{},{}".format( certificate, private_key) elif self.config("basic128rsa15_signandencrypt_on", 0): self.security_string = "Basic128Rsa15,SignAndEncrypt,{},{}".format( certificate, private_key) elif self.config("basic256_sign_on", 0): self.security_string = "Basic256,Sign,{},{}".format( certificate, private_key) elif self.config("basic256_signandencrypt_on", 0): self.security_string = "Basic256,SignAndEncrypt,{},{}".format( certificate, private_key) elif self.config("basic256sha256_sign_on", 0): self.security_string = "Basic256Sha256,Sign,{},{}".format( certificate, private_key) elif self.config("basic256sha256_signandencrypt_on", 0): self.security_string = "Basic256Sha256,SignAndEncrypt,{},{}".format( certificate, private_key) elif self.config("nosecurity_on", 1): self.security_string = "" self.client = opcua.Client(endpoint, connection_timeout) if username: self.client.set_user(username) self.client.set_password(password) # use this to use x509 cert identification instead of username/password or anonymous certificate_on = self.config("certificate_basic256sha256_on", 0) if certificate_on: self.client.load_client_certificate(certificate) self.client.load_private_key(private_key) self.subscription = None
def connect_and_subscribe(): if self.client: try: # if already connected, unsubscribe and disconnect _log.info("Disconnecting due to reconnect") self.client.disconnect() except Exception as e: _log.info("Error during disconnect from %s: %s" % (endpoint, e)) try: error = False client = opcua.Client(endpoint) return _connect_and_subscribe(client) except FatalException as e: error = True _log.error("Fatal error during connection to %s: %s" % (endpoint, e)) except NonFatalException as e: error = True _log.warning("Nonfatal error during connection to %s: %s" % (endpoint, e)) _log.info("Connection retry in {} seconds".format(reconnect_interval)) async.DelayedCall(reconnect_interval, setup) except Exception as e: # For unhandled exceptions, we assume them to be fatal error = True _log.error("Unhandled exception during connection to %s: %s" % (endpoint, e)) finally: if error and client: _log.error("Error occured - disconnecting") client.disconnect()
def addNewScadaDevice(): client = opcua.Client('opc.tcp://10.11.31.40:4840') client.connect() atviseObject = client.get_node( 'ns=1;s=AGENT.OBJECTS.SCAMPY.newDefault.newDevice') atviseObject.set_value( ua.DataValue(ua.Variant(True, ua.VariantType.Boolean))) client.disconnect()
def __init__(self): self.transmitter = opcua.Client("opc.tcp://{}:{}".format(CODE, PORT)) try: self.transmitter.connect() self.root = self.transmitter.get_root_node() # print("Object node is: {}".format(self.root)) print('OPC-UA Interpreter initialized successfully!') except Exception as e: print(e)
def get_robot(address, port): uri = u'opc.tcp://%s:%s' % (address, port) # Create and connect as client: robot = opcua.Client(uri) try: robot.connect() return robot except: return False
def setUpClass(self): #start server in its own process self.srv = ServerProcess() self.srv.start() self.srv.started.wait() # let it initialize #start client self.clt = opcua.Client() self.clt.set_endpoint("opc.tcp://localhost:48410") self.clt.connect() self.opc = self.clt
def setUpClass(self): # start server in its own process global globalserver self.srv = globalserver self.srv.start() self.srv.started.wait() # let it initialize # start client self.clt = opcua.Client() self.clt.connect('opc.tcp://localhost:%d' % port_num1) self.opc = self.clt
def precheckConnection(connection_str): client = opcua.Client(connection_str) try: client.connect_socket() client.send_hello() client.disconnect_socket() except Exception: try: client.disconnect_socket() except: pass return False return True
def hel(host, port): connection_str = "opc.tcp://{}:{}".format(host, port) client = opcua.Client(connection_str) try: client.connect_socket() client.send_hello() client.disconnect_socket() except: try: client.disconnect_socket() except: # Error not yet caught in python opcua implementation pass return False else: return True
def connect_and_subscribe(): try: error = False client = opcua.Client(endpoint) return _connect_and_subscribe(client) except FatalException as e: error = True _log.error("Fatal error during connection to %s: %s" % (endpoint, e)) except NonFatalException as e: error = True _log.warning("Nonfatal error during connection to %s: %s" % (endpoint, e)) async .DelayedCall(reconnect_interval, setup) except Exception as e: # For unhandled exceptions, we assume them to be fatal error = True _log.error("Unhandled exception during connection to %s: %s" % (endpoint, e)) finally: if error and client: client.disconnect()
def valid_login( host, port, user, password, security_mode, security_policy, certpath, keypath, app_uri, ): connection_str = "opc.tcp://{}:{}".format(host, port) client = opcua.Client(connection_str) client.set_user(user) client.set_password(password) if (certpath != None and keypath != None and security_policy != None and security_mode != None): client.set_security(security_policy, certpath, keypath, None, security_mode) if app_uri is not "": client.application_uri = app_uri try: # Possibly increase efficiency by setting up socket etc. once client.connect() client.disconnect() except Exception as e: try: # Make sure session is terminated client.disconnect() except: pass return False else: return True
def opcua_on_off(self): """ Aktiviert und deaktiviert opcua mithilfe des buttons von tkinter :return: // """ if self.opcua_bool: """ Wenn OPC-UA aktiv ist, dann Verbindung trennen, opcua_bool False setzen und Button umbennen """ # opcua False setzen self.opcua_bool = False sleep(3) #verbindung trennen self.client.disconnect() self.update_values_tk() #Text ändern; auf variable über dict zugreifen: self.opcua_button["text"] = "OPC-UA aktivieren" else: """ Wenn OPC-UA deaktiv ist, dann verbinden, opcua_bool false setzen und Button umbennen """ #verbindung aufnehmen: self.client = opcua.Client("opc.tcp://192.168.0.4:4840/") self.client.connect() #opcua True setzen: self.opcua_bool = True #Text ändern; auf die variable über dict zugreifen: self.opcua_button["text"] = "OPC-UA deaktivieren"
def connect_opcua(conn: str): """ Connect to OPCUA client :args: conn:str - OPCUA connection info :param: client:opcua.client.client.Client - connection to OPCUA start:time.time.time - process start time boolean:bool - whether to exit while error_msg:list - record of error messages :return: client """ client = None start = time.time() boolean = False error_msg = [] while boolean == False: try: client = opcua.Client("opc.tcp://%s/" % conn) client.connect() except Exeception as e: if e not in error_msg: print('%s - Failed to connect to OPCUA (Error: %s)' % (datetime.datetime.now(), e)) error_msg.append(e) if time.time() > (start * 3605): print('%s - FAiled to connect to OPCUA for over an hour' % datetime.datetime()) status = True else: time.sleep(30) else: boolean = True return client
def connect(self): self._client = opcua.Client(self._endpoint) self._client.connect()
import opcua url = "opc.tcp://127.0.0.1:4840" if __name__ == "__main__": client = opcua.Client(url) try: client.connect() root = client.get_root_node() print("Objects node is: ", root) children = root.get_children() print("Children of root are: ", children) for ch in children: print("------------------------------------") print("nodeID: ", ch.nodeid) print("browse_name: ", ch.get_browse_name()) for lch in ch.get_children(): print(ch, " browse_name: ", ch.get_browse_name()) print("------------------------------------") finally: client.disconnect()
class SubHandler(opcua.SubscriptionHandler): def __init__(self, *args): opcua.SubscriptionHandler.__init__(self, *args) self.val = None def data_change(self, handle, node, val, attr): print("Python: New data change event", handle, node, val, attr) self.val = val def event(self, handle, event): print("Python: New event", handle, event) self.ev = event if __name__ == "__main__": client = opcua.Client(False) client.connect("opc.tcp://localhost:53530/OPCUA/SimulationServer/") try: root = client.get_root_node() print("I got root: ", root) print("Childs are: ", root.get_children()) print("Objects is: ", client.get_objects_node()) o = client.get_objects_node() print("Children of objects are: ", o.get_children()) myvar = root.get_child(["0:Objects", "5:Simulation", "5:Random1"]) print("yvar is: ", myvar) myfloat = client.get_node("ns=4;s=Float") mydouble = client.get_node("ns=4;s=Double") myint64 = client.get_node("ns=4;s=Int64") myuint64 = client.get_node("ns=4;s=UInt64")
def main(): http_url = "http://129.187.88.30:4567/observedVariables" #opc_url = "opc.tcp://localhost:4840" opc_url = "opc.tcp://localhost:4888" pro_type = -1 #first try to get connect with http server http_status = True while True: if http_status: try: http_client = requests.get(http_url) except requests.exceptions.ConnectionError: #print("http connect failed") http_status = False else: print("connect succssfully") http_status = True try: opc_client = opcua.Client(opc_url) opc_client.connect() except socket.error: print("opo ua server connect failed") opc_status = False time.sleep(5) else: print("opc ua server connect successfully") nodeId_header = 'ns=4;s=|var|CODESYS Control for Raspberry Pi SL.' opc_get_nodeIds = ['Application.PLC_PRG.fb_opc_get.b_opc_request', 'Application.PLC_PRG.fb_opc_get.b_opc_answer', 'Application.PLC_PRG.fb_opc_get.i_opc_type', 'Application.PLC_PRG.fb_opc_get.b_http',] opc_send_nodeIds = ['Application.PLC_PRG.fb_opc_send.b_opc_process', 'Application.PLC_PRG.fb_opc_send.i_opc_counter',] opc_gvl = ['Application.GVL_Inputs.b_i_workpiece_at_beginning',] nodeIds = {} for idx in opc_get_nodeIds: var_name = idx.split(".")[-1] nodeId = nodeId_header + idx nodeIds[var_name] = opc_client.get_node(nodeId) for idx in opc_send_nodeIds: var_name = idx.split(".")[-1] nodeId = nodeId_header + idx nodeIds[var_name] = opc_client.get_node(nodeId) for idx in opc_gvl: var_name = idx.split(".")[-1] nodeId = nodeId_header + idx nodeIds[var_name] = opc_client.get_node(nodeId) #print(nodeIds['b_request'].get_value()) print(nodeIds['b_opc_request'].get_value()) http_status = False if nodeIds['b_opc_request'].get_value(): if not http_status: #pro_type = randint(0, 2) pro_type += 1 if pro_type == 3: pro_type = 0 print("get request and product type: " + str(pro_type)) #print("get request from opcua server and product type: " + str(pro_type)) nodeIds['b_http'].set_value(http_status, ua.VariantType.Boolean) nodeIds['i_opc_type'].set_value(pro_type, ua.VariantType.Int16) nodeIds['b_opc_answer'].set_value(True, ua.VariantType.Boolean) b_opc_process = False while not b_opc_process: b_opc_process = nodeIds['b_opc_process'].get_value() nodeIds['b_opc_answer'].set_value(False, ua.VariantType.Boolean) print(' ...done') else: #print("get no request from opc ua server") time.sleep(1) nodeIds['b_opc_answer'].set_value(False, ua.VariantType.Boolean) opc_counter = nodeIds['i_opc_counter'].get_value() opc_client.disconnect()
def run(args): # Disable unnecessary opcua module logging logging.getLogger("opcua").addHandler(logging.NullHandler()) logging.getLogger("opcua").propagate = False if dependencies_missing: module.log("Module dependency (opcua) is missing, cannot continue", level="error") return module.LogHandler.setup( msg_prefix="{}:{} - ".format(args["rhost"], args["rport"])) host = args["rhost"] port = args["rport"] auth = args["authentication"] user = args["username"] password = args["password"] certpath = args["certificate"] keypath = args["privatekey"] mode = args["mode"] policy = args["policy"] app_uri = args["applicationuri"] valid_auth = ["Anonymous", "Username", "Certificate"] valid_modes = ["None", "Sign", "SignAndEncrypt"] valid_policies = ["Basic128Rsa15", "Basic256", "Basic256Sha256"] connection_str = "opc.tcp://{}:{}".format(host, port) if precheckConnection(connection_str): logging.info("Valid OPC UA response, starting analysis") else: logging.info("No OPC UA response, stop module") return client = opcua.Client(connection_str) if auth not in valid_auth: logging.error( "Authentication method needs to be one of the following: {}". format(valid_auth)) return if auth == "Username": client.set_user(user) client.set_password(password) if auth == "Certificate": if not os.path.isfile(certpath): logging.error("Certificate not found") return if not os.path.isfile(keypath): logging.error("Key not found") return client.load_client_certificate(certpath) client.load_private_key(keypath) # Check Mode if mode not in valid_modes: logging.error( "Security mode needs to be one of the following: {}".format( valid_modes)) return # Check policy if mode not None if mode != "None" and policy not in valid_policies: logging.error( "Security mode other than 'None' is used thus security policy needs to be one of the following: {}" .format(valid_policies)) return # Block for Mode setup security_policy = None security_mode = opcua.ua.MessageSecurityMode.None_ if mode != "None": if not os.path.isfile(certpath): logging.error("Certificate not found") return if not os.path.isfile(keypath): logging.error("Key not found") return if policy == valid_policies[0]: security_policy = opcua.crypto.security_policies.SecurityPolicyBasic128Rsa15 elif policy == valid_policies[1]: security_policy = opcua.crypto.security_policies.SecurityPolicyBasic256 elif policy == valid_policies[2]: security_policy = ( opcua.crypto.security_policies.SecurityPolicyBasic256Sha256) if mode == valid_modes[1]: security_mode = opcua.ua.MessageSecurityMode.Sign elif mode == valid_modes[2]: security_mode = opcua.ua.MessageSecurityMode.SignAndEncrypt # May be necessary to set if app_uri is not "": client.application_uri = app_uri try: client.set_security(security_policy, certpath, keypath, None, security_mode) except Exception as e: logging.error( "Failed to set security mode and policy: {}".format(e)) return endpoints = None servers = None try: client.connect() if args["servers"] == "true": # Ask for all known servers servers = client.find_servers() logging.info("Found Servers:") iterateServers(servers) endpoints = client.get_endpoints() logging.info("Available Endpoints:") iterateEndpoints(endpoints) if args["nodes"] == "true" or args["nodesverbose"] == "true": # Iterate over all nodes and check permissions if args["nodesverbose"] == "true": logging.info("Writable Nodes:") traverseTree(client.get_root_node(), True) else: logging.info("Nodes:") traverseTree(client.get_root_node(), False) client.disconnect() except Exception as e: if str(e) == "": logging.error("Could not obtain information") else: logging.error("Could not obtain information: {}".format(e)) try: client.disconnect() except: pass return
import sys sys.path.insert(0, "..") import datetime import opcua print("connecting") c = opcua.Client("opc.tcp://localhost:4840/") c.connect() print("connected, loading custom type defs") c.load_type_definitions() print("got typedefs, finding methods node") methods = c.get_objects_node().get_child( "2:MyCoolMachine/2:MESServices/2:Methods".split("/")) print("found method node %s, building args" % methods) batchid_arg = opcua.ua.MESServiceMethodParameterStructure() batchid_arg.Value = opcua.ua.Variant("BluePill-XXX") batchid_arg.IsValid = True batchid_arg.Timestamp = datetime.datetime.now() batchid_arg.User = "******" water_arg = opcua.ua.MESServiceMethodParameterStructure() water_arg.Value = opcua.ua.Variant(50.172) water_arg.IsValid = False water_arg.Timestamp = datetime.datetime(2001, 12, 24, 18, 24) water_arg.User = "******" print("calling method StartCleaning with args", batchid_arg.__dict__, water_arg.__dict__) result = methods.call_method("2:StartCleaning", batchid_arg, water_arg) print("called successfully, result is", result)
import sys import logging import socketio import opcua from psct_gui_backend.core import BackendServer logger = logging.getLogger('psct_gui_backend') handler = logging.StreamHandler(sys.stdout) handler.setLevel(logging.DEBUG) formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) logger.addHandler(handler) opcua_client = opcua.Client("opc.tcp://10.0.1.13:48010", timeout=60) sio = socketio.Server() serv = BackendServer(opcua_client, sio) serv.initialize_device_models("2:DeviceTree") panel_0 = serv.device_models['ns=2;s=Panel_0']
class SubHandler(opcua.SubscriptionHandler): def __init__(self, *args): opcua.SubscriptionHandler.__init__(self, *args) self.val = None def data_change(self, handle, node, val, attr): print("Python: New data change event", handle, node, val, attr) self.val = val def event(self, handle, event): print("Python: New event", handle, event) self.ev = event if __name__ == "__main__": client = opcua.Client(True) #client.connect("opc.tcp://localhost:4841") client.connect("opc.tcp://utgaard:12685/ctt-server") #s.connect("opc.tcp://192.168.56.101:48030") #edps = client.get_server_endpoints() try: root = client.get_root_node() print("I got root: ", root) print("Childs are: ", root.get_children()) print("Objects is: ", client.get_objects_node()) o = client.get_objects_node() print("Children of objects are: ", o.get_children()) myvar = root.get_child(["0:Objects", "2:NewObject", "2:MyVariable"]) print("yvar is: ", myvar) sclt = SubHandler()
def opc_connection(self, p_ip, p_port): self.opc_connection_format = "opc.tcp://{0}:{1}".format(p_ip, p_port) self.client = opcua.Client(self.opc_connection_format) self.client.connect()
def setUp(self): config = configparser.ConfigParser() config.read('.env') self.client = opcua.Client(config.get(environment, 'TEST_OPC_URL'))
def get_history(self, start, end): print("Read history", start, end) missing = self._get_missing_intervals(start, end) print("I'm missing data for the following intervals", missing) if not missing.empty: # at least some timeranges seem to be missing, # fill in the holes self._populate_cache(missing) else: print("Request can be satisfied from cache") return self._dvs_from_cache(start, end) c = opcua.Client("opc.tcp://0.0.0.0:4840") c.connect() cache = NodeHistoryCache(c.get_node("ns=3;i=1000114")) pprint( list( cache.get_history(datetime(2020, 2, 18, 9, 34, 0), datetime(2020, 2, 18, 9, 34, 10)))) pprint( list( cache.get_history(datetime(2020, 2, 18, 9, 34, 5), datetime(2020, 2, 18, 9, 34, 7)))) pprint( list( cache.get_history(datetime(2020, 2, 18, 9, 34, 5), datetime(2020, 2, 18, 9, 34, 15))))
from IPython import embed import opcua class SubClient(opcua.SubscriptionClient): def __init__(self, *args): opcua.SubscriptionClient.__init__(self, *args) self.val = None def data_change(self, handle, node, val, attr): print("Python: New data change event", handle, node, val, attr) self.val = val if __name__ == "__main__": client = opcua.Client() client.set_endpoint("opc.tcp://localhost:4841") #s.set_endpoint("opc.tcp://192.168.56.101:48030") client.connect() try: root = client.get_root_node() print("I got root: ", root) print("Childs are: ", root.get_children()) print("Objects is: ", client.get_objects_node()) o = client.get_objects_node() print("Children of objects are: ", o.get_children()) myvar = root.get_child(["0:Objects", "0:testfolder", "0:myvar"]) print("yvar is: ", myvar) sclt = SubClient() sub = client.create_subscription(100, sclt)
def connect(self, notifier): self._client = opcua.Client(self._endpoint) d = threads.defer_to_thread(self._client.connect) d.addCallback(notifier) d.addErrback(self._retry_connect, notifier)
import opcua import time client = opcua.Client("opc.tcp://127.0.0.1:51212/freeopcua/server/") client.connect() uri = "127.0.0.1" idx = client.get_namespace_index(uri) objects = client.get_root_node() var = objects.get_child(["0:Objects", "2:GEDATA", "2:t1"]) while 1: print("Value of variable is:", var.get_value()) time.sleep(0.02)
parser = argparse.ArgumentParser(description="Run the background thread " "connecting to the OPC UA aggregating " "server.") parser.add_argument('opcua_server_address', help="IP address/port for the OPC UA aggregating " "server") parser.add_argument( '--legacy', help= "Use backend server for legacy/old version of OPC UA alignment server") parser.add_argument('--debug', help="", action="store_true") args = parser.parse_args() if args.debug: logger.setLevel(logging.DEBUG) logger.info("Starting OPC UA client for address {}".format( args.opcua_server_address)) opcua_client = opcua.Client(args.opcua_server_address, timeout=300) sio = socketio.Server(async_mode='eventlet', ping_timeout=300, ping_interval=300, allow_upgrades=True) serv = BackendServer(opcua_client, sio) serv.initialize_device_models("2:DeviceTree") app = socketio.WSGIApp(sio) eventlet.wsgi.server(eventlet.listen(('', 5000)), app)
# OPC UA module, we use the client import opcua if __name__ == "__main__": # Assemble server endpoint/URL ep_protocol = "opc.tcp" # OPC UA protocol ep_ip = "localhost" # do not change, localhost ep_port = "____" # TODO: chose the port of your OPC UA server # TODO: add your group number. Path on the server where the address space is accesible. One server can host multiple address spaces ep_path = "freeopcua/server/group____" endpoint = ep_protocol+"://"+ep_ip+":" + \ ep_port+"/"+ep_path # assemble the string # Create instance for client and pass the endpoint client = opcua.Client(endpoint) try: # Connect to server print("Connecting to: " + endpoint) connected = False while (not connected): try: client.connect() connected = True except: sleep(1) print("Connected") # Get the root node of the adress space objects_node = client.get_objects_node()