Esempio n. 1
0
async def main():
    # setup our server
    server = Server()
    await server.init()
    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 = await 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 = await objects.add_object(idx, 'MyObject')
    myvar = await myobj.add_variable(idx, 'MyVariable', 6.7)
    # Set MyVariable to be writable by clients
    await myvar.set_writable()
    await objects.add_method(ua.NodeId('ServerMethod', 2),
                             ua.QualifiedName('ServerMethod', 2), func,
                             [ua.VariantType.Int64], [ua.VariantType.Int64])
    _logger.info('Starting server!')
    async with server:
        count = 0
        while True:
            await asyncio.sleep(1)
            count += 0.1
            _logger.info('Set value of %s to %.1f', myvar, count)
            await myvar.set_value(count)
Esempio n. 2
0
async def start_server(loop: asyncio.AbstractEventLoop):
    server = Server()
    await server.init()
    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 = await 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 = await objects.add_object(idx, "MyObject")
    # Creating a custom event: Approach 1
    # The custom event object automatically will have members from its parent (BaseEventType)
    etype = await server.create_custom_event_type(
        idx, 'MyFirstEvent', ua.ObjectIds.BaseEventType,
        [('MyNumericProperty', ua.VariantType.Float),
         ('MyStringProperty', ua.VariantType.String)])
    myevgen = await server.get_event_generator(etype, myobj)
    # Creating a custom event: Approach 2
    custom_etype = await server.nodes.base_event_type.add_object_type(
        2, 'MySecondEvent')
    await custom_etype.add_property(2, 'MyIntProperty',
                                    ua.Variant(0, ua.VariantType.Int32))
    await custom_etype.add_property(2, 'MyBoolProperty',
                                    ua.Variant(True, ua.VariantType.Boolean))
    mysecondevgen = await server.get_event_generator(custom_etype, myobj)
    await server.start()
    loop.call_later(2, emmit_event, loop, myevgen, mysecondevgen, 1)
Esempio n. 3
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()
Esempio n. 4
0
async def main():
    # Certificates folder
    certs_folder = os.environ.get('CERTS_FOLDER', os.path.dirname(os.path.realpath(__file__)))
    key_pem_path = os.path.join(certs_folder, "key.pem")
    cert_der_path = os.path.join(certs_folder, "certificate.der")

    server = Server()
    await server.init()
    await server.set_application_uri("urn:opcua:iom:server")
    server.set_endpoint('opc.tcp://0.0.0.0:4840/freeopcua/server/')
    server.set_server_name("IoM PLC Server Example")

    # Security
    await server.load_certificate(cert_der_path)
    await server.load_private_key(key_pem_path)
    server.set_security_policy([
                ua.SecurityPolicyType.NoSecurity,
                ua.SecurityPolicyType.Basic256Sha256_SignAndEncrypt])

    # setup our own namespace, not really necessary but should as spec
    idx = await server.register_namespace("https://tknika.eus/opcua/demo/plc")
    # get Objects node, this is where we should put our nodes
    objects = server.get_objects_node()
    # populating our address space
    plc_server = await objects.add_object(idx, 'PLC Server')

    bool_data = await plc_server.add_variable(idx, 'BooleanData', True, datatype=ua.NodeId(1, 0))
    pos_data = await plc_server.add_variable(idx, 'PositiveTrendData', 0, datatype=ua.NodeId(11, 0))
    neg_data = await plc_server.add_variable(idx, 'NegativeTrendData', 0, datatype=ua.NodeId(11, 0))
    temp_data = await plc_server.add_variable(idx, 'TemperatureData', 18.5, datatype=ua.NodeId(11, 0))
    hum_data = await plc_server.add_variable(idx, 'HumidityData', 60.2, datatype=ua.NodeId(11, 0))
    cyc_data = await plc_server.add_variable(idx, 'CyclicData', 0, datatype=ua.NodeId(11, 0))
    mirror_orig_data = await plc_server.add_variable(idx, 'MirrorDataOriginal', True, datatype=ua.NodeId(1, 0))
    mirror_copy_data = await plc_server.add_variable(idx, 'MirrorDataCopy', True, datatype=ua.NodeId(1, 0))
    latitude_data = await plc_server.add_variable(idx, "GPSLatitude", "", datatype=ua.NodeId(12, 0))
    longitude_data = await plc_server.add_variable(idx, "GPSLongitude", "", datatype=ua.NodeId(12, 0))
    latitude_longitude_data = await plc_server.add_variable(idx, "GPSLatitudeAndLongitude", "", datatype=ua.NodeId(12, 0))

    logger.info('Starting OPC UA server!')

    bool_task = asyncio.Task(toggle_data(bool_data, refresh=10, init=True))
    pos_task = asyncio.Task(periodic_data(pos_data, refresh=5))
    neg_task = asyncio.Task(periodic_data(neg_data, refresh=5, increment=-2))
    temp_task = asyncio.Task(random_data(temp_data, refresh=10, init=18.5, min=15, max=22))
    hum_task = asyncio.Task(random_data(hum_data, refresh=10, init=60.2, min=0, max=100))
    cyclic_task = asyncio.Task(cyclic_data(cyc_data, cycle_time=200, step=0.5, init=0, min=-100, max=100))
    
    mirror_handler = MirrorHandler(server, mirror_orig_data, mirror_copy_data)
    await mirror_handler.start()

    tcx_update_handler = TCXUpdateHandler("circular-urnieta-aia-donosti-urnieta.tcx", latitude_data, longitude_data, latitude_longitude_data)
    tcx_task = asyncio.Task(tcx_update_handler.start())

    async with server:
        await asyncio.gather(bool_task, pos_task, neg_task, temp_task, hum_task, cyclic_task, tcx_task)
