2020-06-05 07:26:27 -04:00
|
|
|
# Test MicroPython extensions on CPython asyncio:
|
|
|
|
# - sleep_ms
|
|
|
|
# - wait_for_ms
|
|
|
|
|
|
|
|
try:
|
2023-08-22 11:15:46 -04:00
|
|
|
import time, asyncio
|
2020-06-05 07:26:27 -04:00
|
|
|
except ImportError:
|
|
|
|
print("SKIP")
|
|
|
|
raise SystemExit
|
|
|
|
|
|
|
|
|
|
|
|
async def task(id, t):
|
|
|
|
print("task start", id)
|
2023-08-22 11:15:46 -04:00
|
|
|
await asyncio.sleep_ms(t)
|
2020-06-05 07:26:27 -04:00
|
|
|
print("task end", id)
|
|
|
|
return id * 2
|
|
|
|
|
|
|
|
|
|
|
|
async def main():
|
|
|
|
# Simple sleep_ms
|
2023-08-22 11:15:46 -04:00
|
|
|
t0 = time.ticks_ms()
|
|
|
|
await asyncio.sleep_ms(1)
|
|
|
|
print(time.ticks_diff(time.ticks_ms(), t0) < 100)
|
2020-06-05 07:26:27 -04:00
|
|
|
|
2022-10-14 01:10:38 -04:00
|
|
|
try:
|
|
|
|
# Sleep 1ms beyond maximum allowed sleep value
|
2023-06-08 02:01:38 -04:00
|
|
|
await asyncio.sleep_ms(time.ticks_add(0, -1) // 2 + 1)
|
2022-10-14 01:10:38 -04:00
|
|
|
except OverflowError:
|
|
|
|
print("OverflowError")
|
|
|
|
|
2020-06-05 07:26:27 -04:00
|
|
|
# When task finished before the timeout
|
2023-08-22 11:15:46 -04:00
|
|
|
print(await asyncio.wait_for_ms(task(1, 5), 50))
|
2020-06-05 07:26:27 -04:00
|
|
|
|
|
|
|
# When timeout passes and task is cancelled
|
|
|
|
try:
|
2023-08-22 11:15:46 -04:00
|
|
|
print(await asyncio.wait_for_ms(task(2, 50), 5))
|
|
|
|
except asyncio.TimeoutError:
|
2020-06-05 07:26:27 -04:00
|
|
|
print("timeout")
|
|
|
|
|
|
|
|
print("finish")
|
|
|
|
|
|
|
|
|
2023-10-18 17:49:14 -04:00
|
|
|
uasyncio.run(main())
|