Ejemplo n.º 1
0
class DemoServer:
    def __init__(self):
        self.server = Server()

        self.server.set_endpoint('opc.tcp://0.0.0.0:51210/UA/SampleServer')
        self.server.set_server_name('Custom structure demo server')
        # idx name will be used later for creating the xml used in data type dictionary
        self._idx_name = 'http://examples.freeopcua.github.io'
        self.idx = self.server.register_namespace(self._idx_name)

        self.dict_builder = DataTypeDictionaryBuilder(self.server, self.idx,
                                                      self._idx_name,
                                                      'MyDictionary')

    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()
Ejemplo n.º 2
0
async def main():
    global rpm_is
    puls.when_pressed = callback_rpm # set callback
    # setup our server
    server = Server()
    await server.init()
    server.set_endpoint('opc.tcp://pi.local:4840/freeopcua/server/')

    # setup our own namespace, not really necessary but should as spec
    uri = 'http://examples.freeopcua.github.io'
    idx = await server.register_namespace(uri)

    # populating our address space
    # server.nodes, contains links to very common nodes like objects and root
    myobj = await server.nodes.objects.add_object(idx, 'Car')
    rpm_var = await myobj.add_variable(idx, 'rpm', 0.0)
    motor_var = await myobj.add_variable(idx, 'motor', 0.0)
    # Set MyVariable to be writable by clients
    await rpm_var.set_writable()
    await motor_var.set_writable()
    await server.nodes.objects.add_method(ua.NodeId('ServerMethod', 2), ua.QualifiedName('ServerMethod', 2), func, [ua.VariantType.Int64], [ua.VariantType.Int64])
    _logger.info('Starting server!')
    async with server:
        while True:
            #await asyncio.sleep(0.05)
            #rpm_is = await rpm()
            #if rpm_is>-1:
            #    await rpm_var.write_value(rpm_is)
            #speed = await motor_var.read_value()
            #try:
            #    motor.forward(speed)
            #except ValueError:
            #    _logger.warning(f'\t\t{speed} no valid speed')
            rpm_is, speed = await asyncio.gather(*(get_rpm(rpm_var), set_speed(motor_var)))
            _logger.info(f'\t\tRPM: {rpm_is}\n\t\t\tMotor: {await motor_var.read_value()}')
Ejemplo n.º 3
0
async def main():

    # setup our server
    server = Server()
    await server.init()

    server.set_endpoint("opc.tcp://0.0.0.0:4840/freeopcua/server/")

    # setup our own namespace, not really necessary but should as spec
    uri = "http://examples.freeopcua.github.io"
    idx = await server.register_namespace(uri)

    # create our custom object type
    dev = await server.nodes.base_object_type.add_object_type(0, "MyDevice")
    var = await dev.add_variable(0, "sensor1", 1.0)
    await var.set_modelling_rule(True
                                 )  # make that child instantiated by default
    prop = await dev.add_property(0, "device_id", "0340")
    await prop.set_modelling_rule(True)
    ctrl = await dev.add_object(0, "controller")
    await ctrl.set_modelling_rule(True)
    prop = await ctrl.add_property(0, "state", "Idle")
    await prop.set_modelling_rule(True)

    # instantiate our new object type
    nodes = await instantiate(server.nodes.objects, dev, bname="2:Device0001")
    mydevice = nodes[0]  # the first node created is our main object
    #mydevice = server.nodes.objects.add_object(2, "Device0001", objecttype=dev)  # specificying objecttype to add_object also instanciate a node type
    mydevice_var = await mydevice.get_child(
        ["0:controller", "0:state"])  # get proxy to our device state variable

    # starting!
    async with server:
        while True:
            await asyncio.sleep(1)
Ejemplo n.º 4
0
async def main():
    # setup our server
    server = Server()
    await server.init()
    server.set_endpoint('opc.tcp://*:4840/freeopcua/server/')  #4840
    # setup our own namespace, not really necessary but should as spec
    uri = 'http://examples.freeopcua.github.io'
    idx = await server.register_namespace(uri)
    # get Objects node, this is where we should put our nodes
    objects = server.get_objects_node()

    # populating our address space
    myobj = await objects.add_object(idx, 'MyObject')
    myvar = await myobj.add_variable(idx, 'MyVariable', 6.7)
    await myvar.set_writable()  # Set MyVariable to be writable by clients

    await objects.add_method(ua.NodeId("ServerMethod", 2),
                             ua.QualifiedName('ServerMethod', 2), func,
                             [ua.VariantType.Int64], [ua.VariantType.Int64])

    # starting!
    async with server:
        count = 0
        while True:
            await asyncio.sleep(1)
            count += 0.1
            print("SET VALUE", myvar, count)
            await myvar.set_value(count)
async def main_virtual_device():
    #this code runs on the the cloud server

    # setup our server
    server = Server()
    await server.init()
    server.set_endpoint('opc.tcp://0.0.0.0:4841/virtual/server/')

    # setup our own namespace, not really necessary but should as spec
    uri = 'http://examples.freeopcua.github.io'
    idx = await server.register_namespace(uri)

    # populating our address space
    # server.nodes, contains links to very common nodes like objects and root
    component = await server.nodes.objects.add_object(idx, 'Component')
    sensor_value = await component.add_variable(idx, 'SensorValue', 6.7)
    command_id = await component.add_variable(idx, 'CommandID', 1)
    # Set CommandID to be writable by clients
    await command_id.set_writable()
    # Set SensorValue to be writable by clients (for the mirror server)
    await sensor_value.set_writable()

    _logger.info('Starting Virtual Device Server!')
    async with server:
        while True:
            await asyncio.sleep(update_period_s)
            #update values
            new_sensor_val = await sensor_value.read_value()
            print('[Virtual Device] value of %s is %.1f', sensor_value,
                  new_sensor_val)
            new_command_val = await command_id.read_value()
            print('[Virtual Device] value of %s is %.1f', command_id,
                  new_command_val)
async def main_physical_device():
    #this code runs on the the physical device

    # setup our server
    server = Server()
    await server.init()
    server.set_endpoint('opc.tcp://0.0.0.0:4840/physical/server/')

    # setup our own namespace, not really necessary but should as spec
    uri = 'http://examples.freeopcua.github.io'
    idx = await server.register_namespace(uri)

    # populating our address space
    # server.nodes, contains links to very common nodes like objects and root
    component = await server.nodes.objects.add_object(idx, 'Component')
    sensor_value = await component.add_variable(idx, 'SensorValue', 6.7)
    command_id = await component.add_variable(idx, 'CommandID', 1)
    # Set CommandID to be writable by clients
    await command_id.set_writable()

    _logger.info('Starting Physical Device Server!')
    async with server:
        while True:
            await asyncio.sleep(update_period_s)
            #read command id
            new_command_val = await command_id.read_value()
            print('[Physical Device] value of %s is %.1f', command_id,
                  new_command_val)
            #generate new sensor value
            new_sensor_val = math.sin(new_command_val * time.time())
            print('[Physical Device] Set value of %s to %.1f', sensor_value,
                  new_sensor_val)
            await sensor_value.write_value(new_sensor_val)
Ejemplo n.º 7
0
async def main():

    cert_user_manager = CertificateUserManager()
    await cert_user_manager.add_user(
        "certificates/peer-certificate-example-1.der", name='test_user')

    server = Server(user_manager=cert_user_manager)

    await server.init()

    server.set_endpoint("opc.tcp://0.0.0.0:4840/freeopcua/server/")
    server.set_security_policy(
        [ua.SecurityPolicyType.Basic256Sha256_SignAndEncrypt],
        permission_ruleset=SimpleRoleRuleset())
    # load server certificate and private key. This enables endpoints
    # with signing and encryption.

    await server.load_certificate("certificate-example.der")
    await server.load_private_key("private-key-example.pem")

    idx = 0

    # populating our address space
    myobj = await server.nodes.objects.add_object(idx, "MyObject")
    myvar = await myobj.add_variable(idx, "MyVariable", 0.0)
    await myvar.set_writable()  # Set MyVariable to be writable by clients

    # starting!
    async with server:
        while True:
            await asyncio.sleep(1)
            current_val = await myvar.get_value()
            count = current_val + 0.1
            await myvar.write_value(count)
