Skip to content

Commit 451f4c3

Browse files
committed
Fix bug in interaction between multibutton and button
1 parent d0e48ef commit 451f4c3

File tree

1 file changed

+30
-21
lines changed

1 file changed

+30
-21
lines changed

async_button.py

Lines changed: 30 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@
3131
__repo__ = "https://github.com/furbrain/CircuitPython_async_button.git"
3232

3333
import asyncio
34-
from asyncio import Task, Event
34+
from asyncio import Event
3535

3636
from adafruit_ticks import ticks_add, ticks_less, ticks_ms
3737

@@ -256,7 +256,6 @@ async def _monitor(self):
256256
now = getattr(
257257
evt, "timestamp", ticks_ms()
258258
) # use now if timestamp not there
259-
# print(now, self.last_click_tm, self.double_click_max_duration)
260259
if ticks_less(now, dbl_clk_expires):
261260
self._increase_clicks()
262261
else:
@@ -329,16 +328,22 @@ async def wait(self, click_types: Union[int, Sequence[int]] = ALL_EVENTS):
329328
for evt_type in click_types:
330329
coro = self.events[evt_type].wait()
331330
evts[evt_type] = TaskWrapper(coro, one_event_done)
332-
await one_event_done.wait()
333-
if len(evts) > 1:
334-
await asyncio.sleep(0) # ensure all event types get an opportunity to run
335-
results = []
336-
for evt_type, evt in evts.items():
337-
if evt.done():
338-
results.append(evt_type)
339-
else:
340-
evt.cancel() # cancel unfired events
341-
return results
331+
try:
332+
await one_event_done.wait()
333+
if len(evts) > 1:
334+
await asyncio.sleep(
335+
0
336+
) # ensure all event types get an opportunity to run
337+
results = []
338+
for evt_type, evt in evts.items():
339+
if evt.done():
340+
results.append(evt_type)
341+
return results
342+
finally:
343+
# make sure all tasks are cancelled on exit
344+
for evt in evts.values():
345+
if not evt.done():
346+
evt.cancel()
342347

343348
async def wait_for_click(self):
344349
"""
@@ -398,15 +403,19 @@ async def wait(self, **kwargs):
398403
button = list(kwargs)[0]
399404
results = await self.buttons[button].wait(kwargs[button])
400405
return button, results[0]
401-
tasks: Dict[Any, Task] = {}
406+
tasks: Dict[Any, TaskWrapper] = {}
402407
click_happened = asyncio.Event()
403408
for key, value in kwargs.items():
404409
tasks[key] = TaskWrapper(self.buttons[key].wait(value), click_happened)
405-
await click_happened.wait()
406-
result = (None, None)
407-
for key, task in tasks.items():
408-
if task.done():
409-
result = (key, task.result()[0])
410-
else:
411-
task.cancel()
412-
return result
410+
try:
411+
await click_happened.wait()
412+
result = (None, None)
413+
for key, task in tasks.items():
414+
if task.done():
415+
result = (key, task.result()[0])
416+
return result
417+
finally:
418+
# make sure all tasks are cancelled on exit
419+
for task in tasks.values():
420+
if not task.done():
421+
task.cancel()

0 commit comments

Comments
 (0)