Exemple #1
0
 async def test_serverports_no_conflict(self):
     # When different ports are used, servers should not get into conflict.
     #
     # (To some extent, that this is so easy is the fault of the weird way
     # the other protocols' ports are set for lack of configurability).
     async with Context.create_server_context(None, bind=("::1", 1234)):
         async with Context.create_server_context(None, bind=("::1", None)):
             pass
Exemple #2
0
 async def test_multiple_contexts(self):
     # Not that that'd be a regular thing to do, just checking it *can* be
     # done
     async with Context.create_client_context():
         async with Context.create_client_context():
             # None is an acceptable site; binding to a concrete port
             # removes the worries of situations where the default
             # transports can't bind to "any".
             async with Context.create_server_context(None, bind=("::1", None)):
                 pass
Exemple #3
0
 def setup(self):
     """Setup CoAP resources exposed by this server."""
     root_coap = resource.Site()
     root_coap.add_resource(('server', ), CoapServerResource(self))
     root_coap.add_resource(('alive', ), CoapAliveResource(self))
     asyncio. async (Context.create_server_context(root_coap,
                                                   bind=('::', self.port)))
Exemple #4
0
    def main_func():
        led1 = LEDResource(21)
        led2 = LEDResource(22)
        shutter_func = lambda: (led1.resource.off(), led2.resource.off())

        root = resource.Site()
        root.add_resource(['.well-known', 'core'],
                          resource.WKCResource(
                              root.get_resources_as_linkheader))
        root.add_resource(['led1'], led1)
        root.add_resource(['led2'], led2)
        root.add_resource(['button1'],
                          ButtonResource(11,
                                         lambda: led1.resource.toggle(),
                                         loop=event_loop))
        root.add_resource(['button2'],
                          ButtonResource(12,
                                         lambda: led2.resource.toggle(),
                                         loop=event_loop))

        tasks = []

        asyncio.set_event_loop(event_loop)
        asyncio.Task(
            Context.create_server_context(root, bind=(SERVER_IP, 5683)))
        tasks.append(
            asyncio.ensure_future(
                observe_button('127.0.0.3', 'shutter', shutter_func)))
        event_loop.run_forever()

        for t in tasks:
            t.cancel()
Exemple #5
0
 def __init__(self, upload_path, port=COAP_PORT):
     self.root_coap = resource.Site()
     self.port = port
     self.upload_path = upload_path
     self._bootstrap_resources()
     asyncio.Task(Context.create_server_context(self.root_coap,
                           bind=('::', self.port)))
Exemple #6
0
 def __init__(self, fw_path, port=COAP_PORT):
     self.port = port
     self.fw_path = fw_path
     self.root_coap = resource.Site()
     for filename in os.listdir(fw_path):
         self.add_resources(filename)
     asyncio.async(Context.create_server_context(self.root_coap,
                                                 bind=('::', self.port)))
Exemple #7
0
 def __init__(self, fw_path, port=COAP_PORT):
     self.port = port
     self.fw_path = fw_path
     root_coap = resource.Site()
     root_coap.add_resource(('version', ), FirmwareVersionResource(self))
     root_coap.add_resource(('firmware', ), FirmwareBinaryResource(self))
     asyncio. async (Context.create_server_context(root_coap,
                                                   bind=('::', self.port)))
Exemple #8
0
def coap_server_init(max_time):
    """Initialize the CoAP server."""
    global _max_time
    _max_time = max_time

    root_coap = resource.Site()
    root_coap.add_resource(('server', ), CoapServerResource())
    root_coap.add_resource(('alive', ), CoapAliveResource())
    asyncio. async (Context.create_server_context(root_coap))
Exemple #9
0
    def run(self):
        self._setup_resources()

        self._loop = asyncio.get_event_loop()
        self._loop.add_signal_handler(SIGTERM, self.stop)
        self._loop.add_signal_handler(SIGINT, self.stop)

        asyncio.Task(
            Context.create_server_context(self._root, bind=('::', self._port)))
        self._loop.run_forever()