Ejemplo n.º 8
0
async def main():
    server = Server()

    cert_handler = CertificateHandler()
    await server.init()
    await cert_handler.trust_certificate(
        "certificates/peer-certificate-example-1.der")

    server.set_endpoint("opc.tcp://0.0.0.0:4840/freeopcua/server/")
    server.set_security_policy(
        [ua.SecurityPolicyType.Basic256Sha256_SignAndEncrypt],
        certificate_handler=cert_handler)
    # load server certificate and private key. This enables endpoints
    # with signing and encryption.

    await server.load_certificate("certificate-example.der")
    await server.load_private_key("private-key-example.pem")

    # setup our own namespace, not really necessary but should as spec
    uri = "http://examples.freeopcua.github.io"
    idx = await server.register_namespace(uri)

    # populating our address space
    myobj = await server.nodes.objects.add_object(idx, "MyObject")
    myvar = await myobj.add_variable(idx, "MyVariable", 6.7)
    await myvar.set_writable()  # Set MyVariable to be writable by clients

    # starting!
    async with server:
        count = 0
        while True:
            await asyncio.sleep(1)
            count += 0.1
            await myvar.write_value(count)
Ejemplo n.º 9
0
async def main():
    # setup our server
    server = Server()
    await server.init()

    server.set_endpoint("opc.tcp://0.0.0.0:4840/freeopcua/server/")

    # setup our own namespace, not really necessary but should as spec
    uri = "http://examples.freeopcua.github.io"
    idx = await server.register_namespace(uri)

    myobj = await server.nodes.objects.add_object(idx, "MyObject")
    myvar = await myobj.add_variable(idx, "MyVariable", 6.7)
    await myvar.set_writable()    # Set MyVariable to be writable by clients

    dev = await server.nodes.base_object_type.add_object_type(0, "MyDevice")
    await dev.add_variable(0, "sensor1", 1.0)

    mydevice = await instantiate(server.nodes.objects, dev, bname="2:Device0001")

    node_list = [dev, mydevice[0], myobj, myvar]

    exporter = XmlExporter(server)
    await exporter.build_etree(node_list, ['http://myua.org/test/'])
    await exporter.write_xml('ua-export.xml')
Ejemplo n.º 10
0
async def srv_crypto_one_cert(request):
    cert_user_manager = CertificateUserManager()
    admin_peer_certificate = admin_peer_creds["certificate"]
    user_peer_certificate = user_peer_creds["certificate"]
    anonymous_peer_certificate = anonymous_peer_creds["certificate"]
    key, cert = request.param
    await cert_user_manager.add_admin(admin_peer_certificate, name='Admin')
    await cert_user_manager.add_user(user_peer_certificate, name='User')
    await cert_user_manager.add_role(anonymous_peer_certificate, name='Anonymous', user_role=UserRole.Anonymous)
    srv = Server(user_manager=cert_user_manager)

    srv.set_endpoint(uri_crypto_cert)
    srv.set_security_policy([ua.SecurityPolicyType.Basic256Sha256_SignAndEncrypt],
                            permission_ruleset=SimpleRoleRuleset())
    await srv.init()
    await srv.load_certificate(cert)
    await srv.load_private_key(key)
    idx = 0
    myobj = await srv.nodes.objects.add_object(idx, "MyObject")
    myvar = await myobj.add_variable(idx, "MyVariable", 0.0)
    await myvar.set_writable()  # Set MyVariable to be writable by clients

    await srv.start()
    yield srv
    # stop the server
    await srv.stop()
