def opcua_converter_main(options): # setup our server server = Server() uasecurity = UaSecurity() if uasecurity.get_securitytype() == 'tls': server_cert, client_cert, private_key = uasecurity.get_certificates() if server_cert is None: logger.error( 'tls is enabled, but server cert is missing with current configuration' ) sys.exit(-1) if private_key is None: logger.error( 'tls is enabled, but private key is missing with current configuration' ) sys.exit(-1) server.load_certificate(server_cert) server.load_private_key(private_key) ConfigHistoryStorage(server) server.start() # setup adapter adapter = PlugInAdapter(options.conf_file) handler = SubHandler(server, adapter) handler.run() adapter.subscription(handler.datachange_notification, handler.event_notification) adapter.start() try: while True: logger.debug('opcua converter running......') time.sleep(60) finally: # close connection, remove subcsriptions, etc adapter.stop() server.stop()
import time from opcua import ua, Server if __name__ == "__main__": # setup our server server = Server() server.set_endpoint("opc.tcp://0.0.0.0:4840/freeopcua/server/") # load server certificate and private key. This enables endpoints # with signing and encryption. server.load_certificate("example-certificate.der") server.load_private_key("example-private-key.pem") # setup our own namespace, not really necessary but should as spec uri = "http://examples.freeopcua.github.io" idx = server.register_namespace(uri) # get Objects node, this is where we should put our custom stuff objects = server.get_objects_node() # populating our address space myobj = objects.add_object(idx, "MyObject") myvar = myobj.add_variable(idx, "MyVariable", 6.7) myvar.set_writable() # Set MyVariable to be writable by clients # starting! server.start()
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"] server.set_security_IDs(policyIDs) server.user_manager.set_user_manager(user_manager) """ OPC-UA-Modeling """ root_node = server.get_root_node() object_node = server.get_objects_node()
server.name = "AggregationServer" server.set_endpoint("opc.tcp://127.0.0.1:8000/AggregationServer/") server.set_security_policy([ ua.SecurityPolicyType.NoSecurity, ua.SecurityPolicyType.Basic128Rsa15_Sign, ua.SecurityPolicyType.Basic128Rsa15_SignAndEncrypt, ua.SecurityPolicyType.Basic256_Sign, ua.SecurityPolicyType.Basic256_SignAndEncrypt, ua.SecurityPolicyType.Basic256Sha256_SignAndEncrypt, ua.SecurityPolicyType.Basic256Sha256_Sign ]) # load server certificate and private key. This enables endpoints server.load_certificate(certificate_path + "server_certificate.der") server.load_private_key(certificate_path + "server_private_key.pem") # Setup our namespace uri = "http://Aggregation.Server.opcua" #Getting the index of our nasmespace idx = server.register_namespace(uri) # get Objects node. This is where we should put our custom stuff objects = server.get_objects_node() # populate our namespace with the aggreagated element and their variables aggregator = objects.add_folder(idx, "Aggregated Servers") # definition of our custom object type -> AggregatedServer types = server.get_node(ua.ObjectIds.BaseObjectType) mycustomobj_type = types.add_object_type(idx, "AggregatedServerType")
sys.path.insert(0, "..") from opcua import ua, Server if __name__ == "__main__": # setup our server server = Server() server.set_endpoint("opc.tcp://0.0.0.0:4840/freeopcua/server/") # load server certificate and private key. This enables endpoints # with signing and encryption. server.load_certificate("certificate-example.der") 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 = server.register_namespace(uri) # get Objects node, this is where we should put our custom stuff objects = server.get_objects_node() # populating our address space myobj = objects.add_object(idx, "MyObject") myvar = myobj.add_variable(idx, "MyVariable", 6.7) myvar.set_writable() # Set MyVariable to be writable by clients # starting! server.start()
print("status from AI server:" + str(body)) return str(body) if __name__ == "__main__": # setup our server server = Server() server.set_endpoint("opc.tcp://0.0.0.0:4840/freeopcua/server/") # load server certificate and private key. This enables endpoints # with signing and encryption. pc = getattr(security_policies, 'SecurityPolicy' + "Basic256Sha256") server.load_certificate("certificate-example.der") 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 = server.register_namespace(uri) # get Objects node, this is where we should put our custom stuff objects = server.get_objects_node() # populating our address space myobj = objects.add_object(idx, "MyObject") myvar = myobj.add_variable(idx, "MyVariable", 6.7) myvar.set_writable() # Set MyVariable to be writable by clients # starting! server.start()
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) host.append(i) login.append(i)
from firebase import Firebase from datetime import timedelta # from opcua.server.history_sql import HistorySQLite import time import datetime import sys sys.path.insert(0, "..") import csv server = Server() # adding the trust certificate url= 'opc.tcp://127.0.0.1:8080' server.set_endpoint(url) server.set_security_policy([ua.SecurityPolicyType.Basic256Sha256_SignAndEncrypt]) server.load_certificate('certificate-example.der') server.load_private_key('private-key-example.pem') uri = "http://examples.freeopcua.github.io" #adding the namesapce for the nodes and generating the nodes name = "OPCUA_SIMULATION_SERVER" addspace = server.register_namespace(name) node = server.get_objects_node() #generating the parameters param = node.add_object(addspace,"Parameter") iTemp = param.add_variable(addspace,"Temperature",0) iPress = param.add_variable(addspace,'Pressure',0) iflow=param.add_variable(addspace,'Flow',0) Time = param.add_variable(addspace,'Time',0)
import sys import time import psutil from opcua import ua, Server server = Server() server.set_endpoint("opc.tcp://0.0.0.0:4840/freeopcua/server/") server.load_certificate("myCertificate.der") server.load_private_key("myPrivateKey.pem") server.set_security_policy([ ua.SecurityPolicyType.NoSecurity, ua.SecurityPolicyType.Basic128Rsa15_SignAndEncrypt, ua.SecurityPolicyType.Basic128Rsa15_Sign]) uri = "silvia-notebook.opcua.it/freeopcua/server" idx = server.register_namespace(uri) objects = server.get_objects_node() myobj = objects.add_object(idx, "MyObject") core0temp = myobj.add_variable(idx, "Core0Temperature", psutil.sensors_temperatures()['coretemp'][1].current) core1temp = myobj.add_variable(idx, "Core1Temperature", psutil.sensors_temperatures()['coretemp'][2].current) core0temp.set_writable() core1temp.set_writable() # starting! server.start() try: while True: time.sleep(1) core0temp.set_value(psutil.sensors_temperatures()['coretemp'][1].current)
parser.add_argument('msTimeout', nargs='?', default=10000., type=float, help='Server timeout (ms)') args = parser.parse_args() signal.signal(signal.SIGINT, signal_handler) signal.signal(signal.SIGTERM, signal_handler) # Open server print('Configuring FreeOpcUa test server') #logging.basicConfig(level=logging.DEBUG) server = Server() server.set_endpoint(sUri) cert_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..', '..', 'samples', 'ClientServer', 'data', 'cert') server.load_certificate(os.path.join(cert_dir, 'server_2k_cert.der')) server.load_private_key(os.path.join(cert_dir, 'server_2k_key.pem')) # Nodes are created under the Objects node objects = server.get_objects_node() # Use the same nodes as in the Read test for i,(sTypName,typ,val,_) in enumerate(variantInfoList): nid = 1000 + i + 1 node = objects.add_variable(ua.NodeId(nid, 0), sTypName, ua.Variant(val, typ)) node.set_writable() # Add a node which increments, the target of an interesting subscription nodeCnt = objects.add_variable(ua.NodeId('Counter', 0), 'Counter', ua.Variant(0, ua.VariantType.UInt64)) nodeCnt.set_writable() # Add a writable node, so that a client can subscribe to it, while another one can modify it. nodeStr = objects.add_variable(ua.NodeId('StatusString', 0), 'StatusString', ua.Variant('Everything is ok.', ua.VariantType.String)) nodeStr.set_writable()
class CustomServer(object): def __init__(self): self.SERVER_ENDPOINT = os.environ.get("SERVER_ENDPOINT") self.NAMESPACE = os.environ.get("NAMESPACE") self.SERVER_NAME = os.environ.get("SERVER_NAME") self.ENABLE_CERTIFICATE = bool( strtobool(os.environ.get("ENABLE_CERTIFICATE"))) # setup our server self.server = Server() self.server.set_endpoint(self.SERVER_ENDPOINT) self.server.set_server_name(self.SERVER_NAME) # set the security endpoints for identification of clients if self.ENABLE_CERTIFICATE: # load server certificate and private key. This enables endpoints with signing and encryption. self.CERTIFICATE_PATH_SERVER_CERT = os.path.dirname( os.getcwd()) + os.environ.get("CERTIFICATE_PATH_SERVER_CERT") self.CERTIFICATE_PATH_SERVER_PRIVATE_KEY = os.path.dirname( os.getcwd()) + os.environ.get( "CERTIFICATE_PATH_SERVER_PRIVATE_KEY") self.server.load_certificate(self.CERTIFICATE_PATH_SERVER_CERT) self.server.load_private_key( self.CERTIFICATE_PATH_SERVER_PRIVATE_KEY) # 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, ]) self.server.set_security_IDs(["Username", "Basic256Sha256"]) else: self.server.set_security_policy([ua.SecurityPolicyType.NoSecurity]) self.server.set_security_IDs(["Anonymous", "Username"]) # set the user_manager function self.server.user_manager.set_user_manager(user_manager) # setup our own namespace, not really necessary but should as spec uri = self.NAMESPACE self.idx = self.server.register_namespace(uri) # get important nodes self.root = self.server.get_root_node() self.obj = self.server.get_objects_node() self.init_methods() def init_methods(self): # method: ADD_OBJECTS_DIR inarg1 = ua.Argument() inarg1.Name = "objects folder" inarg1.DataType = ua.NodeId(ua.ObjectIds.String) # String inarg1.ValueRank = -1 inarg1.ArrayDimensions = [] inarg1.Description = ua.LocalizedText("Name the new objects folder") method_node = self.obj.add_method(self.idx, "ADD_NEW_OBJECTS_FOLDER", self.add_objects_subfolder, [inarg1]) # method: ADD_OPC_TAG inarg1 = ua.Argument() inarg1.Name = "opctag" inarg1.DataType = ua.NodeId(ua.ObjectIds.String) # String inarg1.ValueRank = -1 inarg1.ArrayDimensions = [] inarg1.Description = ua.LocalizedText("Name new OPC variable") inarg2 = ua.Argument() inarg2.Name = "variant_type" inarg2.DataType = ua.NodeId(ua.ObjectIds.String) # String inarg2.ValueRank = -1 inarg2.ArrayDimensions = [] inarg2.Description = ua.LocalizedText("Type of variable") inarg3 = ua.Argument() inarg3.Name = "parent_node" inarg3.DataType = ua.NodeId(ua.ObjectIds.String) # String inarg3.ValueRank = -1 inarg3.ArrayDimensions = [] inarg3.Description = ua.LocalizedText( "Type in the name of the parent node the new variable should assigned to" ) method_node = self.obj.add_method(self.idx, "ADD_OPC_TAG", self.register_opc_tag, [inarg1, inarg2, inarg3]) # method: SET_PV_LIMIT inarg1 = ua.Argument() inarg1.Name = "active_power_setpoint" inarg1.DataType = ua.NodeId(ua.ObjectIds.Int32) # Integer inarg1.ValueRank = -1 inarg1.ArrayDimensions = [] inarg1.Description = ua.LocalizedText( "Type in active power setpoint in percent [0 ... 100]") inarg2 = ua.Argument() inarg2.Name = "parent_node" inarg2.DataType = ua.NodeId(ua.ObjectIds.String) # String inarg2.ValueRank = -1 inarg2.ArrayDimensions = [] inarg2.Description = ua.LocalizedText( "Type in the name of the parent node") method_node = self.obj.add_method(self.idx, "SET_PV_LIMIT", self.set_pv_active_power_setpoint, [inarg1, inarg2]) # method: RUN_ONLINE_GRID_PROTECTION inarg1 = ua.Argument() inarg1.Name = "On/Off" inarg1.DataType = ua.NodeId(ua.ObjectIds.Int32) # Integer inarg1.ValueRank = -1 inarg1.ArrayDimensions = [] inarg1.Description = ua.LocalizedText( "Type in 1 to RUN or 0 to STOP ONLINE_GRID_PROTECTION") inarg2 = ua.Argument() inarg2.Name = "parent_node" inarg2.DataType = ua.NodeId(ua.ObjectIds.String) # String inarg2.ValueRank = -1 inarg2.ArrayDimensions = [] inarg2.Description = ua.LocalizedText( "Type in the name of the parent node") method_node = self.obj.add_method(self.idx, "RUN_ONLINE_GRID_PROTECTION", self.run_online_grid_protection, [inarg1, inarg2]) @uamethod def add_objects_subfolder(self, parent, dir_name): # check if old dir with dir_name exists. if so then delete this dir first try: obj = self.root.get_child( ["0:Objects", ("{}:" + dir_name).format(self.idx)]) self.server.delete_nodes([obj], True) except BadNoMatch: print(DateHelper.get_local_datetime(), "There is no old folder with the name: " + dir_name) folder = self.obj.add_folder(self.idx, dir_name) print(DateHelper.get_local_datetime(), "Add subfolder: " + dir_name) @uamethod def register_opc_tag(self, parent, opctag, variant_type="Float", parent_node=""): # Object "parent_node": try: obj = self.root.get_child( ["0:Objects", ("{}:" + parent_node).format(self.idx)]) except BadNoMatch: print( DateHelper.get_local_datetime(), "register_opc_tag(): OPCUA_server_dir the variables should be assigned to, doesn't exists." ) raise var = ua.Variant(0, strings_to_vartyps(variant_type)) mvar = obj.add_variable(self.idx, opctag.strip(), var) mvar.set_writable() print( DateHelper.get_local_datetime(), "Add variable: " + opctag + " of type " + variant_type + " @node " + parent_node) @uamethod def set_pv_active_power_setpoint(self, parent, setpoint, parent_node=""): try: obj = self.root.get_child( ["0:Objects", ("{}:" + parent_node).format(self.idx)]) except BadNoMatch: print( DateHelper.get_local_datetime(), "set_pv_active_power_setpoint(): assign new value to node failed." ) raise for mvar in obj.get_variables(): if "PV" and "CTRL" in mvar.get_browse_name().Name: variant_type = mvar.get_data_value().Value.VariantType mvar.set_value(clamp(setpoint, 0, 100), variant_type) print( DateHelper.get_local_datetime(), "Set Value of node " + mvar.get_browse_name().Name + " to " + str(clamp(setpoint, 0, 100))) @uamethod def run_online_grid_protection(self, parent, setpoint, parent_node=""): try: obj = self.root.get_child( ["0:Objects", ("{}:" + parent_node).format(self.idx)]) except BadNoMatch: print(DateHelper.get_local_datetime(), "run_online_grid_protection(): Change in On/Off failed.") raise for mvar in obj.get_variables(): if "RUN_ONLINE_GRID_PROTECTION" in mvar.get_browse_name().Name: variant_type = mvar.get_data_value().Value.VariantType mvar.set_value(clamp(setpoint, 0, 1), variant_type) print( DateHelper.get_local_datetime(), "Change status of online grid protection to " + str(clamp(setpoint, 0, 1))) def start(self): self.server.start() print(DateHelper.get_local_datetime(), self.__class__.__name__, " successful started") def stop(self): self.server.stop() print(DateHelper.get_local_datetime(), self.__class__.__name__, " successful stopped")
class OPCUAServer: """An OPC UA server which reads variables from a csv file and exposes it. Args: endpoint (:obj:`str`): OPC UA server endpoint. Defaults to 'opc.tcp://0.0.0.0:4840/intry4.0/server/'. server_name (:obj:`str`): OPC UA server name. Defaults to 'InTry 4.0 OPC UA Server'. security_policy (:obj:`list`): Array which contains `opcua.ua.SecurityPolicyType` available in the server. Defaults to [ ua.SecurityPolicyType.NoSecurity, ua.SecurityPolicyType.Basic256Sha256_Sign, ua.SecurityPolicyType.Basic256Sha256_SignAndEncrypt, ] ns_uri(:obj:`str`): the namespace URI where all the variables will be added. Defaults to 'urn:intry4.0:server'. object_name(:obj:`str`): name of the OPC UA object that will be created to hold all variables. Defaults to 'variables'. last_row_file (:obj:`str`): name of the file in which the last row published by the server will be saved. certificate (:obj:`str`): path of the certificate file used by the server. Defaults to '/var/intry-opcua-server/cert.der'. private_key (:obj:`str`): path of the certificate file used by the server. Defaults to '/var/intry-opcua-server/key.pem'. min_time(:obj:`int`): min time elapsed between variable updates. Defaults to 30. logger(:obj:`logging.Logger`): logger to be used. Defaults to None. Attributes: _server (opcua.Server): the OPC UA server. endpoint (str): OPC UA server endpoint. _ns_index (): the namespace index where all the variables will be added. _object () last_row (:obj:`dict`): last row that has been used by the server. For example: { "file": "csv1.csv", "row": "2019-10-02 23:55" } _stop (bool): flag variable that controls the infinite loop of variable updating. """ def __init__( self, endpoint: str = "opc.tcp://0.0.0.0:4840/intry4.0/server/", server_name: str = "InTry 4.0 - OPC UA Server", security_policy: List[ua.SecurityPolicyType] = None, ns_uri: str = "urn:intry:opcua:server", object_name: str = "variables", last_row_file: str = "/var/intry-opcua-server/last_row.log", certificate: str = "/var/intry-opcua-server/cert.der", private_key: str = "/var/intry-opcua-server/key.pem", min_time: int = 30, logger=None, ): if security_policy is None: _security_policy = [ ua.SecurityPolicyType.NoSecurity, ua.SecurityPolicyType.Basic256Sha256_Sign, ua.SecurityPolicyType.Basic256Sha256_SignAndEncrypt, ] self._server = Server() self.endpoint = endpoint self._server.set_endpoint(self.endpoint) self._server.set_security_policy(_security_policy) self._server.load_certificate(certificate) self._server.load_private_key(private_key) self._ns_index = self._server.register_namespace(ns_uri) self._object = self._server.nodes.objects.add_object( self._ns_index, object_name ) self._last_row_file = last_row_file self._logger = logger or logging.getLogger(__name__) self.last_row = {} self._stop = False self.min_time = min_time def _add_variable(self, name, value): """Adds a variable to the OPC UA server. Args: name (:obj:`str`): name of the variable. value (int or float): initial value of the variable. Returns: opcua.common.node.Node: the created variable in the OPC UA server. """ return self._object.add_variable(self._ns_index, name, value) def _get_csvs(self, csv_dir): """Get the CSV files stored in the specified directory and filter the CSV which are not required to start publishing new values from the last row that was published. Args: csv_dir (:obj:`str`): path of the directory containing CSVs. """ self._read_last_row() csvs = get_csvs_in_dir(csv_dir) self._logger.debug(f"CSV files inside {csv_dir}: {len(csvs)}") if not self.last_row: df = pd.read_csv(csvs[0], index_col="date") self.last_row = {"file": csvs[0], "row": df.index[0]} file_index = csvs.index(self.last_row["file"]) return csvs[file_index:] def variable_values_from_csvs(self, csv_dir): """Creates variables inside the OPC UA server from the CSVs contained in the specified directory. Then, each row of the provided CSVs will be read to update the value of each variable. csv_dir (str): path of the directory containing CSVs. """ csvs = self._get_csvs(csv_dir) len_csvs = len(csvs) if len_csvs > 0: variable_name_node = {} for (index, csv) in enumerate(csvs): if self._stop: break self._logger.info(f"Reading file {csv}") df = pd.read_csv(csv, index_col="date") self.last_row["file"] = csv # If first CSV, create variables in the OPC UA Server if index == 0: self._logger.debug( f"First csv readed: {csv}. Creating {len(df.columns)} OPC UA variables from it..." ) df = df[self.last_row["row"] :] for column in df.columns: first_value = df[column].iloc[0] self._logger.debug( f"Adding variable [{column}] with initial value <{first_value}>" ) variable_name_node[column] = self._add_variable( column, first_value ) # remove the first row because its going used for initial value df = df.iloc[1:] # iterate over the rows in the dataframe for updating the value of each variable time_between_update = 0 last_index = None for (index, row) in df.iterrows(): if self._stop: break self.last_row["row"] = index # Calculate the time to sleep between each update with the date of the # last row and this row. if last_index is not None: time_between_update = ( str_to_date(index) - str_to_date(last_index) ).total_seconds() if time_between_update > 60: self._logger.info( "Time between update too high. Setting it to 60 secs..." ) time_between_update = 60.0 elif time_between_update < self.min_time: self._logger.info( f"Time between update was negative or too low. Setting it to {self.min_time} secs..." ) time_between_update = self.min_time self._logger.info(f"Starting sleep of {time_between_update}...") time.sleep(time_between_update) self._logger.info( f"Time of {time_between_update} elapsed. Updating variable values..." ) for (column, node) in variable_name_node.items(): node.set_value(row[column]) last_index = index def _write_last_row(self): """Writes the last row published to a file in JSON format.""" create_path_if_not_exists(self._last_row_file) with open(self._last_row_file, "w+") as f: f.write(json.dumps(self.last_row)) def _read_last_row(self): """Reads the last row published from a JSON file.""" if file_exists(self._last_row_file): self._logger.info(f"Reading last row file {self._last_row_file}") with open(self._last_row_file, "r") as f: self.last_row = json.loads(f.read()) else: self._logger.info(f"File {self._last_row_file} does not exist") self.last_row = {} def start(self): """Starts the OPC UA server execution.""" self._logger.info(f"Starting OPC UA server. Listening on {self.endpoint}") self._server.start() def stop(self): """Stops the OPC UA server execution.""" self._write_last_row() self._logger.info("Stopping OPC UA server...") self._stop = True self._server.stop()
self.tl1.changeState(Light.green) if color == 3: self.tl1.changeState(Light.orange) if __name__ == "__main__": # setup our server server = Server() server.set_endpoint("opc.tcp://0.0.0.0:4840/freeopcua/server/") # setup our own namespace, not really necessary but should as spec uri = "http://alex.freeopcua.github.io" idx = server.register_namespace(uri) server.load_certificate("cert.der") server.load_private_key("private.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, ]) # set the security endpoints for identification of clients #self.server.set_security_IDs(["Anonymous", "Basic256Sha256", "Username"]) #server.set_security_IDs(["Username"]) policyIDs = ["Username"] server.set_security_IDs(policyIDs) # set the user_manager function server.user_manager.set_user_manager(user_manager) # get Objects node, this is where we should put our nodes
class ServerOPC(): def __init__(self, sensori): self.keys=c_gpio.led_dict.keys() self.sensori=sensori self.__led=c_gpio.led_dict self.init_server() def init_server(self): print("inizio settaggio server") self.server=Server() #self.server.set_endpoint("opc.tcp://192.168.1.250:4840") self.server.set_endpoint("opc.tcp://0.0.0.0:4840") self.server.set_server_name("DomoticProject") #carico il certificato e la chiave privata global base_path file_path_cert=(base_path / "../config/certificati/my_cert.der").resolve() file_path_key=(base_path / "../config/certificati/my_private_key.pem").resolve() self.server.load_certificate(file_path_cert) self.server.load_private_key(file_path_key) self.server.set_security_policy([ ua.SecurityPolicyType.NoSecurity, ua.SecurityPolicyType.Basic256Sha256_SignAndEncrypt, ua.SecurityPolicyType.Basic256Sha256_Sign ]) #setup namespace uri="Domotic" self.idx=self.server.register_namespace(uri) self.objects=self.server.get_objects_node() #per contenere le info dei sensori self.sensors_o=self.objects.add_object(self.idx, "Sensori") self.temperatura_s=self.sensors_o.add_variable(self.idx, "Temperatura", 0.00) self.counterbagno_s=self.sensors_o.add_variable(self.idx, "Counter Bagno", 0) self.countersalotto_s=self.sensors_o.add_variable(self.idx, "Counter Salotto", 0) #per contenere le info dei led self.luci_o=self.objects.add_object(self.idx, "Luci") self.luci_o_dict={} for x in self.keys: self.luci_o_dict[x]=self.luci_o.add_variable(self.idx, "Luce "+x, False) self.luci_o_dict[x].set_writable() #per contenere i metodi self.method_o=self.objects.add_object(self.idx, "Metodi") inarg=ua.Argument() inarg.Name="stanza" inarg.DataType=ua.NodeId(ua.ObjectIds.String) inarg.ValueRank=-1 inarg.ArrayDimensions=[] inarg.Description=ua.LocalizedText("stanza su cui applicare il metodo ['salotto', 'camera', 'bagno', 'ingresso']") self.mymethod1=self.method_o.add_method(self.idx, "Accendi luce", self.accendi_luce, [inarg]) self.mymethod2=self.method_o.add_method(self.idx, "Spegni luce", self.spegni_luce, [inarg]) print("server settato") def run(self): print("start server") self.server.start() try: while True: val=ua.Variant(self.sensori["temperatura"], ua.VariantType.Float) val=ua.DataValue(val) val.SourceTimestamp=datetime.utcnow() val.ServerTimestamp=datetime.utcnow() self.temperatura_s.set_data_value(val) val2=ua.Variant(self.sensori["counter_bagno"], ua.VariantType.UInt16) val2=ua.DataValue(val2) val2.SourceTimestamp=datetime.utcnow() val2.ServerTimestamp=datetime.utcnow() self.counterbagno_s.set_data_value(val2) val3=ua.Variant(self.sensori["counter_salotto"], ua.VariantType.UInt16) val3=ua.DataValue(val3) val3.SourceTimestamp=datetime.utcnow() val3.ServerTimestamp=datetime.utcnow() self.countersalotto_s.set_data_value(val3) for x in self.keys: pin=self.__led[x] status=gpio.input(pin) var=ua.Variant(status, ua.VariantType.Boolean) s=ua.DataValue(var) s.SourceTimestamp=datetime.utcnow() s.ServerTimestamp=datetime.utcnow() self.luci_o_dict[x].set_value(s) time.sleep(1) finally: self.server.stop() @uamethod def accendi_luce(self, parent, stanza): pin=self.__led[stanza] if stanza=="salotto": s=gpio.input(2) gpio.output(2, 1) gpio.output(pin, 0) else: gpio.output(pin, 1) @uamethod def spegni_luce(self, parent, stanza): pin=self.__led[stanza] if stanza=="salotto": s=gpio.input(2) gpio.output(2, 0) gpio.output(pin, 1) else: gpio.output(pin, 0)
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 __init__(self, name, shared): super().__init__(name, shared) self.logger = logging.getLogger(self.name) self.logger.info("init") self.shared.config.set_hidden_value(self.name, "user") self.shared.config.set_hidden_value(self.name, "password") self.shared.config.set_hidden_value(self.name, "password_hash") def config(key, val): return self.shared.config.config(self.name, key, val) endpoint = config("endpoint", "no_endpoint") certificate = config("certificate", "") private_key = config("private_key", "") uri = config("uri", "http://examples.freeopcua.github.io") root_object_name = config("root_object_name", "TEST") separator = config("separator", ".") namespace = config("namespace", 2) self.oldnew = config("oldnew_comparision", 0) admin_username = config("user", "admin") admin_password = config("password", "admin") admin_password_hash = config("password_hash", "").replace("$$", "$") security_ids = [] anonymous_on = config("anonymous_on", 0) username_on = config("username_on", 1) certificate_on = config("certificate_basic256sha256_on", 0) if anonymous_on: security_ids.append("Anonymous") if username_on: security_ids.append("Username") if certificate_on: security_ids.append("Basic256Sha256") security_policy = [] if config("nosecurity_on", 1): security_policy.append(ua.SecurityPolicyType.NoSecurity) if config("basic128rsa15_sign_on", 0): security_policy.append(ua.SecurityPolicyType.Basic128Rsa15_Sign) if config("basic128rsa15_signandencrypt_on", 0): security_policy.append( ua.SecurityPolicyType.Basic128Rsa15_SignAndEncrypt) if config("basic256_sign_on", 0): security_policy.append(ua.SecurityPolicyType.Basic256_Sign) if config("basic256_signandencrypt_on", 0): security_policy.append( ua.SecurityPolicyType.Basic256_SignAndEncrypt) if config("basic256sha256_sign_on", 1): security_policy.append(ua.SecurityPolicyType.Basic256Sha256_Sign) if config("basic256sha256_signandencrypt_on", 1): security_policy.append( ua.SecurityPolicyType.Basic256Sha256_SignAndEncrypt) initial_values_is_quality_good = config( "initial_values_is_quality_good", 0) if anonymous_on: server = Server() else: server = Server(iserver=CustomInternalServer()) server.iserver.set_parent(server) server.set_endpoint(endpoint) server.allow_remote_admin(False) if certificate and private_key: server.load_certificate(str(certificate)) server.load_private_key(str(private_key)) if security_ids: server.set_security_IDs(security_ids) if security_policy: server.set_security_policy(security_policy) def custom_user_manager(isession, userName, password): if userName != admin_username: return False if admin_password_hash: if werkzeug.security.check_password_hash( admin_password_hash, password): return True else: # fallback to plaintext if password == admin_password: return True return False if username_on: server.user_manager.set_user_manager(custom_user_manager) idx = server.register_namespace(uri) objects = server.get_objects_node() root = objects.add_object(idx, root_object_name) self.server = server self.objects = objects self.root = root self.sep = separator self.ns = namespace self.items = [] if initial_values_is_quality_good: self.initial_status_code = ua.StatusCodes.Good else: self.initial_status_code = ua.StatusCodes.BadWaitingForInitialData
#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) #logger = logging.getLogger("opcua.subscription_service") # logger.setLevel(logging.DEBUG) # setup our server server = Server() server.set_endpoint("opc.tcp://0.0.0.0:4840/freeopcua/server/") server.set_server_name("FreeOpcUa Example Server") server.load_certificate("robotarm_cert.der") server.load_private_key("robotarm_pk.pem") # setup our own namespace, not really necessary but should as spec uri = "http://examples.freeopcua.github.io" idx = server.register_namespace(uri) # get Objects node, this is where we should put our custom stuff objects = server.get_objects_node() # populating our address space myfolder = objects.add_folder(idx, "GFISmartFleet") myobj = server.get_root_node().get_child(["0:Objects", "2:GFISmartFleet" ]).add_object(idx, "RobotArm") var_Servo_left_angle = myobj.add_variable(idx, "Servo_left_angle", 90) var_Servo_left_angle.set_writable()
import sys sys.path.insert(0, "..") import time from opcua import ua, Server if __name__ == "__main__": # setup our server server = Server() server.set_endpoint("opc.tcp://0.0.0.0:4840/freeopcua/server/") # load server certificate and private key. This enables endpoints # with signing and encryption. server.load_certificate("example-certificate.der") server.load_private_key("example-private-key.pem") # setup our own namespace, not really necessary but should as spec uri = "http://examples.freeopcua.github.io" idx = server.register_namespace(uri) # get Objects node, this is where we should put our custom stuff objects = server.get_objects_node() # populating our address space myobj = objects.add_object(idx, "MyObject") myvar = myobj.add_variable(idx, "MyVariable", 6.7) myvar.set_writable() # Set MyVariable to be writable by clients # starting! server.start()
class TestCryptoConnect(unittest.TestCase): ''' Test connectino with a server supporting crypto ''' @classmethod def setUpClass(self): # start our own server self.srv_crypto = Server() self.uri_crypto = 'opc.tcp://localhost:%d' % port_num1 self.srv_crypto.set_endpoint(self.uri_crypto) # load server certificate and private key. This enables endpoints # with signing and encryption. self.srv_crypto.load_certificate("examples/certificate-example.der") self.srv_crypto.load_private_key("examples/private-key-example.pem") self.srv_crypto.start() # start a server without crypto self.srv_no_crypto = Server() self.uri_no_crypto = 'opc.tcp://localhost:%d' % port_num2 self.srv_no_crypto.set_endpoint(self.uri_no_crypto) self.srv_no_crypto.start() @classmethod def tearDownClass(self): # stop the server self.srv_no_crypto.stop() self.srv_crypto.stop() def test_nocrypto(self): clt = Client(self.uri_no_crypto) clt.connect() try: clt.get_objects_node().get_children() finally: clt.disconnect() def test_nocrypto_feil(self): clt = Client(self.uri_no_crypto) with self.assertRaises(ua.UaError): clt.set_security_string("Basic256,Sign,examples/certificate-example.der,examples/private-key-example.pem") def test_basic256(self): clt = Client(self.uri_crypto) try: clt.set_security_string("Basic256,Sign,examples/certificate-example.der,examples/private-key-example.pem") clt.connect() self.assertTrue(clt.get_objects_node().get_children()) finally: clt.disconnect() def test_basic256_encrypt(self): clt = Client(self.uri_crypto) try: clt.set_security_string("Basic256,SignAndEncrypt,examples/certificate-example.der,examples/private-key-example.pem") clt.connect() self.assertTrue(clt.get_objects_node().get_children()) finally: clt.disconnect() def test_basic128Rsa15(self): clt = Client(self.uri_crypto) try: clt.set_security_string("Basic128Rsa15,Sign,examples/certificate-example.der,examples/private-key-example.pem") clt.connect() self.assertTrue(clt.get_objects_node().get_children()) finally: clt.disconnect() def test_basic128Rsa15_encrypt(self): clt = Client(self.uri_crypto) try: clt.set_security_string("Basic128Rsa15,SignAndEncrypt,examples/certificate-example.der,examples/private-key-example.pem") clt.connect() self.assertTrue(clt.get_objects_node().get_children()) finally: clt.disconnect() def test_basic256_encrypt_success(self): clt = Client(self.uri_crypto) try: clt.set_security(security_policies.SecurityPolicyBasic256, 'examples/certificate-example.der', 'examples/private-key-example.pem', None, ua.MessageSecurityMode.SignAndEncrypt ) clt.connect() self.assertTrue(clt.get_objects_node().get_children()) finally: clt.disconnect() def test_basic256_encrypt_feil(self): # FIXME: how to make it feil??? clt = Client(self.uri_crypto) with self.assertRaises(ua.UaError): clt.set_security(security_policies.SecurityPolicyBasic256, 'examples/certificate-example.der', 'examples/private-key-example.pem', None, ua.MessageSecurityMode.None_ )
class TestCryptoConnect(unittest.TestCase): ''' Test connectino with a server supporting crypto ''' @classmethod def setUpClass(self): # start our own server self.srv_crypto = Server() self.uri_crypto = 'opc.tcp://localhost:%d' % port_num1 self.srv_crypto.set_endpoint(self.uri_crypto) # load server certificate and private key. This enables endpoints # with signing and encryption. self.srv_crypto.load_certificate("examples/certificate-example.der") self.srv_crypto.load_private_key("examples/private-key-example.pem") self.srv_crypto.start() # start a server without crypto self.srv_no_crypto = Server() self.uri_no_crypto = 'opc.tcp://localhost:%d' % port_num2 self.srv_no_crypto.set_endpoint(self.uri_no_crypto) self.srv_no_crypto.start() @classmethod def tearDownClass(self): # stop the server self.srv_no_crypto.stop() self.srv_crypto.stop() def test_nocrypto(self): clt = Client(self.uri_no_crypto) clt.connect() try: clt.get_objects_node().get_children() finally: clt.disconnect() def test_nocrypto_feil(self): clt = Client(self.uri_no_crypto) with self.assertRaises(ua.UaError): clt.set_security_string( "Basic256,Sign,examples/certificate-example.der,examples/private-key-example.pem" ) def test_basic256(self): clt = Client(self.uri_crypto) try: clt.set_security_string( "Basic256,Sign,examples/certificate-example.der,examples/private-key-example.pem" ) clt.connect() self.assertTrue(clt.get_objects_node().get_children()) finally: clt.disconnect() def test_basic256_encrypt(self): clt = Client(self.uri_crypto) try: clt.set_security_string( "Basic256,SignAndEncrypt,examples/certificate-example.der,examples/private-key-example.pem" ) clt.connect() self.assertTrue(clt.get_objects_node().get_children()) finally: clt.disconnect() def test_basic128Rsa15(self): clt = Client(self.uri_crypto) try: clt.set_security_string( "Basic128Rsa15,Sign,examples/certificate-example.der,examples/private-key-example.pem" ) clt.connect() self.assertTrue(clt.get_objects_node().get_children()) finally: clt.disconnect() def test_basic128Rsa15_encrypt(self): clt = Client(self.uri_crypto) try: clt.set_security_string( "Basic128Rsa15,SignAndEncrypt,examples/certificate-example.der,examples/private-key-example.pem" ) clt.connect() self.assertTrue(clt.get_objects_node().get_children()) finally: clt.disconnect() def test_basic256_encrypt_success(self): clt = Client(self.uri_crypto) try: clt.set_security(security_policies.SecurityPolicyBasic256, 'examples/certificate-example.der', 'examples/private-key-example.pem', None, ua.MessageSecurityMode.SignAndEncrypt) clt.connect() self.assertTrue(clt.get_objects_node().get_children()) finally: clt.disconnect() def test_basic256_encrypt_feil(self): # FIXME: how to make it feil??? clt = Client(self.uri_crypto) with self.assertRaises(ua.UaError): clt.set_security(security_policies.SecurityPolicyBasic256, 'examples/certificate-example.der', 'examples/private-key-example.pem', None, ua.MessageSecurityMode.None_)
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)
sys.stdout = MyLogger(logger, logging.INFO) if __name__ == "__main__": #Creamos una instancia del servidor OPC UA server = Server() # Establecemos la comunicación de nuestro servidor opc ua # load server certificate and private key. This enables endpoints #Cargamos el certificado del servidor y la clave privada #esto activa la comunicación con firma y cifrado. if len(sys.argv) == 2: server.set_endpoint("opc.tcp://%s" % sys.argv[1] ) server.load_certificate("certificate-example.der") server.load_private_key("private-key-example.pem") elif len(sys.argv) == 3: server.set_endpoint("opc.tcp://%s" % sys.argv[1] ) server.load_certificate("%s/certificate-example.der" % sys.argv[2]) server.load_private_key("%s/private-key-example.pem" % sys.argv[2]) else: a = len(sys.argv) print ("Numero de argumentos inexperado: %s" %a) print "opcua_server.py ip:puerto (rutacertificado)" sys.exit(1) # Declaración del espacio de nombres (no necesario) uri = "SERVIDOR OPC-UA - ARDUINO:FreeOpcUa:python-opcua" idx = server.register_namespace(uri) # Cargamos los objetos objects = server.get_objects_node()