Esempio n. 5
0
async def serve_state(duration=None, frequency=1, debug=False):
    server = Server()
    await server.init()
    server.set_endpoint("opc.tcp://0.0.0.0:4840/pulsedng/")

    # setup our own namespace, not really necessary but should as spec
    uri = "http://pulsedng.xenon-sc.lngs.infn.it"
    nsidx = await server.register_namespace(uri)

    # --------------------------------------------------------
    # create custom enum data type
    # --------------------------------------------------------
    enums = await server.get_root_node().get_child(
        ["0:Types", "0:DataTypes", "0:BaseDataType", "0:Enumeration"])

    # 1.
    # Create Enum Type
    GeneratorState_type = await enums.add_data_type(nsidx, 'GeneratorState')

    # Or convert the existing IntEnum GeneratorState
    es = await GeneratorState_type.add_property(
        0, "EnumStrings", enum_to_stringlist(GeneratorState))

    await es.set_value_rank(1)
    await es.set_array_dimensions([0])

    # --------------------------------------------------------
    # create object with enum variable
    # --------------------------------------------------------
    # get Objects node, this is where we should put our custom stuff
    objects = server.get_objects_node()

    # create object
    myobj = await objects.add_object(nsidx, 'GeneratorObject')

    # add var with as type the custom enumeration
    GeneratorState_var = await myobj.add_variable(
        nsidx,
        'GeneratorState2Var',
        GeneratorState.off,
        datatype=GeneratorState_type.nodeid)
    await GeneratorState_var.set_writable()
    await GeneratorState_var.set_value(GeneratorState.idle
                                       )  # change value of enumeration

    _logger.info('Starting server!')
    async with server:
        while True:
            for state in GeneratorState:
                await asyncio.sleep(2)
                _logger.info('Set value of %s to %d', GeneratorState_var,
                             state)
                await GeneratorState_var.set_value(state)
Esempio n. 6
0
async def main():
    # setup our server
    server = Server()
    await server.init()
    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 = await server.register_namespace(uri)

    # await server.import_xml('device.xml')
    # # get Objects node, this is where we should put our nodes
    objects = server.get_objects_node()


    suobj=await objects.add_object(idx,'ROCKWELLObj')
    suvar=[]

    device=Rockwell_AB_PLC
    device.IP = '192.168.100.200'
    device.tag_list = ['Program:MainProgram.run', 'Program:MainProgram.start', 'Program:MainProgram.EMG',
                       'Local:1:O.Data.0', 'Local:1:O.Data.1', 'Local:1:O.Data.2','Local:1:O.Data.3', 'Local:1:O.Data.4',
                       'Local:1:O.Data.5','Local:1:O.Data.6', 'Local:1:O.Data.7']
    # 初始化 创建 opc ua变量
    a=0
    for i in device.tag_list:
        suvar.append(i)
        suvar[a]=await suobj.add_variable(idx,i,0) # fixme 初始化都写0
        await suvar[a].set_writable()
        a+=1

    # await objects.add_method(
    #     ua.NodeId('ServerMethod', 2), ua.QualifiedName('ServerMethod', 2),
    #     func, [ua.VariantType.Int64], [ua.VariantType.Int64]
    # )
    # _logger.info('Starting server!')
    async with server:
        count = 0
        while True:
            await asyncio.sleep(1) # 数据更新周期
            # print(device.IP,device.tag_list)
            aa,bb = rockwellread(device.IP,device.tag_list)
            # print(cc.Value)
            # print(aa,bb)
            # count += 0.1
            # _logger.info(aa, bb)
            # await myvar.write_value(count)
            a=0
            for i in bb:
                await suvar[a].write_value(i)
                a+=1
