From ca8e960318b5a2c26c9171e5863950fb669a17c4 Mon Sep 17 00:00:00 2001 From: Artem30801 Date: Sun, 25 Oct 2020 21:48:29 +0300 Subject: [PATCH] changed current usage of callbacks to match new API --- drone/modules/client_core.py | 76 ++++++++++++++++++----------------- lib/messaging.py | 12 +++--- server/modules/server_core.py | 11 ++--- server/server.py | 2 +- 4 files changed, 52 insertions(+), 49 deletions(-) diff --git a/drone/modules/client_core.py b/drone/modules/client_core.py index b13ffee..fa7f5ef 100644 --- a/drone/modules/client_core.py +++ b/drone/modules/client_core.py @@ -51,7 +51,8 @@ class Client(object): self.selector = selectors.DefaultSelector() self.client_socket = None - self.server_connection = messaging.ConnectionManager() + self.callbacks = messaging.CallbackManager() + self.server_connection = messaging.ConnectionManager(self.callbacks) self.connected = False self.client_id = None @@ -60,6 +61,7 @@ class Client(object): self.config = ConfigManager() self.config_path = config_path + global active_client active_client = self @@ -120,6 +122,7 @@ class Client(object): Reloads config and starts infinite loop of connecting to the server and processing said connection. Calling of this method will indefinitely halt execution of any subsequent code. """ self.load_config() + self.register_callbacks() logger.info("Starting client") messaging.NotifierSock().init(self.selector) @@ -245,48 +248,47 @@ class Client(object): logger.warning("No active connections left!") return + def register_callbacks(self): + @self.callbacks.action_callback("config") + def _command_config_write(*args, **kwargs): + mode = kwargs.get("mode", "modify") + # exceptions would be risen in case of incorrect config + if mode == "rewrite": + active_client.config.load_from_dict(kwargs["config"], configspec=active_client.config_path) # with validation + elif mode == "modify": + new_config = ConfigManager() + new_config.load_from_dict(kwargs["config"]) + active_client.config.merge(new_config, validate=True) -@messaging.message_callback("config") -def _command_config_write(*args, **kwargs): - mode = kwargs.get("mode", "modify") - # exceptions would be risen in case of incorrect config - if mode == "rewrite": - active_client.config.load_from_dict(kwargs["config"], configspec=active_client.config_path) # with validation - elif mode == "modify": - new_config = ConfigManager() - new_config.load_from_dict(kwargs["config"]) - active_client.config.merge(new_config, validate=True) + active_client.config.write() + logger.info("Config successfully updated from command") + active_client.load_config() - active_client.config.write() - logger.info("Config successfully updated from command") - active_client.load_config() + @self.callbacks.request_callback("config") + def _response_config(*args, **kwargs): + send_configspec = kwargs.get("send_configspec", False) + response = {"config": active_client.config.full_dict()} + if send_configspec: + response.update({"configspec": dict(active_client.config.config.configspec)}) + return response -@messaging.request_callback("config") -def _response_config(*args, **kwargs): - send_configspec = kwargs.get("send_configspec", False) - response = {"config": active_client.config.full_dict()} - if send_configspec: - response.update({"configspec": dict(active_client.config.config.configspec)}) - return response + @self.callbacks.request_callback("clover_dir") + def _response_clover_dir(*args, **kwargs): + return active_client.config.clover_dir -@messaging.request_callback("clover_dir") -def _response_clover_dir(*args, **kwargs): - return active_client.config.clover_dir + @self.callbacks.request_callback("id") + def _response_id(*args, **kwargs): + new_id = kwargs.get("new_id", None) + if new_id is not None: + active_client.config.set("PRIVATE", "id", new_id, True) + active_client.load_config() + # TODO renaming here -@messaging.request_callback("id") -def _response_id(*args, **kwargs): - new_id = kwargs.get("new_id", None) - if new_id is not None: - active_client.config.set("PRIVATE", "id", new_id, True) - active_client.load_config() - # TODO renaming here + return active_client.client_id - return active_client.client_id - - -@messaging.request_callback("time") -def _response_time(*args, **kwargs): - return active_client.time_now() + @self.callbacks.request_callback("time") + def _response_time(*args, **kwargs): + return active_client.time_now() if __name__ == "__main__": diff --git a/lib/messaging.py b/lib/messaging.py index 4f2d78b..e594c55 100644 --- a/lib/messaging.py +++ b/lib/messaging.py @@ -344,10 +344,8 @@ class ConnectionManager(object): resume_queue (bool): Whether to resume sending queue upon peer reconnection. resend_requests (bool): Whether to resend unanswered requests in queue to reconnected client. """ - messages_callbacks = {} - requests_callbacks = {} - def __init__(self, whoami="computer"): + def __init__(self, callbacks, whoami="computer"): """ Args: whoami (str, optional): What type of system the ConnectionManager is running on (`computer` or `pi`). Defaults to "computer". @@ -359,6 +357,8 @@ class ConnectionManager(object): connection.connect(client_selector, client_socket, client_addr) ``` """ + self.callbacks = callbacks + self.selector = None self.socket = None self.addr = None @@ -462,7 +462,7 @@ class ConnectionManager(object): logger.info("CLOSED connection to {}".format(self.addr)) def process_events(self, mask): - """Processes read\write events with given mask. + """Processes read/write events with given mask. Args: mask (bytes): mask of the selector events. @@ -538,7 +538,7 @@ class ConnectionManager(object): action = message.jsonheader["action"] args = message.content["args"] kwargs = message.content["kwargs"] - callback = self.messages_callbacks.get(action, None) + callback = self.callbacks.action_callbacks.get(action, None) if callback is None: logger.warning("Action {} does not exist!".format(action)) return @@ -559,7 +559,7 @@ class ConnectionManager(object): if filetransfer: value = self._read_file(kwargs["filepath"]) else: - callback = self.requests_callbacks.get(requested_value, None) + callback = self.callbacks.request_callbacks.get(requested_value, None) if callback is None: logger.warning("Request {} does not exist!".format(requested_value)) return diff --git a/server/modules/server_core.py b/server/modules/server_core.py index 021a8b2..7dcb75a 100644 --- a/server/modules/server_core.py +++ b/server/modules/server_core.py @@ -52,6 +52,8 @@ class Server(messaging.Singleton): self.config = ConfigManager() self.config_path = config_path + self.callbacks = messaging.CallbackManager() + # Init threads self.autoconnect_thread = threading.Thread(target=self._client_processor, daemon=True, name='Client processor') @@ -170,8 +172,8 @@ class Server(messaging.Singleton): logging.info("Got connection from: {}".format(str(addr))) conn.setblocking(False) - if not any([client_addr == addr[0] for client_addr in Client.clients.keys()]): - client = Client(addr[0]) + if not any(client_addr == addr[0] for client_addr in Client.clients.keys()): + client = Client(self.callbacks, addr[0]) client.buffer_size = self.config.server_buffer_size logging.info("New client") else: @@ -271,7 +273,6 @@ def requires_any_connected(f): return wrapper -# TODO do a factory class for clients\connection managers with common properties class Client(messaging.ConnectionManager): clients = {} @@ -279,8 +280,8 @@ class Client(messaging.ConnectionManager): on_first_connect = None on_disconnect = None - def __init__(self, ip): - super().__init__() + def __init__(self, callbacks, ip): + super().__init__(callbacks) self.copter_id = None self.clover_dir = None self.connected = False diff --git a/server/server.py b/server/server.py index 03ebd21..b75b856 100644 --- a/server/server.py +++ b/server/server.py @@ -631,7 +631,7 @@ class MainWindow(QtWidgets.QMainWindow): ConfigDialog().call_config_dialog(config, save_callback, restart, name="server config") def register_callbacks(self): - @messaging.message_callback("telemetry") + @self.server.callbacks.action_callback("telemetry") def get_telem_data(client, value, **kwargs): self.update_table_data(client, value)