Last active
November 9, 2019 16:38
-
-
Save Jim-Holmstroem/078cbc5f4b74d7d6c1d919d9fb66aeca to your computer and use it in GitHub Desktop.
async poll keyboard python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from random import seed, randint | |
seed(1337) | |
import asyncio | |
def poll_keyboard(): | |
if randint(1, 5) > 2: | |
return 0 # nothing pushed | |
else: | |
return randint(1, 32) # 1 is enter | |
class Keyboard: | |
def __init__(self): | |
pass | |
async def started(self): | |
value = 0 | |
while True: | |
value = poll_keyboard() | |
if value != 0: | |
break | |
await asyncio.sleep(0.01) | |
async def get_password(self): | |
storage = [] | |
old_value = None | |
while True: | |
value = poll_keyboard() | |
if value == 1: | |
break | |
else: | |
if old_value != value: | |
old_value = value | |
storage.append(value) | |
await asyncio.sleep(0.01) | |
return storage | |
async def main(): | |
keyboard = Keyboard() | |
await keyboard.started() | |
try: | |
password = await asyncio.wait_for(keyboard.get_password(), timeout=1.0) | |
print(password) | |
except asyncio.TimeoutError: | |
print("timeout") | |
asyncio.run(main()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment