当前位置: 首页>>代码示例>>Python>>正文


Python Server.set_endpoint方法代码示例

本文整理汇总了Python中opcua.Server.set_endpoint方法的典型用法代码示例。如果您正苦于以下问题:Python Server.set_endpoint方法的具体用法?Python Server.set_endpoint怎么用?Python Server.set_endpoint使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在opcua.Server的用法示例。


在下文中一共展示了Server.set_endpoint方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: TestClient

# 需要导入模块: from opcua import Server [as 别名]
# 或者: from opcua.Server import set_endpoint [as 别名]
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)
开发者ID:tander67,项目名称:python-opcua,代码行数:33,代码来源:tests.py

示例2: __init__

# 需要导入模块: from opcua import Server [as 别名]
# 或者: from opcua.Server import set_endpoint [as 别名]
class HelloServer:
    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])

    def __enter__(self):
        self.server.start()
        return self.server

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.server.stop()
开发者ID:bitkeeper,项目名称:python-opcua,代码行数:32,代码来源:server.py

示例3: TestRefsWidget

# 需要导入模块: from opcua import Server [as 别名]
# 或者: from opcua.Server import set_endpoint [as 别名]
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)
开发者ID:FreeOpcUa,项目名称:opcua-widgets,代码行数:15,代码来源:tests.py

示例4: test_port_in_use

# 需要导入模块: from opcua import Server [as 别名]
# 或者: from opcua.Server import set_endpoint [as 别名]
    def test_port_in_use(self):

        server1 = Server()
        server1.set_endpoint('opc.tcp://localhost:{0:d}'.format(port_num + 1))
        server1.start()

        server2 = Server()
        server2.set_endpoint('opc.tcp://localhost:{0:d}'.format(port_num + 1))
        try:
            server2.start()
        except Exception:
            pass
        
        server1.stop()
        server2.stop()
开发者ID:bitkeeper,项目名称:python-opcua,代码行数:17,代码来源:tests_server.py

示例5: TestServer

# 需要导入模块: from opcua import Server [as 别名]
# 或者: from opcua.Server import set_endpoint [as 别名]
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")
开发者ID:noseii,项目名称:python-opcua,代码行数:49,代码来源:tests.py

示例6: TestCmdLines

# 需要导入模块: from opcua import Server [as 别名]
# 或者: from opcua.Server import set_endpoint [as 别名]
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()
开发者ID:Johen8,项目名称:python-opcua,代码行数:46,代码来源:tests_cmd_lines.py

示例7: TestServer

# 需要导入模块: from opcua import Server [as 别名]
# 或者: from opcua.Server import set_endpoint [as 别名]
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)
开发者ID:xtofl,项目名称:python-opcua,代码行数:44,代码来源:tests.py

示例8: mymain

# 需要导入模块: from opcua import Server [as 别名]
# 或者: from opcua.Server import set_endpoint [as 别名]
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()
开发者ID:bitkeeper,项目名称:python-opcua,代码行数:23,代码来源:test_perf.py

示例9: ServerPython

# 需要导入模块: from opcua import Server [as 别名]
# 或者: from opcua.Server import set_endpoint [as 别名]
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)
开发者ID:FreeOpcUa,项目名称:opcua-modeler,代码行数:40,代码来源:server_manager.py

示例10: uaserver

# 需要导入模块: from opcua import Server [as 别名]
# 或者: from opcua.Server import set_endpoint [as 别名]
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)
开发者ID:sightmachine,项目名称:python-opcua,代码行数:83,代码来源:tools.py

示例11: TestServer

# 需要导入模块: from opcua import Server [as 别名]
# 或者: from opcua.Server import set_endpoint [as 别名]
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
        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()
        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(), 1)
        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])
        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")
开发者ID:jadro,项目名称:python-opcua,代码行数:82,代码来源:tests.py

示例12: AdminTestClient

# 需要导入模块: from opcua import Server [as 别名]
# 或者: from opcua.Server import set_endpoint [as 别名]
class AdminTestClient(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 admin client
        self.clt = Client('opc.tcp://[email protected]:%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()



    @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(Exception):
            self.clt.bclient._send_request(request)

    def test_objects_anonymous(self):
        objects = self.ro_clt.get_objects_node()
        with self.assertRaises(Exception):
            objects.set_attribute(ua.AttributeIds.WriteMask, ua.DataValue(999))
        with self.assertRaises(Exception):
            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(Exception):
            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(Exception):
            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(Exception):
            v_ro.set_value(9)
        self.assertEqual(v_ro.get_value(), 2)
开发者ID:jadro,项目名称:python-opcua,代码行数:73,代码来源:tests.py

示例13: OPCServer

# 需要导入模块: from opcua import Server [as 别名]
# 或者: from opcua.Server import set_endpoint [as 别名]
class OPCServer(object):
    
    def __init__(self, settings):
        super(OPCServer, self).__init__()
        server_settings = settings.get("server")
        objects = settings.get("objects")
        
        self._endpoint = server_settings["endpoint"]
        self._name = server_settings["name"]
        self._namespace = server_settings["namespace"]
    
        self._init_server()
        
        
        for o in objects:
            self._add_object(o["name"])
            for variable, value in o["ro_variables"].items():
                self._add_variable(o["name"], variable, value)
            for variable, value in o["rw_variables"].items():
                self._add_variable(o["name"], variable, value, True)
        
    def start(self):
        if self._server:
            self._server.start()

    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 stop(self):
        self._server.stop()
        
    def _add_object(self, object_name):
        self._objects[object_name] = { 'object': self._objects_node.add_object(self._index, object_name), 'variables' : {}}
        
    def _add_variable(self, object_name, variable_name, value, writable=False):
        obj = self._objects.get(object_name, None)
        if obj.get('object', None):
            var = self._objects_node.add_variable(self._index, variable_name, str(value))
            obj['variables'][variable_name] = var
            if writable:
                var.set_writable()
            return True
        return False
        
    def _get_variable(self, object_name, variable_name):
        obj = self._objects.get(object_name)
        if obj.get('object', None):
            var = obj['variables'].get(variable_name, None)
            return var
        return None
                        
    def set_value(self, object_name, variable_name, value):
        var = self._get_variable(object_name, variable_name)
        if var:
            var.set_value(str(value))
            return True
        return False
            
    def get_value(self, object_name, variable_name):
        var = self._get_variable(object_name, variable_name)
        if var:
            return var.get_value()
        return None
开发者ID:f1soft,项目名称:calvin-base,代码行数:74,代码来源:server.py

示例14: TestClient

# 需要导入模块: from opcua import Server [as 别名]
# 或者: from opcua.Server import set_endpoint [as 别名]
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)
        add_server_methods(self.srv)
        self.srv.start()

        # start admin client
        # long timeout since travis (automated testing) can be really slow
        self.clt = Client('opc.tcp://[email protected]:%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)
开发者ID:JonSyuGithub,项目名称:python-opcua,代码行数:92,代码来源:tests_client.py

示例15: TestServer

# 需要导入模块: from opcua import Server [as 别名]
# 或者: from opcua.Server import set_endpoint [as 别名]
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):
#.........这里部分代码省略.........
开发者ID:Joy963,项目名称:python-opcua,代码行数:103,代码来源:tests_server.py


注:本文中的opcua.Server.set_endpoint方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。