Esempio n. 7
0
async def main():

    # setup our server
    server = Server()

    # Configure server to use sqlite as history database (default is a simple memory dict)
    server.iserver.history_manager.set_storage(
        HistorySQLite("my_datavalue_history.sql"))

    # initialize server
    await server.init()

    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 = await 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 = await objects.add_object(idx, "MyObject")
    myvar = await myobj.add_variable(idx, "MyVariable",
                                     ua.Variant(0, ua.VariantType.Double))
    await myvar.set_writable()  # Set MyVariable to be writable by clients
    print(myvar)

    # starting!
    await server.start()

    # enable data change history for this particular node, must be called after start since it uses subscription
    await server.historize_node_data_change(myvar, period=None, count=100)

    try:
        count = 0
        while True:
            await asyncio.sleep(1)
            count += 0.1
            await myvar.set_value(math.sin(count))

    finally:
        # close connection, remove subscriptions, etc
        await server.stop()
Esempio n. 8
0
async def main():
    # setup our server
    server = Server()
    await server.init()
    server.set_endpoint('opc.tcp://localhost:4840/sunbeltOPC/server/')
    # 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()

    # Gather updated values from OpenWeather Map api for mapping.
    pressure = 999
    temperature = 999
    humidity = 999
    wind_speed = 999

    # populating our address space
    root_obj = await objects.add_object(idx, 'Weather Data')

    # define variables wanted by the server here.
    w_pressure = await root_obj.add_variable(idx, 'Pressure', pressure)
    w_temperature = await root_obj.add_variable(idx, 'Temperature',
                                                temperature)
    w_humidity = await root_obj.add_variable(idx, 'Humidity', humidity)
    w_wind_speed = await root_obj.add_variable(idx, 'Wind Speed', wind_speed)

    # define variables that you may want to be writable by niagara here
    w_location = await root_obj.add_variable(idx, 'Location',
                                             'Santa Clara, US')

    # Set variables from above to be writable by clients
    await w_location.set_writable()

    _logger.info('Starting server!')
    async with server:
        while True:
            await asyncio.sleep(10)
            loc = await w_location.read_value()
            weather = update_weather(loc)
            await w_pressure.set_value(weather[0])
            await w_temperature.set_value(weather[1])
            await w_humidity.set_value(weather[2])
            await w_wind_speed.set_value(weather[3])
Esempio n. 9
0
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()
Esempio n. 10
0
async def init_server():
    with open(r'../configuration.yml') as config_file:
        config = yaml.load(config_file, Loader=yaml.FullLoader)

        server = Server()
        await server.init()
        server.set_endpoint("opc.tcp://" + config['host'] + ":" +
                            str(config['port']))

        namespace = await server.register_namespace(config['namespace'])
        root_node = server.get_objects_node()
        objects = await root_node.add_object(namespace, "BaseObjects")

        server_rtt = await objects.add_variable(namespace, "server_rtt", None)

        data_pool = await objects.add_variable(namespace, "data_pool", None)

        await server_rtt.set_writable()
        await data_pool.set_writable()

        server_tests = Server_tests(server_rtt, data_pool)

        server.link_method(root_node, server_tests.random_sort)

        random_sort_method = await objects.add_method(
            namespace, "random_sort", server_tests.random_sort,
            [ua.VariantType.Int64, ua.VariantType.Float, ua.VariantType.Float],
            [ua.VariantType.Float])

        await server.start()

        try:
            print("OPC-UA server started")
            while True:
                await asyncio.sleep(1)
        finally:
            await server.stop()
import time

from asyncua 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()

    # Example 1 - create a basic object
    #-------------------------------------------------------------------------------
    myobj = objects.add_object(idx, "MyObject")
    #-------------------------------------------------------------------------------

    # Example 2 - create a new object type and a instance of the new object type
    #-------------------------------------------------------------------------------
    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