Ejemplo n.º 11
0
async def start_server(loop: asyncio.AbstractEventLoop):
    server = Server()
    await server.init()
    server.set_endpoint("opc.tcp://0.0.0.0:4840/freeopcua/server/")
    # setup our own namespace, not really necessary but should as spec
    uri = "http://examples.freeopcua.github.io"
    idx = await server.register_namespace(uri)
    # get Objects node, this is where we should put our custom stuff
    objects = server.get_objects_node()
    # populating our address space
    myobj = await objects.add_object(idx, "MyObject")
    # Creating a custom event: Approach 1
    # The custom event object automatically will have members from its parent (BaseEventType)
    etype = await server.create_custom_event_type(
        idx, 'MyFirstEvent', ua.ObjectIds.BaseEventType,
        [('MyNumericProperty', ua.VariantType.Float),
         ('MyStringProperty', ua.VariantType.String)])
    myevgen = await server.get_event_generator(etype, myobj)
    # Creating a custom event: Approach 2
    custom_etype = await server.nodes.base_event_type.add_object_type(
        2, 'MySecondEvent')
    await custom_etype.add_property(2, 'MyIntProperty',
                                    ua.Variant(0, ua.VariantType.Int32))
    await custom_etype.add_property(2, 'MyBoolProperty',
                                    ua.Variant(True, ua.VariantType.Boolean))
    mysecondevgen = await server.get_event_generator(custom_etype, myobj)
    await server.start()
    loop.call_later(2, emmit_event, loop, myevgen, mysecondevgen, 1)
Ejemplo n.º 12
0
class TestServer:
    def __init__(self):
        " Basic setup of server"
        # async def __init__ doesn't work
        self.server = Server()
        self.idx = None
        self.top = None
        self.vars = []

    async def create_simulator(self):
        await self.server.init()
        self.server.set_endpoint(f'opc.tcp://{LOCAL_HOST}:{PORT}/{PATH}')
        self.server.set_server_name("OPC-UA Test Server")
        uri = "https://github.com/it-hms/my-opcua-test-server"
        self.idx = await self.server.register_namespace(uri)
        self.top = await self.server.nodes.objects.add_object(
            self.idx, 'Dynamic')
        for i in range(MAX_TAG + 1):
            t_var = await self.top.add_variable(self.idx, f"Random.Float{i}",
                                                0)
            self.vars.append(t_var)

    async def run(self):
        async with self.server:
            while True:
                i = 0
                for var in self.vars:
                    await var.write_value(random.gauss(i * 10, 9))
                    i += 1
                await asyncio.sleep(2)
Ejemplo n.º 13
0
async def main():
    # setup our server
    server = Server()
    await server.init()
    server.set_endpoint('opc.tcp://0.0.0.0:4840/freeopcua/server/')

    # setup our own namespace, not really necessary but should as spec
    uri = 'http://examples.freeopcua.github.io'
    idx = await server.register_namespace(uri)

    # populating our address space
    # server.nodes, contains links to very common nodes like objects and root
    myobj = await server.nodes.objects.add_object(idx, 'MyObject')
    myvar = await myobj.add_variable(idx, 'MyVariable', 6.7)
    # Set MyVariable to be writable by clients
    await myvar.set_writable()
    await server.nodes.objects.add_method(ua.NodeId('ServerMethod', 2),
                                          ua.QualifiedName('ServerMethod', 2),
                                          func, [ua.VariantType.Int64],
                                          [ua.VariantType.Int64])
    _logger.info('Starting server!')
    async with server:
        count = 0
        while True:
            await asyncio.sleep(1)
            count += 0.1
            _logger.info('Set value of %s to %.1f', myvar, count)
            await myvar.write_value(count)
Ejemplo n.º 14
0
class HelloServer:
    def __init__(self, endpoint, name, model_filepath):
        self.server = Server()

        #  This need to be imported at the start or else it will overwrite the data
        self.server.import_xml(model_filepath)

        self.server.set_endpoint(endpoint)
        self.server.set_server_name(name)

        objects = self.server.get_objects_node()

        freeopcua_namespace = self.server.get_namespace_index(
            "urn:freeopcua:python:server")
        hellower = objects.get_child("0:Hellower")
        hellower_say_hello = hellower.get_child("0:SayHello")

        self.server.link_method(hellower_say_hello, say_hello_xml)

        hellower.add_method(freeopcua_namespace, "SayHello2", say_hello,
                            [ua.VariantType.Boolean], [ua.VariantType.String])

        hellower.add_method(freeopcua_namespace, "SayHelloArray",
                            say_hello_array, [ua.VariantType.Boolean],
                            [ua.VariantType.String])

    def __enter__(self):
        self.server.start()
        return self.server

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.server.stop()
Ejemplo n.º 15
0
async def mymain():

    # setup our server
    server = Server()
    await server.init()
    server.set_endpoint("opc.tcp://0.0.0.0:4840/freeopcua/server/")

    # setup our own namespace, not really necessary but should as spec
    uri = "http://examples.freeopcua.github.io"
    idx = await server.register_namespace(uri)

    # populating our address space
    myobj = await server.nodes.objects.add_object(idx, "MyObject")
    myvar = await myobj.add_variable(idx, "MyVariable", 6.7)
    await myvar.set_writable()  # Set MyVariable to be writable by clients

    # starting!
    async with server:
        while True:
            await asyncio.sleep(10)
        #nb = 100000
        #start = time.time()
        #for i in range(nb):
        #await server.write_attribute_value(myvar.nodeid, ua.DataValue(i))
        #await myvar.write_value(i)
    print("\n Write frequency: \n", nb / (time.time() - start))
Ejemplo n.º 16
0
async def main():
    global rpm_is
    
    puls.when_pressed = callback_rpm # set callback
    
    # initialize Server
    server = Server()
    await server.init()
    server.set_endpoint('opc.tcp://pi.local:4840/freeopcua/server/')
    server.set_server_name("OPC UA Raspi Server")
    # all possible endpoint policies set for client connection
    server.set_security_policy([
            ua.SecurityPolicyType.NoSecurity,
            ua.SecurityPolicyType.Basic256Sha256_SignAndEncrypt,
            ua.SecurityPolicyType.Basic256Sha256_Sign])
    
    # setup namespace
    uri = "example-uri.edu"
    idx = await server.register_namespace(uri)
    
    # create Motor-node type for later use
    base_motor = await motor_object(idx, server)


    # populateing address space
    motor = await server.nodes.objects.add_object(idx, "Motor", base_motor)
    rpm_var = await motor.get_child([f"{idx}:RPM"]) # rounds per minute
    await rpm_var.set_writable()
    speed_var = await motor.get_child([f"{idx}:Speed"]) # motor speed
    await speed_var.set_writable()
    
    # Start!
    async with server:
        while True:
            rpm_is, speed_is = await asyncio.gather(*(get_rpm(rpm_var), set_speed(speed_var)))
Ejemplo n.º 17
0
async def main():
    server = Server()
    await server.init()
    server.set_endpoint('opc.tcp://192.168.0.100:4840/opcua/')
    server.set_server_name("OPC-UA Server")

    uri = 'http://devnetiot.com/opcua/'
    idx = await server.register_namespace(uri)

    obj_plc = await server.nodes.objects.add_object(idx, 'PLC')
    var_temperature = await obj_plc.add_variable(idx, 'temperature', 0)
    var_humidity = await obj_plc.add_variable(idx, 'humidity', 0)

    _logger.info('Starting server!')
    async with server:
        while True:
            humidity, temperature = Adafruit_DHT.read_retry(
                Adafruit_DHT.DHT11, DHT_DATA_PIN)

            if humidity is not None and temperature is not None:
                print('temperature: {0:0.1f}*C'.format(temperature))
                print('humidity: {0:0.1f}%'.format(humidity))
                await var_temperature.write_value(float(temperature))
                await var_humidity.write_value(float(humidity))
            else:
                print('Failed to get DHT11 reading, trying again in ',
                      DHT_READ_TIMEOUT, 'seconds')

            await asyncio.sleep(DHT_READ_TIMEOUT)
