working input detection

main
Shinyzenith 2 years ago
parent 2e3a3f5227
commit f58f07c5be
No known key found for this signature in database
GPG Key ID: 6DD485917B553B7B

@ -0,0 +1,43 @@
#!/usr/bin/python3
import asyncio
import getpass
import grp
import libevdev
import pwd
import signal
import sys
from utils.log import LOG_UTILS
from utils.input import INPUT_UTILS
class SWHKD:
"""
Main Class.
"""
def __init__(self):
signal.signal(signal.SIGINT, self.signalhandler)
signal.signal(signal.SIGTERM, self.signalhandler)
self.log_util = LOG_UTILS()
self.input_util = INPUT_UTILS()
self.user = getpass.getuser()
async def signalhandler(self,sig,frame):
await self.log_util.log_info('Gracefully quitting.')
sys.exit(0)
async def run_swhkd(self):
groups = [g.gr_name for g in grp.getgrall() if self.user in g.gr_mem]
gid = pwd.getpwnam(self.user).pw_gid
groups.append(grp.getgrgid(gid).gr_name)
for group in groups:
if group.lower() == "input":
await self.log_util.log_warn("User is in input group, proceeding.")
break;
await self.input_util.get_keyboard_devices()
asyncio.run(SWHKD().run_swhkd())

@ -0,0 +1,30 @@
#!/usr/bin/python3
import glob
import libevdev
import asyncio
from . log import LOG_UTILS
class INPUT_UTILS:
def __init__(self):
self.log_util=LOG_UTILS()
async def check_keyboard(self,device_path) -> bool :
fd = open(device_path, 'rb')
device = libevdev.Device(fd)
fd.close()
if device.has(libevdev.EV_KEY.KEY_ENTER):
await self.log_util.log_info("Device {} is a keyboard".format(device_path))
return True
else:
await self.log_util.log_error("Device {} is not a keyboard".format(device_path))
return False
async def get_keyboard_devices(self):
devices = glob.glob('/dev/input/event*')
keyboards = []
for device in devices:
out = await self.check_keyboard(device)
if out ==True:
keyboards.append(device)
return keyboards

@ -1,6 +1,6 @@
import time
class SWHKD_UTILS():
class LOG_UTILS():
"""
Helper Functions.
"""
@ -11,11 +11,11 @@ class SWHKD_UTILS():
self.COLOR_BLUE="\033[1;34m"
self.COLOR_RESET="\033[0m"
def log_info(self, message:str):
async def log_info(self, message:str):
print(f"{self.COLOR_GREEN}[{time.ctime()}] INFO:{self.COLOR_RESET} {message}")
def log_error(self, message:str):
async def log_error(self, message:str):
print(f"{self.COLOR_RED}[{time.ctime()}] ERROR:{self.COLOR_RESET} {message}")
def log_warn(self, message:str):
async def log_warn(self, message:str):
print(f"{self.COLOR_YELLOW}[{time.ctime()}] WARN:{self.COLOR_RESET} {message}")

@ -1,48 +0,0 @@
#!/usr/bin/python3
from utils import SWHKD_UTILS
import getpass
import grp
import libevdev
import pwd
import signal
import sys
class SWHKD:
"""
Main Class.
"""
def __init__(self):
signal.signal(signal.SIGINT, self.signalhandler)
signal.signal(signal.SIGTERM, self.signalhandler)
self.utils = SWHKD_UTILS()
self.user = getpass.getuser()
def signalhandler(self,sig,frame):
self.utils.log_info('Quitting!')
sys.exit(0)
def run_swhkd(self):
groups = [g.gr_name for g in grp.getgrall() if self.user in g.gr_mem]
gid = pwd.getpwnam(self.user).pw_gid
groups.append(grp.getgrgid(gid).gr_name)
for group in groups:
if group.lower() == "input":
self.utils.log_warn("User is in input group, proceeding.")
break;
fd = open('/dev/input/event7','rb')
device = libevdev.Device(fd)
if not device.has(libevdev.EV_KEY.BTN_LEFT):
self.utils.log_error("Device is not a mouse.")
sys.exit(0)
while True:
for event in device.events():
if not event.matches(libevdev.EV_KEY):
continue
if event.matches(libevdev.EV_KEY.BTN_LEFT):
self.utils.log_info('Left button event')
elif event.matches(libevdev.EV_KEY.BTN_RIGHT):
self.utils.log_info('Right button event')
SWHKD().run_swhkd()

@ -1,91 +0,0 @@
#!/usr/bin/env python3
import sys
import libevdev
def print_capabilities(l):
v = l.driver_version
print("Input driver version is {}.{}.{}".format(v >> 16, (v >> 8) & 0xff, v & 0xff))
id = l.id
print("Input device ID: bus {:#x} vendor {:#x} product {:#x} version {:#x}".format(
id["bustype"],
id["vendor"],
id["product"],
id["version"],
))
print("Input device name: {}".format(l.name))
print("Supported events:")
for t, cs in l.evbits.items():
print(" Event type {} ({})".format(t.value, t.name))
for c in cs:
if t in [libevdev.EV_LED, libevdev.EV_SND, libevdev.EV_SW]:
v = l.value[c]
print(" Event code {} ({}) state {}".format(c.value, c.name, v))
else:
print(" Event code {} ({})".format(c.value, c.name))
if t == libevdev.EV_ABS:
a = l.absinfo[c]
print(" {:10s} {:6d}".format('Value', a.value))
print(" {:10s} {:6d}".format('Minimum', a.minimum))
print(" {:10s} {:6d}".format('Maximum', a.maximum))
print(" {:10s} {:6d}".format('Fuzz', a.fuzz))
print(" {:10s} {:6d}".format('Flat', a.flat))
print(" {:10s} {:6d}".format('Resolution', a.resolution))
print("Properties:")
for p in l.properties:
print(" Property type {} ({})".format(p.value, p.name))
def print_event(e):
print("Event: time {}.{:06d}, ".format(e.sec, e.usec), end='')
if e.matches(libevdev.EV_SYN):
if e.matches(libevdev.EV_SYN.SYN_MT_REPORT):
print("++++++++++++++ {} ++++++++++++".format(e.code.name))
elif e.matches(libevdev.EV_SYN.SYN_DROPPED):
print(">>>>>>>>>>>>>> {} >>>>>>>>>>>>".format(e.code.name))
else:
print("-------------- {} ------------".format(e.code.name))
else:
print("type {:02x} {} code {:03x} {:20s} value {:4d}".format(e.type.value, e.type.name, e.code.value, e.code.name, e.value))
def main(args):
path = args[1]
try:
with open(path, "rb") as fd:
dev = libevdev.Device(fd)
print_capabilities(dev)
print("################################\n"
"# Waiting for events #\n"
"################################")
while True:
try:
for e in dev.events():
print_event(e)
except libevdev.EventsDroppedException:
for e in dev.sync():
print_event(e)
except KeyboardInterrupt:
pass
except IOError as e:
import errno
if e.errno == errno.EACCES:
print("Insufficient permissions to access {}".format(path))
elif e.errno == errno.ENOENT:
print("Device {} does not exist".format(path))
else:
raise e
if __name__ == "__main__":
if len(sys.argv) < 2:
print("Usage: {} /dev/input/eventX".format(sys.argv[0]))
sys.exit(1)
main(sys.argv)
Loading…
Cancel
Save