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.')
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)
async def render_put(self, request): self.value = request.payload.replace(b'0', b'O') return aiocoap.Message(code=aiocoap.CHANGED)
async def render_get(self, request): return aiocoap.Message(code=aiocoap.CONTENT, payload=b"Welcome to the test server")
async def render_get(self, request): while self._cancel_right_away: self._cancel_right_away.pop(0)() return aiocoap.Message()
async def render_get(self, request): await asyncio.sleep(0.2) return aiocoap.Message()
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)
async def render_get(self, request): print("Attributes List Request") attr_str = '#'.join(self.attr) return aiocoap.Message(payload = attr_str.encode('utf-8'))
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()
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'))
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)
async def render_get(self, request): content = b"" with self.path.open('rb') as f: content = f.read() return aiocoap.Message(payload=content)
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.')
async def render_get(self, request): return aiocoap.Message(code=aiocoap.CONTENT, payload=str(self.count).encode('ascii'))
async def render_get(self, request): return aiocoap.Message(payload=self.to_json().encode("utf-8"), token=request.token)
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'))
async def render_put(self, request): self.metrics.append(json.loads(request.payload)) self.seen() return aiocoap.Message(code=aiocoap.CHANGED, token=request.token)
async def render_get(self, request): return aiocoap.Message(code=aiocoap.UNAUTHORIZED)
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
async def render_get(self, request): return aiocoap.Message(code=aiocoap.CONTENT, payload=self.value)
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'))
async def render_post(self, request): response = request.payload.replace(b'0', b'O') return aiocoap.Message(code=aiocoap.CONTENT, payload=response)
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)
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)
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
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)
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)