Esempio n. 12
0
async def main():
    print('starting OPC server ')
    opc_server = Server()
    await opc_server.init()
    opc_url = "opc.tcp://0.0.0.0:4840"
    opc_server.set_endpoint(opc_url)

    print('starting OPC server ..')
    opc_name = "Grove-opcua-server"
    addspace = await opc_server.register_namespace(opc_name)
    print('starting OPC server ...')

    opc_node = opc_server.get_objects_node()
    param = await opc_node.add_object(addspace, "Parameters")

    opc_time = await param.add_variable(addspace, "Time", 0)
    opc_warehouse_state = await param.add_variable(addspace, "Warehouse state",
                                                   0)
    opc_door_outside = await param.add_variable(addspace, "Outside door", 0)
    opc_door_inside = await param.add_variable(addspace, "Inside door", 0)
    opc_temperature_d = await param.add_variable(addspace,
                                                 "Temperature doorlock", 0.0)
    opc_temperature_w = await param.add_variable(addspace,
                                                 "Temperature warehouse", 0.0)

    await opc_time.set_read_only()
    await opc_warehouse_state.set_read_only()
    await opc_door_outside.set_read_only()
    await opc_door_inside.set_read_only()
    await opc_temperature_d.set_read_only()
    await opc_temperature_w.set_read_only()

    print('starting OPC server .....')
    print("OPC UA Server started at {}".format(opc_url))
    print("time      Doors Warehouse (Celsius)")

    # is voor terminal-mode, niet voor windows mode
    async with opc_server:

        while True:
            try:
                await asyncio.sleep(2)
                time_stamp = datetime.now()
                await opc_time.set_value(time_stamp)
                await opc_temperature_d.set_value(temperature_doors.temperature
                                                  )
                await opc_temperature_w.set_value(
                    temperature_warehouse.temperature)
                print('{} {:.1f} {:.1f}'.format(
                    time_stamp.strftime("%X"), temperature_doors.temperature,
                    temperature_warehouse.temperature))
                await opc_warehouse_state.set_value(warehouse_state)
                await opc_door_outside.set_value(door_outside_state)
                await opc_door_inside.set_value(door_inside_state)
            except KeyboardInterrupt:
                warehouse_relay.off()
                door_outside_relay.off()
                door_inside_relay.off()
                warehouse_button.led_off()
                door_outside_button.led_off()
                door_inside_button.led_off()
                await opc_server.stop()
                print("exit")
                exit(1)
Esempio n. 13
0
async def main():
    # optional: setup logging
    logging.basicConfig(level=logging.WARN)
    # logger = logging.getLogger("asyncua.address_space")
    # logger.setLevel(logging.DEBUG)
    # logger = logging.getLogger("asyncua.internal_server")
    # logger.setLevel(logging.DEBUG)
    # logger = logging.getLogger("asyncua.binary_server_asyncio")
    # logger.setLevel(logging.DEBUG)
    # logger = logging.getLogger("asyncua.uaprocessor")
    # logger.setLevel(logging.DEBUG)
    # logger = logging.getLogger("asyncua.subscription_service")
    # logger.setLevel(logging.DEBUG)

    # now setup our server
    server = Server()
    await server.init()
    # 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 = await 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
    await objects.add_folder(idx, "myEmptyFolder")
    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
    myarrayvar = await myobj.add_variable(idx, "myarrayvar", [6.7, 7.9])
    await myobj.add_variable(idx, "myStronglytTypedVariable",
                             ua.Variant([], ua.VariantType.UInt32))
    await myobj.add_property(idx, "myproperty", "I am a property")
    await myobj.add_method(idx, "mymethod", func, [ua.VariantType.Int64],
                           [ua.VariantType.Boolean])

    inargx = ua.Argument()
    inargx.Name = "x"
    inargx.DataType = ua.NodeId(ua.ObjectIds.Int64)
    inargx.ValueRank = -1
    inargx.ArrayDimensions = []
    inargx.Description = ua.LocalizedText("First number x")
    inargy = ua.Argument()
    inargy.Name = "y"
    inargy.DataType = ua.NodeId(ua.ObjectIds.Int64)
    inargy.ValueRank = -1
    inargy.ArrayDimensions = []
    inargy.Description = ua.LocalizedText("Second number y")
    outarg = ua.Argument()
    outarg.Name = "Result"
    outarg.DataType = ua.NodeId(ua.ObjectIds.Int64)
    outarg.ValueRank = -1
    outarg.ArrayDimensions = []
    outarg.Description = ua.LocalizedText("Multiplication result")

    await myobj.add_method(idx, "multiply", multiply, [inargx, inargy],
                           [outarg])
    await myobj.add_method(idx, "multiply_async", multiply_async,
                           [inargx, inargy], [])
    await myobj.add_method(idx, "func_async", func_async,
                           [ua.VariantType.Int64], [])

    async with server:
        while True:
            await asyncio.sleep(1)
