I have a lot of boards and usually need to re-use code even for different projects.

keyboard.py 2.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import sys
  2. class Keyboard:
  3. def __init__(self):
  4. # the number row starts with 3 and ends with the number, e.g. key number 5 is 0x35
  5. self.number_row=["0x30","0x31","0x32","0x33","0x34","0x35","0x36","0x37","0x38","0x39"]
  6. self.chars={
  7. "0x21":"!","0x40":"@","0x23":"#","0x24":"$","0x25":"%","0x5e":"^","0x26":"&","0x2a":"*","0x28":"(","0x29":")", "0x3f":"?",
  8. "0x27":"'", "0x22":"\"", "0x3a":":", "0x3c":"<", "0x3e":">"
  9. }
  10. self.lowercase={
  11. "0x71":"q", "0x77":"w", "0x65":"e", "0x72":"r", "0x74":"t", "0x79":"y", "0x75":"u", "0x69":"i", "0x6f":"o", "0x70":"p",
  12. "0x61":"a", "0x73":"s", "0x64":"d", "0x66":"f", "0x67":"g", "0x68":"h", "0x6a":"j", "0x6b":"k", "0x6c":"l",
  13. "0x7a":"z", "0x78":"x", "0x63":"c", "0x76":"v", "0x62":"b", "0x6e":"n", "0x6d":"m"
  14. }
  15. self.uppercase={
  16. "0x51":"Q", "0x57":"W", "0x45":"E", "0x52":"R", "0x54":"T", "0x59":"Y", "0x55":"U", "0x49":"I", "0x4f":"O", "0x50":"P",
  17. "0x41":"A", "0x53":"S", "0x44":"D", "0x46":"F", "0x47":"G", "0x48":"H", "0x4a":"J", "0x4b":"K", "0x4c":"L",
  18. "0x5a":"Z", "0x58":"X", "0x43":"C", "0x56":"V", "0x42":"B", "0x4e":"N", "0x4d":"M"
  19. }
  20. self.special={
  21. "0xa":"\n", "0x8":"BACKSP", "0x20":" ", "0x3b":"UP", "0x2e":"DOWN", "0x2c":"LEFT", "0x2f":"RIGHT", "0x10d":"OPTD",
  22. "0x4":"CTRLD", "0x13":"CTRLS", "0x9":" ", "0x60":"ESC", "0xf":"CTRLO"
  23. }
  24. def scan(self):
  25. code=hex(ord(sys.stdin.read(1)))
  26. #printing the code can be useful for debugging purposes, to check that the codes have been logged correctly if something unexpected is happening
  27. #print(code)
  28. key = None
  29. if code in self.number_row:
  30. key = str(self.number_row.index(code))
  31. elif code in self.chars:
  32. key = self.chars[code]
  33. elif code in self.lowercase:
  34. key = self.lowercase[code]
  35. elif code in self.uppercase:
  36. key = self.uppercase[code]
  37. elif code in self.special:
  38. key = self.special[code]
  39. if key:
  40. return key
  41. else:
  42. return "UNKNOWN "+code
  43. def is_alphanumeric(self, key):
  44. if key in self.special.values() or key in self.chars.values():
  45. return False
  46. else:
  47. return True