Skip to content

Commit 2a6aaab

Browse files
API: add TaskManager that wraps asyncio
1 parent 73fa096 commit 2a6aaab

File tree

3 files changed

+39
-0
lines changed

3 files changed

+39
-0
lines changed

internal_filesystem/lib/mpos/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
from .content.intent import Intent
66
from .activity_navigator import ActivityNavigator
77
from .content.package_manager import PackageManager
8+
from .task_manager import TaskManager
89

910
# Common activities (optional)
1011
from .app.activities.chooser import ChooserActivity

internal_filesystem/lib/mpos/main.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import task_handler
22
import _thread
33
import lvgl as lv
4+
import mpos
45
import mpos.apps
56
import mpos.config
67
import mpos.ui
@@ -71,6 +72,8 @@ def custom_exception_handler(e):
7172
# This will throw an exception if there is already a "/builtin" folder present
7273
print("main.py: WARNING: could not import/run freezefs_mount_builtin: ", e)
7374

75+
mpos.TaskManager()
76+
7477
try:
7578
from mpos.net.wifi_service import WifiService
7679
_thread.stack_size(mpos.apps.good_stack_size())
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import asyncio # this is the only place where asyncio is allowed to be imported - apps should not use it directly but use this TaskManager
2+
import _thread
3+
4+
class TaskManager:
5+
6+
task_list = [] # might be good to periodically remove tasks that are done, to prevent this list from growing huge
7+
8+
def __init__(self):
9+
print("TaskManager starting asyncio_thread")
10+
_thread.stack_size(1024) # tiny stack size is enough for this simple thread
11+
_thread.start_new_thread(asyncio.run, (self._asyncio_thread(), ))
12+
13+
async def _asyncio_thread(self):
14+
print("asyncio_thread started")
15+
while True:
16+
#print("asyncio_thread tick")
17+
await asyncio.sleep_ms(100) # This delay determines how quickly new tasks can be started, so keep it below human reaction speed
18+
print("WARNING: asyncio_thread exited, this shouldn't happen because now asyncio.create_task() won't work anymore!")
19+
20+
@classmethod
21+
def create_task(cls, coroutine):
22+
cls.task_list.append(asyncio.create_task(coroutine))
23+
24+
@classmethod
25+
def list_tasks(cls):
26+
for index, task in enumerate(cls.task_list):
27+
print(f"task {index}: ph_key:{task.ph_key} done:{task.done()} running {task.coro}")
28+
29+
@staticmethod
30+
def sleep_ms(ms):
31+
return asyncio.sleep_ms(ms)
32+
33+
@staticmethod
34+
def sleep(s):
35+
return asyncio.sleep(s)

0 commit comments

Comments
 (0)