async def main():
    # setup our server
    server = Server()
    endpoint_url = "opc.tcp://0.0.0.0:4840/freeopcua/server/"
    if len(sys.argv) > 1:
        endpoint_url = sys.argv[1]
    print("Use Server Endpoint: " + endpoint_url)
    await server.init()
    server.set_endpoint(endpoint_url)
    # setup our own namespace, not really necessary but should as spec
    uri = 'http://examples.codecentric.de'
    idx = await server.register_namespace(uri)
    # get Objects node, this is where we should put our nodes
    objects = server.get_objects_node()
    # populating our address space
    _logger.info('Starting server!')

    belt1 = await objects.add_object(idx, "Convoyer Belt1")
    arm = await objects.add_object(idx, "Robot Arm")

    pre_stage_temp = 25.0
    mid_stage_temp = 65.0
    post_stage_temp = 90.0

    # motor has a possible degree from 0 to 180
    motor_degree = 0

    pre_stage = await belt1.add_variable(idx, "PreStage", pre_stage_temp)
    mid_stage = await belt1.add_variable(idx, "MidStage", mid_stage_temp)
    post_stage = await belt1.add_variable(idx, "PostStage", post_stage_temp)

    motor_degree_var = await arm.add_variable(idx, "Motor", motor_degree)

    ts = await belt1.add_variable(idx, "TimeStamp", datetime.now().isoformat())
    ts_arm = await arm.add_variable(idx, "TimeStamp", datetime.now().isoformat())
    async with server:
        count = 0
        current_pos = 0
        positive_direction = True
        while True:
            await asyncio.sleep(0.1)
            count += 1
            randomizer = randrange(1, 10)
            now = datetime.now().isoformat()
            temp = calc_temp(pre_stage_temp, count, randomizer * 200)
            temp2 = calc_temp(mid_stage_temp, count, randomizer * 1000)
            temp3 = calc_temp(post_stage_temp, count, randomizer * 500)

            await pre_stage.set_value(temp)
            await mid_stage.set_value(temp2)
            await post_stage.set_value(temp3)
            await ts.set_value(now)

            step_size = 1

            # every 500 steps, delay:
            if count % (randomizer * 500) == 0:
                _logger.info("Delay Robot Arm")
                step_size = 0

            if positive_direction and current_pos < 180:
                current_pos += step_size
            elif positive_direction and current_pos >= 180:
                positive_direction = False
                current_pos -= step_size
            elif not positive_direction and 0 < current_pos < 180:
                current_pos -= step_size
            elif not positive_direction and current_pos <= 0:
                positive_direction = True
                current_pos += step_size

            await ts_arm.set_value(now)
            await motor_degree_var.set_value(current_pos)
            _logger.debug('Set value of %s to %.1f', temp, count)
            _logger.debug('Arm Position of %s to %.1f', str(positive_direction), current_pos)

            if count == 10000:
                count = 0
Esempio n. 15
0
async def main():
    @uamethod
    async def callback(parent, in_extobj):
        out_extobj = ua.uaprotocol_auto.AxisInformation(
        )  # get new instanace of AxisInformation
        out_extobj.EngineeringUnits = in_extobj.EngineeringUnits
        out_extobj.EURange.Low = in_extobj.EURange.Low
        out_extobj.EURange.High = in_extobj.EURange.High
        out_extobj.Title = in_extobj.Title
        out_extobj.AxisScaleType = in_extobj.AxisScaleType
        out_extobj.AxisSteps = in_extobj.AxisSteps

        await axis_info.set_value(out_extobj)  #write values to variable

        ret = (ua.Variant(out_extobj, ua.VariantType.ExtensionObject),
               ua.Variant("test", ua.VariantType.String))

        return ret

    server = Server()
    await server.init()
    server.set_endpoint("opc.tcp://0.0.0.0:4840/freeopcua/server/")
    server.set_security_policy([ua.SecurityPolicyType.NoSecurity])

    obj = server.get_objects_node()
    idx = await server.register_namespace("http://examples.freeopcua.github.io"
                                          )

    await server.load_data_type_definitions()

    inarg_extobj = ua.Argument()
    inarg_extobj.Name = "In"
    inarg_extobj.DataType = ua.NodeId(12079, 0)
    inarg_extobj.ValueRank = -1
    inarg_extobj.ArrayDimensions = []
    inarg_extobj.Description = ua.LocalizedText("Wanted AxisInformation")

    outarg_extobj = ua.Argument()
    outarg_extobj.Name = "Out"
    outarg_extobj.DataType = ua.NodeId(12079, 0)
    outarg_extobj.ValueRank = -1
    outarg_extobj.ArrayDimensions = []
    outarg_extobj.Description = ua.LocalizedText("Actual AxisInformation")

    status = ua.Argument()
    status.Name = "Status"
    status.DataType = ua.NodeId(12, 0)
    status.ValueRank = -1
    status.ArrayDimensions = []
    status.Description = ua.LocalizedText("MSG")

    method_parent = await obj.add_object(idx, "Methods")
    method_node = await method_parent.add_method(idx, "SetAxisInformation",
                                                 callback, [inarg_extobj],
                                                 [outarg_extobj, status])

    #add a variable of type AxisInformation
    axis_info = await obj.add_variable(
        idx,
        "AxisInformation",
        ua.uaprotocol_auto.AxisInformation(),
        varianttype=ua.VariantType.ExtensionObject)

    async with server:
        while 1:
            await asyncio.sleep(0)
