Created
August 10, 2023 20:06
-
-
Save muromec/037fd290d19b644245a288c5f6c98129 to your computer and use it in GitHub Desktop.
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 contextlib import contextmanager | |
import libevdev | |
from periphery import GPIO | |
import time | |
# 230 69 73 80 | |
gpio_out1 = GPIO("/dev/gpiochip0", 230, "out") | |
gpio_out2 = GPIO("/dev/gpiochip0", 69, "out") | |
gpio_out3 = GPIO("/dev/gpiochip0", 73, "out") | |
gpio_out4 = GPIO("/dev/gpiochip0", 80, "out") | |
# 68 70 74 75 | |
gpio_in1 = GPIO("/dev/gpiochip0", 68, "in", bias='pull_up') | |
gpio_in2 = GPIO("/dev/gpiochip0", 70, "in", bias='pull_up') | |
gpio_in3 = GPIO("/dev/gpiochip0", 74, "in", bias='pull_up') | |
gpio_in4 = GPIO("/dev/gpiochip0", 75, "in", bias='pull_up') | |
k = libevdev.EV_KEY | |
KEYS = [ | |
k.KEY_1, k.KEY_2, k.KEY_3, k.KEY_0, | |
k.KEY_4, k.KEY_5, k.KEY_6, k.KEY_BACK, | |
k.KEY_7, k.KEY_8, k.KEY_9, k.KEY_0, | |
k.KEY_NUMERIC_STAR, k.KEY_0, k.KEY_NUMERIC_POUND, k.KEY_AGAIN, | |
] | |
def write_all_out(value): | |
gpio_out1.write(value) | |
gpio_out2.write(value) | |
gpio_out3.write(value) | |
gpio_out4.write(value) | |
@contextmanager | |
def open_input_device(): | |
device = libevdev.Device() | |
device.name = 'phone keyboard' | |
for key in KEYS: | |
device.enable(key) | |
try: | |
uinput = device.create_uinput_device() | |
yield uinput | |
finally: | |
uinput.close() | |
def close_all(): | |
for gpio in [gpio_out1, gpio_out2, gpio_out3, gpio_out4] + [gpio_in1, gpio_in2, gpio_in3, gpio_in4]: | |
gpio.close() | |
def report_key(inp_dev, key): | |
print('report key', inp_dev, key) | |
press = [libevdev.InputEvent(key, value=1), | |
libevdev.InputEvent(libevdev.EV_SYN.SYN_REPORT, value=0)] | |
inp_dev.send_events(press) | |
release = [libevdev.InputEvent(key, value=0), | |
libevdev.InputEvent(libevdev.EV_SYN.SYN_REPORT, value=0)] | |
inp_dev.send_events(release) | |
def loop_once(inp_dev): | |
write_all_out(True) | |
for idx, out in enumerate([gpio_out1, gpio_out2, gpio_out3, gpio_out4]): | |
row = idx << 2 | |
out.write(False) | |
key = None | |
if not gpio_in1.read(): | |
key = KEYS[row | 0] | |
if not gpio_in2.read(): | |
key = KEYS[row | 1] | |
if not gpio_in3.read(): | |
key = KEYS[row | 2] | |
if not gpio_in4.read(): | |
key = KEYS[row | 3] | |
out.write(True) | |
if key is not None: | |
report_key(inp_dev, key) | |
def main(): | |
with open_input_device() as inp_dev: | |
try: | |
while True: | |
loop_once(inp_dev) | |
time.sleep(1/6) | |
except KeyboardInterrupt: | |
pass | |
finally: | |
close_all() | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment