Created
March 13, 2025 17:56
-
-
Save mswain/2154a2bb80f6230cb0aa72050022ec32 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| import signal | |
| class TimeoutException(Exception): | |
| pass | |
| def timeout_handler(signum, frame): | |
| raise TimeoutException("Timeout occurred!") | |
| def exit_handler(signum, frame): | |
| print("Exiting") | |
| exit(0) | |
| def knock_handler(signum, frame): | |
| print("Knocking") | |
| signal.signal(signal.SIGALRM, timeout_handler) | |
| signal.signal(signal.SIGINT, exit_handler) | |
| signal.signal(signal.SIGUSR2, knock_handler) | |
| def listen(duration) -> bool: | |
| signal.setitimer(signal.ITIMER_REAL, duration) | |
| try: | |
| signal.pause() | |
| signal.alarm(0) | |
| return True | |
| except TimeoutException: | |
| signal.alarm(0) | |
| return False | |
| def unlock(): | |
| print("UNLOCKED!") | |
| slice = 0.1 | |
| tolerance_factor = 30 | |
| # Knock pattern is an array | |
| # of coefficients of the slice time | |
| pattern = [100, 200, 100] | |
| class KnockTooSoon(Exception): | |
| pass | |
| while True: | |
| try: | |
| print("Starting Listen Loop!") | |
| listen(0) | |
| t = 0 | |
| for i in pattern: | |
| while t <= i * slice + tolerance_factor * slice: | |
| knock = listen(slice) | |
| t += slice | |
| if knock and t >= i * slice - tolerance_factor * slice: | |
| print("Received knock within window!") | |
| t = 0 | |
| break | |
| elif knock and t < i * slice + tolerance_factor * slice: | |
| raise KnockTooSoon | |
| else: | |
| break | |
| else: | |
| unlock() | |
| except KnockTooSoon: | |
| print("Knock too soon!") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment