diff --git a/stechuhr_client/client.py b/stechuhr_client/client.py index 2dc6993af04d4a7fc6c0aaa0c1799f7735605f52..094a768b59276844766d40370e6153fe6d1f9290 100644 --- a/stechuhr_client/client.py +++ b/stechuhr_client/client.py @@ -41,6 +41,15 @@ EVENT_FORMAT = "llHHI" EVENT_SIZE = struct.calcsize(EVENT_FORMAT) +def string_to_list(s:str, delimiter: str="\n") -> List[str]: + """ + Split a string to a list derived from a delimiter. If the string contains + no delimiter, still return a list containing the string + """ + if delimiter in s: + return s.split(delimiter) + else: + return [s] def repeat(l, index): @@ -320,16 +329,36 @@ def read_key_input(input_queue, config, logger): time.sleep(0.01) -def update_id_patterns(config) -> 'Config': +def update_id_patterns(config, logger) -> 'Config': + """ + Update the id_patterns from the server via http + """ if config["server"]["port"] == 80: protocol = "http" else: protocol = "https" url = '{}://{}/config/database/id_patterns'.format(protocol, config["server"]["address"].rstrip("/")) - r = requests.get(url) - print(r.text) - # config["client"]["id_patterns"] + logger.debug("Requesting id_pattern update at address: {}".format(url)) + + # Send request + r = requests.get(url, timeout=config["server"]["timeout"]) + + # If the response was ok update the pattern if it changed, else display a warning + if r.ok: + patterns = string_to_list(r.text) + if set(patterns) == set(config["client"]["id_patterns"]): + logger.debug("No change in serverside id_pattern, so didn't update") + else: + # Only compile the patterns once we know something changed + patterns = [re.compile(p) for p in patterns] + config["client"]["id_patterns"] = patterns + logger.info("Received a newly updated patterns list from the server") + else: + logger.warn("Server at \"{}\" responded with {}".format(url, r.status)) + + return config + def main(): logger = logging.getLogger(APPLICATION_NAME) @@ -374,9 +403,10 @@ def main(): else: time.sleep(0.01) + # Update the patterns at the pace defined by config["server"]["update_frequency"] if last_pattern_update is None or time.time() - last_pattern_update > config["server"]["update_frequency"]: last_pattern_update = time.time() - update_id_patterns(config) + config = update_id_patterns(config, logger) time.sleep(0.01) diff --git a/stechuhr_client/config.py b/stechuhr_client/config.py index 951b0a4c574baa1b760b3626b7837087f3effada..72507acb74d813f8cca9ac646139cf84d0d8c73d 100644 --- a/stechuhr_client/config.py +++ b/stechuhr_client/config.py @@ -26,7 +26,9 @@ address = "127.0.0.1" port = 80 timeout = 5 verify_cert = true -update_frequency = 10 + +# Frequency of requesting pattern updates from the server in seconds +update_frequency = 600 [client] location = "lerchenfeld/mensa"