Beispiel #1
0
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()
    #-------------------------------------------------------------------------------
    types = server.get_node(ua.ObjectIds.BaseObjectType)

    object_type_to_derive_from = server.get_root_node().get_child(
        ["0:Types", "0:ObjectTypes", "0:BaseObjectType"])
    mycustomobj_type = types.add_object_type(idx, "MyCustomObjectType")
    mycustomobj_type.add_variable(0, "var_should_be_there_after_instantiate",
                                  1.0)  # demonstrates instantiate

    myobj = objects.add_object(idx, "MyCustomObjectA", mycustomobj_type.nodeid)
    #-------------------------------------------------------------------------------

    # Example 3 - import a new object from xml address space and create a instance of the new object type
    #-------------------------------------------------------------------------------
    # Import customobject type
    server.import_xml('customobject.xml')

    # get nodeid of custom object type by one of the following 3 ways:
    # 1) Use node ID
    # 2) Or Full path
    # 3) Or As child from parent
    myobject1_type_nodeid = ua.NodeId.from_string('ns=%d;i=2' % idx)
    myobject2_type_nodeid = server.get_root_node().get_child([
        "0:Types", "0:ObjectTypes", "0:BaseObjectType",
        "%d:MyCustomObjectType" % idx
    ]).nodeid
    myobject3_type_nodeid = server.get_node(
        ua.ObjectIds.BaseObjectType).get_child(["%d:MyCustomObjectType" % idx
                                                ]).nodeid

    # populating our address space
Beispiel #3
0
async 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.nodes.objects
        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])

    try:
        await server.init()
        async with server:

            if args.shell:
                embed()
            elif args.populate:
                count = 0
                while True:
                    await asyncio.sleep(1)
                    myvar.write_value(math.sin(count / 10))
                    myarrayvar.write_value(
                        [math.sin(count / 10),
                         math.sin(count / 100)])
                    count += 1
            else:
                while True:
                    await asyncio.sleep(1)
    except OSError as e:
        print(e)
        sys.exit(1)
    except KeyboardInterrupt:
        pass
    sys.exit(0)