def on_message(self, msg): """ Callback when a message is received on the backend. It parses and posts the message on the main bus. It should be called by the derived classes whenever a new message should be processed. :param msg: Received message. It can be either a key-value dictionary, a platypush.message.Message object, or a string/byte UTF-8 encoded string """ msg = Message.build(msg) if not getattr(msg, 'target') or msg.target != self.device_id: return # Not for me self.logger.debug('Message received on the {} backend: {}'.format( self.__class__.__name__, msg)) if self._is_expected_response(msg): # Expected response, trigger the response handler clear_timeout() self._request_context['on_response'](msg) self.stop() return if isinstance(msg, StopEvent) and msg.targets_me(): self.logger.info('Received STOP event on {}'.format( self.__class__.__name__)) self._stop = True else: msg.backend = self # Augment message to be able to process responses self.bus.post(msg)
def send_request(action: str, timeout: Optional[float] = None, args: Optional[dict] = None, parse_json: bool = True, authenticate: bool = True, **kwargs): if not timeout: timeout = request_timeout if not args: args = {} auth = (test_user, test_pass) if authenticate else kwargs.pop('auth', ()) set_timeout(seconds=timeout, on_timeout=on_timeout('Receiver response timed out')) response = requests.post('{}/execute'.format(base_url), auth=auth, json={ 'type': 'request', 'action': action, 'args': args, }, **kwargs) clear_timeout() if parse_json: response = parse_response(response) return response
def register_user(username: Optional[str] = None, password: Optional[str] = None): if not username: username = test_user password = test_pass set_timeout(seconds=request_timeout, on_timeout=on_timeout('User registration response timed out')) response = requests.post( '{base_url}/register?redirect={base_url}/'.format(base_url=base_url), data={ 'username': username, 'password': password, 'confirm_password': password, }) clear_timeout() return response
def send_request(self): set_timeout(seconds=self.timeout, on_timeout=self.on_timeout('Receiver response timed out')) response = requests.post( u'http://localhost:8123/execute', json = { 'type': 'request', 'target': Config.get('device_id'), 'action': 'shell.exec', 'args': { 'cmd':'echo ping' } } ) clear_timeout() response = Message.build(response.json()) self.assertTrue(isinstance(response, Response)) self.assertEqual(response.output.strip(), 'ping') self.receiver.stop_app()