Ejemplo n.º 18
0
async def opc(request):
    """
    Fixture for tests that should run for both `Server` and `Client`
    :param request:
    :return:
    """
    if request.param == 'client':
        srv = Server()
        await srv.init()
        srv.set_endpoint(f'opc.tcp://127.0.0.1:{port_num}')
        await add_server_methods(srv)
        await srv.start()
        # start client
        # long timeout since travis (automated testing) can be really slow
        clt = Client(f'opc.tcp://[email protected]:{port_num}', timeout=10)
        await clt.connect()
        yield Opc(clt, srv)
        await clt.disconnect()
        await srv.stop()
    elif request.param == 'server':
        # start our own server
        srv = Server()
        await srv.init()
        srv.set_endpoint(f'opc.tcp://127.0.0.1:{port_num1}')
        await add_server_methods(srv)
        await srv.start()
        yield Opc(srv, srv)
        # stop the server
        await srv.stop()
    else:
        raise ValueError("invalid internal test config")
Ejemplo n.º 19
0
async def srv_no_crypto():
    # start our own server
    srv = Server()
    await srv.init()
    srv.set_endpoint(uri_no_crypto)
    await srv.start()
    yield srv
    # stop the server
    await srv.stop()
Ejemplo n.º 20
0
async def main():
    # setup our server
    server = Server()
    await server.init()
    server.set_endpoint("opc.tcp://0.0.0.0:4840/freeopcua/server/")

    # setup our own namespace, not really necessary but should as spec
    uri = "http://examples.freeopcua.github.io"
    nsidx = await server.register_namespace(uri)

    # --------------------------------------------------------
    # create custom enum data type
    # --------------------------------------------------------

    # 1.
    # Create Enum Type
    myenum_type = await server.nodes.enum_data_type.add_data_type(
        nsidx, 'MyEnum')

    # 2.
    # Add enumerations as EnumStrings (Not yet tested with EnumValues)
    # Essential to use namespace 0 for EnumStrings !

    es = await myenum_type.add_property(0, "EnumStrings", [
        ua.LocalizedText("ok"),
        ua.LocalizedText("idle"),
    ])

    # 3. load enums froms erver
    await server.load_enums()

    # now we have a python enum available to play with
    val = ua.MyEnum.ok

    # not sure these are necessary
    #es.write_value_rank(1)
    #es.write_array_dimensions([0])

    # --------------------------------------------------------
    # create object with enum variable
    # --------------------------------------------------------

    # create object
    myobj = await server.nodes.objects.add_object(nsidx, 'MyObjectWithEnumVar')

    # add var with as type the custom enumeration
    myenum_var = await myobj.add_variable(nsidx,
                                          'MyEnum2Var',
                                          val,
                                          datatype=myenum_type.nodeid)
    await myenum_var.set_writable()
    await myenum_var.write_value(ua.MyEnum.idle)  # change value of enumeration

    async with server:
        while True:
            time.sleep(0.5)
Ejemplo n.º 21
0
async def discovery_server():
    # start our own server
    srv = Server()
    await srv.init()
    await srv.set_application_uri('urn:freeopcua:python:discovery')
    srv.set_endpoint(f'opc.tcp://127.0.0.1:{port_discovery}')
    await srv.start()
    yield srv
    # stop the server
    await srv.stop()
Ejemplo n.º 22
0
 async def server(url):
     srv = Server()
     srv.set_endpoint(url)
     await srv.init()
     await add_server_methods(srv)
     await add_server_custom_enum_struct(srv)
     async with srv:
         while t.do_run:
             await asyncio.sleep(1)
     await srv.stop()
Ejemplo n.º 23
0
async def main():
    # Certificates folder
    certs_folder = os.environ.get('CERTS_FOLDER', os.path.dirname(os.path.realpath(__file__)))
    key_pem_path = os.path.join(certs_folder, "key.pem")
    cert_der_path = os.path.join(certs_folder, "certificate.der")

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

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

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

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

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

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

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

    async with server:
        await asyncio.gather(bool_task, pos_task, neg_task, temp_task, hum_task, cyclic_task, tcx_task)
