1# Test Event class
2
3try:
4    import uasyncio as asyncio
5except ImportError:
6    try:
7        import asyncio
8    except ImportError:
9        print("SKIP")
10        raise SystemExit
11
12
13async def task(id, ev):
14    print("start", id)
15    print(await ev.wait())
16    print("end", id)
17
18
19async def task_delay_set(t, ev):
20    await asyncio.sleep(t)
21    print("set event")
22    ev.set()
23
24
25async def main():
26    ev = asyncio.Event()
27
28    # Set and clear without anything waiting, and test is_set()
29    print(ev.is_set())
30    ev.set()
31    print(ev.is_set())
32    ev.clear()
33    print(ev.is_set())
34
35    # Create 2 tasks waiting on the event
36    print("----")
37    asyncio.create_task(task(1, ev))
38    asyncio.create_task(task(2, ev))
39    print("yield")
40    await asyncio.sleep(0)
41    print("set event")
42    ev.set()
43    print("yield")
44    await asyncio.sleep(0)
45
46    # Create a task waiting on the already-set event
47    print("----")
48    asyncio.create_task(task(3, ev))
49    print("yield")
50    await asyncio.sleep(0)
51
52    # Clear event, start a task, then set event again
53    print("----")
54    print("clear event")
55    ev.clear()
56    asyncio.create_task(task(4, ev))
57    await asyncio.sleep(0)
58    print("set event")
59    ev.set()
60    await asyncio.sleep(0)
61
62    # Cancel a task waiting on an event (set event then cancel task)
63    print("----")
64    ev = asyncio.Event()
65    t = asyncio.create_task(task(5, ev))
66    await asyncio.sleep(0)
67    ev.set()
68    t.cancel()
69    await asyncio.sleep(0.1)
70
71    # Cancel a task waiting on an event (cancel task then set event)
72    print("----")
73    ev = asyncio.Event()
74    t = asyncio.create_task(task(6, ev))
75    await asyncio.sleep(0)
76    t.cancel()
77    ev.set()
78    await asyncio.sleep(0.1)
79
80    # Wait for an event that does get set in time
81    print("----")
82    ev.clear()
83    asyncio.create_task(task_delay_set(0.01, ev))
84    await asyncio.wait_for(ev.wait(), 0.1)
85    await asyncio.sleep(0)
86
87    # Wait for an event that doesn't get set in time
88    print("----")
89    ev.clear()
90    asyncio.create_task(task_delay_set(0.1, ev))
91    try:
92        await asyncio.wait_for(ev.wait(), 0.01)
93    except asyncio.TimeoutError:
94        print("TimeoutError")
95    await ev.wait()
96
97
98asyncio.run(main())
99