class Servidor_OPCUA: def __init__(self): self.server = Server() self.server.set_endpoint("opc.tcp://localhost:4840/freeopcua/server/") self.server.set_server_name("Stack IIoT") self.namespaces = {} self.objects = self.server.get_objects_node() # Para agregar un nuevo namespace def new_namespace(self, uri, namespace, nombre): idx = self.server.register_namespace(uri) print('New namespace: {}'.format(idx)) Namespace = namespace( self.objects, idx, self.server) # Se declaran todas las variables del nuevo namespace self.namespaces[nombre] = Namespace def start(self): global alarma, valor_alarma, mensaje_alarma self.server.start() for nombre, namespace in self.namespaces.items(): namespace.subscripciones() # Se incia el loop del servidor try: while True: time.sleep(0.1) for nombre, namespace in self.namespaces.items(): namespace.monitorea_alarma() finally: self.server.stop()
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()
def __init__(self, port=Opcx.DEFAULT_PORT, name='OpcxServer'): from opcua import Server server = Server() server.set_server_name(name) server.set_endpoint("opc.tcp://0.0.0.0:%d/freeopcua/server/" % port) self.objix = server.register_namespace(Opcx.DEFAULT_URI) self.server = server
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()
class DemoServer: def __init__(self): self.server = Server() self.server.set_endpoint('opc.tcp://0.0.0.0:4840') 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') def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): quit() def start_server(self): self.server.start() def create_structure(self, name): # save the created data type return self.dict_builder.create_data_type(name) def complete_creation(self): self.dict_builder.set_dict_byte_string()
def server_opc(): server = Server() server.set_endpoint("opc.tcp://0.0.0.0:4840/vm_opc") server.set_server_name("Servidor notificaciones vm") # setup our own namespace, not really necessary but should as spec uri = "notif VM" 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, "notif_vm") event_id = myobj.add_variable(idx, "ID evento", float(0)) # new_st.set_writable() tss = myobj.add_variable(idx, "Timestamp", datetime.datetime.now()) # new_st.set_writable() progresiva = myobj.add_variable(idx, "Progresiva", float(-1)) estado_alarma = myobj.add_variable(idx, "Estado alarma", 'inicio') criticidad = myobj.add_variable(idx, "Criticidad", float(-1)) ack_bit = myobj.add_variable(idx, "ACK bit", False) ack_bit.set_writable() alarma_activa = myobj.add_variable(idx, "Alarma presente", False) # starting! tags = { 'id': event_id, 'tss': tss, 'prog': progresiva, 'st': estado_alarma, 'crit': criticidad, 'ack': ack_bit, 'active': alarma_activa } server.start() try: while True: if np.random.uniform() >= 0.5: tags['id'].set_value(float(np.random.randint(500))) tags['tss'].set_value(datetime.datetime.now()) tags['st'].set_value(choice(['inicio', 'cambio', 'fin'])) else: print 'Bit ACK: ', tags['ack'].get_value( ), datetime.datetime.now() time.sleep(3) finally: #close connection, remove subcsriptions, etc server.stop()
class MyDeviceServer(object): def __init__(self, endpoint, name): # Logging configuration self.logger = logging.getLogger('MyDeviceServer') self.logger.setLevel(logging.INFO) # Setup server self.server = Server() self.server.import_xml("MyDevice.xml") self.server.set_endpoint(endpoint) self.server.set_server_name(name) self.objects_node = self.server.get_objects_node() self.my_device_node = self.objects_node.get_child("0:MyDevice") self.my_device_toggle_b = self.my_device_node.get_child("0:ToggleB") self.my_device_toggle_c = self.my_device_node.get_child("0:ToggleC") self.my_device_toggle_d = self.my_device_node.get_child("0:ToggleD") self.server.link_method(self.my_device_toggle_b, self.toggle_b) self.server.link_method(self.my_device_toggle_c, self.toggle_c) self.server.link_method(self.my_device_toggle_d, self.toggle_d) self.my_variable_a = self.my_device_node.get_child("0:VariableA") self.my_variable_b = self.my_device_node.get_child("0:VariableB") self.my_variable_c = self.my_device_node.get_child("0:VariableC") self.my_variable_d = self.my_device_node.get_child("0:VariableD") self.my_variable_e = self.my_device_node.get_child("0:VariableE") @uamethod def toggle_b(self, parent): self.logger.info("Call Toggle B method") self.my_variable_b.set_value(not self.my_variable_b.get_value()) @uamethod def toggle_c(self, parent): self.logger.info("Call Toggle C method") self.my_variable_c.set_value(not self.my_variable_c.get_value()) @uamethod def toggle_d(self, parent): self.logger.info("Call Toggle D method") self.my_variable_d.set_value(not self.my_variable_d.get_value()) def start(self): self.server.start() def stop(self): self.server.stop() def setVarA(self, intNumber): self.my_variable_a.set_value(intNumber) def setVarE(self, intNumber): self.my_variable_e.set_value(intNumber)
def create_Server_Basics(name, port): url = 'opc.tcp://0.0.0.0:' + port gebName = 'MEMAP_' + name server = Server() server.set_endpoint(url) server.set_server_name('MEMAP Mockup ' + name) idx = server.register_namespace(gebName) # Root node objects = server.get_objects_node() return (server, url, idx, objects)
def start(self): server = Server() server.set_endpoint("opc.tcp://0.0.0.0:4840/thingsroot/server") server.set_server_name("ThingsRoot Example OpcUA Server") self.idx = server.register_namespace("http://opcua.thingsroot.com") self.objects = server.get_objects_node() self.server = server self.devices = _dict({}) self.devices_sub_handle = _dict({}) self.device_types = _dict({}) # self.load_redis_db() server.start()
class CTSServer: ''' CTSClient class is the OpcUa client for the CTS OpcUa server. It also contains various high level function allowing to turn on and off leds, run scans, display the CTS status, load MC events in the CTS, etc... Input: - angle_cts : the configuration of the CTS (0., 120. or 240. degrees ) ''' def __init__(self, angle_cts): ''' Initialise function for CTSClient Input: - angle_cts : the configuration of the CTS (0., 120. or 240. degrees) ''' self.server = Server() self.cts = camtestsetup.CTS('config/cts_config_' + str(int(angle_cts)) + '.cfg', 'config/camera_config.cfg', angle=angle_cts, connected=True) com.initialise_can(self.cts) # optional: setup logging logging.basicConfig(level=logging.WARN) self.logger = logging.getLogger("opcua.address_space") self.logger.setLevel(logging.DEBUG) self.server.set_endpoint( "opc.tcp://0.0.0.0:4843/cameratestsetup/server/") self.server.set_server_name("Camera Test Setup OpcUa Server") # setup our own namespace #uri = "http://isdc.unige.ch/" #idx = self.server.register_namespace(uri) # get Objects node, this is where we should put our custom stuff self.objects = self.server.get_objects_node() ## create the ua structure create_opcua_structure(self.cts, self.objects) # starting! ready = True self.server.start()
def create_Server_Basics(objectName, ems, port): url = 'opc.tcp://0.0.0.0:' + port gebName = objectName + ems server = Server() server.set_endpoint(url) server.set_server_name(objectName + '_OPCUA_Server_' + ems) idx = server.register_namespace(gebName) ''' server.set_security_policy([ ua.SecurityPolicyType.NoSecurity, ua.SecurityPolicyType.Basic256Sha256_SignAndEncrypt, ua.SecurityPolicyType.Basic256Sha256_Sign]) ''' # Root node objects = server.get_objects_node() return (server, url, idx, objects)
class ServerPython(object): def __init__(self): self._server = None self.nodes = None self.get_node = None self.get_namespace_array = None def start_server(self, endpoint): logger.info("Starting python-opcua server") self._server = Server() self._server.set_endpoint(endpoint) self._server.set_server_name("OpcUa Modeler Server") self.nodes = self._server.nodes self.get_node = self._server.get_node self.get_namespace_array = self._server.get_namespace_array self.load_type_definitions = self._server.load_type_definitions self.load_enums = self._server.load_enums # now remove freeopcua namespace, not necessary when modeling and # ensures correct idx for exported nodesets ns_node = self._server.get_node( ua.NodeId(ua.ObjectIds.Server_NamespaceArray)) nss = ns_node.get_value() ns_node.set_value(nss[:1]) self._server.start() def stop_server(self): if self._server is not None: self._server.stop() self._server = None self.get_node = None self.get_namespace_array = None def import_xml(self, path): return self._server.import_xml(path) def export_xml(self, nodes, uris, path): exp = XmlExporter(self._server) exp.build_etree(nodes, uris=uris) exp.write_xml(path)
class ServerPython(object): def __init__(self): self._server = None self.nodes = None self.get_node = None self.get_namespace_array = None def start_server(self, endpoint): logger.info("Starting python-opcua server") self._server = Server() self._server.set_endpoint(endpoint) self._server.set_server_name("OpcUa Modeler Server") self.nodes = self._server.nodes self.get_node = self._server.get_node self.get_namespace_array = self._server.get_namespace_array self.load_type_definitions = self._server.load_type_definitions self.load_enums = self._server.load_enums # now remove freeopcua namespace, not necessary when modeling and # ensures correct idx for exported nodesets ns_node = self._server.get_node(ua.NodeId(ua.ObjectIds.Server_NamespaceArray)) nss = ns_node.get_value() ns_node.set_value(nss[:1]) self._server.start() def stop_server(self): if self._server is not None: self._server.stop() self._server = None self.get_node = None self.get_namespace_array = None def import_xml(self, path): return self._server.import_xml(path) def export_xml(self, nodes, uris, path): exp = XmlExporter(self._server) exp.build_etree(nodes, uris=uris) exp.write_xml(path)
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() ESP8266=self.server.get_node("ns=0;i=20005") print("ESP8266: ") print(ESP8266) #death_button=ESP8266.get_children() watering_status=ESP8266.get_value() print(watering_status) switch_method=self.server.get_node("ns=0;i=20006") 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(switch_method, switch_mtd) # 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()
from opcua import ua, Server import asyncio, random, time from datetime import datetime server = Server() server.set_endpoint("opc.tcp://127.0.0.1:4840") server.set_server_name("OPCUA-Test") address_space = server.register_namespace("http://andreas-heine.net/UA") root_node = server.get_root_node() object_node = server.get_objects_node() server_node = server.get_server_node() parameter_obj = object_node.add_object(address_space, "Parameter") random_node = parameter_obj.add_variable(address_space, "random", ua.Variant(0, ua.VariantType.UInt64)) etype = server.create_custom_event_type( address_space, 'MyFirstEvent', ua.ObjectIds.BaseEventType, [('MyNumericProperty', ua.VariantType.Float), ('MyStringProperty', ua.VariantType.String)]) myevgen = server.get_event_generator(etype, parameter_obj) vars_obj = object_node.add_object(address_space, "Vars") var_list = [] for i in range(100): var = vars_obj.add_variable( ua.NodeId.from_string(f'ns={address_space};s=DB_DATA.Test.var{i}'), f'Test.var{i}', 0) var.set_writable(True) var_list.append(var)
import sys sys.path.insert(0, "..") import time from opcua import ua, Server if __name__ == "__main__": # setup our server server = Server() server.set_server_name('hhhh') 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) print 'idx ', idx # get Objects node, this is where we should put our nodes objects = server.get_objects_node() # populating our address space obj = objects.add_object(idx, "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ") f1 = obj.add_variable(idx, "F1", 6.7) f1.set_writable() # Set MyVariable to be writable by clients f2 = obj.add_variable(idx, "F2", 'hello') f2.set_writable() custom_etype = server.nodes.base_event_type.add_object_type( 2, 'MySecondEvent') custom_etype.add_property(2, 'MyIntProperty', ua.Variant(0, ua.VariantType.Int32))
@author: mayer """ from opcua import Server import time import numpy as np #import requests, json import random #from numpy import genfromtxt # ============================== Building 1 ============================== Geb = "Building1_" server1 = Server() url1 = "opc.tcp://0.0.0.0:4880" server1.set_endpoint(url1) server1.set_server_name("MEMAP fortiss Server 1") name = "MEMAP_Building1" idx = server1.register_namespace(name) # Root node objects = server1.get_objects_node() # ================= Defining the Namespace Building 1 ===================== #General = objects.add_object(idx, "General") #Classification = General.add_folder(idx, "Classification") BuildingClass = General.add_variable(idx, "BuildingClass", 0) ### Demand Demand = objects.add_object(idx, "Demand")
class StationUAServer: def __init__(self, pick_by_light): self._pbl = pick_by_light self._setup_nodes() self._generate_tags() self.ua_server.start() self._generate_subscriptions() Thread(target=self._var_updater, daemon=True).start() def _setup_nodes(self): # Create server instance self.ua_server = Server('./opcua_cache') self.ua_server.set_endpoint('opc.tcp://0.0.0.0:4840/UA/PickByLight') self.ua_server.set_server_name("Pick By Light Server") # idx name will be used later for creating the xml used in data type dictionary # setup our own namespace, not really necessary but should as spec idx_name = 'http://examples.freeopcua.github.io' self.idx = self.ua_server.register_namespace(idx_name) # Set all possible endpoint policies for clients to connect through self.ua_server.set_security_policy([ ua.SecurityPolicyType.NoSecurity, ua.SecurityPolicyType.Basic128Rsa15_SignAndEncrypt, ua.SecurityPolicyType.Basic128Rsa15_Sign, ua.SecurityPolicyType.Basic256_SignAndEncrypt, ua.SecurityPolicyType.Basic256_Sign ]) # get Objects node, this is where we should put our custom stuff objects = self.ua_server.get_objects_node() # Create objects for the pack tags using the above created packMLBasedObjectType self.Status = objects.add_folder('ns=2;s=Status', "Status") self.Command = objects.add_folder('ns=2;s=Command', "Command") self.Command.add_method('ns=2;s=Command.SelectPort', "SelectPort", self._select_method, [ua.VariantType.Int32, ua.VariantType.String], [ua.VariantType.Boolean]) self.Command.add_method('ns=2;s=Command.DeselectPort', "DeselectPort", self._deselect_method, [ua.VariantType.Int32], [ua.VariantType.Boolean]) self.Command.add_method('ns=2;s=Command.DeselectAllPorts', "DeselectAllPorts", self._deselect_all_method, [], [ua.VariantType.Boolean]) root = self.ua_server.get_root_node() DummyFestoObj = root.add_object( "ns=2;s=|var|CECC-LK.Application.Flexstation_globalVariables", "DummyFesto") DummyFestoObj.add_variable( "ns=2;s=|var|CECC-LK.Application.Flexstation_globalVariables.FlexStationStatus", "FlexStationStatus", val=0).set_writable() DummyFestoObj.add_variable( "ns=2;s=|var|CECC-LK.Application.FBs.stpStopper1.stAppControl.uiOpNo", "uiOpNo", val=0).set_writable() DummyFestoObj.add_variable( "ns=2;s=ns=2;s=|var|CECC-LK.Application.AppModul.stRcvData.sOderDes", "sOderDes", val="").set_writable() def _generate_tags(self): # for all ports generate tags for port_number, port in self._pbl.get_ports(): # Make a folder with the port_number as the name b_obj = self.Status.add_object( 'ns=2;s=Status.Port_{}'.format(port_number), "Port_{}".format(port_number)) content = self._pbl.get_content(port_number) b_obj.add_variable( "ns=2;s=Status.Port_{}.Selected".format(port_number), "Selected", bool()) b_obj.add_variable( "ns=2;s=Status.Port_{}.WorkFinished".format(port_number), "WorkFinished", bool()) b_obj.add_variable( "ns=2;s=Status.Port_{}.Instructions".format(port_number), "Instructions", "") b_obj.add_variable( "ns=2;s=Status.Port_{}.Activity".format(port_number), "Activity", bool()) b_obj.add_variable( "ns=2;s=Status.Port_{}.ActivityTimestamp".format(port_number), "ActivityTimestamp", datetime.fromtimestamp(0)) b_obj.add_variable( "ns=2;s=Status.Port_{}.LightState".format(port_number), "LightState", 0) b_obj.add_variable( "ns=2;s=Status.Port_{}.ContentDisplayName".format(port_number), "ContentDisplayName", content['display_name']) b_obj.add_variable( "ns=2;s=Status.Port_{}.ContentName".format(port_number), "ContentName", content['name']) b_obj.add_variable( "ns=2;s=Status.Port_{}.ContentDescription".format(port_number), "ContentDescription", content['description']) b_obj.add_variable( "ns=2;s=Status.Port_{}.ContentImagePath".format(port_number), "ContentImagePath", content['image_path']) ''' create command tags for clients that does not support ua methods. ''' b_obj = self.Command.add_object( 'ns=2;s=Command.Port_{}'.format(port_number), "Port_{}".format(port_number)) b_obj.add_variable( "ns=2;s=Command.Port_{}.Select".format(port_number), "Select", bool()).set_writable() b_obj.add_variable( "ns=2;s=Command.Port_{}.Deselect".format(port_number), "Deselect", bool()).set_writable() b_obj.add_variable( "ns=2;s=Command.Port_{}.Instructions".format(port_number), "Instructions", "").set_writable() b_obj.add_variable( "ns=2;s=Command.Port_{}.ContentDisplayName".format( port_number), "ContentDisplayName", content['display_name']).set_writable() b_obj.add_variable( "ns=2;s=Command.Port_{}.ContentName".format(port_number), "ContentName", content['name']).set_writable() b_obj.add_variable( "ns=2;s=Command.Port_{}.ContentDescription".format( port_number), "ContentDescription", content['description']).set_writable() b_obj.add_variable( "ns=2;s=Command.Port_{}.ContentImagePath".format(port_number), "ContentImagePath", content['image_path']).set_writable() ''' Generate some common commands ''' # Make a folder for the commons b_obj = self.Command.add_object('ns=2;s=Command.ByContent', 'ByContent') b_obj.add_variable("ns=2;s=Command.ByContent.Select", "Select", bool()).set_writable() b_obj.add_variable("ns=2;s=Command.ByContent.Deselect", "Deselect", bool()).set_writable() b_obj.add_variable("ns=2;s=Command.ByContent.Name", "Name", "").set_writable() b_obj.add_variable("ns=2;s=Command.ByContent.Instructions", "Instructions", "").set_writable() b_obj.add_variable("ns=2;s=Command.ByContent.Result", "Result", -1).set_writable() def _generate_subscriptions(self): # Create UA subscriber node for the box. Set self as handler. sub = self.ua_server.create_subscription(100, self) # Subscribe to the Select tag and all the content tags for port_number, port in self._pbl.get_ports(): ac = self.ua_server.get_node( "ns=2;s=Command.Port_{}.Select".format(port_number)) sub.subscribe_data_change(ac) ac = self.ua_server.get_node( "ns=2;s=Command.Port_{}.Deselect".format(port_number)) sub.subscribe_data_change(ac) b = self.ua_server.get_node( "ns=2;s=Command.Port_{}.ContentDisplayName".format( port_number)) sub.subscribe_data_change(b) c = self.ua_server.get_node( "ns=2;s=Command.Port_{}.ContentName".format(port_number)) sub.subscribe_data_change(c) d = self.ua_server.get_node( "ns=2;s=Command.Port_{}.ContentDescription".format( port_number)) sub.subscribe_data_change(d) e = self.ua_server.get_node( "ns=2;s=Command.Port_{}.ContentImagePath".format(port_number)) sub.subscribe_data_change(e) a = self.ua_server.get_node("ns=2;s=Command.ByContent.Select") sub.subscribe_data_change(a) a = self.ua_server.get_node("ns=2;s=Command.ByContent.Deselect") sub.subscribe_data_change(a) a = self.ua_server.get_node("ns=2;s=Command.ByContent.Name") sub.subscribe_data_change(a) a = self.ua_server.get_node( "ns=2;s=Command.ByContent.Instructions") sub.subscribe_data_change(a) def _event_notification(self, event): logger.warning( "Python: New event. No function implemented. {}".format(event)) def _select_method(self, parrent, port_number, instructions): r = self._pbl.select_port(port_number.Value, instructions=instructions.Value) return [ua.Variant(value=r, varianttype=ua.VariantType.Boolean)] def _deselect_method(self, parrent, port_number): r = self._pbl.deselect_port(port_number.Value) return [ua.Variant(value=r, varianttype=ua.VariantType.Boolean)] def _deselect_all_method(self, parrent): r = self._pbl.deselect_all() return [ua.Variant(value=r, varianttype=ua.VariantType.Boolean)] def datachange_notification(self, node, val, data): """UA server callback on data change notifications Arguments: node {Node} -- [description] val {[type]} -- [description] data {[type]} -- [description] """ logger.debug("New data change event. node:{}, value:{}".format( node, val)) # Sorry about these lines of code, but I don't see any nicer way of determining the port number than from # the identifier string. Then splitting it up to isolate the port number. # Example "Status.Port_2.Selected" is split into ['Status', 'Port_2', 'Selected'] then 'Port_2' is split into # ['Port', '2'] and then the '2' is turned into an intiger. path_list = str(node.nodeid.Identifier).split(".") # We can safely assume that the last term is the tag that updated. tag = path_list[-1] # Figure out the port number port_number = None if 'Port' in path_list[1]: port_number = int(path_list[1].split("_")[-1]) """ Switch for each possible tag""" # If the command tag "Select" changes go select that port with the instructions saved in the command tag. if tag == 'Select' and port_number: if val == True: node = self.ua_server.get_node( "ns=2;s=Command.Port_{}.Instructions".format(port_number)) instructions = node.get_value() self._pbl.select_port(port_number, instructions=instructions) # Reset the select flag node = self.ua_server.get_node( "ns=2;s=Command.Port_{}.Select".format(port_number)) node.set_value(False) elif tag == 'Deselect' and port_number: if val == True: self._pbl.deselect_port(port_number, work_finished=True) # Reset the select flag node = self.ua_server.get_node( "ns=2;s=Command.Port_{}.Deselect".format(port_number)) node.set_value(False) elif tag == 'ContentDisplayName' and port_number: self._pbl.set_content_key(port_number, 'display_name', str(val)) elif tag == 'ContentName' and port_number: self._pbl.set_content_key(port_number, 'name', str(val)) elif tag == 'ContentDescription' and port_number: self._pbl.set_content_key(port_number, 'description', str(val)) elif tag == 'ContentImagePath' and port_number: self._pbl.set_content_key(port_number, 'image_path', str(val)) elif tag == 'Select' and 'ByContent' in path_list[1]: if val == True: instructions = self.ua_server.get_node( "ns=2;s=Command.ByContent.Instructions").get_value() name = self.ua_server.get_node( "ns=2;s=Command.ByContent.Name").get_value() _, selected_port = self._pbl.select_content( name=name, instructions=instructions) # Reset the select flag node = self.ua_server.get_node( "ns=2;s=Command.ByContent.Select") node.set_value(False) node = self.ua_server.get_node( "ns=2;s=Command.ByContent.Result") node.set_value(selected_port) elif tag == 'Deselect' and 'ByContent' in path_list[1]: if val == True: name = self.ua_server.get_node( "ns=2;s=Command.ByContent.Name").get_value() self._pbl.deselect_content(name=name, work_finished=True) # Reset the select flag node = self.ua_server.get_node( "ns=2;s=Command.ByContent.Deselect") node.set_value(False) def _var_updater(self): while True: sleep(0.1) # for all boxes update tags for port_number, port in self._pbl.get_ports(): # get the object in the packml status object using our unique idx node = self.ua_server.get_node( "ns=2;s=Status.Port_{}.Activity".format(port_number)) node.set_value(port.activity) node = self.ua_server.get_node( "ns=2;s=Status.Port_{}.ActivityTimestamp".format( port_number)) node.set_value(port.activity_timestamp) node = self.ua_server.get_node( "ns=2;s=Status.Port_{}.LightState".format(port_number)) node.set_value(port.get_light()) state = self._pbl.get_port_state(port_number) node = self.ua_server.get_node( "ns=2;s=Status.Port_{}.Selected".format(port_number)) node.set_value(state.selected) node = self.ua_server.get_node( "ns=2;s=Status.Port_{}.WorkFinished".format(port_number)) node.set_value(state.work_finished) node = self.ua_server.get_node( "ns=2;s=Status.Port_{}.Instructions".format(port_number)) node.set_value(state.select_instructions) content = self._pbl.get_content(port_number) node = self.ua_server.get_node( "ns=2;s=Status.Port_{}.ContentDisplayName".format( port_number)) node.set_value(content['display_name']) node = self.ua_server.get_node( "ns=2;s=Status.Port_{}.ContentName".format(port_number)) node.set_value(content['name']) node = self.ua_server.get_node( "ns=2;s=Status.Port_{}.ContentDescription".format( port_number)) node.set_value(content['description']) node = self.ua_server.get_node( "ns=2;s=Status.Port_{}.ContentImagePath".format( port_number)) node.set_value(content['image_path'])
led_b.off() def event_notification(self, event): print("Python: New event", event) if __name__ == "__main__": global ledR, ledG, ledB, switch1, switch2, rotaryVal, rangeVal, flameVal, sinGen led_r.off() led_g.off() led_b.off() server = Server() server.set_endpoint("opc.tcp://0.0.0.0:4840/pi-box") server.set_server_name("OPC-UA Pi Box") # 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 ]) idx = server.register_namespace("opcua-pi-box") # get Objects node, this is where we should put our nodes objects = server.get_objects_node() myobj = objects.add_object(idx, "OPCUA-PI-BOX") ledR = myobj.add_variable(idx, "Led_R", False, ua.VariantType.Boolean) ledR.set_writable()
def main(): # logging.basicConfig(level=logging.ERROR) # logger=logging.getLogger("opcua.server.internal_subscription") # logger.setLevel(logging.ERROR) read = open('config.txt', 'r') configs = read.readlines() read.close() server = Server() endpoint = configs[0].split('@')[1].rstrip('\n') servername = configs[1].split('@')[1].rstrip('\n') kafkaservers = configs[2].split('@')[1].replace("'", "").replace( "\"", "").rstrip('\n') kafkaserver = kafkaservers[1:-1].split(',') kafkatopic = configs[3].split('@')[1].rstrip('\n') eventname = configs[4].split('@')[1].rstrip('\n') # auto_offset_reset='earlist' consumer = KafkaConsumer(kafkatopic, bootstrap_servers=kafkaserver) server.set_endpoint(endpoint) server.set_server_name(servername) print("Program running......") print("Please do not close this page") # 证书 # server.load_certificate("certificate-example.der") # server.load_private_key("private-key-example.pem") # 安全策略 server.set_security_policy([ ua.SecurityPolicyType.NoSecurity, # ua.SecurityPolicyType.Basic256Sha256_SignAndEncrypt, # ua.SecurityPolicyType.Basic256Sha256_Sign ]) uri = "http://taiji.com.cn" idx = server.register_namespace(uri) objs = server.get_objects_node() myobj = objs.add_object(idx, "MyObject") # 节点 taglists = readFile("node.csv") for taglist in taglists: # myobj.add_variable(idx, taglist, 6.7).set_writable() myobj.add_variable(idx, taglist, random.random()).set_writable() # myobj.add_variable(idx, taglist, 6.7) attrs = readFile("ae_attr.csv") custom_etype = server.nodes.base_event_type.add_object_type(idx, eventname) for attr in attrs: custom_etype.add_property(2, attr, ua.Variant("", ua.VariantType.String)) myevent = server.get_event_generator(custom_etype, myobj) server.start() try: rootnode = server.get_root_node().get_child( ["0:Objects", "{}:MyObject".format(idx)]) rootnodes = rootnode.get_variables() nodeAll = {} for i in range(len(rootnodes)): nodeId = rootnodes[i] nodeName = rootnodes[i].get_browse_name().Name nodeAll.update({nodeName: nodeId}) for message in consumer: recv = message.value.decode("utf8") # print("recvevent=",recv) if recv[0] == '{' and recv[-1] == '}': nodeKafka = json.loads(recv) # print("nodeKafka=", nodeKafka) comName = nodeKafka.keys() & nodeAll.keys() for row in comName: rootnode.get_child(["2:{}".format(row) ]).set_value(nodeKafka[row]) else: recv = recv.replace('\n', '').replace('\r', '') datas = recv.split("|")[1:] # print("datas=", datas) if len(datas) == 9: for i in range(len(attrs)): # exec("myevent.event.{}='{}'".format(attrs[i], datas[i].replace('\n', '').replace('\r', ''))) exec("myevent.event.{}='{}'".format( attrs[i], datas[i])) myevent.trigger() else: # continue f = open('ErrorAE.bak', 'a', encoding='utf8') f.write(recv) f.write('\n') f.close # print("mysecondevgen=",mysecondevgen) # print("mysecondevgen=", myevent.event) except Exception as e: print(e) finally: server.stop()
print("OPCUA: New data change event", displayname, val) if displayname == "Connect": self.connection(val) def event_notification(self, event): print("OPCUA: New event", event) if __name__ == "__main__": server = Server("./cache/cache") server.set_endpoint("opc.tcp://0.0.0.0:4840/dobotopcua/server/") server.set_server_name("Dobot FreeOpcUa Server") # server.set_security_policy([ # ua.SecurityPolicyType.NoSecurity, # ua.SecurityPolicyType.Basic256Sha256_SignAndEncrypt, # ua.SecurityPolicyType.Basic256Sha256_Sign]) # server.load_certificate("my_cert.der") # server.load_certificate("my_cert.pem") # server.load_private_key("my_private_key.pem") # set up namespace uri = "http://opcfoundation.org/UA/" idx = server.register_namespace(uri)
class OPCServer(object): def __init__(self, settings): super(OPCServer, self).__init__() server_settings = settings.get("server") objects = settings.get("objects") self._endpoint = server_settings["endpoint"] self._name = server_settings["name"] self._namespace = server_settings["namespace"] self._init_server() for o in objects: self._add_object(o["name"]) for variable, value in o["ro_variables"].items(): self._add_variable(o["name"], variable, value) for variable, value in o["rw_variables"].items(): self._add_variable(o["name"], variable, value, True) def start(self): if self._server: self._server.start() def _init_server(self): self._server = Server() self._server.set_endpoint(self._endpoint) self._server.set_server_name(self._name) self._index = self._server.register_namespace(self._namespace) _log.info("Index: %r" % (self._index,)) self._objects_node = self._server.get_objects_node() _log.info("Node: %r" % (self._objects_node)) self._objects = {} _log.info("Endpoints: %r" % (self._server.get_endpoints())) def stop(self): self._server.stop() def _add_object(self, object_name): self._objects[object_name] = { 'object': self._objects_node.add_object(self._index, object_name), 'variables' : {}} def _add_variable(self, object_name, variable_name, value, writable=False): obj = self._objects.get(object_name, None) if obj.get('object', None): var = self._objects_node.add_variable(self._index, variable_name, str(value)) obj['variables'][variable_name] = var if writable: var.set_writable() return True return False def _get_variable(self, object_name, variable_name): obj = self._objects.get(object_name) if obj.get('object', None): var = obj['variables'].get(variable_name, None) return var return None def set_value(self, object_name, variable_name, value): var = self._get_variable(object_name, variable_name) if var: var.set_value(str(value)) return True return False def get_value(self, object_name, variable_name): var = self._get_variable(object_name, variable_name) if var: return var.get_value() return None
# logger = logging.getLogger("opcua.uaprocessor") # logger.setLevel(logging.DEBUG) # now setup our server server = Server() # Bearbeitungszentrum anlegen, mit BearbeitungscenterDB-Klasse als parameter center = Bearbeitungscenter(opcuaDB) # Registrieren der zu erfassenden Signale signal.signal(signal.SIGALRM, center.updateServer) # signal 14 signal.signal(signal.SIGTERM, center.unregisterServer) # signal 15 # server.disable_clock() # 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("Fräsmaschine01 Server") # Anlegen der möglichen Endpunktrichtlinien für Clients fest, # über die eine Verbindung hergestellt werden soll server.set_security_policy([ ua.SecurityPolicyType.NoSecurity, ua.SecurityPolicyType.Basic256Sha256_SignAndEncrypt, ua.SecurityPolicyType.Basic256Sha256_Sign, ]) # Adressraum festlegen uri = "http://freeopcua.github.io" idx = server.register_namespace(uri) # Erstellen eines neuen Knotentyp, den wir in unserem Adressraum instanziieren können dev = server.nodes.base_object_type.add_object_type(idx, "MyDevice") dev.add_variable(idx, "sensor1", 1.0).set_modelling_rule(True)
logging.basicConfig(level=logging.WARN) #logger = logging.getLogger("opcua.address_space") # logger.setLevel(logging.DEBUG) #logger = logging.getLogger("opcua.internal_server") # logger.setLevel(logging.DEBUG) #logger = logging.getLogger("opcua.binary_server_asyncio") # logger.setLevel(logging.DEBUG) #logger = logging.getLogger("opcua.uaprocessor") # logger.setLevel(logging.DEBUG) # now setup our server server = Server() #server.disable_clock() #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.Basic128Rsa15_SignAndEncrypt, ua.SecurityPolicyType.Basic128Rsa15_Sign, ua.SecurityPolicyType.Basic256_SignAndEncrypt, ua.SecurityPolicyType.Basic256_Sign ]) # setup our own namespace uri = "http://examples.freeopcua.github.io" idx = server.register_namespace(uri) # create a new node type we can instantiate in our address space dev = server.nodes.base_object_type.add_object_type(0, "MyDevice")
def uaserver(): parser = argparse.ArgumentParser( description= "Run an example OPC-UA server. By importing xml definition and using uawrite command line, it is even possible to expose real data using this server" ) # we setup a server, this is a bit different from other tool so we do not reuse common arguments parser.add_argument( "-u", "--url", help="URL of OPC UA server, default is opc.tcp://0.0.0.0:4840", default='opc.tcp://0.0.0.0:4840', metavar="URL") parser.add_argument( "-v", "--verbose", dest="loglevel", choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'], default='WARNING', help="Set log level") parser.add_argument( "-x", "--xml", metavar="XML_FILE", help="Populate address space with nodes defined in XML") parser.add_argument("-p", "--populate", action="store_true", help="Populate address space with some sample nodes") parser.add_argument( "-c", "--disable-clock", action="store_true", help= "Disable clock, to avoid seeing many write if debugging an application" ) parser.add_argument( "-s", "--shell", action="store_true", help="Start python shell instead of randomly changing node values") parser.add_argument("--certificate", help="set server certificate") parser.add_argument("--private_key", help="set server private key") args = parser.parse_args() logging.basicConfig(format="%(levelname)s: %(message)s", level=getattr(logging, args.loglevel)) server = Server() server.set_endpoint(args.url) if args.certificate: server.load_certificate(args.certificate) if args.private_key: server.load_private_key(args.private_key) server.disable_clock(args.disable_clock) server.set_server_name("FreeOpcUa Example Server") if args.xml: server.import_xml(args.xml) if args.populate: @uamethod def multiply(parent, x, y): print("multiply method call with parameters: ", x, y) return x * y uri = "http://examples.freeopcua.github.io" idx = server.register_namespace(uri) objects = server.get_objects_node() myobj = objects.add_object(idx, "MyObject") mywritablevar = myobj.add_variable(idx, "MyWritableVariable", 6.7) mywritablevar.set_writable( ) # Set MyVariable to be writable by clients myvar = myobj.add_variable(idx, "MyVariable", 6.7) myarrayvar = myobj.add_variable(idx, "MyVarArray", [6.7, 7.9]) myprop = myobj.add_property(idx, "MyProperty", "I am a property") mymethod = myobj.add_method( idx, "MyMethod", multiply, [ua.VariantType.Double, ua.VariantType.Int64], [ua.VariantType.Double]) server.start() try: if args.shell: embed() elif args.populate: count = 0 while True: time.sleep(1) myvar.set_value(math.sin(count / 10)) myarrayvar.set_value( [math.sin(count / 10), math.sin(count / 100)]) count += 1 else: while True: time.sleep(1) finally: server.stop() sys.exit(0)
def getdata(parent, rfid): #Test data later from database db_value = 1234 print(f"Method 'getdata' got called with inputParameter: {rfid}") return ( ua.Variant(rfid, ua.VariantType.UInt64), #RFID ua.Variant(db_value, ua.VariantType.UInt64) #Value from database ) if __name__ == "__main__": """ OPC-UA-Server Setup """ server = Server() server.set_endpoint("opc.tcp://127.0.0.1:4840") server.set_server_name("PythonOpcUaServer") security_policy = [ ua.SecurityPolicyType.NoSecurity, #ua.SecurityPolicyType.Basic256Sha256_SignAndEncrypt, #ua.SecurityPolicyType.Basic256Sha256_Sign ] server.set_security_policy(security_policy) policyIDs = [ "Anonymous", "Basic256Sha256", "Username" ] server.set_security_IDs(policyIDs) address_space = server.register_namespace("http://andreas-heine.net/UA") """ OPC-UA-Modeling """
def run(nodejson, endpoint, namespace, description): # now setup our server server = Server() #server.set_endpoint("opc.tcp://localhost:4840/freeopcua/server/") server.set_endpoint(endpoint) server.set_server_name(description) # setup our own namespace uri = namespace idx = server.register_namespace(uri) # get Objects node, this is where we should put our custom stuff objects = server.get_objects_node() variables = {} nodeId = 5 def add_variable(f, vals, nodeId): for x in vals: k = x if isinstance(x, str) or isinstance(x, unicode) else x.keys()[0] #v = f.add_variable("ns=6;i=600%d" % nodeId, k, ua.Variant([], ua.VariantType.Float)) v = f.add_variable("ns=6;i=600%d" % nodeId, x, ua.Variant([], ua.VariantType.Float)) # nodeid, browsename, value, [variant type] #v = f.add_variable("ns=6;s=%s" % x, x, ua.Variant([], ua.VariantType.Float)) v.set_writable() variables[k] = v nodeId = nodeId+1 return nodeId def add_folder(p, pid, val, nodeId): for n, v in val.items(): mf = p.add_folder("ns=%d;i=%d00%d" % (pid, pid, nodeId), n) #mf = p.add_folder("ns=%d;s=%s" % (pid, n), n) if isinstance(v, list) or isinstance(v, tuple): nodeId = add_variable(mf, v, nodeId+1) else: nodeId = add_folder(mf, pid+1, v, nodeId+1) return nodeId # populating our address space add_folder(objects, 5, nodejson, nodeId) ''' myobj = objects.add_object(idx, "MyObject") myvar = myobj.add_variable(idx, "MyVariable", 6.7) myvar.set_writable() # Set MyVariable to be writable by clients myarrayvar = myobj.add_variable(idx, "myarrayvar", [6.7, 7.9]) myarrayvar = myobj.add_variable(idx, "myStronglytTypedVariable", ua.Variant([], ua.VariantType.UInt32)) myprop = myobj.add_property(idx, "myproperty", "I am a property") mymethod = 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") multiply_node = myobj.add_method(idx, "multiply", multiply, [inargx, inargy], [outarg]) ''' # starting! server.start() #print("Available loggers are: ", logging.Logger.manager.loggerDict.keys()) return server, variables
Out2 = 12345 return (ua.Variant(Out1, ua.VariantType.Int64), ua.Variant(Out2, ua.VariantType.Int64)) if __name__ == "__main__": """ OPC-UA-Server Setup """ server = Server() endpoint = "opc.tcp://127.0.0.1:4840" server.set_endpoint(endpoint) servername = "Python-OPC-UA" server.set_server_name(servername) address_space = server.register_namespace("http://andreas-heine.net/UA") uri = "urn:opcua:python:server" server.set_application_uri(uri) server.load_certificate("certificate.pem") server.load_private_key("key.pem") server.set_security_policy([ # ua.SecurityPolicyType.NoSecurity, # ua.SecurityPolicyType.Basic128Rsa15_Sign, # ua.SecurityPolicyType.Basic128Rsa15_SignAndEncrypt, # ua.SecurityPolicyType.Basic256Sha256_Sign, ua.SecurityPolicyType.Basic256Sha256_SignAndEncrypt ]) policyIDs = ["Username"]
# connDb = sqlite3.connect('f:\scadapy\config\db\srvDb.db') cursor = connDb.cursor() for row in cursor.execute( 'SELECT ip,port,tty,speed,timeout FROM servers where id =' + idServ): serverSlave = row[0] portSlave = row[1] serialPort = row[2] ttySpeed = row[3] timeOut = row[4] server = Server() server.set_endpoint("opc.tcp://" + serverSlave + ":" + portSlave + "/srv/") server.set_server_name("Server") server.load_certificate(pathFolder + "server_cert.der") server.load_private_key(pathFolder + "server_private_key.pem") uri = "http://opcua.server.ru" idx = server.register_namespace(uri) objects = server.get_objects_node() cursor.execute( "select ip,reg,toAdr,fromCount,comment,login,password from master_http where serverId = " + idServ) dt = cursor.fetchall() units = len(dt) for i in range(0, len(dt)): reg.append(i)
def uaserver(): parser = argparse.ArgumentParser(description="Run an example OPC-UA server. By importing xml definition and using uawrite command line, it is even possible to expose real data using this server") # we setup a server, this is a bit different from other tool so we do not reuse common arguments parser.add_argument("-u", "--url", help="URL of OPC UA server, default is opc.tcp://0.0.0.0:4840", default='opc.tcp://0.0.0.0:4840', metavar="URL") parser.add_argument("-v", "--verbose", dest="loglevel", choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'], default='WARNING', help="Set log level") parser.add_argument("-x", "--xml", metavar="XML_FILE", help="Populate address space with nodes defined in XML") parser.add_argument("-p", "--populate", action="store_true", help="Populate address space with some sample nodes") parser.add_argument("-c", "--disable-clock", action="store_true", help="Disable clock, to avoid seeing many write if debugging an application") parser.add_argument("-s", "--shell", action="store_true", help="Start python shell instead of randomly changing node values") parser.add_argument("--certificate", help="set server certificate") parser.add_argument("--private_key", help="set server private key") args = parser.parse_args() logging.basicConfig(format="%(levelname)s: %(message)s", level=getattr(logging, args.loglevel)) server = Server() server.set_endpoint(args.url) if args.certificate: server.load_certificate(args.certificate) if args.private_key: server.load_private_key(args.private_key) server.disable_clock(args.disable_clock) server.set_server_name("FreeOpcUa Example Server") if args.xml: server.import_xml(args.xml) if args.populate: @uamethod def multiply(parent, x, y): print("multiply method call with parameters: ", x, y) return x * y uri = "http://examples.freeopcua.github.io" idx = server.register_namespace(uri) objects = server.get_objects_node() myobj = objects.add_object(idx, "MyObject") mywritablevar = myobj.add_variable(idx, "MyWritableVariable", 6.7) mywritablevar.set_writable() # Set MyVariable to be writable by clients myvar = myobj.add_variable(idx, "MyVariable", 6.7) myarrayvar = myobj.add_variable(idx, "MyVarArray", [6.7, 7.9]) myprop = myobj.add_property(idx, "MyProperty", "I am a property") mymethod = myobj.add_method(idx, "MyMethod", multiply, [ua.VariantType.Double, ua.VariantType.Int64], [ua.VariantType.Double]) server.start() try: if args.shell: embed() elif args.populate: count = 0 while True: time.sleep(1) myvar.set_value(math.sin(count / 10)) myarrayvar.set_value([math.sin(count / 10), math.sin(count / 100)]) count += 1 else: while True: time.sleep(1) finally: server.stop() sys.exit(0)
class ROSServer: def __init__(self): self.namespace_ros = rospy.get_param("/rosopcua/namespace") self.topicsDict = {} self.servicesDict = {} self.actionsDict = {} rospy.init_node("rosopcua") self.server = Server() self.server.set_endpoint("opc.tcp://0.0.0.0:21554/") self.server.set_server_name("ROS ua Server") self.server.start() # setup our own namespaces, this is expected uri_topics = "http://ros.org/topics" # two different namespaces to make getting the correct node easier for get_node (otherwise had object for service and topic with same name uri_services = "http://ros.org/services" uri_actions = "http://ros.org/actions" idx_topics = self.server.register_namespace(uri_topics) idx_services = self.server.register_namespace(uri_services) idx_actions = self.server.register_namespace(uri_actions) # get Objects node, this is where we should put our custom stuff objects = self.server.get_objects_node() # one object per type we are watching topics_object = objects.add_object(idx_topics, "ROS-Topics") services_object = objects.add_object(idx_services, "ROS-Services") actions_object = objects.add_object(idx_actions, "ROS_Actions") while not rospy.is_shutdown(): # ros_topics starts a lot of publisher/subscribers, might slow everything down quite a bit. ros_services.refresh_services(self.namespace_ros, self, self.servicesDict, idx_services, services_object) ros_topics.refresh_topics_and_actions(self.namespace_ros, self, self.topicsDict, self.actionsDict, idx_topics, idx_actions, topics_object, actions_object) # Don't clog cpu time.sleep(60) self.server.stop() quit() def find_service_node_with_same_name(self, name, idx): rospy.logdebug("Reached ServiceCheck for name " + name) for service in self.servicesDict: rospy.logdebug( "Found name: " + str(self.servicesDict[service].parent.nodeid.Identifier)) if self.servicesDict[service].parent.nodeid.Identifier == name: rospy.logdebug("Found match for name: " + name) return self.servicesDict[service].parent return None def find_topics_node_with_same_name(self, name, idx): rospy.logdebug("Reached TopicCheck for name " + name) for topic in self.topicsDict: rospy.logdebug( "Found name: " + str(self.topicsDict[topic].parent.nodeid.Identifier)) if self.topicsDict[topic].parent.nodeid.Identifier == name: rospy.logdebug("Found match for name: " + name) return self.topicsDict[topic].parent return None def find_action_node_with_same_name(self, name, idx): rospy.logdebug("Reached ActionCheck for name " + name) for topic in self.actionsDict: rospy.logdebug( "Found name: " + str(self.actionsDict[topic].parent.nodeid.Identifier)) if self.actionsDict[topic].parent.nodeid.Identifier == name: rospy.logdebug("Found match for name: " + name) return self.actionsDict[topic].parent return None
class TestServer: lang = "cs" def __init__(self, endpoint, name): parser = argparse.ArgumentParser() parser.add_argument("--start_state", "-s", type=int, default=0) args = parser.parse_args() start_state = args.start_state root_dir = os.path.join(os.path.dirname(__file__), os.path.pardir).replace('\\', '/') print(root_dir) variants_file = os.path.join(root_dir, "utils", "next_states.json").replace('\\', '/') variants_file_desc = os.path.join(root_dir, "utils", "state_description.json").replace( '\\', '/') with open(variants_file, encoding="utf-8") as f: self.state_descriptions = json.load(f, encoding="utf-8")[self.lang] with open(variants_file_desc, encoding="utf-8") as f: self.next_state_description = json.load( f, encoding="utf-8")[self.lang] self.server = Server() # self.server.import_xml(model_filepath) # normally, definition would be loaded here self.server.set_endpoint(endpoint) # specify the endpoint (address) self.server.set_server_name(name) # specify server name (whatever) objects = self.server.get_objects_node( ) # get the object containing entity myobj = objects.add_object(4, "DATA") # create new object horse = myobj.add_object(4, "horse") # create new object self.mic_active = horse.add_variable(4, "request", False) self.mic_active.set_writable() response_string = horse.add_variable(4, "response", "") response_string.set_writable() self.actual_state = horse.add_variable(4, "actual_state", True) self.actual_state_num = self.actual_state.add_variable(4, "number", 0) self.actual_state.add_variable(4, "ready", True) next_state_choice = horse.add_variable(4, "next_state_choice", True) self.request_var = next_state_choice.add_variable(4, "request", False) self.request_var.set_writable() dt = ua.DataValue(ua.Variant( 0, ua.VariantType.Int16)) # to ensure correct data type self.state_num = next_state_choice.add_variable(4, "state_num", dt) self.state_num.set_writable() self.next_state_possibilities = horse.add_variable( 4, "next_state_possibilities", [1, 70, 80]) self.change_state(start_state) print( f"Server is in state {self.actual_state_num.get_value()} and the possibilities are {type(self.next_state_possibilities.get_value())}" ) self.start() # start the server self.mic_active.set_value(False) subHandler = SubHandler(self) sub = self.server.create_subscription(500, subHandler) handle = sub.subscribe_data_change(self.request_var) handle_response = sub.subscribe_data_change(response_string) handle_actual = sub.subscribe_data_change(self.actual_state_num) # while True: try: print("Server started.") while True: # print("mic mic", self.mic_active.get_value()) # time.sleep(10) # the variable "mic_active" will be changed periodically every 10 seconds in this loop # change the mic_active (if True -> False, if False -> True) # mic_active.set_value(not mic_active.get_value()) inp = readInput("", timeout=10) if inp == "q": break elif inp == "r": self.mic_active.set_value(True) print( f"Variable 'mic_active' changed to {self.mic_active.get_value()}." ) elif inp == "w": self.mic_active.set_value(False) print( f"Variable 'mic_active' changed to {self.mic_active.get_value()}." ) except KeyboardInterrupt: print("User requested interruption.") except Exception: exc_type, exc_value, exc_traceback = sys.exc_info() traceback.print_exception(exc_type, exc_value, exc_traceback, limit=2, file=sys.stdout) sub.unsubscribe(handle) # cancel subscription sub.unsubscribe(handle_response) # cancel subscription sub.unsubscribe(handle_actual) # cancel subscription sub.delete() def change_state(self, next_state): current_state = str(self.actual_state_num.get_value()) print(f"Changing state from {current_state} to {next_state}.") if current_state in self.state_descriptions: self.next_state_possibilities.set_value( self.state_descriptions[current_state]) self.actual_state_num.set_value(next_state) def check_current_state(self): state = str(self.actual_state_num.get_value()) if state in self.state_descriptions: next_states = self.state_descriptions[state] # self.next_state_possibilities = horse.add_variable(4, "next_state_possibilities", next_states) self.next_state_possibilities.set_value(next_states) # self.next_state_possibilities.set_value = next_states if len(next_states) == 1: next_state = next_states[0] # print(self.next_state_description) if str(next_state) in self.next_state_description: print( f"Current state {state} has single next state: {next_state}" ) print(self.next_state_possibilities) print(self.actual_state) self.mic_active.set_value(True) else: print( f"Current state {state} does not require user input, skipping to next state: {next_state}" ) self.actual_state_num.set_value(next_state) self.mic_active.set_value(False) else: print( f"Current state {state} has multiple choices: {next_states}" ) self.mic_active.set_value(True) else: print("Current state is not in the state description file!") def start(self): self.server.start() return self.server def stop(self): self.server.stop()
logging.basicConfig(level=logging.WARN) #logger = logging.getLogger("opcua.address_space") # logger.setLevel(logging.DEBUG) #logger = logging.getLogger("opcua.internal_server") # logger.setLevel(logging.DEBUG) #logger = logging.getLogger("opcua.binary_server_asyncio") # logger.setLevel(logging.DEBUG) #logger = logging.getLogger("opcua.uaprocessor") # logger.setLevel(logging.DEBUG) # now setup our server server = Server() #server.disable_clock() #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 = server.register_namespace(uri) # create a new node type we can instantiate in our address space dev = server.nodes.base_object_type.add_object_type(0, "MyDevice") dev.add_variable(0, "sensor1", 1.0) dev.add_property(0, "device_id", "0340") ctrl = dev.add_object(0, "controller") ctrl.add_property(0, "state", "Idle") # populating our address space # First a folder to organise our nodes
while True: client.loop() if __name__ == "__main__": client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.connect(server_url, server_port, 60) time.sleep(.1) send_thread = threading.Thread(target=loop) send_thread.start() server = Server() server.set_endpoint(f"opc.tcp://{opc_url}:4840/eztelemetry/server/") server.set_server_name("EZTelemetry") # 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://colton.levelops.com" idx = server.register_namespace(uri) # populating our address space # First a folder to organise our nodes device_folder = server.nodes.objects.add_folder(idx, "Devices") # starting!
class OpcUaConnectorGeneralTest(ConnectorTestBase): def test_number_one(self): self._create_connector("connection_test.json") self.assertTrue(self.connector is not None) self.check_or_create_server() self.connector.open() def check_or_create_server(self): if not hasattr(self, "test_server"): self.test_server = Server() self.__server_thread = Thread(target=self.__server_run, name="Test OPC UA server", args=(self.test_server,)) self.assertTrue(self.test_server is not None) def __server_run(self, test_server): self.test_server = test_server class SubHandler(object): def datachange_notification(self, node, val, data): print("Python: New data change event", node, val) def event_notification(self, event): print("Python: New event", event) @uamethod def multiply(parent, x, y): return x * y self.test_server.set_endpoint("opc.tcp://0.0.0.0:4840/freeopcua/server/") self.test_server.set_server_name("Test Server") self.test_server.set_security_policy([ ua.SecurityPolicyType.NoSecurity, ua.SecurityPolicyType.Basic256Sha256_SignAndEncrypt, ua.SecurityPolicyType.Basic256Sha256_Sign]) uri = "http://127.0.0.1" idx = self.test_server.register_namespace(uri) device = self.test_server.nodes.objects.add_object(idx, "Device1") name = self.test_server.nodes.objects.add_variable(idx, "serialNumber", "TEST") name.set_writable() temperature_and_humidity = device.add_object(idx, "TemperatureAndHumiditySensor") temperature = temperature_and_humidity.add_variable(idx, "Temperature", 56.7) humidity = temperature_and_humidity.add_variable(idx, "Humidity", 68.7) battery = device.add_object(idx, "Battery") battery_level = battery.add_variable(idx, "batteryLevel", 24) device.add_method(idx, "multiply", multiply, [ua.VariantType.Int64, ua.VariantType.Int64], [ua.VariantType.Int64]) self.test_server.start() try: while self.server_running: sleep(.1) finally: self.test_server.stop() def stop_test_server(self): self.server_running = False def tearDown(self): super().tearDown() self.stop_test_server()
import sys import psutil sys.path.insert(0, "..") import time from opcua import ua, Server from opcua.server.history_sql import HistorySQLite if __name__ == "__main__": # setup our server server = Server() server.set_endpoint("opc.tcp://0.0.0.0:4840/freeopcua/server/") server.set_server_name("PTB Metrology Cloud Measuring Device") # 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, "System Load", ua.Variant(psutil.cpu_percent(interval=1), ua.VariantType.Double)) myvar.set_writable() # Set MyVariable to be writable by clients