send_string.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. #!/usr/bin/python3
  2. import os # used to all external commands
  3. import sys # used to exit the script
  4. import dbus
  5. import dbus.service
  6. import dbus.mainloop.glib
  7. import time
  8. # import thread
  9. import keymap
  10. DBUS_OBJ_BTK_NAME = 'org.thanhle.btkbservice'
  11. DBUS_OBJ_BTK_PATH = '/org/thanhle/btkbservice'
  12. class BtkStringClient():
  13. # constants
  14. KEY_DOWN_TIME = 0.01
  15. KEY_DELAY = 0.01
  16. def __init__(self):
  17. # the structure for a bt keyboard input report (size is 10 bytes)
  18. self.state = [
  19. 0xA1, # this is an input report
  20. 0x01, # Usage report = Keyboard
  21. # Bit array for Modifier keys
  22. [0, # Right GUI - Windows Key
  23. 0, # Right ALT
  24. 0, # Right Shift
  25. 0, # Right Control
  26. 0, # Left GUI
  27. 0, # Left ALT
  28. 0, # Left Shift
  29. 0], # Left Control
  30. 0x00, # Vendor reserved
  31. 0x00, # rest is space for 6 keys
  32. 0x00,
  33. 0x00,
  34. 0x00,
  35. 0x00,
  36. 0x00]
  37. self.scancodes = {" ": "KEY_SPACE"}
  38. # connect with the Bluetooth keyboard server
  39. print("setting up DBus Client")
  40. self.bus = dbus.SystemBus()
  41. self.btkservice = self.bus.get_object(DBUS_OBJ_BTK_NAME, DBUS_OBJ_BTK_PATH)
  42. self.iface = dbus.Interface(self.btkservice, DBUS_OBJ_BTK_NAME)
  43. def send_key_state(self):
  44. """sends a single frame of the current key state to the emulator server"""
  45. bin_str = ""
  46. element = self.state[2]
  47. for bit in element:
  48. bin_str += str(bit)
  49. self.iface.send_keys(int(bin_str, 2), self.state[4:10])
  50. def send_key_down(self, scancode):
  51. """sends a key down event to the server"""
  52. self.state[4] = scancode
  53. self.send_key_state()
  54. def send_key_up(self):
  55. """sends a key up event to the server"""
  56. self.state[4] = 0
  57. self.send_key_state()
  58. def send_string(self, string_to_send):
  59. for c in string_to_send:
  60. cu = c.upper()
  61. if(cu in self.scancodes):
  62. scantablekey = self.scancodes[cu]
  63. else:
  64. scantablekey = "KEY_"+c.upper()
  65. print(scantablekey)
  66. scancode = keymap.keytable[scantablekey]
  67. self.send_key_down(scancode)
  68. time.sleep(BtkStringClient.KEY_DOWN_TIME)
  69. self.send_key_up()
  70. time.sleep(BtkStringClient.KEY_DELAY)
  71. if __name__ == "__main__":
  72. if(len(sys.argv) < 2):
  73. print("Usage: send_string <string to send ")
  74. exit()
  75. dc = BtkStringClient()
  76. string_to_send = sys.argv[1]
  77. print("Sending " + string_to_send)
  78. dc.send_string(string_to_send)
  79. print("Done.")