Ejemplo n.º 24
0
async def server():
    # start our own server
    srv = Server()
    await srv.init()
    srv.set_endpoint(f'opc.tcp://127.0.0.1:{port_num}')
    await add_server_methods(srv)
    await add_server_custom_enum_struct(srv)
    await srv.start()
    yield srv
    # stop the server
    await srv.stop()
Ejemplo n.º 25
0
async def srv_crypto():
    # start our own server
    srv = Server()
    await srv.init()
    srv.set_endpoint(uri_crypto)
    await srv.load_certificate(f"{EXAMPLE_PATH}certificate-example.der")
    await srv.load_private_key(f"{EXAMPLE_PATH}private-key-example.pem")
    await srv.start()
    yield srv
    # stop the server
    await srv.stop()
Ejemplo n.º 26
0
async def srv_crypto_all_certs(request):
    # start our own server
    srv = Server()
    key, cert = request.param
    await srv.init()
    srv.set_endpoint(uri_crypto)
    await srv.load_certificate(cert)
    await srv.load_private_key(key)
    await srv.start()
    yield srv
    # stop the server
    await srv.stop()
Ejemplo n.º 27
0
 async def run_server(self, url):
     srv = Server()
     srv.set_endpoint(url)
     await srv.init()
     await add_server_methods(srv)
     await add_server_custom_enum_struct(srv)
     async with srv:
         with self.cond:
             self.cond.notify_all()
         while not self.stop_ev.is_set():
             await asyncio.sleep(1)
     await srv.stop()
Ejemplo n.º 28
0
async def server_with_certificates(server_url,
                                   server_certificate_path,
                                   server_private_key_path,
                                   certificates=None,
                                   test=False):
    """
    :param server_url:
    :type server_url: str
    :param server_certificate_path:
    :type server_certificate_path: str
    :param server_private_key_path:
    :type server_private_key_path: str
    :param certificates:
    :type certificates: list
    :return:
    """
    # setup our serverclone_and_subscribe(client_node, server_node, sub_handler)
    certificate_handler = CertificateUserManager()
    if certificates is not None and test is not True:
        for role_add in certificates:
            certificate_path = role_add['certificate_path']
            name = role_add['name']
            role = role_add['role']
            if role == 'admin':
                await certificate_handler.add_admin(
                    certificate_path=certificate_path, name=name)
            elif role == 'user':
                await certificate_handler.add_user(
                    certificate_path=certificate_path, name=name)
            else:
                raise NotImplementedError

        server = Server(user_manager=certificate_handler)
    else:
        server = Server()
    await server.init()
    server.set_endpoint(server_url)
    security_policies = []
    permission_ruleset = SimpleRoleRuleset()

    if certificates is not None:
        security_policies.append(
            ua.SecurityPolicyType.Basic256Sha256_SignAndEncrypt)

    if certificates is None or test:
        security_policies.append(ua.SecurityPolicyType.NoSecurity)

    server.set_security_policy(security_policies,
                               permission_ruleset=permission_ruleset)
    if server_certificate_path:
        await server.load_certificate(server_certificate_path)
        await server.load_private_key(server_private_key_path)
    return server, certificate_handler
Ejemplo n.º 29
0
async def serve_state(duration=None, frequency=1, debug=False):
    server = Server()
    await server.init()
    server.set_endpoint("opc.tcp://0.0.0.0:4840/pulsedng/")

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

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

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

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

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

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

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

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

    _logger.info('Starting server!')
    async with server:
        while True:
            for state in GeneratorState:
                await asyncio.sleep(2)
                _logger.info('Set value of %s to %d', GeneratorState_var,
                             state)
                await GeneratorState_var.set_value(state)
Ejemplo n.º 30
0
async def main():
    # setup our server
    server = Server()
    await server.init()
    server.set_endpoint('opc.tcp://0.0.0.0:4840/freeopcua/server/')
    # setup our own namespace, not really necessary but should as spec
    uri = 'http://examples.freeopcua.github.io'
    idx = await server.register_namespace(uri)

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


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

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

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