Exemplo n.º 1
0
 async def render_put(self, request):
     print('\nReceived notification from a camera: %s' % request.payload)
     print('\n')
     self.set_content(request.payload)
     return aiocoap.Message(code=aiocoap.CHANGED,
                            payload=b'Notification received.')
Exemplo n.º 2
0
 async def render_get(self, request):
     payload = datetime.datetime.now().\
             strftime("%Y-%m-%d %H:%M").encode('ascii')
     return aiocoap.Message(payload=payload)
 async def render_get(self, request):
     await asyncio.sleep(0.2)
     # 1.6kb
     payload = b"0123456789----------" * 80
     return aiocoap.Message(payload=payload)
Exemplo n.º 4
0
 async def render_put(self, request):
     self.value = request.payload.replace(b'0', b'O')
     return aiocoap.Message(code=aiocoap.CHANGED)
Exemplo n.º 5
0
 async def render_get(self, request):
     return aiocoap.Message(code=aiocoap.CONTENT,
                            payload=b"Welcome to the test server")
Exemplo n.º 6
0
 async def render_get(self, request):
     while self._cancel_right_away:
         self._cancel_right_away.pop(0)()
     return aiocoap.Message()
Exemplo n.º 7
0
 async def render_get(self, request):
     await asyncio.sleep(0.2)
     return aiocoap.Message()
Exemplo n.º 8
0
 async def render_get(self, request):
     temp = tuple(mc.player.getPos())
     self.content = (temp[0], temp[1], temp[2], self.token_id, self.x)
     g = pickle.dumps(self.content)
     return aiocoap.Message(payload=g)
Exemplo n.º 9
0
 async def render_get(self, request):
     print("Attributes List Request")
     attr_str = '#'.join(self.attr)
     return aiocoap.Message(payload = attr_str.encode('utf-8'))
Exemplo n.º 10
0
async def single_request(args, context=None):
    parser = build_parser()
    options = parser.parse_args(args)

    pretty_print_modules = aiocoap.defaults.prettyprint_missing_modules()
    if pretty_print_modules and \
            (options.color is True or options.pretty_print is True):
        parser.error("Color and pretty printing require the following"
                     " additional module(s) to be installed: %s" %
                     ", ".join(pretty_print_modules))
    if options.color is None:
        options.color = sys.stdout.isatty() and not pretty_print_modules
    if options.pretty_print is None:
        options.pretty_print = sys.stdout.isatty() and not pretty_print_modules

    configure_logging((options.verbose or 0) - (options.quiet or 0))

    try:
        code = getattr(aiocoap.numbers.codes.Code, options.method.upper())
    except AttributeError:
        try:
            code = aiocoap.numbers.codes.Code(int(options.method))
        except ValueError:
            raise parser.error("Unknown method")

    if context is None:
        context = await aiocoap.Context.create_client_context()

    if options.credentials is not None:
        apply_credentials(context, options.credentials, parser.error)

    request = aiocoap.Message(
        code=code, mtype=aiocoap.NON if options.non else aiocoap.CON)
    try:
        request.set_request_uri(options.url, set_uri_host=options.set_hostname)
    except ValueError as e:
        raise parser.error(e)

    if not request.opt.uri_host and not request.unresolved_remote:
        raise parser.error("Request URLs need to be absolute.")

    if options.accept:
        try:
            request.opt.accept = int(options.accept)
        except ValueError:
            try:
                request.opt.accept = aiocoap.numbers.media_types_rev[
                    options.accept]
            except KeyError:
                raise parser.error("Unknown accept type")

    if options.observe:
        request.opt.observe = 0
        observation_is_over = asyncio.Future()

    if options.content_format:
        try:
            request.opt.content_format = int(options.content_format)
        except ValueError:
            try:
                request.opt.content_format = aiocoap.numbers.media_types_rev[
                    options.content_format]
            except KeyError:
                raise parser.error("Unknown content format")

    if options.payload:
        if options.payload.startswith('@'):
            filename = options.payload[1:]
            if filename == "-":
                f = sys.stdin.buffer
            else:
                f = open(filename, 'rb')
            try:
                request.payload = f.read()
            except OSError as e:
                raise parser.error("File could not be opened: %s" % e)
        else:
            if contenttype.categorize(
                    aiocoap.numbers.media_types.get(request.opt.content_format,
                                                    "")) == 'cbor':
                try:
                    import cbor2 as cbor
                except ImportError as e:
                    raise parser.error("CBOR recoding not available (%s)" % e)
                import json
                try:
                    decoded = json.loads(options.payload)
                except json.JSONDecodeError as e:
                    import ast
                    try:
                        decoded = ast.literal_eval(options.payload)
                    except ValueError:
                        raise parser.error(
                            "JSON and Python recoding failed. Make sure quotation marks are escaped from the shell. JSON error: %s"
                            % e)
                request.payload = cbor.dumps(decoded)
            else:
                request.payload = options.payload.encode('utf8')

    if options.payload_initial_szx is not None:
        request.opt.block1 = aiocoap.optiontypes.BlockOption.BlockwiseTuple(
            0,
            False,
            options.payload_initial_szx,
        )

    if options.proxy is None:
        interface = context
    else:
        interface = aiocoap.proxy.client.ProxyForwarder(options.proxy, context)

    try:
        requested_uri = request.get_request_uri()

        requester = interface.request(request)

        if options.observe:
            requester.observation.register_errback(
                observation_is_over.set_result)
            requester.observation.register_callback(
                lambda data, options=options: incoming_observation(
                    options, data))

        try:
            response_data = await requester.response
        except aiocoap.error.ResolutionError as e:
            print("Name resolution error:", e, file=sys.stderr)
            sys.exit(1)
        except aiocoap.error.NetworkError as e:
            print("Network error:", e, file=sys.stderr)
            sys.exit(1)
        # Fallback while not all backends raise NetworkErrors
        except OSError as e:
            text = str(e)
            if not text:
                text = repr(e)
            if not text:
                # eg ConnectionResetError flying out of a misconfigured SSL server
                text = type(e)
            print("Error:", text, file=sys.stderr)
            sys.exit(1)

        response_uri = response_data.get_request_uri()
        if requested_uri != response_uri:
            print("Response arrived from different address; base URI is",
                  response_uri,
                  file=sys.stderr)
        if response_data.code.is_successful():
            present(response_data, options)
        else:
            print(colored(response_data.code, options, 'red'), file=sys.stderr)
            present(response_data, options, file=sys.stderr)
            sys.exit(1)

        if options.observe:
            exit_reason = await observation_is_over
            print("Observation is over: %r" % (exit_reason, ), file=sys.stderr)
    finally:
        if not requester.response.done():
            requester.response.cancel()
        if options.observe and not requester.observation.cancelled:
            requester.observation.cancel()