Exemple #10
0
def main():
    if len(sys.argv) < 2:
        print("Pass in key as second argument")
        return

    PSK_STORE[b'Client_identity'] = sys.argv[1].encode('utf-8')

    msg = Message(code=GET, uri="coaps://192.168.1.19:5684/15001")
    protocol = yield from Context.create_client_context()
    res = yield from protocol.request(msg).response
    print("RECEIVED STATUS", res.code)
    print("RECEIVED PAYLOAD", res.payload.decode('utf-8'))
Exemple #11
0
def physical():
    """Run coap resources on real raspberry pi"""
    root = resource.Site()
    root.add_resource(['.well-known', 'core'],
                      resource.WKCResource(root.get_resources_as_linkheader))
    root.add_resource(['led'], LEDResource(17))
    root.add_resource(['buzzer'], BuzzerResource(22, active_high=False))
    root.add_resource(['button'],
                      ButtonResource(27, lambda: print("Button pressed")))

    asyncio.set_event_loop(event_loop)
    asyncio.Task(Context.create_server_context(root, bind=(SERVER_IP, 5683)))
    event_loop.run_forever()
Exemple #12
0
def coap_message(message=None):
    protocol = yield from Context.create_client_context()

    if message is None:
        request = Message(code=POST, payload="Hello Twitter".encode('utf-8'))
        request.set_request_uri('coap://localhost/alive')
    else:
        request = Message(code=POST,
                          payload="twitter:{}".format(message).encode('utf-8'))
        request.set_request_uri('coap://localhost/server')

    try:
        yield from protocol.request(request).response
    except Exception as e:
        print('Failed to fetch resource:')
        print(e)
Exemple #13
0
 def __init__(self, port=COAP_PORT):
     self.port = port
     self.root_coap = resource.Site()
     self.root_coap.add_resource((
         'suit',
         'trigger',
     ), TriggerResource())
     self.root_coap.add_resource((
         'suit',
         'slot',
         'inactive',
     ), InactiveResource())
     asyncio.ensure_future(
         Context.create_server_context(self.root_coap,
                                       bind=('::', self.port)))
     LOGGER.debug("CoAP server started, listening on port %s", COAP_PORT)
Exemple #14
0
def start_server():
    protocol = yield from Context.create_client_context()

    request = Message(code = Code.GET, mtype=aiocoap.CON)
    request.set_request_uri('coap://127.0.0.1/button')
    # set observe bit from None to 0
    request.opt.observe = 0

    def handle_notification(response):
        print("asdsadsa")
        print(response)
        import code; code.interact(local=dict(globals(), **locals()))

    protocol_request = protocol.request(request)
    protocol_request.observation.register_callback(handle_notification)
    protocol_request.observation.register_errback(handle_notification)
    response = yield from protocol_request.response
Exemple #15
0
def _coap_resource(url, method=GET, payload=b''):
    protocol = yield from Context.create_client_context()
    request = Message(code=method, payload=payload)
    request.set_request_uri(url)
    try:
        response = yield from protocol.request(request).response
    except Exception as e:
        code = "Failed to fetch resource"
        payload = '{0}'.format(e)
    else:
        code = response.code
        payload = response.payload.decode('utf-8')
    finally:
        yield from protocol.shutdown()

    logger.debug('Code: {0} - Payload: {1}'.format(code, payload))

    return code, payload
Exemple #16
0
    def __init__(self, keys, options):
        self.port = options.coap_port
        self.max_time = options.max_time
        self.node_mapping = {}  # map node address to its uuid (TODO: FIXME)

        super().__init__(keys, options)

        # Configure the CoAP server
        root_coap = resource.Site()
        root_coap.add_resource(('server', ), CoapServerResource(self))
        root_coap.add_resource(('alive', ), CoapAliveResource(self))
        asyncio.ensure_future(
            Context.create_server_context(root_coap, bind=('::', self.port)))

        # Start the periodic node cleanup task
        PeriodicCallback(self.check_dead_nodes, 1000).start()

        logger.info('CoAP gateway application started')
Exemple #17
0
def alive_message(args):
    path = args.path
    payload = args.payload,
    server = args.server

    protocol = yield from Context.create_client_context()

    if path == "alive":
        request = Message(code=POST, payload="Alive".encode('utf-8'))
        request.set_request_uri('coap://{}/{}'.format(server, path))
    else:
        request = Message(code=POST, payload=payload.encode('utf-8'))
        request.set_request_uri('coap://{}/server'.format(server))

    try:
        yield from protocol.request(request).response
    except Exception as e:
        print('Failed to fetch resource:')
        print(e)
