From 8df3d9054babdaba27dc4b708a808b6f3edc5000 Mon Sep 17 00:00:00 2001 From: Matthew Wilkes Date: Wed, 26 Jun 2024 18:16:05 +0100 Subject: [PATCH] Improve async compatibility of app store This moves some code from the background task to the main task, and refactors it to allow use of async methods. This looks like these tasks were in background from the idea that the background task runs 'in the background', rather than runs 'when the app is in the background'. There are two calls that use requests.get, which block the update task. By refactoring slightly to use async, we can use async_helpers.unblock to move them to a thread. --- modules/firmware_apps/app_store.py | 40 ++++++++++++++++++++---------- 1 file changed, 27 insertions(+), 13 deletions(-) diff --git a/modules/firmware_apps/app_store.py b/modules/firmware_apps/app_store.py index 70e083f..d391da8 100644 --- a/modules/firmware_apps/app_store.py +++ b/modules/firmware_apps/app_store.py @@ -4,10 +4,12 @@ import json import os import tarfile +import time from tarfile import DIRTYPE, TarFile from typing import Any, Callable import app +import async_helpers import wifi import shutil import machine @@ -77,18 +79,6 @@ def get_index(self): return self.update_state("refreshing_index") - def background_update(self, delta): - if self.state == "refreshing_index": - try: - self.response = get(APP_STORE_LISTING_URL) - except Exception: - self.update_state("no_index") - return - self.update_state("index_received") - if self.to_install_app: - self.install_app(self.to_install_app) - self.to_install_app = None - def handle_index(self): if not self.response: print(self.response) @@ -231,7 +221,17 @@ def error_screen(self, ctx, message): ctx.gray(1).move_to(0, start_y + i * ctx.font_size).text(line) ctx.restore() - def update(self, delta): + async def run(self, render_update): + last_time = time.ticks_ms() + await render_update() + while True: + cur_time = time.ticks_ms() + delta_ticks = time.ticks_diff(cur_time, last_time) + await self.main_loop(delta_ticks, render_update) + await render_update() + last_time = cur_time + + async def main_loop(self, delta, render_update): if self.state == "init": if not wifi.status(): self.update_state("wifi_init") @@ -255,6 +255,20 @@ def update(self, delta): self.prepare_available_menu() elif self.state == "installed_menu" and not self.installed_menu: self.prepare_installed_menu() + elif self.state == "refreshing_index": + try: + self.response = await async_helpers.unblock( + get, render_update, APP_STORE_LISTING_URL + ) + except Exception: + self.update_state("no_index") + self.update_state("index_received") + + if self.to_install_app: + await async_helpers.unblock( + self.install_app, render_update, self.to_install_app + ) + self.to_install_app = None if self.menu: self.menu.update(delta)