def __init__(self): " Basic setup of server" # async def __init__ doesn't work self.server = Server() self.idx = None self.top = None self.vars = []
async def main(): global rpm_is puls.when_pressed = callback_rpm # set callback # setup our server server = Server() await server.init() server.set_endpoint('opc.tcp://pi.local: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) # populating our address space # server.nodes, contains links to very common nodes like objects and root myobj = await server.nodes.objects.add_object(idx, 'Car') rpm_var = await myobj.add_variable(idx, 'rpm', 0.0) motor_var = await myobj.add_variable(idx, 'motor', 0.0) # Set MyVariable to be writable by clients await rpm_var.set_writable() await motor_var.set_writable() await server.nodes.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: while True: #await asyncio.sleep(0.05) #rpm_is = await rpm() #if rpm_is>-1: # await rpm_var.write_value(rpm_is) #speed = await motor_var.read_value() #try: # motor.forward(speed) #except ValueError: # _logger.warning(f'\t\t{speed} no valid speed') rpm_is, speed = await asyncio.gather(*(get_rpm(rpm_var), set_speed(motor_var))) _logger.info(f'\t\tRPM: {rpm_is}\n\t\t\tMotor: {await motor_var.read_value()}')
class TestServer: def __init__(self): " Basic setup of server" # async def __init__ doesn't work self.server = Server() self.idx = None self.top = None self.vars = [] async def create_simulator(self): await self.server.init() self.server.set_endpoint(f'opc.tcp://{LOCAL_HOST}:{PORT}/{PATH}') self.server.set_server_name("OPC-UA Test Server") uri = "https://github.com/it-hms/my-opcua-test-server" self.idx = await self.server.register_namespace(uri) self.top = await self.server.nodes.objects.add_object( self.idx, 'Dynamic') for i in range(MAX_TAG + 1): t_var = await self.top.add_variable(self.idx, f"Random.Float{i}", 0) self.vars.append(t_var) async def run(self): async with self.server: while True: i = 0 for var in self.vars: await var.write_value(random.gauss(i * 10, 9)) i += 1 await asyncio.sleep(2)
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) myobj = await server.nodes.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 dev = await server.nodes.base_object_type.add_object_type(0, "MyDevice") await dev.add_variable(0, "sensor1", 1.0) mydevice = await instantiate(server.nodes.objects, dev, bname="2:Device0001") node_list = [dev, mydevice[0], myobj, myvar] exporter = XmlExporter(server) await exporter.build_etree(node_list, ['http://myua.org/test/']) await exporter.write_xml('ua-export.xml')
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)
async def main(): # setup our server server = Server() await server.init() server.set_endpoint('opc.tcp://*: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() # 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 await objects.add_method(ua.NodeId("ServerMethod", 2), ua.QualifiedName('ServerMethod', 2), func, [ua.VariantType.Int64], [ua.VariantType.Int64]) # starting! async with server: count = 0 while True: await asyncio.sleep(1) count += 0.1 print("SET VALUE", myvar, count) await myvar.set_value(count)
async def mymain(): # 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) # populating our address space myobj = await server.nodes.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: while True: await asyncio.sleep(10) #nb = 100000 #start = time.time() #for i in range(nb): #await server.write_attribute_value(myvar.nodeid, ua.DataValue(i)) #await myvar.write_value(i) print("\n Write frequency: \n", nb / (time.time() - start))
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) # create our custom object type dev = await server.nodes.base_object_type.add_object_type(0, "MyDevice") var = await dev.add_variable(0, "sensor1", 1.0) await var.set_modelling_rule(True ) # make that child instantiated by default prop = await dev.add_property(0, "device_id", "0340") await prop.set_modelling_rule(True) ctrl = await dev.add_object(0, "controller") await ctrl.set_modelling_rule(True) prop = await ctrl.add_property(0, "state", "Idle") await prop.set_modelling_rule(True) # instantiate our new object type nodes = await instantiate(server.nodes.objects, dev, bname="2:Device0001") mydevice = nodes[0] # the first node created is our main object #mydevice = server.nodes.objects.add_object(2, "Device0001", objecttype=dev) # specificying objecttype to add_object also instanciate a node type mydevice_var = await mydevice.get_child( ["0:controller", "0:state"]) # get proxy to our device state variable # starting! async with server: while True: await asyncio.sleep(1)
async def main_virtual_device(): #this code runs on the the cloud server # setup our server server = Server() await server.init() server.set_endpoint('opc.tcp://0.0.0.0:4841/virtual/server/') # setup our own namespace, not really necessary but should as spec uri = 'http://examples.freeopcua.github.io' idx = await server.register_namespace(uri) # populating our address space # server.nodes, contains links to very common nodes like objects and root component = await server.nodes.objects.add_object(idx, 'Component') sensor_value = await component.add_variable(idx, 'SensorValue', 6.7) command_id = await component.add_variable(idx, 'CommandID', 1) # Set CommandID to be writable by clients await command_id.set_writable() # Set SensorValue to be writable by clients (for the mirror server) await sensor_value.set_writable() _logger.info('Starting Virtual Device Server!') async with server: while True: await asyncio.sleep(update_period_s) #update values new_sensor_val = await sensor_value.read_value() print('[Virtual Device] value of %s is %.1f', sensor_value, new_sensor_val) new_command_val = await command_id.read_value() print('[Virtual Device] value of %s is %.1f', command_id, new_command_val)
async def main_physical_device(): #this code runs on the the physical device # setup our server server = Server() await server.init() server.set_endpoint('opc.tcp://0.0.0.0:4840/physical/server/') # setup our own namespace, not really necessary but should as spec uri = 'http://examples.freeopcua.github.io' idx = await server.register_namespace(uri) # populating our address space # server.nodes, contains links to very common nodes like objects and root component = await server.nodes.objects.add_object(idx, 'Component') sensor_value = await component.add_variable(idx, 'SensorValue', 6.7) command_id = await component.add_variable(idx, 'CommandID', 1) # Set CommandID to be writable by clients await command_id.set_writable() _logger.info('Starting Physical Device Server!') async with server: while True: await asyncio.sleep(update_period_s) #read command id new_command_val = await command_id.read_value() print('[Physical Device] value of %s is %.1f', command_id, new_command_val) #generate new sensor value new_sensor_val = math.sin(new_command_val * time.time()) print('[Physical Device] Set value of %s to %.1f', sensor_value, new_sensor_val) await sensor_value.write_value(new_sensor_val)
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) # populating our address space # server.nodes, contains links to very common nodes like objects and root myobj = await server.nodes.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 server.nodes.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.write_value(count)
async def srv_no_crypto(): # start our own server srv = Server() await srv.init() srv.set_endpoint(uri_no_crypto) await srv.start() yield srv # stop the server await srv.stop()
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" nsidx = await server.register_namespace(uri) # -------------------------------------------------------- # create custom enum data type # -------------------------------------------------------- # 1. # Create Enum Type myenum_type = await server.nodes.enum_data_type.add_data_type( nsidx, 'MyEnum') # 2. # Add enumerations as EnumStrings (Not yet tested with EnumValues) # Essential to use namespace 0 for EnumStrings ! es = await myenum_type.add_property(0, "EnumStrings", [ ua.LocalizedText("ok"), ua.LocalizedText("idle"), ]) # 3. load enums froms erver await server.load_enums() # now we have a python enum available to play with val = ua.MyEnum.ok # not sure these are necessary #es.write_value_rank(1) #es.write_array_dimensions([0]) # -------------------------------------------------------- # create object with enum variable # -------------------------------------------------------- # create object myobj = await server.nodes.objects.add_object(nsidx, 'MyObjectWithEnumVar') # add var with as type the custom enumeration myenum_var = await myobj.add_variable(nsidx, 'MyEnum2Var', val, datatype=myenum_type.nodeid) await myenum_var.set_writable() await myenum_var.write_value(ua.MyEnum.idle) # change value of enumeration async with server: while True: time.sleep(0.5)
async def discovery_server(): # start our own server srv = Server() await srv.init() await srv.set_application_uri('urn:freeopcua:python:discovery') srv.set_endpoint(f'opc.tcp://127.0.0.1:{port_discovery}') await srv.start() yield srv # stop the server await srv.stop()
async def server(url): srv = Server() srv.set_endpoint(url) await srv.init() await add_server_methods(srv) await add_server_custom_enum_struct(srv) async with srv: while t.do_run: await asyncio.sleep(1) await srv.stop()
async def server(): # start our own server srv = Server() await srv.init() srv.set_endpoint(f'opc.tcp://127.0.0.1:{port_num}') await add_server_methods(srv) await add_server_custom_enum_struct(srv) await srv.start() yield srv # stop the server await srv.stop()
async def srv_crypto(): # start our own server srv = Server() await srv.init() srv.set_endpoint(uri_crypto) await srv.load_certificate(f"{EXAMPLE_PATH}certificate-example.der") await srv.load_private_key(f"{EXAMPLE_PATH}private-key-example.pem") await srv.start() yield srv # stop the server await srv.stop()
async def run_server(self, url): srv = Server() srv.set_endpoint(url) await srv.init() await add_server_methods(srv) await add_server_custom_enum_struct(srv) async with srv: with self.cond: self.cond.notify_all() while not self.stop_ev.is_set(): await asyncio.sleep(1) await srv.stop()
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)
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')
async def srv_crypto_all_certs(request): # start our own server srv = Server() key, cert = request.param await srv.init() srv.set_endpoint(uri_crypto) await srv.load_certificate(cert) await srv.load_private_key(key) await srv.start() yield srv # stop the server await srv.stop()
async def test_server_read_write_attribute_value(server: Server): node = await server.get_objects_node().add_variable( 0, "0:TestVar", 0, varianttype=ua.VariantType.Int64) dv = server.read_attribute_value(node.nodeid, attr=ua.AttributeIds.Value) assert dv.Value.Value == 0 dv = ua.DataValue( Value=ua.Variant(Value=5, VariantType=ua.VariantType.Int64)) await server.write_attribute_value(node.nodeid, dv, attr=ua.AttributeIds.Value) dv = server.read_attribute_value(node.nodeid, attr=ua.AttributeIds.Value) assert dv.Value.Value == 5 await server.delete_nodes([node])
async def setup(self): # OPCUA Server Setup try: # configure the endpoint opc_url = self.config["ServerUrlPattern"].format( ip=self.config["IPAddress"], port=self.config["Port"]) # init the server self.opcua_server_instance = Server() await self.opcua_server_instance.init() self.opcua_server_instance.set_endpoint(opc_url) self.opcua_server_instance.set_server_name( self.config["ServerDiscoveryName"]) await self.opcua_server_instance.set_application_uri( self.config["ApplicationUri"]) self.logger.info("[SERVER CONFIG] ENDPOINT: %s" % opc_url) self.logger.info("[SERVER CONFIG] APPLICATION URI: %s" % self.config["ApplicationUri"]) self.logger.info("[SERVER CONFIG] APPLICATION NAME: %s" % self.config["ServerDiscoveryName"]) # Set NameSpace(s) for pattern in self.config["IoTCentralPatterns"]: if pattern["ModelType"] == "Twins": self.opcua_id_namespace_twins = await self.opcua_server_instance.register_namespace( pattern["NameSpace"]) if pattern["ModelType"] == "Gateways": self.opcua_id_namespace_gateways = await self.opcua_server_instance.register_namespace( pattern["NameSpace"]) if pattern["ModelType"] == "Devices": self.opcua_id_namespace_devices = await self.opcua_server_instance.register_namespace( pattern["NameSpace"]) self.logger.info("[SERVER CONFIG] NAMESPACE TWINS: %s" % self.opcua_id_namespace_twins) self.logger.info("[SERVER CONFIG] NAMESPACE TWINS: %s" % self.opcua_id_namespace_gateways) self.logger.info("[SERVER CONFIG] NAMESPACE DEVICES: %s" % self.opcua_id_namespace_devices) except Exception as ex: self.logger.error("[ERROR] %s" % ex) self.logger.error( "[TERMINATING] We encountered an error in OPCUA Server Setup::setup()" ) return
async def main(): global rpm_is puls.when_pressed = callback_rpm # set callback # initialize Server server = Server() await server.init() server.set_endpoint('opc.tcp://pi.local:4840/freeopcua/server/') server.set_server_name("OPC UA Raspi Server") # all possible endpoint policies set for client connection server.set_security_policy([ ua.SecurityPolicyType.NoSecurity, ua.SecurityPolicyType.Basic256Sha256_SignAndEncrypt, ua.SecurityPolicyType.Basic256Sha256_Sign]) # setup namespace uri = "example-uri.edu" idx = await server.register_namespace(uri) # create Motor-node type for later use base_motor = await motor_object(idx, server) # populateing address space motor = await server.nodes.objects.add_object(idx, "Motor", base_motor) rpm_var = await motor.get_child([f"{idx}:RPM"]) # rounds per minute await rpm_var.set_writable() speed_var = await motor.get_child([f"{idx}:Speed"]) # motor speed await speed_var.set_writable() # Start! async with server: while True: rpm_is, speed_is = await asyncio.gather(*(get_rpm(rpm_var), set_speed(speed_var)))
async def opc(request): """ Fixture for tests that should run for both `Server` and `Client` :param request: :return: """ if request.param == 'client': srv = Server() await srv.init() srv.set_endpoint(f'opc.tcp://127.0.0.1:{port_num}') await add_server_methods(srv) await srv.start() # start client # long timeout since travis (automated testing) can be really slow clt = Client(f'opc.tcp://[email protected]:{port_num}', timeout=10) await clt.connect() yield Opc(clt, srv) await clt.disconnect() await srv.stop() elif request.param == 'server': # start our own server srv = Server() await srv.init() srv.set_endpoint(f'opc.tcp://127.0.0.1:{port_num1}') await add_server_methods(srv) await srv.start() yield Opc(srv, srv) # stop the server await srv.stop() else: raise ValueError("invalid internal test config")
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)
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
async def test_context_manager(): # Context manager calls start() and stop() state = [0] async 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 async with server: # test if server started assert 1 == state[0] # test if server stopped assert 2 == state[0]
async def check_eventgenerator_source_server(evgen, server: Server): server_node = server.get_server_node() assert evgen.event.SourceName == (await server_node.get_browse_name()).Name assert evgen.event.SourceNode == ua.NodeId(ua.ObjectIds.Server) assert await server_node.get_event_notifier() == {ua.EventNotifier.SubscribeToEvents} refs = await server_node.get_referenced_nodes(ua.ObjectIds.GeneratesEvent, ua.BrowseDirection.Forward, ua.NodeClass.ObjectType, False) assert len(refs) >= 1
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) # Example 1 - create a basic object #------------------------------------------------------------------------------- myobj = await server.nodes.objects.add_object(idx, "MyObject") #------------------------------------------------------------------------------- # Example 2 - create a new object type and a instance of the new object type #------------------------------------------------------------------------------- mycustomobj_type = await server.nodes.base_object_type.add_object_type(idx, "MyCustomObjectType") var = await mycustomobj_type.add_variable(0, "var_should_be_there_after_instantiate", 1.0) # demonstrates instantiate await var.set_modelling_rule(True) # make sure the variable is instansiated myobj = await server.nodes.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 await server.import_xml('customobject.xml') # get nodeid of custom object type by one of the following 2 ways: # 1) Use node ID # 3) Or As child from BaseObjectType myobject1_type_nodeid = ua.NodeId.from_string('ns=%d;i=2' % idx) myobject2_type_nodeid = (await server.nodes.base_object_type.get_child([f"{idx}:MyCustomObjectType"])).nodeid # populating our address space myobj = await server.nodes.objects.add_object(idx, "MyCustomObjectB", myobject2_type_nodeid) #------------------------------------------------------------------------------- # starting! async with server: while True: await asyncio.sleep(1)