Exemple #18
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--fake', dest='real', action='store_false')
    parser.add_argument('--real', dest='real', action='store_true')

    parser.add_argument('--server-address', default='::', metavar='HOST')
    parser.add_argument('--server-port',
                        type=int,
                        default=COAP_PORT,
                        metavar='PORT')

    parser.add_argument('--temperature-resource',
                        default='temperature',
                        metavar='RESOURCE')
    parser.add_argument('--actuator-resource',
                        default='actuator',
                        metavar='RESOURCE')

    parser.add_argument('--update-interval',
                        default=60,
                        type=int,
                        metavar='SECS')

    parser.set_defaults(real=True)

    args = parser.parse_args()

    if args.real:
        hw = Hardware()
    else:
        hw = Fake()

    root = resource.Site()

    root.add_resource((args.temperature_resource, ), TemperatureResource(hw))
    root.add_resource((args.actuator_resource, ), ActuatorResource(hw))

    asyncio.Task(
        Context.create_server_context(root,
                                      bind=(args.server_address,
                                            args.server_port)))
    asyncio.get_event_loop().run_forever()
Exemple #19
0
    def main_func():
        led1 = LEDResource(21)
        led2 = LEDResource(22)

        root = resource.Site()
        root.add_resource(['.well-known', 'core'],
                          resource.WKCResource(
                              root.get_resources_as_linkheader))
        root.add_resource(['led1'], led1)
        root.add_resource(['led2'], led2)
        root.add_resource(['button1'],
                          ButtonResource(11,
                                         lambda: led1.resource.toggle(),
                                         loop=event_loop))
        root.add_resource(['shutter'],
                          ButtonResource(12,
                                         lambda: led1.resource.off(),
                                         loop=event_loop))

        asyncio.set_event_loop(event_loop)
        asyncio.Task(
            Context.create_server_context(root, bind=(SERVER_IP, 5683)))
        event_loop.run_forever()
 async def _get_protocol(self):
     if self._protocol is None:
         self._protocol = asyncio.Task(
             Context.create_client_context(loop=self._loop))
     return (await self._protocol)
Exemple #21
0

if __name__ == "__main__":
    from ecdsa import VerifyingKey, SigningKey

    rs_identity = SigningKey.from_der(
        bytes.fromhex(
            "307702010104200ffc411715d3cc4917bd27ac4f310552b085b1ca0bb0a8"
            "bbb9d8931d651544c1a00a06082a8648ce3d030107a144034200046cc415"
            "12d92fb03cb3b35bed5b494643a8a8a55503e87a90282c78d6c58a7e3c88"
            "a21c0287e7e8d76b0052b1f1a2dcebfea57714c1210d42f17b335adcb76d"
            "7a"))

    as_public_key = VerifyingKey.from_der(
        bytes.fromhex(
            "3059301306072a8648ce3d020106082a8648ce3d030107034200047069be"
            "d49cab8ffa5b1c820271aef0bc0c8f5cd149e05c5b9e37686da06d02bd5f"
            "7bc35ea8265be7c5e276ad7e7d0eb05e4a0551102a66bba88b02b5eb4c33"
            "55"))

    loop = asyncio.get_event_loop()
    root = resource.Site()
    server = TemperatureServer(audience="tempSensor0",
                               identity=rs_identity,
                               as_url='http://localhost:8080',
                               as_public_key=as_public_key,
                               site=root)
    asyncio.ensure_future(Context.create_server_context(server.site),
                          loop=loop)
    loop.run_forever()