Exemplo n.º 11
0
 async def render_get(self, request):
     logger = logging.getLogger("coap-server")
     logger.info('GET request: %s' % request.payload)
     return aiocoap.Message(payload = "JO".encode('ascii'))
Exemplo n.º 12
0
 async def render_put(self, request):
     print('PUT payload: %s' % request.payload)
     self.content = request.payload
     payload = ("I've accepted the new payload. You may inspect it here in "\
             "Python's repr format:\n\n%r"%self.content).encode('utf8')
     return aiocoap.Message(payload=payload)
Exemplo n.º 13
0
 async def render_get(self, request):
     content = b""
     with self.path.open('rb') as f:
         content = f.read()
     return aiocoap.Message(payload=content)
Exemplo n.º 14
0
 async def render_put(self, request):
     print('\nTest content has be re-set: %s' % request.payload)
     print('\n')
     self.set_content(request.payload)
     return aiocoap.Message(code=aiocoap.CHANGED,
                            payload=b'Confirmed changed test content.')
Exemplo n.º 15
0
 async def render_get(self, request):
     return aiocoap.Message(code=aiocoap.CONTENT,
                            payload=str(self.count).encode('ascii'))
Exemplo n.º 16
0
 async def render_get(self, request):
     return aiocoap.Message(payload=self.to_json().encode("utf-8"),
                            token=request.token)
Exemplo n.º 17
0
 async def render_fetch(self, request):
     return aiocoap.Message(
         code=aiocoap.CONTENT,
         payload=("%s; request had length %s" %
                  (self.count, len(request.payload))).encode('ascii'))
Exemplo n.º 18
0
    async def render_put(self, request):
        self.metrics.append(json.loads(request.payload))
        self.seen()

        return aiocoap.Message(code=aiocoap.CHANGED, token=request.token)
Exemplo n.º 19
0
 async def render_get(self, request):
     return aiocoap.Message(code=aiocoap.UNAUTHORIZED)
Exemplo n.º 20
0
 async def _change_counter(self, method=aiocoap.POST):
     request = aiocoap.Message(code=method, uri_path=('deep', 'count'))
     request.unresolved_remote = self.servernetloc
     await self.client.request(request).response_raising
Exemplo n.º 21
0
 async def render_get(self, request):
     return aiocoap.Message(code=aiocoap.CONTENT, payload=self.value)
Exemplo n.º 22
0
 def test_counter_fetch(self):
     self._test_counter(
         aiocoap.Message(code=aiocoap.FETCH, payload=b'12345'), lambda x:
         ('%s; request had length 5' % x).encode('ascii'))
Exemplo n.º 23
0
 async def render_post(self, request):
     response = request.payload.replace(b'0', b'O')
     return aiocoap.Message(code=aiocoap.CONTENT, payload=response)
Exemplo n.º 24
0
 def put(b):
     m = aiocoap.Message(code=aiocoap.PUT, payload=b)
     m.unresolved_remote = self.servernetloc
     m.opt.uri_path = ['deep', 'echo']
     response = yieldfrom(self.client.request(m).response)
     self.assertEqual(response.code, aiocoap.CHANGED)
Exemplo n.º 25
0
 async def render_put(self, request):
     print('PUT payload: %s' % request.payload)
     self.set_content(request.payload)
     return aiocoap.Message(code=aiocoap.CHANGED, payload=self.content)
Exemplo n.º 26
0
 async def render_delete(self, request):
     self.count = 0
     self.updated_state()
     return aiocoap.Message(code=aiocoap.CHANGED)
 def build_request(self):
     request = aiocoap.Message(code=aiocoap.GET)
     request.unresolved_remote = self.servernetloc
     return request
Exemplo n.º 28
0
 async def render_post(self, request):
     self.count += 1
     self.updated_state()
     return aiocoap.Message(code=aiocoap.CHANGED)
 async def render_get(self, request):
     return aiocoap.Message(payload=self.value)
Exemplo n.º 30
0
 def render_get(self, request):
     yield from asyncio.sleep(0.2)
     # 1.6kb
     payload = b"0123456789----------" * 80
     return aiocoap.Message(code=aiocoap.CONTENT, payload=payload)