async def main(): cert_user_manager = CertificateUserManager() await cert_user_manager.add_user( "certificates/peer-certificate-example-1.der", name='test_user') server = Server(user_manager=cert_user_manager) await server.init() server.set_endpoint("opc.tcp://0.0.0.0:4840/freeopcua/server/") server.set_security_policy( [ua.SecurityPolicyType.Basic256Sha256_SignAndEncrypt], permission_ruleset=SimpleRoleRuleset()) # load server certificate and private key. This enables endpoints # with signing and encryption. await server.load_certificate("certificate-example.der") await server.load_private_key("private-key-example.pem") idx = 0 # populating our address space myobj = await server.nodes.objects.add_object(idx, "MyObject") myvar = await myobj.add_variable(idx, "MyVariable", 0.0) await myvar.set_writable() # Set MyVariable to be writable by clients # starting! async with server: while True: await asyncio.sleep(1) current_val = await myvar.get_value() count = current_val + 0.1 await myvar.write_value(count)
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 srv_crypto_one_cert(request): cert_user_manager = CertificateUserManager() admin_peer_certificate = admin_peer_creds["certificate"] user_peer_certificate = user_peer_creds["certificate"] anonymous_peer_certificate = anonymous_peer_creds["certificate"] key, cert = request.param await cert_user_manager.add_admin(admin_peer_certificate, name='Admin') await cert_user_manager.add_user(user_peer_certificate, name='User') await cert_user_manager.add_role(anonymous_peer_certificate, name='Anonymous', user_role=UserRole.Anonymous) srv = Server(user_manager=cert_user_manager) srv.set_endpoint(uri_crypto_cert) srv.set_security_policy([ua.SecurityPolicyType.Basic256Sha256_SignAndEncrypt], permission_ruleset=SimpleRoleRuleset()) await srv.init() await srv.load_certificate(cert) await srv.load_private_key(key) idx = 0 myobj = await srv.nodes.objects.add_object(idx, "MyObject") myvar = await myobj.add_variable(idx, "MyVariable", 0.0) await myvar.set_writable() # Set MyVariable to be writable by clients await srv.start() yield srv # stop the server await srv.stop()
async def main(): server = Server() cert_handler = CertificateHandler() await server.init() await cert_handler.trust_certificate( "certificates/peer-certificate-example-1.der") server.set_endpoint("opc.tcp://0.0.0.0:4840/freeopcua/server/") server.set_security_policy( [ua.SecurityPolicyType.Basic256Sha256_SignAndEncrypt], certificate_handler=cert_handler) # load server certificate and private key. This enables endpoints # with signing and encryption. await server.load_certificate("certificate-example.der") await server.load_private_key("private-key-example.pem") # 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: count = 0 while True: await asyncio.sleep(1) count += 0.1 await myvar.write_value(count)
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 server_with_certificates(server_url, server_certificate_path, server_private_key_path, certificates=None, test=False): """ :param server_url: :type server_url: str :param server_certificate_path: :type server_certificate_path: str :param server_private_key_path: :type server_private_key_path: str :param certificates: :type certificates: list :return: """ # setup our serverclone_and_subscribe(client_node, server_node, sub_handler) certificate_handler = CertificateUserManager() if certificates is not None and test is not True: for role_add in certificates: certificate_path = role_add['certificate_path'] name = role_add['name'] role = role_add['role'] if role == 'admin': await certificate_handler.add_admin( certificate_path=certificate_path, name=name) elif role == 'user': await certificate_handler.add_user( certificate_path=certificate_path, name=name) else: raise NotImplementedError server = Server(user_manager=certificate_handler) else: server = Server() await server.init() server.set_endpoint(server_url) security_policies = [] permission_ruleset = SimpleRoleRuleset() if certificates is not None: security_policies.append( ua.SecurityPolicyType.Basic256Sha256_SignAndEncrypt) if certificates is None or test: security_policies.append(ua.SecurityPolicyType.NoSecurity) server.set_security_policy(security_policies, permission_ruleset=permission_ruleset) if server_certificate_path: await server.load_certificate(server_certificate_path) await server.load_private_key(server_private_key_path) return server, certificate_handler
async def test_always_catch_new_cert_on_set_security(): """ Test client reconnection after server cert update. This could be useful when we prefer to keep a unique client instance (i.e HaClient). """ # Client connecting with encryption to server srv = Server() await srv.init() srv.set_endpoint(uri_crypto_cert) srv.set_security_policy( [ua.SecurityPolicyType.Basic256Sha256_SignAndEncrypt]) key, cert = srv_crypto_params[0] await srv.load_certificate(cert) await srv.load_private_key(key) await srv.start() clt = Client(uri_crypto_cert) peer_cert = peer_creds["certificate"] peer_key = peer_creds["private_key"] security_string = f"Basic256Sha256,SignAndEncrypt,{peer_cert},{peer_key}" await clt.set_security_string(security_string) assert await clt.connect_and_get_server_endpoints() srv_original_cert = clt.security_policy.peer_certificate await srv.stop() # Simulation of a server cert renewal srv = Server() await srv.init() srv.set_endpoint(uri_crypto_cert) srv.set_security_policy( [ua.SecurityPolicyType.Basic256Sha256_SignAndEncrypt]) key, cert = srv_crypto_params[1] await srv.load_certificate(cert) await srv.load_private_key(key) await srv.start() # The same client instance fails to open a SecureChannel because the # security_policy contains the previous SecurityMode and server certificate. with pytest.raises(TimeoutError): await clt.connect_and_get_server_endpoints() assert clt.security_policy == clt.uaclient.security_policy assert clt.security_policy.peer_certificate == srv_original_cert # If the server cert isn't passed to set_security we clear the security_policy await clt.set_security_string(security_string) assert await clt.connect_and_get_server_endpoints() assert clt.security_policy == clt.uaclient.security_policy assert clt.security_policy.peer_certificate assert clt.security_policy.peer_certificate != srv_original_cert await srv.stop()
async def srv_crypto_one_cert(request): srv = Server() peer_certificate = peer_creds["certificate"] cert_handler = CertificateHandler() key, cert = request.param await cert_handler.trust_certificate(peer_certificate) await srv.init() srv.set_endpoint(uri_crypto_cert) srv.set_security_policy([ua.SecurityPolicyType.Basic256Sha256_SignAndEncrypt], certificate_handler=cert_handler) await srv.load_certificate(cert) await srv.load_private_key(key) await srv.start() yield srv # stop the server await srv.stop()
async def create_srv(port, key, cert): srv = Server() srvs.append(srv) await srv.init() await srv.set_application_uri("urn:freeopcua:python:discovery") srv.set_endpoint(f"opc.tcp://127.0.0.1:{port}") srv.set_security_policy([ ua.SecurityPolicyType.NoSecurity, ua.SecurityPolicyType.Basic256Sha256_SignAndEncrypt, ]) await srv.load_certificate(cert) await srv.load_private_key(key) await srv.start() # default the service level to 255 once started slevel = srv.get_node(ua.NodeId(ua.ObjectIds.Server_ServiceLevel)) await slevel.write_value(ua.Variant(255, ua.VariantType.Byte)) return srv
async def srv_crypto_one_cert(request): peer_certificate = peer_creds["certificate"] user_manager = CertificateUserManager() key, cert = request.param await user_manager.add_admin(peer_certificate, 'test1') srv = Server(user_manager=user_manager) await srv.init() srv.set_endpoint(uri_crypto_cert) srv.set_security_policy([ua.SecurityPolicyType.Basic256Sha256_SignAndEncrypt]) await srv.load_certificate(cert) await srv.load_private_key(key) await srv.start() yield srv, cert # stop the server await srv.stop()
async def main(): # Create Server server = Server() await server.init() # Set server configuration server.set_endpoint(_opc_ua_server) server.set_server_name(_opc_ua_server_name) server.set_security_policy([ ua.SecurityPolicyType.NoSecurity, ua.SecurityPolicyType.Basic256Sha256_SignAndEncrypt, ua.SecurityPolicyType.Basic256Sha256_Sign ]) # Set namespace idx = await server.register_namespace(_opc_ua_namespace) # Create Sensor object with two properties sensor = await server.nodes.base_object_type.add_object_type(idx, "Sensor") await (await sensor.add_variable(idx, "value", 0.0)).set_modelling_rule(True) # Populate the address space sensor0 = await server.nodes.objects.add_object(idx, "Sensor0", sensor) await (await sensor0.add_property(idx, "id", 0)).set_modelling_rule(True) await (await sensor0.add_property(idx, "name", "Sensor0")).set_modelling_rule(True) # Start Server async with server: # Retrieve Sensor0 value variable, in order to read/write it sensor0_value_var = await sensor0.get_child([f"{idx}:value"]) while True: # Generate a random float between 0.0 and 100.0 sensor0_value = uniform(0.0, 100.0) # Write the value to trigger data change await sensor0_value_var.write_value(sensor0_value) # Wait 5 seconds before triggering next event await asyncio.sleep(5)
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
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)
async def main(): # setup our server print('***请确保机器人控制程序已启动,输入任意键继续 ***:') aaa = input() print('【正在初始化OPC UA Server...】') server = Server() await server.init() server.default_timeout = 60 endpoint = 'opc.tcp://0.0.0.0:4840/' server.set_endpoint(endpoint) # server.set_endpoint('opc.tcp://192.168.100.173:4840/') # setup our own namespace, not really necessary but should as spec try: ################################# # # 设置加密和密钥后 prosys可以连接 None方式不行 await server.load_certificate("certificate.der") await server.load_private_key("private-key.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 ]) ######################################## except Exception as e: print(e) else: uri = 'http://su600.cn' idx = await server.register_namespace(uri) # 导入xml文件 await server.import_xml('kuka.xml') # 获取xml中的UA node # todo 待优化 root = server.get_root_node() x1 = await root.get_child( ["0:Objects", "3:制孔机器人", '3:制孔TCP坐标', '3:x_Drilling']) y1 = await root.get_child( ["0:Objects", "3:制孔机器人", '3:制孔TCP坐标', '3:y_Drilling']) z1 = await root.get_child( ["0:Objects", "3:制孔机器人", '3:制孔TCP坐标', '3:z_Drilling']) a1 = await root.get_child( ["0:Objects", "3:制孔机器人", '3:制孔TCP坐标', '3:a_Drilling']) b1 = await root.get_child( ["0:Objects", "3:制孔机器人", '3:制孔TCP坐标', '3:b_Drilling']) c1 = await root.get_child( ["0:Objects", "3:制孔机器人", '3:制孔TCP坐标', '3:c_Drilling']) A1 = await root.get_child( ["0:Objects", "3:制孔机器人", '3:制孔关节角度', '3:A1_Drilling']) A2 = await root.get_child( ["0:Objects", "3:制孔机器人", '3:制孔关节角度', '3:A2_Drilling']) A3 = await root.get_child( ["0:Objects", "3:制孔机器人", '3:制孔关节角度', '3:A3_Drilling']) A4 = await root.get_child( ["0:Objects", "3:制孔机器人", '3:制孔关节角度', '3:A4_Drilling']) A5 = await root.get_child( ["0:Objects", "3:制孔机器人", '3:制孔关节角度', '3:A5_Drilling']) A6 = await root.get_child( ["0:Objects", "3:制孔机器人", '3:制孔关节角度', '3:A6_Drilling']) x2 = await root.get_child( ["0:Objects", "3:铆接机器人", '3:铆接TCP坐标', '3:x_Riveting']) y2 = await root.get_child( ["0:Objects", "3:铆接机器人", '3:铆接TCP坐标', '3:y_Riveting']) z2 = await root.get_child( ["0:Objects", "3:铆接机器人", '3:铆接TCP坐标', '3:z_Riveting']) a2 = await root.get_child( ["0:Objects", "3:铆接机器人", '3:铆接TCP坐标', '3:a_Riveting']) b2 = await root.get_child( ["0:Objects", "3:铆接机器人", '3:铆接TCP坐标', '3:b_Riveting']) c2 = await root.get_child( ["0:Objects", "3:铆接机器人", '3:铆接TCP坐标', '3:c_Riveting']) A7 = await root.get_child( ["0:Objects", "3:铆接机器人", '3:铆接关节角度', '3:A1_Riveting']) A8 = await root.get_child( ["0:Objects", "3:铆接机器人", '3:铆接关节角度', '3:A2_Riveting']) A9 = await root.get_child( ["0:Objects", "3:铆接机器人", '3:铆接关节角度', '3:A3_Riveting']) A10 = await root.get_child( ["0:Objects", "3:铆接机器人", '3:铆接关节角度', '3:A4_Riveting']) A11 = await root.get_child( ["0:Objects", "3:铆接机器人", '3:铆接关节角度', '3:A5_Riveting']) A12 = await root.get_child( ["0:Objects", "3:铆接机器人", '3:铆接关节角度', '3:A6_Riveting']) actuator1 = await root.get_child(["0:Objects", "3:末端执行器", '3:主轴']) actuator2 = await root.get_child(["0:Objects", "3:末端执行器", '3:压脚']) actuator3 = await root.get_child(["0:Objects", "3:末端执行器", '3:滑台1']) actuator4 = await root.get_child(["0:Objects", "3:末端执行器", '3:滑台2']) normal1 = await root.get_child(["0:Objects", "3:法向", '3:B']) normal2 = await root.get_child(["0:Objects", "3:法向", '3:C']) normal3 = await root.get_child(["0:Objects", "3:法向", '3:D']) data_name = [ x1, y1, z1, a1, b1, c1, A1, A2, A3, A4, A5, A6, x2, y2, z2, a2, b2, c2, A7, A8, A9, A10, A11, A12, actuator1, actuator2, actuator3, actuator4, normal1, normal2, normal3 ] # 设置可写 for i in data_name: await i.set_writable() print('\n') print('【OPC UA Server初始化完成】') print('【读取config.txt参数配置】') file = 'config.txt' try: with open(file) as f: lines = f.readlines() ip = lines[0].split(':')[1].strip() port = int(lines[1].split(':')[1]) cycle = int(lines[2].split(':')[1]) / 1000 except Exception as e: print(e) else: print(f'【开始与{ip}:{port}机器人程序建立连接】') # socket通信 def socket_client(ip, port): try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((ip, port)) except socket.error as e: print(f'Socket连接错误:{e} 请确认连接参数重新启动程序') # sys.exit(1) else: send_data = '0' s.send(send_data.encode()) receive_data = s.recv(1024).decode() # kuka_data=data_analysis(send_data,receive_data) # print("收到信息", receive_data) # s.close() return receive_data # OPC UA 数据更新 async with server: print(f'【OPC UA Server启动完成开始转发数据】') print(f'【OPC UA Server地址{endpoint} 采集周期{cycle * 1000}ms】') while True: await asyncio.sleep(cycle) # 数据更新周期 data = socket_client(ip, port) try: n = 0 for i in data_name: await i.write_value(data.split(',')[n]) n += 1 except Exception as e: # print(f'ERROR: {e}') pass else: pass
async def main(): _logger = logging.getLogger('Server') #logger = logging.getLogger("asyncua.address_space") #logger = logging.getLogger("asyncua.internal_server") #logger = logging.getLogger("asyncua.binary_server_asyncio") #logger = logging.getLogger("asyncua.uaprocessor") server = Server() await server.init() server.set_endpoint("opc.tcp://0.0.0.0:16703/") server.set_server_name("Servidor OPC eMPC MA") await server.set_application_uri(uri="http://servidor-eMPC-MA.com/test/") server.set_security_policy([ua.SecurityPolicyType.NoSecurity]) server._permission_ruleset = None server._policyIDs = ["Anonymous"] server.certificate = None uri = "Servidor OPC eMPC MA" idx = await server.register_namespace(uri) await server.import_xml("deck_opcua.xml") _logger.info("Iniciando servidor OPC-UA...") _logger.info("Escuchando en: opc.tcp://localhost:16703/") # Crear instancia del controlador controlador = clase_MPC.Controlador() # starting! async with server: while True: await asyncio.sleep(0.01) command_run = await server.get_node("ns=6;s=command_run" ).get_value() if command_run == 1: _logger.info( f' [{datetime.now().strftime("%H:%M:%S.%f")[:-3]}]\t Node read: command_run = {command_run}' ) _logger.info( f' [{datetime.now().strftime("%H:%M:%S.%f")[:-3]}]\t Executing...' ) await controlador.recibir_variables(server) controlador.actualizar_arrays() ControlFlag = await server.get_node("ns=4;s=ControlFlag" ).read_value() _logger.info( f' [{datetime.now().strftime("%H:%M:%S.%f")[:-3]}]\t Node read: Control_Flag = {ControlFlag}' ) if ControlFlag: controlador.ejecutar() await server.write_attribute_value( server.get_node("ns=4;s=uq[1]").nodeid, ua.DataValue(controlador.uq1)) _logger.info( f' [{datetime.now().strftime("%H:%M:%S.%f")[:-3]}]\t \ Node written: uq1 = {controlador.uq1:.3f}') await server.write_attribute_value( server.get_node("ns=4;s=uFr[1]").nodeid, ua.DataValue(controlador.uFr1)) _logger.info( f' [{datetime.now().strftime("%H:%M:%S.%f")[:-3]}]\t \ Node written: uFr1 = {controlador.uFr1:.3f}' ) # Falta escribir todas las variables del controlador al servidor await controlador.escribir_variables(server) await server.write_attribute_value( server.get_node("ns=6;s=command_run").nodeid, ua.DataValue(0)) _logger.info( f' [{datetime.now().strftime("%H:%M:%S.%f")[:-3]}]\t Node written: command_run = 0' )
async def main(): # setup our server print('【正在初始化OPC UA Server...】') server = Server() await server.init() server.default_timeout = 60 server.set_endpoint('opc.tcp://0.0.0.0:4840/') # server.set_endpoint('opc.tcp://192.168.100.170:4840/') # setup our own namespace, not really necessary but should as spec try: ################################# # # 设置加密和密钥后 prosys可以连接 None方式不行 await server.load_certificate("certificate.der") await server.load_private_key("private-key.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 ]) ######################################## except Exception as e: print(e) else: uri = 'http://su600.cn' idx = await server.register_namespace(uri) # 导入xml文件 await server.import_xml('kuka.xml') # 获取xml中的UA node # todo 待优化 root = server.get_root_node() actuator1 = await root.get_child( ["0:Objects", "0:Actuator", '0:actuator1']) actuator2 = await root.get_child( ["0:Objects", "0:Actuator", '0:actuator2']) actuator3 = await root.get_child( ["0:Objects", "0:Actuator", '0:actuator3']) actuator4 = await root.get_child( ["0:Objects", "0:Actuator", '0:actuator4']) degree1 = await root.get_child( ["0:Objects", "0:Drilling_Robot", '0:Degree', '0:degree1']) degree2 = await root.get_child( ["0:Objects", "0:Drilling_Robot", '0:Degree', '0:degree2']) degree3 = await root.get_child( ["0:Objects", "0:Drilling_Robot", '0:Degree', '0:degree3']) degree4 = await root.get_child( ["0:Objects", "0:Drilling_Robot", '0:Degree', '0:degree4']) degree5 = await root.get_child( ["0:Objects", "0:Drilling_Robot", '0:Degree', '0:degree5']) degree6 = await root.get_child( ["0:Objects", "0:Drilling_Robot", '0:Degree', '0:degree6']) degree7 = await root.get_child( ["0:Objects", "0:Riveting_Robot", '0:Degree_R', '0:degree7']) degree8 = await root.get_child( ["0:Objects", "0:Riveting_Robot", '0:Degree_R', '0:degree8']) degree9 = await root.get_child( ["0:Objects", "0:Riveting_Robot", '0:Degree_R', '0:degree9']) degree10 = await root.get_child( ["0:Objects", "0:Riveting_Robot", '0:Degree_R', '0:degree10']) degree11 = await root.get_child( ["0:Objects", "0:Riveting_Robot", '0:Degree_R', '0:degree11']) degree12 = await root.get_child( ["0:Objects", "0:Riveting_Robot", '0:Degree_R', '0:degree12']) x1 = await root.get_child( ["0:Objects", "0:Drilling_Robot", '0:Joint', '0:x1']) x2 = await root.get_child( ["0:Objects", "0:Riveting_Robot", '0:Joint_R', '0:x2']) y1 = await root.get_child( ["0:Objects", "0:Drilling_Robot", '0:Joint', '0:y1']) y2 = await root.get_child( ["0:Objects", "0:Riveting_Robot", '0:Joint_R', '0:y2']) z1 = await root.get_child( ["0:Objects", "0:Drilling_Robot", '0:Joint', '0:z1']) z2 = await root.get_child( ["0:Objects", "0:Riveting_Robot", '0:Joint_R', '0:z2']) a1 = await root.get_child( ["0:Objects", "0:Drilling_Robot", '0:Joint', '0:a1']) a2 = await root.get_child( ["0:Objects", "0:Riveting_Robot", '0:Joint_R', '0:a2']) b1 = await root.get_child( ["0:Objects", "0:Drilling_Robot", '0:Joint', '0:b1']) b2 = await root.get_child( ["0:Objects", "0:Riveting_Robot", '0:Joint_R', '0:b2']) c1 = await root.get_child( ["0:Objects", "0:Drilling_Robot", '0:Joint', '0:c1']) c2 = await root.get_child( ["0:Objects", "0:Riveting_Robot", '0:Joint_R', '0:c2']) normal1 = await root.get_child(["0:Objects", "0:Normals", '0:normal1']) normal2 = await root.get_child(["0:Objects", "0:Normals", '0:normal2']) normal3 = await root.get_child(["0:Objects", "0:Normals", '0:normal3']) data_name = [ x1, y1, z1, a1, b1, c1, degree1, degree2, degree3, degree4, degree5, degree6, x2, y2, z2, a2, b2, c2, degree7, degree8, degree9, degree10, degree11, degree12, actuator1, actuator2, actuator3, actuator4, normal1, normal2, normal3 ] # todo 设置可写 for i in data_name: await i.set_writable() print('\n') print('【OPC UA Server初始化完成】') # todo 错误处理 自动重连 print('***请确保机器人控制程序已启动,然后输入IP地址***:') ip = input() # print('请输入端口号(默认6008):') # try: # port = int(input()) # except Exception as e: # print(e, '端口号格式错误') # print('请重新输入端口号') # port = int(input()) port = 6008 print('请输入采集周期(单位ms):') try: cycle = int(input()) / 1000 except Exception as e: print(e, '周期输入有误 请重新输入') # print('请重新输入端口号') cycle = int(input()) / 1000 # socket通信 def socket_client(ip, port): try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((ip, port)) except socket.error as e: print(e) # sys.exit(1) else: # send_data = input('请输入发送命令: ').strip() send_data = '0' s.send(send_data.encode()) receive_data = s.recv(1024).decode() # kuka_data=data_analysis(send_data,receive_data) # print("收到信息", receive_data) # s.close() return receive_data # OPC UA 数据更新 async with server: # count = 0 print('【OPC UA Server启动完成开始转发数据】') while True: # cycle=0.05 await asyncio.sleep(cycle) # 数据更新周期 data = socket_client(ip, port) n = 0 for i in data_name: await i.write_value(data.split(',')[n]) n += 1
class TestOpcServer: def __init__(self) -> None: self.opc_server = OpcServer(user_manager=UserManager()) async def ping_handler( self, request: web.Request, # noqa: U100 ) -> web.Response: return web.Response(text="PONG") async def api_delete_handler( self, request: web.Request, # noqa: U100 ) -> web.Response: await self.reset_opc_data() return web.Response() async def change_node_handler(self, request: web.Request) -> web.Response: request_kind = request.query["kind"] if request_kind == "monitored": var = ua.MonitoredStructure() var.Name = "A changed name" var.Id = 84 await self.monitored_var.write_value(var) elif request_kind == "recorded": vars = [] for index in range(2): var = ua.RecordedStructure() var.Age = [67, 12][index] var.Active = [False, True][index] vars.append(var) await self.recorded_var.write_value(vars) else: raise web.HTTPBadRequest(reason="Unknown kind parameter") return web.Response() async def get_subscriptions_handler( self, request: web.Request, # noqa: U100 ) -> web.Response: return web.json_response( list(self.opc_server.iserver.subscription_service.subscriptions)) async def reset_opc_data(self) -> None: var = ua.MonitoredStructure() var.Name = "A name" var.Id = 42 await self.monitored_var.write_value(var) vars = [] for index in range(2): var = ua.RecordedStructure() var.Age = [18, 32][index] var.Active = [True, False][index] vars.append(var) await self.recorded_var.write_value(vars) async def run(self, http_port: int) -> None: await self.opc_server.init() self.opc_server.set_security_policy([ ua.SecurityPolicyType.Basic256Sha256_Sign, ua.SecurityPolicyType.Basic256Sha256_SignAndEncrypt, ]) await self.opc_server.load_certificate("test-server-cert.der") await self.opc_server.load_private_key("test-server-key.pem") idx = await self.opc_server.register_namespace(NAMESPACE_URI) dict_builder = DataTypeDictionaryBuilder(self.opc_server, idx, NAMESPACE_URI, "SimaticStructures") await dict_builder.init() monitored_structure = await dict_builder.create_data_type( "MonitoredStructure") monitored_structure.add_field("Name", ua.VariantType.String) monitored_structure.add_field("Id", ua.VariantType.Int32) recorded_structure = await dict_builder.create_data_type( "RecordedStructure") recorded_structure.add_field("Age", ua.VariantType.Int16) recorded_structure.add_field("Active", ua.VariantType.Boolean) await dict_builder.set_dict_byte_string() await self.opc_server.load_type_definitions() self.monitored_var = await self.opc_server.nodes.objects.add_variable( NodeId("Monitored", idx), "Monitored", None, datatype=monitored_structure.data_type, ) self.recorded_var = await self.opc_server.nodes.objects.add_variable( NodeId("Recorded", idx), "Recorded", None, datatype=recorded_structure.data_type, ) await self.reset_opc_data() app = web.Application() app.add_routes([ web.get("/ping", self.ping_handler), web.delete("/api", self.api_delete_handler), web.post("/api/node", self.change_node_handler), web.get("/api/subscriptions", self.get_subscriptions_handler), ]) runner = web.AppRunner(app) await runner.setup() site = web.TCPSite(runner, port=http_port) await site.start() async with self.opc_server: await asyncio.sleep(3600)
async def main(): # optional: setup logging #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) # now setup our server server = Server() await server.init() server.disable_clock() #for debuging #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") # 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 ]) # setup our own namespace uri = "http://examples.freeopcua.github.io" idx = await server.register_namespace(uri) # create a new node type we can instantiate in our address space dev = await server.nodes.base_object_type.add_object_type(idx, "MyDevice") await (await dev.add_variable(idx, "sensor1", 1.0)).set_modelling_rule(True) await (await dev.add_property(idx, "device_id", "0340")).set_modelling_rule(True) ctrl = await dev.add_object(idx, "controller") await ctrl.set_modelling_rule(True) await (await ctrl.add_property(idx, "state", "Idle")).set_modelling_rule(True) # populating our address space # First a folder to organise our nodes myfolder = await server.nodes.objects.add_folder(idx, "myEmptyFolder") # instanciate one instance of our device mydevice = await server.nodes.objects.add_object(idx, "Device0001", dev) mydevice_var = await mydevice.get_child( [f"{idx}:controller", f"{idx}:state"]) # get proxy to our device state variable # create directly some objects and variables 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 mystringvar = await myobj.add_variable(idx, "MyStringVariable", "Really nice string") await mystringvar.set_writable( ) # Set MyVariable to be writable by clients mydtvar = await myobj.add_variable(idx, "MyDateTimeVar", datetime.utcnow()) await mydtvar.set_writable() # Set MyVariable to be writable by clients myarrayvar = await myobj.add_variable(idx, "myarrayvar", [6.7, 7.9]) myarrayvar = await myobj.add_variable( idx, "myStronglytTypedVariable", ua.Variant([], ua.VariantType.UInt32)) myprop = await myobj.add_property(idx, "myproperty", "I am a property") mymethod = await myobj.add_method(idx, "mymethod", func, [ua.VariantType.Int64], [ua.VariantType.Boolean]) multiply_node = await myobj.add_method( idx, "multiply", multiply, [ua.VariantType.Int64, ua.VariantType.Int64], [ua.VariantType.Int64]) # import some nodes from xml await server.import_xml("custom_nodes.xml") # creating a default event object # The event object automatically will have members for all events properties # you probably want to create a custom event type, see other examples myevgen = await server.get_event_generator() myevgen.event.Severity = 300 # starting! async with server: print("Available loggers are: ", logging.Logger.manager.loggerDict.keys()) # enable following if you want to subscribe to nodes on server side #handler = SubHandler() #sub = server.create_subscription(500, handler) #handle = sub.subscribe_data_change(myvar) # trigger event, all subscribed clients wil receive it var = await myarrayvar.read_value( ) # return a ref to value in db server side! not a copy! var = copy.copy( var ) # WARNING: we need to copy before writting again otherwise no data change event will be generated var.append(9.3) await myarrayvar.write_value(var) await mydevice_var.write_value("Running") await myevgen.trigger(message="This is BaseEvent") await server.write_attribute_value( myvar.nodeid, ua.DataValue(0.9) ) # Server side write method which is a bit faster than using write_value while True: await asyncio.sleep(0.1) await server.write_attribute_value(myvar.nodeid, ua.DataValue(sin(time.time())))
class server: def __init__(self): logging.info("Creating a opc server") self._server = Server() self._config = False self.nsindex = "" async def NewOPCServer(self, IP): # now setup our server await self._server.init() self._server.disable_clock() #for debuging self.IP = IP.strip() self.mynodes = [] self._server.set_endpoint( self.IP ) #ip removing whitespace Address to pass "opc.tcp://0.0.0.0:4840/freeopcua/server/" self._server.set_server_name("OPC Server Name") # set all possible endpoint policies for clients to connect through self._server.set_security_policy([ ua.SecurityPolicyType.NoSecurity, ua.SecurityPolicyType.Basic256Sha256_SignAndEncrypt, ua.SecurityPolicyType.Basic256Sha256_Sign ]) def checkdata(self, data): if len(data) < 5: return False if len(data['measure']) < 1: return False #TODO implement more data check async def LoadConfig(self, path): with open(path) as f: data = json.load(f) if not self.checkdata(data): return False # setup our own namespace await self._server.register_namespace(self.nsindex) self._config = False self.scan = data['scaninterval'] self.nsindex = data['namespaceindex'] self.namespace = data['namespace'] self.devices = data['device'] # create a new node type we can instantiate in our address space dev = await self._server.nodes.base_object_type.add_object_type( int(self.nsindex), self.devices) #Creating the nodes i = 0 for element in data['measure']: self.mynodes.append(await dev.add_variable( ua.NodeId.from_string('ns=' + self.nsindex + ';s=' + self.namespace + '.' + self.devices + '.' + element['name']), element['name'], 0)) await self.mynodes[i].set_writable() i += 1 myevgen = await self._server.get_event_generator() myevgen.event.Severity = 300 logging.info("Configuration loaded") self._config = True async def Start(self): if self._config: async with self._server: #print("Available loggers are: ", logging.Logger.manager.loggerDict.keys()) logging.info("Server Started") while True: await asyncio.sleep(self.scan) for element in self.mynodes: #updating values await self._server.write_attribute_value( element.nodeid, ua.DataValue(sin(time.time()))) logging.warning("The server need to be configure it first") async def CreateXML(self): ipremove = self.IP.replace("opc.tcp://", "") port = ipremove[ipremove.index(":") + 1:] #creating the xml await self._server.export_xml_by_ns( "gen/Configuration" + port + ".xml", int(self.nsindex)) logging.info("XML File created successfully")