Exemple #22
0
def api_factory(host, security_code, loop=None):
    """Generate a request method."""
    if loop is None:
        loop = asyncio.get_event_loop()

    PatchedDTLSSecurityStore.SECRET_PSK = security_code.encode('utf-8')

    _observations_err_callbacks = []
    _protocol = yield from Context.create_client_context(loop=loop)

    @asyncio.coroutine
    def _get_protocol():
        """Get the protocol for the request."""
        nonlocal _protocol
        if not _protocol:
            _protocol = yield from Context.create_client_context(loop=loop)
        return _protocol

    @asyncio.coroutine
    def _reset_protocol(exc):
        """Reset the protocol if an error occurs.
           This can be removed when chrysn/aiocoap#79 is closed."""
        # Be responsible and clean up.
        protocol = yield from _get_protocol()
        yield from protocol.shutdown()
        nonlocal _protocol
        _protocol = None
        # Let any observers know the protocol has been shutdown.
        nonlocal _observations_err_callbacks
        for ob_error in _observations_err_callbacks:
            ob_error(exc)
        _observations_err_callbacks.clear()

    @asyncio.coroutine
    def _get_response(msg):
        """Perform the request, get the response."""
        try:
            protocol = yield from _get_protocol()
            pr = protocol.request(msg)
            r = yield from pr.response
            return (pr, r)
        except ConstructionRenderableError as e:
            raise ClientError("There was an error with the request.", e)
        except RequestTimedOut as e:
            yield from _reset_protocol(e)
            raise RequestTimeout('Request timed out.', e)
        except Error as e:
            yield from _reset_protocol(e)
            raise ServerError("There was an error with the request.", e)

    @asyncio.coroutine
    def _execute(api_command):
        """Execute the command."""
        if api_command.observe:
            yield from _observe(api_command)
            return

        method = api_command.method
        path = api_command.path
        data = api_command.data
        parse_json = api_command.parse_json
        url = api_command.url(host)

        kwargs = {}

        if data is not None:
            kwargs['payload'] = json.dumps(data).encode('utf-8')
            _LOGGER.debug('Executing %s %s %s: %s', host, method, path, data)
        else:
            _LOGGER.debug('Executing %s %s %s', host, method, path)

        api_method = Code.GET
        if method == 'put':
            api_method = Code.PUT

        msg = Message(code=api_method, uri=url, **kwargs)

        _, res = yield from _get_response(msg)

        api_command.result = _process_output(res, parse_json)

        return api_command.result

    @asyncio.coroutine
    def request(*api_commands):
        """Make a request."""
        if len(api_commands) == 1:
            result = yield from _execute(api_commands[0])
            return result

        commands = (_execute(api_command) for api_command in api_commands)
        command_results = yield from asyncio.gather(*commands, loop=loop)

        return command_results

    @asyncio.coroutine
    def _observe(api_command):
        """Observe an endpoint."""
        duration = api_command.observe_duration
        url = api_command.url(host)
        err_callback = api_command.err_callback

        msg = Message(code=Code.GET, uri=url, observe=duration)

        # Note that this is necessary to start observing
        pr, r = yield from _get_response(msg)

        api_command.result = _process_output(r)

        def success_callback(res):
            api_command.result = _process_output(res)

        def error_callback(ex):
            err_callback(ex)

        ob = pr.observation
        ob.register_callback(success_callback)
        ob.register_errback(error_callback)
        nonlocal _observations_err_callbacks
        _observations_err_callbacks.append(ob.error)

    # This will cause a RequestError to be raised if credentials invalid
    yield from request(Command('get', ['status']))

    return request
Exemple #23
0
 def _get_protocol():
     """Get the protocol for the request."""
     protocol = yield from Context.create_client_context(loop=loop)
     return protocol
Exemple #24
0
 async def _get_protocol(self):
     """Get the protocol for the request."""
     if self._protocol is None:
         self._protocol = asyncio.Task(
             Context.create_client_context(loop=self._loop))
     return (await self._protocol)
Exemple #25
0
 def _get_protocol():
     """Get the protocol for the request."""
     nonlocal _protocol
     if not _protocol:
         _protocol = yield from Context.create_client_context(loop=loop)
     return _protocol
Exemple #26
0
 def main():
     asyncio.set_event_loop(event_loop)
     asyncio.Task(
         Context.create_server_context(root, bind=(SERVER_IP, 5683)))
     event_loop.run_forever()
 async def _get_protocol(self) -> Context:
     """Get the protocol for the request."""
     if self._protocol is None:
         self._protocol = asyncio.create_task(
             Context.create_client_context())
     return await self._protocol
Exemple #28
0
 async def test_empty_contextmgr(self):
     async with Context.create_client_context():
         pass