Python Library Keyboard
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

__init__.py 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. #
  4. """
  5. keyboard (Keyboard Module)
  6. ==========================
  7. **Author:**
  8. * Dirk Alders <sudo-dirk@mount-mockery.de>
  9. **Description:**
  10. This Module supports functions and classes for collecting keyboard strokes.
  11. **Submodules:**
  12. * :class:`keyboard.keyboard`
  13. * :class:`keyboard.keyboard_csp`
  14. **Unittest:**
  15. See also the :download:`unittest <../../keyboard/_testresults_/unittest.pdf>` documentation.
  16. """
  17. __DEPENDENCIES__ = ['stringtools', 'task']
  18. import stringtools
  19. import task
  20. import evdev
  21. import logging
  22. import select
  23. import sys
  24. import time
  25. logger_name = 'KEYBOARD'
  26. logger = logging.getLogger(logger_name)
  27. __DESCRIPTION__ = """The Module {\\tt %s} is designed to fetch data from a keyboatd (e.g. RFID-Reader).
  28. For more Information read the sphinx documentation.""" % __name__.replace('_', '\_')
  29. """The Module Description"""
  30. __INTERPRETER__ = (2, 3)
  31. """The Tested Interpreter-Versions"""
  32. class keyboard(object):
  33. LOG_PREFIX = 'KBD:'
  34. WARN_MSG_INIT_DEVICES = 1
  35. WARN_MSG_RUNTIME = 2
  36. LEFT_SHIFT = 42
  37. RIGHT_SHIFT = 54
  38. CAPS_LOCK = 58
  39. NUM_LOCK = 69
  40. SCROLL_LOCK = 70
  41. STATE_BITS_LEFT = {
  42. LEFT_SHIFT: 1,
  43. CAPS_LOCK: 2, # CAPS LOCK
  44. 29: 4, # Left Ctrl
  45. 56: 8, # Alt
  46. 125: 32, # Left Windows
  47. NUM_LOCK: 64, # Num Lock
  48. SCROLL_LOCK: 128, # Scroll Lock
  49. }
  50. STATE_BITS_RIGHT = {
  51. RIGHT_SHIFT: 1,
  52. 97: 4, # Right Ctrl
  53. 100: 16, # Alt Gr
  54. 126: 32, # Right Windows
  55. }
  56. SCANCODES = {
  57. # Scancode: ASCIICode
  58. 2: u'1', 3: u'2', 4: u'3', 5: u'4', 6: u'5', 7: u'6', 8: u'7', 9: u'8', 10: u'9', 11: u'0', 12: u'-', 13: u'=',
  59. 16: u'q', 17: u'w', 18: u'e', 19: u'r', 20: u't', 21: u'y', 22: u'u', 23: u'i', 24: u'o', 25: u'p', 26: u'[', 27: u']',
  60. 28: u'\n', 30: u'a', 31: u's', 32: u'd', 33: u'f', 34: u'g', 35: u'h', 36: u'j', 37: u'k', 38: u'l', 39: u';', 40: u'"',
  61. 41: u'`', 43: u'\\', 44: u'z', 45: u'x', 46: u'c', 47: u'v', 48: u'b', 49: u'n', 50: u'm', 51: u',', 52: u'.', 53: u'/',
  62. 57: u' '
  63. }
  64. CAPSCODES = {
  65. 2: u'!', 3: u'@', 4: u'#', 5: u'$', 6: u'%', 7: u'^', 8: u'&', 9: u'*', 10: u'(', 11: u')', 12: u'_', 13: u'+',
  66. 16: u'Q', 17: u'W', 18: u'E', 19: u'R', 20: u'T', 21: u'Y', 22: u'U', 23: u'I', 24: u'O', 25: u'P', 26: u'{', 27: u'}',
  67. 30: u'A', 31: u'S', 32: u'D', 33: u'F', 34: u'G', 35: u'H', 36: u'J', 37: u'K', 38: u'L', 39: u':', 40: u'\'', 41: u'~',
  68. 43: u'|', 44: u'Z', 45: u'X', 46: u'C', 47: u'V', 48: u'B', 49: u'N', 50: u'M', 51: u'<', 52: u'>', 53: u'?',
  69. 57: u' '
  70. }
  71. CAPSKEYS = list(range(16, 26)) + list(range(30, 39)) + list(range(44, 51))
  72. def __init__(self, device_list):
  73. if sys.version_info >= (3, 0):
  74. str_types = [str]
  75. else:
  76. str_types = [str, unicode]
  77. if type(device_list) in str_types:
  78. device_list = [device_list]
  79. self.__device_list__ = []
  80. for device in device_list:
  81. if device is not None:
  82. self.__device_list__.append(device)
  83. self.__devices__ = None
  84. self.__last_warn_message__ = None
  85. #
  86. self.__init_rx_buffer__()
  87. #
  88. self.__data_available_callback__ = {}
  89. #
  90. self.__state_byte__ = 0
  91. self.__state_byte_left__ = 0
  92. self.__state_byte_right__ = 0
  93. self.__rx_queue__ = task.threaded_queue()
  94. self.__rx_queue__.enqueue(5, self.__receive_task__)
  95. self.__rx_queue__.run()
  96. self.__cb_queue__ = task.threaded_queue()
  97. self.__cb_queue__.run()
  98. def __init_rx_buffer__(self):
  99. self.__rx_data__ = {}
  100. for device in self.__device_list__:
  101. if device is not None:
  102. self.__rx_data__[device] = ''
  103. def __calc_keyboard_lock_state__(self, device):
  104. leds = device.leds()
  105. if evdev.ecodes.LED_NUML in leds:
  106. self.__state_byte_left__ |= self.STATE_BITS_LEFT[self.NUM_LOCK]
  107. else:
  108. self.__state_byte_left__ &= ~self.STATE_BITS_LEFT[self.NUM_LOCK]
  109. if evdev.ecodes.LED_CAPSL in leds:
  110. self.__state_byte_left__ |= self.STATE_BITS_LEFT[self.CAPS_LOCK]
  111. else:
  112. self.__state_byte_left__ &= ~self.STATE_BITS_LEFT[self.CAPS_LOCK]
  113. if evdev.ecodes.LED_SCROLLL in leds:
  114. self.__state_byte_left__ |= self.STATE_BITS_LEFT[self.SCROLL_LOCK]
  115. else:
  116. self.__state_byte_left__ &= ~self.STATE_BITS_LEFT[self.SCROLL_LOCK]
  117. self.__state_byte__ = self.__state_byte_left__ | self.__state_byte_right__
  118. def __calc_keyboard_state__(self, cevent):
  119. if cevent.scancode in self.STATE_BITS_LEFT:
  120. if cevent.scancode not in [self.CAPS_LOCK, self.NUM_LOCK, self.SCROLL_LOCK]:
  121. if cevent.keystate == 1:
  122. self.__state_byte_left__ |= self.STATE_BITS_LEFT[cevent.scancode]
  123. elif cevent.keystate == 0:
  124. self.__state_byte_left__ &= ~self.STATE_BITS_LEFT[cevent.scancode]
  125. return True
  126. elif cevent.scancode in self.STATE_BITS_RIGHT:
  127. if cevent.keystate == 1:
  128. self.__state_byte_right__ |= self.STATE_BITS_RIGHT[cevent.scancode]
  129. elif cevent.keystate == 0:
  130. self.__state_byte_right__ &= ~self.STATE_BITS_RIGHT[cevent.scancode]
  131. return True
  132. else:
  133. return False
  134. def __get_ascii__(self, scancode):
  135. shift = self.__state_byte__ & self.STATE_BITS_LEFT[self.LEFT_SHIFT]
  136. caps = self.__state_byte__ & self.STATE_BITS_LEFT[self.CAPS_LOCK]
  137. if not caps and not shift:
  138. return self.SCANCODES.get(scancode, None)
  139. elif not caps and shift:
  140. return self.CAPSCODES.get(scancode, None)
  141. elif caps and shift:
  142. return self.SCANCODES.get(scancode, None)
  143. else:
  144. return self.CAPSCODES.get(scancode, None)
  145. def __append_rx_buffer__(self, device, c):
  146. self.__rx_data__[device.fn] += c
  147. if sys.version_info >= (3, 0):
  148. logger.debug('%s RX[%s] <- "%s"', self.LOG_PREFIX, device.fn, stringtools.hexlify(bytes(c, 'ascii')))
  149. else:
  150. logger.debug('%s RX[%s] <- "%s"', self.LOG_PREFIX, device.fn, stringtools.hexlify(c))
  151. return len(c) > 0
  152. def __parse_ascii__(self, cevent, device):
  153. self.__calc_keyboard_lock_state__(device)
  154. if self.__calc_keyboard_state__(cevent):
  155. pass
  156. else:
  157. if cevent.keystate == 1:
  158. c = self.__get_ascii__(cevent.scancode)
  159. if c is not None:
  160. self.__append_rx_buffer__(device, c)
  161. else:
  162. logger.warning('%s No character in dictionary for scancode %d', self.LOG_PREFIX, cevent.scancode)
  163. def register_callback(self, callback, device_name):
  164. """
  165. :param callback: The callback which will be executed, when data is available.
  166. :type callback: function
  167. This method sets the callback which is executed, if data is available. You need to execute :func:`receive` of the instance
  168. given with the first argument.
  169. .. note:: The :func:`callback` is executed with these arguments:
  170. :param self: This communication instance
  171. """
  172. self.__data_available_callback__[device_name] = callback
  173. def receive(self, device_name, timeout=1, num=None):
  174. rv = None
  175. tm = time.time()
  176. while (num is not None and len(self.__rx_data__.get(device_name, [])) < num) or (num is None and len(self.__rx_data__.get(device_name, [])) < 1):
  177. if time.time() > tm + timeout:
  178. logger.warning('%s TIMEOUT (%ss): Not enough data in buffer. Requested %s and buffer size is %d.', self.LOG_PREFIX, repr(timeout), repr(num or 'all'), len(self.__receive_buffer__))
  179. return None
  180. time.sleep(0.05)
  181. if num is None:
  182. rv = self.__rx_data__[device_name]
  183. else:
  184. rv = self.__rx_data__[device_name][:num]
  185. self.__rx_data__[device_name] = self.__rx_data__[device_name][len(rv):]
  186. return rv
  187. def __receive_task__(self, queue_inst):
  188. if self.__devices__ is None:
  189. # A mapping of file descriptors (integers) to InputDevice instances.
  190. try:
  191. self.__devices__ = map(evdev.InputDevice, self.__device_list__)
  192. self.__devices__ = {dev.fd: dev for dev in self.__devices__}
  193. logger.info('%s Listening to the following Devices: %s', self.LOG_PREFIX, repr(self.__device_list__))
  194. except OSError:
  195. self.__devices__ = None
  196. if self.__last_warn_message__ is not self.WARN_MSG_INIT_DEVICES:
  197. logger.warning('%s Error while initialising the devices: %s', self.LOG_PREFIX, repr(self.__device_list__))
  198. self.__last_warn_message__ = self.WARN_MSG_INIT_DEVICES
  199. else:
  200. r = select.select(self.__devices__, [], [])[0]
  201. for fd in r:
  202. try:
  203. for event in self.__devices__[fd].read():
  204. if event.type == evdev.ecodes.EV_KEY:
  205. if self.__devices__[fd].fn in self.__device_list__:
  206. self.__parse_ascii__(evdev.categorize(event), self.__devices__[fd])
  207. except IOError:
  208. if self.__last_warn_message__ is not self.WARN_MSG_RUNTIME:
  209. logger.warning('%s Error reading from device: %s', self.LOG_PREFIX, repr(self.__devices__[fd].fn))
  210. self.__devices__ = None
  211. self.__last_warn_message__ = self.WARN_MSG_RUNTIME
  212. # enqueue required callbacks
  213. for device_name in self.__device_list__:
  214. if len(self.__rx_data__.get(device_name, [])) > 0:
  215. self.__cb_queue__.enqueue(5, self.__callback_execution_queue__, device_name)
  216. #
  217. queue_inst.enqueue(5, self.__receive_task__)
  218. def __callback_execution_queue__(self, queue_inst, device_name):
  219. cb = self.__data_available_callback__.get(device_name)
  220. if cb is not None and len(self.__rx_data__.get(device_name, [])) > 0:
  221. logger.debug("%s Executing callback: %s(self, %s)", self.LOG_PREFIX, cb.__name__, repr(device_name))
  222. cb(self, device_name)
  223. if len(self.__rx_data__.get(device_name, [])) > 0:
  224. queue_inst.enqueue(5, self.__callback_execution_queue__, device_name)
  225. def close(self):
  226. """
  227. This method closes the active keyboard channel, if channel exists.
  228. """
  229. self.__rx_queue__.stop()
  230. self.__rx_queue__.join()
  231. self.__cb_queue__.stop()
  232. self.__cb_queue__.join()
  233. def __del__(self):
  234. self.close()
  235. class keyboard_csp(keyboard):
  236. """
  237. Class to gather keystrokes for specific devices. All data till \\\\n will be collected to a frame.
  238. :param device_list: The device to listen to.
  239. :type device_list: str or list
  240. :param rx_lvl: The log level for single keystrokes
  241. :type rx_lvl: int
  242. **Example:**
  243. .. literalinclude:: ../../keyboard/_examples_/keyboard_csp.py
  244. Will result to the following output (if user scans an rfid-tag and types "12345\\\\n"):
  245. .. literalinclude:: ../../keyboard/_examples_/keyboard_csp.log
  246. """
  247. LOG_PREFIX = 'KBD_CSP:'
  248. def __init_rx_buffer__(self):
  249. self.__rx_data__ = {}
  250. self.__csp__ = {}
  251. for device in self.__device_list__:
  252. if device is not None:
  253. self.__rx_data__[device] = []
  254. self.__csp__[device] = stringtools.csp.csp()
  255. def __append_rx_buffer__(self, device, c):
  256. if sys.version_info >= (3, 0):
  257. content = self.__csp__[device.fn].process(bytes(c, 'ascii'))
  258. else:
  259. content = self.__csp__[device.fn].process(str(c))
  260. if len(content) > 0:
  261. for msg in content:
  262. logger.debug('%s RX[%s] <- "%s"', self.LOG_PREFIX, device.fn, stringtools.hexlify(msg))
  263. self.__rx_data__[device.fn] += content
  264. return True
  265. else:
  266. return False
  267. def receive(self, device_name, timeout=1):
  268. return keyboard.receive(self, device_name, timeout=timeout, num=1)[0]