Created
May 21, 2022 08:59
-
-
Save lbt/13a7293e07a51d39c2f8356905d202de to your computer and use it in GitHub Desktop.
IR in 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
#!/usr/bin/env python3 | |
import asyncio | |
import evdev | |
from evdev import ecodes | |
from evdev.events import KeyEvent | |
from PySide2.QtCore import QObject | |
class IR(QObject): | |
def __init__(self, loop=None, parent=None): | |
QObject.__init__(self, parent) | |
self._allowed_actions = (KeyEvent.key_up, | |
KeyEvent.key_down, | |
KeyEvent.key_hold) | |
self._behaviour = {} | |
self._behaviour = dict.fromkeys(self._allowed_actions, {}) | |
self.isActive = False | |
devices = [evdev.InputDevice(path) for path in evdev.list_devices()] | |
if not loop: | |
loop = asyncio.get_running_loop() | |
found_device = None | |
for device in devices: | |
# print(device.path, device.name, device.phys) | |
if device.name == 'gpio_ir_recv': | |
self.isActive = True | |
print("found the ir device at %s" % device.path) | |
found_device = device | |
found_device.grab() | |
loop.create_task(self.watch(found_device)) | |
break | |
def addBehaviour(self, action, keyname, call): | |
code = ecodes.ecodes[keyname] | |
self._behaviour[action][code] = call | |
async def watch(self, my_ir_device): | |
async for event in my_ir_device.async_read_loop(): | |
if event.type == ecodes.EV_KEY: | |
key = KeyEvent(event) | |
# print("David's IR thingy saw %s" % key) | |
if key.keystate not in self._behaviour: | |
next | |
if key.event.code in self._behaviour[key.keystate]: | |
action = self._behaviour[key.keystate][key.event.code] | |
action() | |
else: | |
print(f"No behaviour for {key.keycode}") | |
if __name__ == "__main__": | |
ir = IR() | |
print("Should recognise Volume Up key") | |
ir.addBehaviour(KeyEvent.key_up, "KEY_VOLUMEUP", | |
lambda: print("key_up on Volume up recognised")) | |
ir.addBehaviour(KeyEvent.key_down, "KEY_VOLUMEDOWN", | |
lambda: print("key_down on Volume down recognised")) | |
ir.addBehaviour(KeyEvent.key_hold, "KEY_PAUSE", | |
lambda: print("key_hold on Pause recognised")) | |
if ir.isActive: | |
asyncio.get_event_loop().run_forever() | |
else: | |
print("No devices found") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment