send_string.py 2.2 KB

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