summaryrefslogtreecommitdiffstatshomepage
path: root/tests/extmod/uasyncio_micropython.py
blob: de1687ca8b98879ec5f1f0e2d69eb8f54b83ed38 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# Test MicroPython extensions on CPython asyncio:
# - sleep_ms
# - wait_for_ms

try:
    import time, uasyncio
except ImportError:
    print("SKIP")
    raise SystemExit


async def task(id, t):
    print("task start", id)
    await uasyncio.sleep_ms(t)
    print("task end", id)
    return id * 2


async def main():
    # Simple sleep_ms
    t0 = time.ticks_ms()
    await uasyncio.sleep_ms(1)
    print(time.ticks_diff(time.ticks_ms(), t0) < 100)

    try:
        # Sleep 1ms beyond maximum allowed sleep value
        await uasyncio.sleep_ms(time.ticks_add(0, -1) // 2 + 1)
    except OverflowError:
        print("OverflowError")

    # When task finished before the timeout
    print(await uasyncio.wait_for_ms(task(1, 5), 50))

    # When timeout passes and task is cancelled
    try:
        print(await uasyncio.wait_for_ms(task(2, 50), 5))
    except uasyncio.TimeoutError:
        print("timeout")

    print("finish")


uasyncio.run(main())