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
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'))
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)
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
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
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)
def _get_protocol(): """Get the protocol for the request.""" protocol = yield from Context.create_client_context(loop=loop) return protocol
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)
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
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
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
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)
async def test_empty_contextmgr(self): async with Context.create_client_context(): pass