Esempio n. 16
0
async def main():
    # setup our server
    server = Server()
    await server.init()
    server.default_timeout = 60
    # server.set_endpoint('opc.tcp://0.0.0.0:4840/freeopcua/server/')
    server.set_endpoint('opc.tcp://192.168.100.170:4840/')
    # setup our own namespace, not really necessary but should as spec

    # 设置加密和密钥后 prosys可以连接
    await server.load_certificate("certificate-example.der")
    await server.load_private_key("private-key-example.pem")

    # set all possible endpoint policies for clients to connect through
    server.set_security_policy([
        ua.SecurityPolicyType.NoSecurity,
        ua.SecurityPolicyType.Basic256Sha256_SignAndEncrypt,
        ua.SecurityPolicyType.Basic256Sha256_Sign
    ])

    uri = 'http://examples.freeopcua.github.io'
    idx = await server.register_namespace(uri)

    # await server.import_xml('device.xml')
    # # get Objects node, this is where we should put our nodes
    objects = server.get_objects_node()

    suobj = await objects.add_object(idx, 'ROCKWELLObj')
    suvar = []

    device = Rockwell_AB_PLC
    device.IP = '192.168.100.200'
    device.tag_list = [
        'Program:MainProgram.run', 'Program:MainProgram.start',
        'Program:MainProgram.EMG', 'Local:1:O.Data.0', 'Local:1:O.Data.1',
        'Local:1:O.Data.2', 'Local:1:O.Data.3', 'Local:1:O.Data.4',
        'Local:1:O.Data.5', 'Local:1:O.Data.6', 'Local:1:O.Data.7',
        'Program:MainProgram.EP_Timer.PRE', 'Program:MainProgram.EP_Timer.ACC',
        'Program:MainProgram.EP_Timer.EN', 'Program:MainProgram.EP_Timer.TT',
        'Program:MainProgram.EP_Timer.DN'
    ]
    # 初始化 创建 opc ua变量
    a = 0
    for i in device.tag_list:
        suvar.append(i)
        nodeid = (f'ns={idx};s={i}')
        # print(nodeid,type(nodeid))
        # i=i.replace(':','-')
        # 添加变量,add_variable(NodeId(xxxx), QualifiedName(xxxx), DataValue(xxx))
        # 加QualifiedName()否则直接写字符串":"会分割字符串 报错
        suvar[a] = await suobj.add_variable(ua.NodeId(nodeid),
                                            ua.QualifiedName(i), True)
        # fixme 初始化需不需要特殊操作? 暂时都写0 最好和后续变量类型一致
        await suvar[a].set_writable()
        a += 1

    # await objects.add_method(
    #     ua.NodeId('ServerMethod', 2), ua.QualifiedName('ServerMethod', 2),
    #     func, [ua.VariantType.Int64], [ua.VariantType.Int64]
    # )
    # _logger.info('Starting server!')
    async with server:
        count = 0
        while True:
            await asyncio.sleep(1)  # 数据更新周期
            # print(device.IP,device.tag_list)
            aa, bb = rockwellread(device.IP, device.tag_list)
            # print(cc.Value)
            # print(aa,bb)
            # count += 0.1
            # _logger.info(aa, bb)
            # await myvar.write_value(count)
            a = 0
            for i in bb:
                await suvar[a].write_value(i)
                a += 1