From b457999d3d883d668139b753528ce8467f547aba Mon Sep 17 00:00:00 2001 From: Remy Moll Date: Mon, 12 Jul 2021 18:42:14 +0200 Subject: [PATCH] fixing recursion issues --- .vscode/launch.json | 15 ------ run_client.sh => autostart/run_client.sh | 0 run_server.sh => autostart/run_server.sh | 0 bot/api/weather.py | 5 ++ bot/commands/alias.py | 1 - bot/commands/lists.py | 1 - bot/commands/status.py | 2 +- clock/c_back.py | 21 +------- clock/c_out.py | 62 +++++++++++------------- clock/hardware/sim.py | 1 - launcher.py | 10 ++-- persistence/models.py | 4 +- persistence/p_io.py | 2 +- 13 files changed, 44 insertions(+), 80 deletions(-) delete mode 100644 .vscode/launch.json rename run_client.sh => autostart/run_client.sh (100%) rename run_server.sh => autostart/run_server.sh (100%) diff --git a/.vscode/launch.json b/.vscode/launch.json deleted file mode 100644 index f636bac..0000000 --- a/.vscode/launch.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - // Use IntelliSense to learn about possible attributes. - // Hover to view descriptions of existing attributes. - // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 - "version": "0.2.0", - "configurations": [ - { - "name": "Python: Aktuelle Datei", - "type": "python", - "request": "launch", - "program": "${file}", - "console": "integratedTerminal" - } - ] -} \ No newline at end of file diff --git a/run_client.sh b/autostart/run_client.sh similarity index 100% rename from run_client.sh rename to autostart/run_client.sh diff --git a/run_server.sh b/autostart/run_server.sh similarity index 100% rename from run_server.sh rename to autostart/run_server.sh diff --git a/bot/api/weather.py b/bot/api/weather.py index 7e173b5..66dc921 100644 --- a/bot/api/weather.py +++ b/bot/api/weather.py @@ -1,10 +1,13 @@ import requests import datetime +import logging +logger = logging.getLogger(__name__) class WeatherFetch(): def __init__(self, key): self.last_fetch = datetime.datetime.fromtimestamp(0) self.last_weather = "" + self.calls = 0 self.url = "https://api.openweathermap.org/data/2.5/onecall?" self.key = key @@ -15,6 +18,8 @@ class WeatherFetch(): data = {"lat" : location[0], "lon" : location[1], "exclude" : "minutely,hourly", "appid" : self.key, "units" : "metric"} + self.calls += 1 + logger.info("Just fetched weather. ({}th time)".format(self.calls)) # today = datetime.datetime.today().weekday() # days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] diff --git a/bot/commands/alias.py b/bot/commands/alias.py index ec6fb4b..4528201 100644 --- a/bot/commands/alias.py +++ b/bot/commands/alias.py @@ -26,7 +26,6 @@ class Alias(BotFunc): def entry_point(self, update: Update, context: CallbackContext) -> None: test = self.dispatcher - print(self.dispatcher.handlers[0]) keyboard = [ [InlineKeyboardButton("All aliases", callback_data="all")], [InlineKeyboardButton("Create new alias", callback_data="new")], diff --git a/bot/commands/lists.py b/bot/commands/lists.py index 214b42d..8dbe771 100644 --- a/bot/commands/lists.py +++ b/bot/commands/lists.py @@ -163,7 +163,6 @@ class Lists(BotFunc): item = update.message.text it = self.db.lists.get(self.db.lists.name == self.current_name) sl = it.content - print("SLSLLLL: {} -- {}".format(sl, type(sl))) sl += item + "<-->" self.db.lists.update(content=sl).where(self.db.lists.name == self.current_name).execute() diff --git a/bot/commands/status.py b/bot/commands/status.py index 2f2780e..ffe2da1 100644 --- a/bot/commands/status.py +++ b/bot/commands/status.py @@ -83,7 +83,7 @@ class Status(BotFunc): query = update.callback_query wanted = query.data.replace("status-","") query.answer() - with open("persistence/complete.log") as l: + with open("persistence/server.log") as l: query.message.reply_document(l) super().log_activity(read = False, execute = False, send = True) diff --git a/clock/c_back.py b/clock/c_back.py index 0b7923e..133028a 100644 --- a/clock/c_back.py +++ b/clock/c_back.py @@ -12,15 +12,11 @@ class ClockBackend: self.weather_raw = {} self.weather_face_swap = False - self.brightness = 1 - self.brightness_overwrite = {"value" : 1, "duration" : 0} - def start(self): self.out = self.modules["broadcast"] helpers.timer.RepeatedTimer(15, self.clock_loop) - def clock_loop(self): t = int(datetime.datetime.now().strftime("%H%M")) @@ -40,7 +36,7 @@ class ClockBackend: self.weather["weather"] = "error" self.weather["high"] = "error" self.weather["low"] = "error" - # if weather == self.weather.raw do nothing + self.weather_face_swap = not self.weather_face_swap self.send_face() @@ -54,23 +50,10 @@ class ClockBackend: if self.weather_face_swap: matrices = [matrices[0], matrices[2], matrices[1]] - # apply brightness - b = self.get_brightness() - matrices = [(b * m).tolist() for m in matrices] + matrices = [m.tolist() for m in matrices] self.out.queue.append({"matrices" : matrices}) - def get_brightness(self): - """Checks, what brightness rules to apply""" - - is_WE = datetime.datetime.now().weekday() > 4 - now = int(datetime.datetime.now().strftime("%H%M")) - if (is_WE and (now > 1000 and now < 2200)) or ((not is_WE) and (now > 800 and now < 2130)): - brightness = 0.8 - else: - brightness = 0.01 - - return brightness # def text_scroll(self, text, color=[[200,200,200]]): diff --git a/clock/c_out.py b/clock/c_out.py index fbcfc85..8beab4b 100644 --- a/clock/c_out.py +++ b/clock/c_out.py @@ -21,44 +21,38 @@ class ClockFace: self.kill_output = False def start(self): - # helpers.timer.RepeatedTimer(60, self.clock_loop) - # # schedule for in 60 seconds Thread(target = self.clock_loop).start() -# TODO Turn off when button pressed? - def clock_loop(self): - t_start = datetime.datetime.now() - - t_minutes = int(datetime.datetime.now().strftime("%H%M")) + while True: # TODO: allow this to be exited gracefully - has_queue, data = self.modules["receive"].fetch_data() - self.set_brightness() - - if data == {}: - matrices = self.MOP.get_fallback() - else: - matrices = [np.asarray(d).astype(int) for d in data["matrices"]] - - if not self.kill_output: - self.IO.put(matrices) - else: - z = np.zeros((16,16,3)) - self.IO.put([z,z,z]) - - if has_queue: - tnext = 1 - else: - tnext = 30 + t_start = datetime.datetime.now() + self.set_brightness() - t_end = datetime.datetime.now() - delta_planned = datetime.timedelta(seconds = tnext) - delta = delta_planned - (t_end - t_start) - - time.sleep(max(delta.total_seconds(), 0)) - self.clock_loop() + has_queue, data = self.modules["receive"].fetch_data() + tnext = 1 if has_queue else 30 + + if data == {}: + matrices = self.MOP.get_fallback() + matrices[0][0,0] = [255, 0, 0] # red dot on the top left + else: + matrices = [np.asarray(d).astype(int) for d in data["matrices"]] + matrices[0][0,0] = [0, 255, 0] # green dot on the top left + + if not self.kill_output: + self.IO.put(matrices) + else: + z = np.zeros((16,16,3)) + self.IO.put([z,z,z]) + + + t_end = datetime.datetime.now() + delta_planned = datetime.timedelta(seconds = tnext) + delta = delta_planned - (t_end - t_start) + + time.sleep(max(delta.total_seconds(), 0)) def set_brightness(self): @@ -66,8 +60,6 @@ class ClockFace: is_WE = datetime.datetime.now().weekday() > 4 now = int(datetime.datetime.now().strftime("%H%M")) - if (is_WE and (now > 1000 and now < 2200)) or ((not is_WE) and (now > 830 and now < 2130)): - self.kill_output = False - else: - self.kill_output = True + + self.kill_output = (now < 1000 or now > 2200) if is_WE else (now < 830 or now > 2130) diff --git a/clock/hardware/sim.py b/clock/hardware/sim.py index 7743f0e..a43a21f 100644 --- a/clock/hardware/sim.py +++ b/clock/hardware/sim.py @@ -26,7 +26,6 @@ class ClockOut: self.screen.fill((0, 0, 0)) for event in pygame.event.get(): # User did something if event.type == pygame.QUIT: - print("Exiting...") pygame.quit() sys.exit() diff --git a/launcher.py b/launcher.py index fe3f6b2..b58771f 100644 --- a/launcher.py +++ b/launcher.py @@ -3,6 +3,9 @@ import logging from persistence import p_io, p_out +logger = logging.getLogger(__name__) + + class Launcher: """base launcher that launches other submodules""" @@ -11,8 +14,7 @@ class Launcher: self.persistence = p_io.PersistentDict("persistence/prst.json") self.db = p_out.DBLogging() - self.logger = logging.getLogger(__name__) - self.logger.info(self.__class__.__name__ + " initialized") + logger.info(self.__class__.__name__ + " initialized") self.modules = modules if len(self.persistence) == 0: @@ -26,7 +28,7 @@ class Launcher: def launch_modules(self): for module in self.modules.values(): - self.logger.info("Starting module "+ module.__class__.__name__) + logger.info("Starting module "+ module.__class__.__name__) module.modules = self.modules module.persistence = self.persistence module.db = self.db @@ -34,7 +36,7 @@ class Launcher: def init_persistence(self): - self.logger.warning("No persistence found, created a new one") + logger.warning("No persistence found, created a new one") self.persistence["global"] ={ "lists" : {}, diff --git a/persistence/models.py b/persistence/models.py index b01b50f..64c3dac 100644 --- a/persistence/models.py +++ b/persistence/models.py @@ -25,7 +25,7 @@ class DBModel(Model): # db.close() except Exception as e: logger.error("Could not write to db. Dropping content of {}".format(self.__class__.__name__)) - print(e) + logger.error(e) # db.atomic().rollback() @@ -33,7 +33,7 @@ class Metric(DBModel): time = DateTimeField() - +### Actual metrics: class SensorMetric(Metric): # this is a continuous metric diff --git a/persistence/p_io.py b/persistence/p_io.py index bb6727c..a9dac9f 100644 --- a/persistence/p_io.py +++ b/persistence/p_io.py @@ -83,5 +83,5 @@ def create_struct(struct_type, own_name, parent_name, *args, **kwargs): def append(self, *args): super().append(*args) self.parent.__setitem__(self.name, self) - print(*args) + return HookedStruct(own_name, parent_name, *args, **kwargs)