def test_context_manager(self): """ Context manager calls start() and stop() """ state = [0] def increment_state(self, *args, **kwargs): state[0] += 1 # create server and replace instance methods with dummy methods server = Server() server.start = increment_state.__get__(server) server.stop = increment_state.__get__(server) assert state[0] == 0 with server: # test if server started self.assertEqual(state[0], 1) # test if server stopped self.assertEqual(state[0], 2)
class Servidor_OPCUA: def __init__(self): self.server = Server() self.server.set_endpoint("opc.tcp://localhost:4840/freeopcua/server/") self.server.set_server_name("Stack IIoT") self.namespaces = {} self.objects = self.server.get_objects_node() # Para agregar un nuevo namespace def new_namespace(self, uri, namespace, nombre): idx = self.server.register_namespace(uri) print('New namespace: {}'.format(idx)) Namespace = namespace( self.objects, idx, self.server) # Se declaran todas las variables del nuevo namespace self.namespaces[nombre] = Namespace def start(self): global alarma, valor_alarma, mensaje_alarma self.server.start() for nombre, namespace in self.namespaces.items(): namespace.subscripciones() # Se incia el loop del servidor try: while True: time.sleep(0.1) for nombre, namespace in self.namespaces.items(): namespace.monitorea_alarma() finally: self.server.stop()
def run_opcua_server(): """ Creates the OPC/UA server and starts it. """ # setup our server server = Server() server.set_endpoint("opc.tcp://localhost:26543/example/server") # setup our own namespace, not really necessary but should as spec uri = "https://github.com/nathanagood/aws-greengrass-samples" idx = server.register_namespace(uri) # get Objects node, this is where we should put our nodes objects = server.get_objects_node() # populating our address space myobj = objects.add_object(idx, "MyObject") myvar = myobj.add_variable(idx, "MyVariable", 6.7) myvar.set_writable() # Set MyVariable to be writable by clients # starting! server.start() try: count = 0 while True: time.sleep(5) count += 1 logger.debug('Setting value: %s', count) myvar.set_value(count) finally: #close connection, remove subcsriptions, etc server.stop()
def __init__(self, endpoint, name, model_filepath): self.server = Server() # This need to be imported at the start or else it will overwrite the data self.server.import_xml(model_filepath) self.server.set_endpoint(endpoint) self.server.set_server_name(name) objects = self.server.get_objects_node() freeopcua_namespace = self.server.get_namespace_index( "urn:freeopcua:python:server") hellower = objects.get_child("0:Hellower") hellower_say_hello = hellower.get_child("0:SayHello") hellower_exe_calculate = hellower.get_child("0:Calculator") self.server.link_method(hellower_say_hello, say_hello_xml) self.server.link_method(hellower_exe_calculate, exe_calculator) hellower.add_method(freeopcua_namespace, "SayHello2", say_hello, [ua.VariantType.Boolean], [ua.VariantType.String]) hellower.add_method(freeopcua_namespace, "SayHelloArray", say_hello_array, [ua.VariantType.Boolean], [ua.VariantType.String])
def __init__(self, endpoint, name): # Logging configuration self.logger = logging.getLogger('MyDeviceServer') self.logger.setLevel(logging.INFO) # Setup server self.server = Server() self.server.import_xml("MyDevice.xml") self.server.set_endpoint(endpoint) self.server.set_server_name(name) self.objects_node = self.server.get_objects_node() self.my_device_node = self.objects_node.get_child("0:MyDevice") self.my_device_toggle_b = self.my_device_node.get_child("0:ToggleB") self.my_device_toggle_c = self.my_device_node.get_child("0:ToggleC") self.my_device_toggle_d = self.my_device_node.get_child("0:ToggleD") self.server.link_method(self.my_device_toggle_b, self.toggle_b) self.server.link_method(self.my_device_toggle_c, self.toggle_c) self.server.link_method(self.my_device_toggle_d, self.toggle_d) self.my_variable_a = self.my_device_node.get_child("0:VariableA") self.my_variable_b = self.my_device_node.get_child("0:VariableB") self.my_variable_c = self.my_device_node.get_child("0:VariableC") self.my_variable_d = self.my_device_node.get_child("0:VariableD") self.my_variable_e = self.my_device_node.get_child("0:VariableE")
def setUpClass(cls): # start our own server cls.srv_crypto = Server() cls.uri_crypto = 'opc.tcp://127.0.0.1:{0:d}'.format(port_num1) cls.srv_crypto.set_endpoint(cls.uri_crypto) # load server certificate and private key. This enables endpoints # with signing and encryption. cls.srv_crypto.load_certificate("../examples/certificate-example.der") cls.srv_crypto.load_private_key("../examples/private-key-example.pem") cls.srv_crypto.start() # start a server without crypto cls.srv_no_crypto = Server() cls.uri_no_crypto = 'opc.tcp://127.0.0.1:{0:d}'.format(port_num2) cls.srv_no_crypto.set_endpoint(cls.uri_no_crypto) cls.srv_no_crypto.start() # start server with long key cls.srv_crypto2 = Server() cls.uri_crypto2 = 'opc.tcp://127.0.0.1:{0:d}'.format(port_num3) cls.srv_crypto2.set_endpoint(cls.uri_crypto2) cls.srv_crypto2.load_certificate("../examples/certificate-3072-example.der") cls.srv_crypto2.load_private_key("../examples/private-key-3072-example.pem") cls.srv_crypto2.start() cls.srv_crypto_no_anoymous = Server() cls.uri_crypto_no_anoymous = 'opc.tcp://127.0.0.1:{0:d}'.format(port_num4) cls.srv_crypto_no_anoymous.set_endpoint(cls.uri_crypto_no_anoymous) cls.srv_crypto_no_anoymous.load_certificate("examples/certificate-3072-example.der") cls.srv_crypto_no_anoymous.load_private_key("examples/private-key-3072-example.pem") cls.srv_crypto_no_anoymous.set_security_IDs(["Username", "Basic256Sha256"]) cls.srv_crypto_no_anoymous.start()
def __init__(self, logger): self.isinit = False self.logger = logger # setup our server self.server = Server() self.server.set_endpoint('opc.tcp://localhost:4840/') self.server.allow_remote_admin(True) # setup our own namespace, not really necessary but should as spec uri = "http://yourorganisation.org/DCSControllerDesign/" self.idx = self.server.register_namespace(uri) # get Objects node, this is where we should put our nodes self.objects = self.server.get_objects_node() # populating our address space; in most real use cases this should be # imported from UA spec XML. self.logger.notice('Import UA spec from xml ...') self.server.import_xml('dcscontrollerdesign.xml') self.dctni = ua.NodeId.from_string(f'ns={self.idx};i=1003') self.logger.info(f'{self.dctni}') self.logger.success('Done')
def __init__(self, template, template_directory, args): Server.__init__(self) self.template = template self.variables = [] self.event_dict = {} # 首先解析XML self.parse()
async def task(loop): # setup our server server = Server() await server.init() server.set_endpoint('opc.tcp://0.0.0.0:4840/freeopcua/server/') #4840 # setup our own namespace, not really necessary but should as spec uri = 'http://examples.freeopcua.github.io' idx = await server.register_namespace(uri) # get Objects node, this is where we should put our nodes objects = server.get_objects_node() await objects.add_method(ua.NodeId("ServerMethod", 2), ua.QualifiedName('ServerMethod', 2), func, [ua.VariantType.Int64], [ua.VariantType.Int64]) # populating our address space myobj = await objects.add_object(idx, 'MyObject') myvar = await myobj.add_variable(idx, 'MyVariable', 6.7) await myvar.set_writable() # Set MyVariable to be writable by clients # starting! async with server: count = 0 while True: await asyncio.sleep(1) count += 0.1 await myvar.set_value(count)
def check_or_create_server(self): if not hasattr(self, "test_server"): self.test_server = Server() self.__server_thread = Thread(target=self.__server_run, name="Test OPC UA server", args=(self.test_server, )) self.assertTrue(self.test_server is not None)
def __init__( self, endpoint: str = "opc.tcp://0.0.0.0:4840/intry4.0/server/", server_name: str = "InTry 4.0 - OPC UA Server", security_policy: List[ua.SecurityPolicyType] = None, ns_uri: str = "urn:intry:opcua:server", object_name: str = "variables", last_row_file: str = "/var/intry-opcua-server/last_row.log", certificate: str = "/var/intry-opcua-server/cert.der", private_key: str = "/var/intry-opcua-server/key.pem", min_time: int = 30, logger=None, ): if security_policy is None: _security_policy = [ ua.SecurityPolicyType.NoSecurity, ua.SecurityPolicyType.Basic256Sha256_Sign, ua.SecurityPolicyType.Basic256Sha256_SignAndEncrypt, ] self._server = Server() self.endpoint = endpoint self._server.set_endpoint(self.endpoint) self._server.set_security_policy(_security_policy) self._server.load_certificate(certificate) self._server.load_private_key(private_key) self._ns_index = self._server.register_namespace(ns_uri) self._object = self._server.nodes.objects.add_object( self._ns_index, object_name ) self._last_row_file = last_row_file self._logger = logger or logging.getLogger(__name__) self.last_row = {} self._stop = False self.min_time = min_time
def __init__(self): self.server = None self.uri = "" self.idx = 0 self.scan_thread = None self.scan_enable = False self.devices = [] # setup our server self.server = Server() self.server.set_endpoint("opc.tcp://0.0.0.0:4840/freeopcua/server/") # setup our own namespace, not really necessary but should as spec uri = "http://examples.freeopcua.github.io" idx = self.server.register_namespace(uri) # import address space which has a device object self.server.import_xml("device.xml") # get Objects node objects = self.server.get_objects_node() # get the device object type so we can find all the devices in the address space hw_type = self.server.nodes.base_object_type.get_child("2:Device") device_nodes = find_o_types(objects, hw_type) # instantiate a device python object and make it an attribute of the server class # FIXME do your own organization, most likely an object oriented model for device_node in device_nodes: device = Device(self.server, device_node) setattr(self, device.b_name, device) # keep track of the device because so that we can update it cyclically using the driver self.devices.append(device)
def setUp(self): self.server = Server() url = "opc.tcp://localhost:48400/freeopcua/server/" self.server.set_endpoint(url) self.server.start() self.client = Window() self.client.ui.addrComboBox.setCurrentText(url) self.client.connect()
def __init__(self, eflex_type=EFLEXAgentType.CONSUMER, port=4840, name="EFLEX Agent"): self.eflex_type = eflex_type self.name = name self.port = port self.server = Server() self.configure_server(self.server)
def generate_server(): """ GERANDO SERVIDOR - NOME, URL E IP """ server = Server() server.set_endpoint(URL) addspace = server.register_namespace(SERVER_NAME) return server, addspace
def __init__(self): self.server = Server() # setup our server self.server.set_endpoint(os.environ.get("SERVER_ENDPOINT")) # setup our own namespace, not really necessary but should as spec uri = os.environ.get("NAMESPACE") self.idx = self.server.register_namespace(uri)
def setUpClass(self): self.srv = Server() self.srv.set_endpoint('opc.tcp://localhost:%d' % port_num) add_server_methods(self.srv) self.srv.start() self.opc = self.srv self.discovery = Server() self.discovery.set_application_uri("urn:freeopcua:python:discovery") self.discovery.set_endpoint('opc.tcp://localhost:%d' % port_discovery) self.discovery.start()
def setUpClass(self): self.srv = Server() self.srv_url = 'opc.tcp://localhost:%d' % port_num self.srv.set_endpoint(self.srv_url) objects = self.srv.get_objects_node() obj = objects.add_object(4, "directory") var = obj.add_variable(4, "variable", 1.999) var2 = obj.add_variable(4, "variable2", 1.777) var2.set_writable() self.srv.start()
def setUpClass(cls): cls.srv = Server() cls.srv.set_endpoint('opc.tcp://127.0.0.1:{0:d}'.format(port_num)) add_server_methods(cls.srv) cls.srv.start() cls.opc = cls.srv cls.discovery = Server() cls.discovery.set_application_uri("urn:freeopcua:python:discovery") cls.discovery.set_endpoint('opc.tcp://127.0.0.1:{0:d}'.format(port_discovery)) cls.discovery.start()
def start(self, host, port): self.set_endpoint("opc.tcp://" + str(host) + ":" + str(port) + "/ua/server/") logger.info('OPCUA server started on: %s', (host, port)) Server.start(self) # Subscription Handler handler = SubHandler() sub = self.create_subscription(500, handler) for ua_variable in self.variables: sub.subscribe_data_change(ua_variable)
def __init__(self): self.server = Server() self.server.set_endpoint('opc.tcp://0.0.0.0:51210/UA/SampleServer') self.server.set_server_name('Custom structure demo server') # idx name will be used later for creating the xml used in data type dictionary self._idx_name = 'http://examples.freeopcua.github.io' self.idx = self.server.register_namespace(self._idx_name) self.dict_builder = DataTypeDictionaryBuilder(self.server, self.idx, self._idx_name, 'MyDictionary')
def _init_server(self): self._server = Server() self._server.set_endpoint(self._endpoint) self._server.set_server_name(self._name) self._index = self._server.register_namespace(self._namespace) _log.info("Index: %r" % (self._index,)) self._objects_node = self._server.get_objects_node() _log.info("Node: %r" % (self._objects_node)) self._objects = {} _log.info("Endpoints: %r" % (self._server.get_endpoints()))
def start(self): server = Server() server.set_endpoint("opc.tcp://0.0.0.0:4840/thingsroot/server") server.set_server_name("ThingsRoot Example OpcUA Server") self.idx = server.register_namespace("http://opcua.thingsroot.com") self.objects = server.get_objects_node() self.server = server self.devices = _dict({}) self.devices_sub_handle = _dict({}) self.device_types = _dict({}) # self.load_redis_db() server.start()
def run(self): """Instantiate and run server """ logger.info("starting OPC service") params = self._params self._server = Server() self._server.set_endpoint(params["endpoint"]) self._server.set_server_name(params["name"]) idx = self._server.register_namespace(params["uri"]) self._create_nodes(idx, params["nodes"]) self._server.start() self._start_simulations()
def _setup_nodes(self): # Create server instance self.ua_server = Server('./opcua_cache') self.ua_server.set_endpoint('opc.tcp://0.0.0.0:4840/UA/PickByLight') self.ua_server.set_server_name("Pick By Light Server") # idx name will be used later for creating the xml used in data type dictionary # setup our own namespace, not really necessary but should as spec idx_name = 'http://examples.freeopcua.github.io' self.idx = self.ua_server.register_namespace(idx_name) # Set all possible endpoint policies for clients to connect through self.ua_server.set_security_policy([ ua.SecurityPolicyType.NoSecurity, ua.SecurityPolicyType.Basic128Rsa15_SignAndEncrypt, ua.SecurityPolicyType.Basic128Rsa15_Sign, ua.SecurityPolicyType.Basic256_SignAndEncrypt, ua.SecurityPolicyType.Basic256_Sign ]) # get Objects node, this is where we should put our custom stuff objects = self.ua_server.get_objects_node() # Create objects for the pack tags using the above created packMLBasedObjectType self.Status = objects.add_folder('ns=2;s=Status', "Status") self.Command = objects.add_folder('ns=2;s=Command', "Command") self.Command.add_method('ns=2;s=Command.SelectPort', "SelectPort", self._select_method, [ua.VariantType.Int32, ua.VariantType.String], [ua.VariantType.Boolean]) self.Command.add_method('ns=2;s=Command.DeselectPort', "DeselectPort", self._deselect_method, [ua.VariantType.Int32], [ua.VariantType.Boolean]) self.Command.add_method('ns=2;s=Command.DeselectAllPorts', "DeselectAllPorts", self._deselect_all_method, [], [ua.VariantType.Boolean]) root = self.ua_server.get_root_node() DummyFestoObj = root.add_object( "ns=2;s=|var|CECC-LK.Application.Flexstation_globalVariables", "DummyFesto") DummyFestoObj.add_variable( "ns=2;s=|var|CECC-LK.Application.Flexstation_globalVariables.FlexStationStatus", "FlexStationStatus", val=0).set_writable() DummyFestoObj.add_variable( "ns=2;s=|var|CECC-LK.Application.FBs.stpStopper1.stAppControl.uiOpNo", "uiOpNo", val=0).set_writable() DummyFestoObj.add_variable( "ns=2;s=ns=2;s=|var|CECC-LK.Application.AppModul.stRcvData.sOderDes", "sOderDes", val="").set_writable()
def init_opc(self): """Initializes the actual OPC Server and creates all folder, nodes, etc. :return: None """ self._server = Server() self._server.set_endpoint( "opc.tcp://localhost:4840/sms-digital/iba-playback/") self._server.set_server_name("iba Files Playback OPC UA Server") # set all possible endpoint policies for clients to connect through self._server.set_security_policy([ ua.SecurityPolicyType.NoSecurity, ua.SecurityPolicyType.Basic256Sha256_SignAndEncrypt, ua.SecurityPolicyType.Basic256Sha256_Sign ]) # setup our own namespace uri = "http://iba-playback.sms-digital.io" idx = self._server.register_namespace(uri) # add modules folder modules = self._server.nodes.objects.add_folder(idx, "Modules") for module, channel in self.iba_info['modules'].items(): print('\tModule: {} ...'.format(module)) # create a new folder for the module module_folder = modules.add_folder(idx, module) # create a folder for analog and digital signals analog_folder = module_folder.add_folder(idx, 'Analog') digital_folder = module_folder.add_folder(idx, 'Digital') # add the channel for chan in channel: # create channel if chan['type'] == 'analog': opc_channel = analog_folder.add_object(idx, chan['name']) val = 0.0 else: opc_channel = digital_folder.add_object(idx, chan['name']) val = False # define the channel object value_var = opc_channel.add_variable(idx, "value", val) value_var.set_writable(True) for key, val in chan.items(): opc_channel.add_variable(idx, key, val).set_writable(False) # store the handles to the value variable and the opc_channel in the channel dict chan['opc_obj'] = opc_channel chan['opc_value'] = value_var
def run_simulation_server(steps): """ This support function creates a simple OPC UA server with node listed in the config file :param steps: Lifecycle of the server :return: """ with open('../src_test/config_test.yaml') as config_file: cfg = yaml.safe_load(config_file) # setup the server server = Server() server.set_endpoint(cfg['opcua']['url']) # setup the namespace uri = "http://examples.freeopcua.github.io" idx = server.register_namespace(uri) # get objects node objects = server.get_objects_node() # server start server.start() log_event(cfg, 'OPCUA TEST SERVER', '', 'INFO', 'OPC UA server started') # populating the address space myobj = objects.add_object(idx, "TestDataAssembly") nodes = [] metrics = cfg['metrics'] for metric in metrics: metric_id = metric['metric_id'] meas = metric['measurement'] tag = metric['tagname'] var = metric['variable'] ns = metric['nodeNamespace'] id = metric['nodeId'] method = metric['method'] time_interval = metric['interval'] node_str = 'ns=' + str(ns) + '; i=' + str(id) nodes.append(myobj.add_variable(node_str, var, -1)) # update variable time.sleep(1) for it in range(steps): for node in nodes: node.set_value(node.get_value() + 1) time.sleep(0.5) time.sleep(2) server.stop() log_event(cfg, 'OPCUA TEST SERVER', '', 'INFO', 'OPC UA server stopped')
def main(): # setup our server server = Server() server.set_endpoint("opc.tcp://0.0.0.0:4840/freeopcua/server/") # setup our own namespace, not really necessary but should as spec server_namespace = "http://examples.freeopcua.github.io" address_space = server.register_namespace(server_namespace) # get Objects node, this is where we should put our custom stuff objects_node = server.get_objects_node() # Add the ocp objects (vars, features,...) # cresting the first object my_first_object = objects_node.add_object(address_space, "MyFirstObject") ##creating an array my_array = ChargeControllerObject.add_variable(address_space, "MyArray", [6.7, 7.9]) # the variable could be hard typed my_hardtyped_array = ChargeControllerObject.add_variable( address_space, "MyHardtypedArray", ua.Variant([], ua.VariantType.Float)) # starting! server.start() print("Server starting ...") while True: time.sleep(1) ## update array variables burst = [random.random() for _ in range(1024)] my_array.set_value(burst) my_hardtyped_array.set_value(burst)
def start_server(url): server = Server() server.set_endpoint(url) name = "OPC UA Simulation Server" addspace = server.register_namespace(name) node = server.get_objects_node() lvl = node.add_object(addspace, "Level Sensors") lvl1 = lvl.add_variable(addspace, "LVL1", 5) lvl2 = lvl.add_variable(addspace, "LVL2", 6) lvl3 = lvl.add_variable(addspace, "LVL3", 7) lvl4 = lvl.add_variable(addspace, "LVL4", 8) lvl5 = lvl.add_variable(addspace, "LVL5", 9) lvl6 = lvl.add_variable(addspace, "LVL6", 10) flow = node.add_object(addspace, "Flow Sensors") flow1 = flow.add_variable(addspace, "FLOW1", 1) flow2 = flow.add_variable(addspace, "FLOW2", 2) flow3 = flow.add_variable(addspace, "FLOW3", 3) flow4 = flow.add_variable(addspace, "FLOW4", 4) pump = node.add_object(addspace, "Pump Actuators") pump1 = pump.add_variable(addspace, "PUMP1", 0.1) pump2 = pump.add_variable(addspace, "PUMP2", 0.2) pump3 = pump.add_variable(addspace, "PUMP3", 0.3) pump4 = pump.add_variable(addspace, "PUMP4", 0.4) pump5 = pump.add_variable(addspace, "PUMP5", 0.5) pump6 = pump.add_variable(addspace, "PUMP6", 0.6) server.start() return server
def start_server(self, endpoint): logger.info("Starting python-opcua server") self._server = Server() self._server.set_endpoint(endpoint) self._server.set_server_name("OpcUa Modeler Server") self.nodes = self._server.nodes self.get_node = self._server.get_node self.get_namespace_array = self._server.get_namespace_array # now remove freeopcua namespace, not necessary when modeling and # ensures correct idx for exported nodesets ns_node = self._server.get_node(ua.NodeId(ua.ObjectIds.Server_NamespaceArray)) nss = ns_node.get_value() ns_node.set_value(nss[1:]) self._server.start()
class EFLEXAgent(): def __init__(self, eflex_type=EFLEXAgentType.CONSUMER, port=4840, name="EFLEX Agent"): self.eflex_type = eflex_type self.name = name self.port = port self.server = Server() self.configure_server(self.server) def __str__(self): return "EFLEX AGENT OPC UA Server: %s" % self.port def configure_server(self, server): """ Configure the agent OPC UA Server """ server.set_endpoint("opc.tcp://0.0.0.0:%s/EFlex-Agent" % self.port) server.set_server_name("%s" % self.name) server.set_security_policy([ ua.SecurityPolicyType.NoSecurity, ua.SecurityPolicyType.Basic256Sha256_SignAndEncrypt, ua.SecurityPolicyType.Basic256Sha256_Sign ]) server.set_application_uri("urn:fau:faps:OPCUAEFLEXAgent:server") objects = server.get_objects_node() server.import_xml("./IM/Opc.Ua.Di.NodeSet2.xml") server.import_xml("./IM/Opc.Ua.Plc.NodeSet2.xml") server.import_xml("./IM/packmltest.xml") server.import_xml("./IM/packml_eflex_modified.xml") uri = "http://faps.fau.de/OPCUAEFLEXAgent" idx = server.register_namespace(uri) idx_eflex = server.get_namespace_index( "http://siemens.com/PackML_Eflex/") # Configure the method calls method_node = server.get_node(ua.NodeId(9850), idx_eflex) def start(self): """ Start the agent OPC UA Server """ self.server.start() def stop(self): """ Stop the agent OPC UA Server """ self.server.stop()
def setUpClass(self): # start our own server self.srv_crypto = Server() self.uri_crypto = 'opc.tcp://localhost:%d' % port_num1 self.srv_crypto.set_endpoint(self.uri_crypto) # load server certificate and private key. This enables endpoints # with signing and encryption. self.srv_crypto.load_certificate("examples/certificate-example.der") self.srv_crypto.load_private_key("examples/private-key-example.pem") self.srv_crypto.start() # start a server without crypto self.srv_no_crypto = Server() self.uri_no_crypto = 'opc.tcp://localhost:%d' % port_num2 self.srv_no_crypto.set_endpoint(self.uri_no_crypto) self.srv_no_crypto.start()
def runTest(self): tmpfile = NamedTemporaryFile() path = tmpfile.name tmpfile.close() #create cache file server = Server(cacheFile = path) #modify cache content id = ua.NodeId(ua.ObjectIds.Server_ServerStatus_SecondsTillShutdown) s = shelve.open(path, "w", writeback = True) s[id.to_string()].attributes[ua.AttributeIds.Value].value = ua.DataValue(123) s.close() #ensure that we are actually loading from the cache server = Server(cacheFile = path) self.assertEqual(server.get_node(id).get_value(), 123) os.remove(path)
def setUpClass(self): # start our own server self.srv = Server() self.srv.set_endpoint('opc.tcp://localhost:%d' % port_num1) add_server_methods(self.srv) self.srv.start() # start client self.clt = Client('opc.tcp://localhost:%d' % port_num1) self.clt.connect() self.opc = self.clt
class TestClient(unittest.TestCase, CommonTests): ''' Run common tests on client side Of course we need a server so we start a server in another process using python Process module Tests that can only be run on client side must be defined here ''' @classmethod def setUpClass(self): # start our own server self.srv = Server() self.srv.set_endpoint('opc.tcp://localhost:%d' % port_num1) add_server_methods(self.srv) self.srv.start() # start client self.clt = Client('opc.tcp://localhost:%d' % port_num1) self.clt.connect() self.opc = self.clt @classmethod def tearDownClass(self): self.clt.disconnect() # stop the server in its own process self.srv.stop() def test_service_fault(self): request = ua.ReadRequest() request.TypeId = ua.FourByteNodeId(999) # bad type! with self.assertRaises(Exception): self.clt.bclient._send_request(request)
class ServerPython(object): def __init__(self): self._server = None self.nodes = None self.get_node = None self.get_namespace_array = None def start_server(self, endpoint): logger.info("Starting python-opcua server") self._server = Server() self._server.set_endpoint(endpoint) self._server.set_server_name("OpcUa Modeler Server") self.nodes = self._server.nodes self.get_node = self._server.get_node self.get_namespace_array = self._server.get_namespace_array self.load_type_definitions = self._server.load_type_definitions self.load_enums = self._server.load_enums # now remove freeopcua namespace, not necessary when modeling and # ensures correct idx for exported nodesets ns_node = self._server.get_node(ua.NodeId(ua.ObjectIds.Server_NamespaceArray)) nss = ns_node.get_value() ns_node.set_value(nss[:1]) self._server.start() def stop_server(self): if self._server is not None: self._server.stop() self._server = None self.get_node = None self.get_namespace_array = None def import_xml(self, path): return self._server.import_xml(path) def export_xml(self, nodes, uris, path): exp = XmlExporter(self._server) exp.build_etree(nodes, uris=uris) exp.write_xml(path)
class TestServer(unittest.TestCase, CommonTests): ''' Run common tests on server side Tests that can only be run on server side must be defined here ''' @classmethod def setUpClass(self): self.srv = Server() self.srv.set_endpoint('opc.tcp://localhost:%d' % port_num2) add_server_methods(self.srv) self.srv.start() self.opc = self.srv @classmethod def tearDownClass(self): self.srv.stop() def test_register_namespace(self): uri = 'http://mycustom.Namespace.com' idx1 = self.opc.register_namespace(uri) idx2 = self.opc.get_namespace_index(uri) self.assertEqual(idx1, idx2) def test_register_use_namespace(self): uri = 'http://my_very_custom.Namespace.com' idx = self.opc.register_namespace(uri) root = self.opc.get_root_node() myvar = root.add_variable(idx, 'var_in_custom_namespace', [5]) myid = myvar.nodeid self.assertEqual(idx, myid.NamespaceIndex) def test_server_method(self): def func(parent, variant): variant.Value *= 2 return [variant] o = self.opc.get_objects_node() v = o.add_method(3, 'Method1', func, [ua.VariantType.Int64], [ua.VariantType.Int64]) result = o.call_method(v, ua.Variant(2.1)) self.assertEqual(result, 4.2) def test_xml_import(self): self.srv.import_xml("tests/custom_nodes.xml") o = self.opc.get_objects_node() v = o.get_child(["MyXMLFolder", "MyXMLObject", "MyXMLVariable"]) val = v.get_value() self.assertEqual(val, "StringValue")
def setUpClass(self): # start our own server self.srv = Server() self.srv.set_endpoint("opc.tcp://*****:*****@localhost:%d" % port_num1) self.clt.connect() self.opc = self.clt # start anonymous client self.ro_clt = Client("opc.tcp://localhost:%d" % port_num1) self.ro_clt.connect()
def mymain(): # setup our server server = Server() server.set_endpoint("opc.tcp://0.0.0.0:4840/freeopcua/server/") # setup our own namespace, not really necessary but should as spec uri = "http://examples.freeopcua.github.io" idx = server.register_namespace(uri) # get Objects node, this is where we should put our nodes objects = server.get_objects_node() # populating our address space myobj = objects.add_object(idx, "MyObject") myvar = myobj.add_variable(idx, "MyVariable", 6.7) myvar.set_writable() # Set MyVariable to be writable by clients # starting! server.start() server.stop()
def start_server(self, endpoint): logger.info("Starting python-opcua server") self._server = Server() self._server.set_endpoint(endpoint) self._server.set_server_name("OpcUa Modeler Server") self.nodes = self._server.nodes self.get_node = self._server.get_node self.get_namespace_array = self._server.get_namespace_array self.load_type_definitions = self._server.load_type_definitions self.load_enums = self._server.load_enums # now remove freeopcua namespace, not necessary when modeling and # ensures correct idx for exported nodesets ns_node = self._server.get_node(ua.NodeId(ua.ObjectIds.Server_NamespaceArray)) nss = ns_node.get_value() ns_node.set_value(nss[:1]) self._server.start()
def setUpClass(self): # start our own server self.srv = Server() self.srv.set_endpoint('opc.tcp://*****:*****@localhost:%d' % port_num1, timeout=10) self.clt.connect() self.opc = self.clt # start anonymous client self.ro_clt = Client('opc.tcp://localhost:%d' % port_num1) self.ro_clt.connect()
class TestRefsWidget(unittest.TestCase): def setUp(self): self.server = Server() self.server.set_endpoint("opc.tcp://0.0.0.0:48409/freeopcua/server/") self.server.start() self.widget = RefsWidget(QTableView()) def tearDown(self): self.server.stop() def test_1(self): o = self.server.nodes.objects self.widget.show_refs(o)
class TestCmdLines(unittest.TestCase): ''' Test command lines ''' @classmethod def setUpClass(self): self.srv = Server() self.srv_url = 'opc.tcp://localhost:%d' % port_num self.srv.set_endpoint(self.srv_url) objects = self.srv.get_objects_node() obj = objects.add_object(4, "directory") var = obj.add_variable(4, "variable", 1.999) var2 = obj.add_variable(4, "variable2", 1.777) var2.set_writable() self.srv.start() def test_uals(self): s = subprocess.check_output(["python", "tools/uals", "--url", self.srv_url]) self.assertIn(b"i=85", s) self.assertNotIn(b"i=89", s) self.assertNotIn(b"1.999", s) s = subprocess.check_output(["python", "tools/uals", "--url", self.srv_url, "-d", "3"]) self.assertIn(b"1.999", s) def test_uaread(self): s = subprocess.check_output(["python", "tools/uaread", "--url", self.srv_url, "--path", "0:Objects,4:directory,4:variable"]) self.assertIn(b"1.999", s) def test_uawrite(self): s = subprocess.check_output(["python", "tools/uawrite", "--url", self.srv_url, "--path", "0:Objects,4:directory,4:variable2", "1.789"]) s = subprocess.check_output(["python", "tools/uaread", "--url", self.srv_url, "--path", "0:Objects,4:directory,4:variable2"]) self.assertIn(b"1.789", s) self.assertNotIn(b"1.999", s) def test_uadiscover(self): s = subprocess.check_output(["python", "tools/uadiscover", "--url", self.srv_url]) self.assertIn(b"opc.tcp://localhost", s) self.assertIn(b"FreeOpcUa", s) self.assertIn(b"urn:freeopcua:python:server", s) @classmethod def tearDownClass(self): self.srv.stop()
def __init__(self, endpoint, name, model_filepath): self.server = Server() # This need to be imported at the start or else it will overwrite the data self.server.import_xml(model_filepath) self.server.set_endpoint(endpoint) self.server.set_server_name(name) objects = self.server.get_objects_node() freeopcua_namespace = self.server.get_namespace_index("urn:freeopcua:python:server") hellower = objects.get_child("0:Hellower") hellower_say_hello = hellower.get_child("0:SayHello") self.server.link_method(hellower_say_hello, say_hello_xml) hellower.add_method( freeopcua_namespace, "SayHello2", say_hello, [ua.VariantType.Boolean], [ua.VariantType.String]) hellower.add_method( freeopcua_namespace, "SayHelloArray", say_hello_array, [ua.VariantType.Boolean], [ua.VariantType.String])
class TestClient(unittest.TestCase): def setUp(self): self.server = Server() url = "opc.tcp://localhost:48400/freeopcua/server/" self.server.set_endpoint(url) self.server.start() self.client = Window() self.client.ui.addrComboBox.setCurrentText(url) self.client.connect() def tearDown(self): self.client.disconnect() self.server.stop() def get_attr_value(self, text): idxlist = self.client.attrs_ui.model.match(self.client.attrs_ui.model.index(0, 0), Qt.DisplayRole, text, 1, Qt.MatchExactly | Qt.MatchRecursive) idx = idxlist[0] idx = idx.sibling(idx.row(), 1) item = self.client.attrs_ui.model.itemFromIndex(idx) return item.data(Qt.UserRole).value def test_select_objects(self): objects = self.server.nodes.objects self.client.tree_ui.set_current_node("Objects") self.assertEqual(objects, self.client.tree_ui.get_current_node()) self.assertGreater(self.client.attrs_ui.model.rowCount(), 6) print("REF COUNT", self.client.refs_ui.model.rowCount()) self.assertGreater(self.client.refs_ui.model.rowCount(), 1) data = self.get_attr_value("NodeId") self.assertEqual(data, objects.nodeid) def test_select_server_node(self): self.client.tree_ui.set_current_node("Objects") self.client.tree_ui.expand_current_node() # must be expanded to load children server_node = self.server.nodes.server self.client.tree_ui.set_current_node("Server") self.assertEqual(server_node, self.client.tree_ui.get_current_node()) self.assertGreater(self.client.attrs_ui.model.rowCount(), 6) self.assertGreater(self.client.refs_ui.model.rowCount(), 10) data = self.get_attr_value("NodeId") self.assertEqual(data, server_node.nodeid)
class TestServer(unittest.TestCase, CommonTests): """ Run common tests on server side Tests that can only be run on server side must be defined here """ @classmethod def setUpClass(self): self.srv = Server() self.srv.set_endpoint("opc.tcp://localhost:%d" % port_num2) add_server_methods(self.srv) self.srv.start() self.opc = self.srv @classmethod def tearDownClass(self): self.srv.stop() def test_register_namespace(self): uri = "http://mycustom.Namespace.com" idx1 = self.opc.register_namespace(uri) idx2 = self.opc.get_namespace_index(uri) self.assertEqual(idx1, idx2) def test_register_use_namespace(self): uri = "http://my_very_custom.Namespace.com" idx = self.opc.register_namespace(uri) root = self.opc.get_root_node() myvar = root.add_variable(idx, "var_in_custom_namespace", [5]) myid = myvar.nodeid self.assertEqual(idx, myid.NamespaceIndex) def test_server_method(self): def func(parent, variant): variant.Value *= 2 return [variant] o = self.opc.get_objects_node() v = o.add_method(3, "Method1", func, [ua.VariantType.Int64], [ua.VariantType.Int64]) result = o.call_method(v, ua.Variant(2.1)) self.assertEqual(result, 4.2)
import sys sys.path.insert(0, "..") import time import math from opcua import ua, Server from opcua.server.history_sql import HistorySQLite if __name__ == "__main__": # setup our server server = Server() server.set_endpoint("opc.tcp://0.0.0.0:4840/freeopcua/server/") # setup our own namespace, not really necessary but should as spec uri = "http://examples.freeopcua.github.io" idx = server.register_namespace(uri) # get Objects node, this is where we should put our custom stuff objects = server.get_objects_node() # populating our address space myobj = objects.add_object(idx, "MyObject") myvar = myobj.add_variable(idx, "MyVariable", ua.Variant(0, ua.VariantType.Double)) myvar.set_writable() # Set MyVariable to be writable by clients # Creating a custom event: Approach 1 # The custom event object automatically will have members from its parent (BaseEventType) etype = server.create_custom_event_type(2, 'MyFirstEvent', ua.ObjectIds.BaseEventType,
def uaserver(): parser = argparse.ArgumentParser(description="Run an example OPC-UA server. By importing xml definition and using uawrite command line, it is even possible to expose real data using this server") # we setup a server, this is a bit different from other tool so we do not reuse common arguments parser.add_argument("-u", "--url", help="URL of OPC UA server, default is opc.tcp://0.0.0.0:4840", default='opc.tcp://0.0.0.0:4840', metavar="URL") parser.add_argument("-v", "--verbose", dest="loglevel", choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'], default='WARNING', help="Set log level") parser.add_argument("-x", "--xml", metavar="XML_FILE", help="Populate address space with nodes defined in XML") parser.add_argument("-p", "--populate", action="store_true", help="Populate address space with some sample nodes") parser.add_argument("-c", "--disable-clock", action="store_true", help="Disable clock, to avoid seeing many write if debugging an application") parser.add_argument("-s", "--shell", action="store_true", help="Start python shell instead of randomly changing node values") parser.add_argument("--certificate", help="set server certificate") parser.add_argument("--private_key", help="set server private key") args = parser.parse_args() logging.basicConfig(format="%(levelname)s: %(message)s", level=getattr(logging, args.loglevel)) server = Server() server.set_endpoint(args.url) if args.certificate: server.load_certificate(args.certificate) if args.private_key: server.load_private_key(args.private_key) server.disable_clock(args.disable_clock) server.set_server_name("FreeOpcUa Example Server") if args.xml: server.import_xml(args.xml) if args.populate: @uamethod def multiply(parent, x, y): print("multiply method call with parameters: ", x, y) return x * y uri = "http://examples.freeopcua.github.io" idx = server.register_namespace(uri) objects = server.get_objects_node() myobj = objects.add_object(idx, "MyObject") mywritablevar = myobj.add_variable(idx, "MyWritableVariable", 6.7) mywritablevar.set_writable() # Set MyVariable to be writable by clients myvar = myobj.add_variable(idx, "MyVariable", 6.7) myarrayvar = myobj.add_variable(idx, "MyVarArray", [6.7, 7.9]) myprop = myobj.add_property(idx, "MyProperty", "I am a property") mymethod = myobj.add_method(idx, "MyMethod", multiply, [ua.VariantType.Double, ua.VariantType.Int64], [ua.VariantType.Double]) server.start() try: if args.shell: embed() elif args.populate: count = 0 while True: time.sleep(1) myvar.set_value(math.sin(count / 10)) myarrayvar.set_value([math.sin(count / 10), math.sin(count / 100)]) count += 1 else: while True: time.sleep(1) finally: server.stop() sys.exit(0)
class TestClient(unittest.TestCase, CommonTests, SubscriptionTests): ''' Run common tests on client side Of course we need a server so we start also start a server Tests that can only be run on client side must be defined in this class ''' @classmethod def setUpClass(self): # start our own server self.srv = Server() self.srv.set_endpoint('opc.tcp://*****:*****@localhost:%d' % port_num1, timeout=10) self.clt.connect() self.opc = self.clt # start anonymous client self.ro_clt = Client('opc.tcp://localhost:%d' % port_num1) self.ro_clt.connect() @classmethod def tearDownClass(self): #stop our clients self.ro_clt.disconnect() self.clt.disconnect() # stop the server self.srv.stop() def test_service_fault(self): request = ua.ReadRequest() request.TypeId = ua.FourByteNodeId(999) # bad type! with self.assertRaises(ua.UaStatusCodeError): self.clt.uaclient._uasocket.send_request(request) def test_objects_anonymous(self): objects = self.ro_clt.get_objects_node() with self.assertRaises(ua.UaStatusCodeError): objects.set_attribute(ua.AttributeIds.WriteMask, ua.DataValue(999)) with self.assertRaises(ua.UaStatusCodeError): f = objects.add_folder(3, 'MyFolder') def test_folder_anonymous(self): objects = self.clt.get_objects_node() f = objects.add_folder(3, 'MyFolderRO') f_ro = self.ro_clt.get_node(f.nodeid) self.assertEqual(f, f_ro) with self.assertRaises(ua.UaStatusCodeError): f2 = f_ro.add_folder(3, 'MyFolder2') def test_variable_anonymous(self): objects = self.clt.get_objects_node() v = objects.add_variable(3, 'MyROVariable', 6) v.set_value(4) #this should work v_ro = self.ro_clt.get_node(v.nodeid) with self.assertRaises(ua.UaStatusCodeError): v_ro.set_value(2) self.assertEqual(v_ro.get_value(), 4) v.set_writable(True) v_ro.set_value(2) #now it should work self.assertEqual(v_ro.get_value(), 2) v.set_writable(False) with self.assertRaises(ua.UaStatusCodeError): v_ro.set_value(9) self.assertEqual(v_ro.get_value(), 2) def test_context_manager(self): """ Context manager calls connect() and disconnect() """ state = [0] def increment_state(self, *args, **kwargs): state[0] += 1 # create client and replace instance methods with dummy methods client = Client('opc.tcp://dummy_address:10000') client.connect = increment_state.__get__(client) client.disconnect = increment_state.__get__(client) assert state[0] == 0 with client: # test if client connected self.assertEqual(state[0], 1) # test if client disconnected self.assertEqual(state[0], 2)
if __name__ == "__main__": # optional: setup logging logging.basicConfig(level=logging.WARN) #logger = logging.getLogger("opcua.address_space") # logger.setLevel(logging.DEBUG) #logger = logging.getLogger("opcua.internal_server") # logger.setLevel(logging.DEBUG) #logger = logging.getLogger("opcua.binary_server_asyncio") # logger.setLevel(logging.DEBUG) #logger = logging.getLogger("opcua.uaprocessor") # logger.setLevel(logging.DEBUG) #logger = logging.getLogger("opcua.subscription_service") # logger.setLevel(logging.DEBUG) # now setup our server server = Server() #server.set_endpoint("opc.tcp://localhost:4841/freeopcua/server/") server.set_endpoint("opc.tcp://0.0.0.0:4841/freeopcua/server/") server.set_server_name("FreeOpcUa Example Server") # setup our own namespace uri = "http://examples.freeopcua.github.io" idx = server.register_namespace(uri) # get Objects node, this is where we should put our custom stuff objects = server.get_objects_node() # populating our address space myfolder = objects.add_folder(idx, "myEmptyFolder") myobj = objects.add_object(idx, "NewObject") myvar = myobj.add_variable(idx, "MyVariable", 6.7)
import sys sys.path.insert(0, "..") import time from opcua import ua, Server if __name__ == "__main__": # setup our server server = Server() server.set_endpoint("opc.tcp://0.0.0.0:4840/freeopcua/server/") # setup our own namespace, not really necessary but should as spec uri = "http://examples.freeopcua.github.io" idx = server.register_namespace(uri) # get Objects node, this is where we should put our custom stuff objects = server.get_objects_node() # populating our address space myobj = objects.add_object(idx, "MyObject") myvar = myobj.add_variable(idx, "MyVariable", 6.7) myvar.set_writable() # Set MyVariable to be writable by clients # starting! server.start() try: count = 0
class TestServer(unittest.TestCase, CommonTests, SubscriptionTests): ''' Run common tests on server side Tests that can only be run on server side must be defined here ''' @classmethod def setUpClass(self): self.srv = Server() self.srv.set_endpoint('opc.tcp://localhost:%d' % port_num) add_server_methods(self.srv) self.srv.start() self.opc = self.srv self.discovery = Server() self.discovery.set_application_uri("urn:freeopcua:python:discovery") self.discovery.set_endpoint('opc.tcp://localhost:%d' % port_discovery) self.discovery.start() @classmethod def tearDownClass(self): self.srv.stop() self.discovery.stop() def test_discovery(self): client = Client(self.discovery.endpoint.geturl()) client.connect() try: servers = client.find_servers() new_app_uri = "urn:freeopcua:python:server:test_discovery" self.srv.application_uri = new_app_uri self.srv.register_to_discovery(self.discovery.endpoint.geturl(), 0) time.sleep(0.1) # let server register registration new_servers = client.find_servers() self.assertEqual(len(new_servers) - len(servers) , 1) self.assertFalse(new_app_uri in [s.ApplicationUri for s in servers]) self.assertTrue(new_app_uri in [s.ApplicationUri for s in new_servers]) finally: client.disconnect() def test_find_servers2(self): client = Client(self.discovery.endpoint.geturl()) client.connect() try: servers = client.find_servers() new_app_uri1 = "urn:freeopcua:python:server:test_discovery1" self.srv.application_uri = new_app_uri1 self.srv.register_to_discovery(self.discovery.endpoint.geturl(), period=0) new_app_uri2 = "urn:freeopcua:python:test_discovery2" self.srv.application_uri = new_app_uri2 self.srv.register_to_discovery(self.discovery.endpoint.geturl(), period=0) time.sleep(0.1) # let server register registration new_servers = client.find_servers() self.assertEqual(len(new_servers) - len(servers) , 2) self.assertFalse(new_app_uri1 in [s.ApplicationUri for s in servers]) self.assertFalse(new_app_uri2 in [s.ApplicationUri for s in servers]) self.assertTrue(new_app_uri1 in [s.ApplicationUri for s in new_servers]) self.assertTrue(new_app_uri2 in [s.ApplicationUri for s in new_servers]) # now do a query with filer new_servers = client.find_servers(["urn:freeopcua:python:server"]) self.assertEqual(len(new_servers) - len(servers) , 0) self.assertTrue(new_app_uri1 in [s.ApplicationUri for s in new_servers]) self.assertFalse(new_app_uri2 in [s.ApplicationUri for s in new_servers]) # now do a query with filer new_servers = client.find_servers(["urn:freeopcua:python"]) self.assertEqual(len(new_servers) - len(servers) , 2) self.assertTrue(new_app_uri1 in [s.ApplicationUri for s in new_servers]) self.assertTrue(new_app_uri2 in [s.ApplicationUri for s in new_servers]) finally: client.disconnect() """ # not sure if this test is necessary, and there is a lot repetition with previous test def test_discovery_server_side(self): servers = self.discovery.find_servers() self.assertEqual(len(servers), 1) self.srv.register_to_discovery(self.discovery.endpoint.geturl(), 1) time.sleep(1) # let server register registration servers = self.discovery.find_servers() print("SERVERS 2", servers) self.assertEqual(len(servers), 2) """ #def test_register_server2(self): #servers = self.opc.register_server() def test_register_namespace(self): uri = 'http://mycustom.Namespace.com' idx1 = self.opc.register_namespace(uri) idx2 = self.opc.get_namespace_index(uri) self.assertEqual(idx1, idx2) def test_register_use_namespace(self): uri = 'http://my_very_custom.Namespace.com' idx = self.opc.register_namespace(uri) root = self.opc.get_root_node() myvar = root.add_variable(idx, 'var_in_custom_namespace', [5]) myid = myvar.nodeid self.assertEqual(idx, myid.NamespaceIndex) def test_server_method(self): def func(parent, variant): variant.Value *= 2 return [variant] o = self.opc.get_objects_node() v = o.add_method(3, 'Method1', func, [ua.VariantType.Int64], [ua.VariantType.Int64]) result = o.call_method(v, ua.Variant(2.1)) self.assertEqual(result, 4.2) def test_xml_import(self): self.srv.import_xml("tests/custom_nodes.xml") o = self.opc.get_objects_node() v = o.get_child(["MyXMLFolder", "MyXMLObject", "MyXMLVariable"]) val = v.get_value() self.assertEqual(val, "StringValue") def test_historize_variable(self): o = self.opc.get_objects_node() var = o.add_variable(3, "test_hist", 1.0) self.srv.iserver.enable_history_data_change(var, timedelta(days=1)) time.sleep(1) var.set_value(2.0) var.set_value(3.0) self.srv.iserver.disable_history_data_change(var) def test_historize_events(self): srv_node = self.srv.get_node(ua.ObjectIds.Server) srvevgen = self.srv.get_event_generator() self.srv.iserver.enable_history_event(srv_node, period=None) srvevgen.trigger(message="Message") self.srv.iserver.disable_history_event(srv_node) def test_references_for_added_nodes_method(self): objects = self.opc.get_objects_node() o = objects.add_object(3, 'MyObject') nodes = objects.get_referenced_nodes(refs=ua.ObjectIds.Organizes, direction=ua.BrowseDirection.Forward, includesubtypes=False) self.assertTrue(o in nodes) nodes = o.get_referenced_nodes(refs=ua.ObjectIds.Organizes, direction=ua.BrowseDirection.Inverse, includesubtypes=False) self.assertTrue(objects in nodes) self.assertEqual(o.get_parent(), objects) self.assertEqual(o.get_type_definition(), ua.ObjectIds.BaseObjectType) @uamethod def callback(parent): return m = o.add_method(3, 'MyMethod', callback) nodes = o.get_referenced_nodes(refs=ua.ObjectIds.HasComponent, direction=ua.BrowseDirection.Forward, includesubtypes=False) self.assertTrue(m in nodes) nodes = m.get_referenced_nodes(refs=ua.ObjectIds.HasComponent, direction=ua.BrowseDirection.Inverse, includesubtypes=False) self.assertTrue(o in nodes) self.assertEqual(m.get_parent(), o) # This should work for following BaseEvent tests to work (maybe to write it a bit differentlly since they are not independent) def test_get_event_from_type_node_BaseEvent(self): ev = opcua.common.events.get_event_obj_from_type_node(opcua.Node(self.opc.iserver.isession, ua.NodeId(ua.ObjectIds.BaseEventType))) check_base_event(self, ev) def test_get_event_from_type_node_Inhereted_AuditEvent(self): ev = opcua.common.events.get_event_obj_from_type_node(opcua.Node(self.opc.iserver.isession, ua.NodeId(ua.ObjectIds.AuditEventType))) self.assertIsNot(ev, None) # we did not receive event self.assertIsInstance(ev, BaseEvent) self.assertIsInstance(ev, AuditEvent) self.assertEqual(ev.EventType, ua.NodeId(ua.ObjectIds.AuditEventType)) self.assertEqual(ev.Severity, 1) self.assertEqual(ev.ActionTimeStamp, None) self.assertEqual(ev.Status, False) self.assertEqual(ev.ServerId, None) self.assertEqual(ev.ClientAuditEntryId, None) self.assertEqual(ev.ClientUserId, None) def test_eventgenerator_default(self): evgen = self.opc.get_event_generator() check_eventgenerator_BaseEvent(self, evgen) check_eventgenerator_SourceServer(self, evgen) def test_eventgenerator_BaseEvent_object(self): evgen = self.opc.get_event_generator(BaseEvent()) check_eventgenerator_BaseEvent(self, evgen) check_eventgenerator_SourceServer(self, evgen) def test_eventgenerator_BaseEvent_Node(self): evgen = self.opc.get_event_generator(opcua.Node(self.opc.iserver.isession, ua.NodeId(ua.ObjectIds.BaseEventType))) check_eventgenerator_BaseEvent(self, evgen) check_eventgenerator_SourceServer(self, evgen) def test_eventgenerator_BaseEvent_NodeId(self): evgen = self.opc.get_event_generator(ua.NodeId(ua.ObjectIds.BaseEventType)) check_eventgenerator_BaseEvent(self, evgen) check_eventgenerator_SourceServer(self, evgen) def test_eventgenerator_BaseEvent_ObjectIds(self): evgen = self.opc.get_event_generator(ua.ObjectIds.BaseEventType) check_eventgenerator_BaseEvent(self, evgen) check_eventgenerator_SourceServer(self, evgen) def test_eventgenerator_BaseEvent_Identifier(self): evgen = self.opc.get_event_generator(2041) check_eventgenerator_BaseEvent(self, evgen) check_eventgenerator_SourceServer(self, evgen) def test_eventgenerator_sourceServer_Node(self): evgen = self.opc.get_event_generator(source=opcua.Node(self.opc.iserver.isession, ua.NodeId(ua.ObjectIds.Server))) check_eventgenerator_BaseEvent(self, evgen) check_eventgenerator_SourceServer(self, evgen) def test_eventgenerator_sourceServer_NodeId(self): evgen = self.opc.get_event_generator(source=ua.NodeId(ua.ObjectIds.Server)) check_eventgenerator_BaseEvent(self, evgen) check_eventgenerator_SourceServer(self, evgen) def test_eventgenerator_sourceServer_ObjectIds(self): evgen = self.opc.get_event_generator(source=ua.ObjectIds.Server) check_eventgenerator_BaseEvent(self, evgen) check_eventgenerator_SourceServer(self, evgen) def test_eventgenerator_sourceMyObject(self): objects = self.opc.get_objects_node() o = objects.add_object(3, 'MyObject') evgen = self.opc.get_event_generator(source=o) check_eventgenerator_BaseEvent(self, evgen) check_event_generator_object(self, evgen, o) def test_eventgenerator_source_collision(self): objects = self.opc.get_objects_node() o = objects.add_object(3, 'MyObject') event = BaseEvent(sourcenode=o.nodeid) evgen = self.opc.get_event_generator(event, ua.ObjectIds.Server) check_eventgenerator_BaseEvent(self, evgen) check_event_generator_object(self, evgen, o) def test_eventgenerator_InheritedEvent(self): evgen = self.opc.get_event_generator(ua.ObjectIds.AuditEventType) check_eventgenerator_SourceServer(self, evgen) ev = evgen.event self.assertIsNot(ev, None) # we did not receive event self.assertIsInstance(ev, BaseEvent) self.assertIsInstance(ev, AuditEvent) self.assertEqual(ev.EventType, ua.NodeId(ua.ObjectIds.AuditEventType)) self.assertEqual(ev.Severity, 1) self.assertEqual(ev.ActionTimeStamp, None) self.assertEqual(ev.Status, False) self.assertEqual(ev.ServerId, None) self.assertEqual(ev.ClientAuditEntryId, None) self.assertEqual(ev.ClientUserId, None) def test_create_custom_event_type_ObjectId(self): etype = self.opc.create_custom_event_type(2, 'MyEvent', ua.ObjectIds.BaseEventType, [('PropertyNum', ua.VariantType.Float), ('PropertyString', ua.VariantType.String)]) check_custom_event_type(self, etype) def test_create_custom_event_type_NodeId(self): etype = self.opc.create_custom_event_type(2, 'MyEvent', ua.NodeId(ua.ObjectIds.BaseEventType), [('PropertyNum', ua.VariantType.Float), ('PropertyString', ua.VariantType.String)]) check_custom_event_type(self, etype) def test_create_custom_event_type_Node(self): etype = self.opc.create_custom_event_type(2, 'MyEvent', opcua.Node(self.opc.iserver.isession, ua.NodeId(ua.ObjectIds.BaseEventType)), [('PropertyNum', ua.VariantType.Float), ('PropertyString', ua.VariantType.String)]) check_custom_event_type(self, etype) def test_get_event_from_type_node_CustomEvent(self): etype = self.opc.create_custom_event_type(2, 'MyEvent', ua.ObjectIds.BaseEventType, [('PropertyNum', ua.VariantType.Float), ('PropertyString', ua.VariantType.String)]) ev = opcua.common.events.get_event_obj_from_type_node(etype) check_custom_event(self, ev, etype) self.assertEqual(ev.PropertyNum, None) self.assertEqual(ev.PropertyString, None) def test_eventgenerator_customEvent(self): etype = self.opc.create_custom_event_type(2, 'MyEvent', ua.ObjectIds.BaseEventType, [('PropertyNum', ua.VariantType.Float), ('PropertyString', ua.VariantType.String)]) evgen = self.opc.get_event_generator(etype, ua.ObjectIds.Server) check_eventgenerator_CustomEvent(self, evgen, etype) check_eventgenerator_SourceServer(self, evgen) self.assertEqual(evgen.event.PropertyNum, None) self.assertEqual(evgen.event.PropertyString, None) def test_eventgenerator_double_customEvent(self): event1 = self.opc.create_custom_event_type(3, 'MyEvent1', ua.ObjectIds.BaseEventType, [('PropertyNum', ua.VariantType.Float), ('PropertyString', ua.VariantType.String)]) event2 = self.opc.create_custom_event_type(4, 'MyEvent2', event1, [('PropertyBool', ua.VariantType.Boolean), ('PropertyInt', ua.VariantType.Int32)]) evgen = self.opc.get_event_generator(event2, ua.ObjectIds.Server) check_eventgenerator_CustomEvent(self, evgen, event2) check_eventgenerator_SourceServer(self, evgen) # Properties from MyEvent1 self.assertEqual(evgen.event.PropertyNum, None) self.assertEqual(evgen.event.PropertyString, None) # Properties from MyEvent2 self.assertEqual(evgen.event.PropertyBool, None) self.assertEqual(evgen.event.PropertyInt, None) def test_eventgenerator_customEvent_MyObject(self): objects = self.opc.get_objects_node() o = objects.add_object(3, 'MyObject') etype = self.opc.create_custom_event_type(2, 'MyEvent', ua.ObjectIds.BaseEventType, [('PropertyNum', ua.VariantType.Float), ('PropertyString', ua.VariantType.String)]) evgen = self.opc.get_event_generator(etype, o) check_eventgenerator_CustomEvent(self, evgen, etype) check_event_generator_object(self, evgen, o) self.assertEqual(evgen.event.PropertyNum, None) self.assertEqual(evgen.event.PropertyString, None)
if __name__ == "__main__": # optional: setup logging logging.basicConfig(level=logging.WARN) #logger = logging.getLogger("opcua.address_space") # logger.setLevel(logging.DEBUG) #logger = logging.getLogger("opcua.internal_server") # logger.setLevel(logging.DEBUG) #logger = logging.getLogger("opcua.binary_server_asyncio") # logger.setLevel(logging.DEBUG) #logger = logging.getLogger("opcua.uaprocessor") # logger.setLevel(logging.DEBUG) # now setup our server server = Server() #server.disable_clock() #server.set_endpoint("opc.tcp://localhost:4840/freeopcua/server/") server.set_endpoint("opc.tcp://0.0.0.0:4840/freeopcua/server/") server.set_server_name("FreeOpcUa Example Server") # setup our own namespace uri = "http://examples.freeopcua.github.io" idx = server.register_namespace(uri) # create a new node type we can instantiate in our address space dev = server.nodes.base_object_type.add_object_type(0, "MyDevice") dev.add_variable(0, "sensor1", 1.0) dev.add_property(0, "device_id", "0340") ctrl = dev.add_object(0, "controller") ctrl.add_property(0, "state", "Idle")
class TestCryptoConnect(unittest.TestCase): ''' Test connectino with a server supporting crypto ''' @classmethod def setUpClass(self): # start our own server self.srv_crypto = Server() self.uri_crypto = 'opc.tcp://localhost:%d' % port_num1 self.srv_crypto.set_endpoint(self.uri_crypto) # load server certificate and private key. This enables endpoints # with signing and encryption. self.srv_crypto.load_certificate("examples/certificate-example.der") self.srv_crypto.load_private_key("examples/private-key-example.pem") self.srv_crypto.start() # start a server without crypto self.srv_no_crypto = Server() self.uri_no_crypto = 'opc.tcp://localhost:%d' % port_num2 self.srv_no_crypto.set_endpoint(self.uri_no_crypto) self.srv_no_crypto.start() @classmethod def tearDownClass(self): # stop the server self.srv_no_crypto.stop() self.srv_crypto.stop() def test_nocrypto(self): clt = Client(self.uri_no_crypto) clt.connect() try: clt.get_objects_node().get_children() finally: clt.disconnect() 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") def test_basic256(self): clt = Client(self.uri_crypto) try: clt.set_security_string("Basic256,Sign,examples/certificate-example.der,examples/private-key-example.pem") clt.connect() self.assertTrue(clt.get_objects_node().get_children()) finally: clt.disconnect() def test_basic256_encrypt(self): clt = Client(self.uri_crypto) try: clt.set_security_string("Basic256,SignAndEncrypt,examples/certificate-example.der,examples/private-key-example.pem") clt.connect() self.assertTrue(clt.get_objects_node().get_children()) finally: clt.disconnect() def test_basic128Rsa15(self): clt = Client(self.uri_crypto) try: clt.set_security_string("Basic128Rsa15,Sign,examples/certificate-example.der,examples/private-key-example.pem") clt.connect() self.assertTrue(clt.get_objects_node().get_children()) finally: clt.disconnect() def test_basic128Rsa15_encrypt(self): clt = Client(self.uri_crypto) try: clt.set_security_string("Basic128Rsa15,SignAndEncrypt,examples/certificate-example.der,examples/private-key-example.pem") clt.connect() self.assertTrue(clt.get_objects_node().get_children()) finally: clt.disconnect() def test_basic256_encrypt_success(self): clt = Client(self.uri_crypto) try: clt.set_security(security_policies.SecurityPolicyBasic256, 'examples/certificate-example.der', 'examples/private-key-example.pem', None, ua.MessageSecurityMode.SignAndEncrypt ) clt.connect() self.assertTrue(clt.get_objects_node().get_children()) finally: clt.disconnect() def test_basic256_encrypt_feil(self): # FIXME: how to make it feil??? clt = Client(self.uri_crypto) with self.assertRaises(ua.UaError): clt.set_security(security_policies.SecurityPolicyBasic256, 'examples/certificate-example.der', 'examples/private-key-example.pem', None, ua.MessageSecurityMode.None_ )