Debian Codegraph @

addons/iot_drivers/iot_handlers/drivers/keyboard_usb_driver_L.py

raw
1 # Part of Odoo. See LICENSE file for full copyright and licensing details.
2
3 import ctypes
4 import evdev
5 import json
6 import logging
7 from lxml import etree
8 import os
9 from queue import Queue, Empty
10 import re
11 import requests
12 import subprocess
13 from threading import Lock
14 import time
15 from usb import util
16
17 from odoo import http
18 from odoo.addons.iot_drivers.controllers.proxy import proxy_drivers
19 from odoo.addons.iot_drivers.driver import Driver
20 from odoo.addons.iot_drivers.event_manager import event_manager
21 from odoo.addons.iot_drivers.main import iot_devices
22 from odoo.addons.iot_drivers.tools import helpers, route
23
24 _logger = logging.getLogger(__name__)
25 xlib = ctypes.cdll.LoadLibrary('libX11.so.6')
26
27
28 class KeyboardUSBDriver(Driver):
29 # The list of devices can be found in /proc/bus/input/devices
30 # or "ls -l /dev/input/by-path"
31 # Note: the user running "evdev" commands must be inside the "input" group
32 # Each device's input will correspond to a file in /dev/input/event*
33 # The exact file can be found by looking at the "Handlers" line in /proc/bus/input/devices
34 # Example: "H: Handlers=sysrq kbd leds event0" -> The file used is /dev/input/event0
35 # If you read the file "/dev/input/event0" you will get the input from the device in real time
36 # One usb device can have multiple associated event files (like a foot pedal which has 3 event files)
37
38 connection_type = 'usb'
39 keyboard_layout_groups = []
40 available_layouts = []
41 input_devices = []
42
43 def __init__(self, identifier, device):
44 if not hasattr(KeyboardUSBDriver, 'display'):
45 os.environ['XAUTHORITY'] = "/run/lightdm/pi/xauthority"
46 KeyboardUSBDriver.display = xlib.XOpenDisplay(bytes(":0.0", "utf-8"))
47
48 super().__init__(identifier, device)
49 self.device_connection = 'direct'
50 self.device_name = self._set_name()
51
52 self._actions.update({
53 'update_layout': self._update_layout,
54 'update_is_scanner': self._save_is_scanner,
55 '': self._action_default,
56 })
57
58 # from https://github.com/xkbcommon/libxkbcommon/blob/master/test/evdev-scancodes.h
59 self._scancode_to_modifier = {
60 42: 'left_shift',
61 54: 'right_shift',
62 58: 'caps_lock',
63 69: 'num_lock',
64 100: 'alt_gr', # right alt
65 }
66 self._tracked_modifiers = {modifier: False for modifier in self._scancode_to_modifier.values()}
67
68 if not KeyboardUSBDriver.available_layouts:
69 KeyboardUSBDriver.load_layouts_list()
70 KeyboardUSBDriver.send_layouts_list()
71
72 for evdev_device in [evdev.InputDevice(path) for path in evdev.list_devices()]:
73 if (device.idVendor == evdev_device.info.vendor) and (device.idProduct == evdev_device.info.product):
74 self.input_devices.append(evdev_device)
75
76 self._set_device_type('scanner') if self._is_scanner() else self._set_device_type()
77
78 @classmethod
79 def supported(cls, device):
80 for cfg in device:
81 for itf in cfg:
82 if itf.bInterfaceClass == 3 and itf.bInterfaceProtocol != 2:
83 device.interface_protocol = itf.bInterfaceProtocol
84 return True
85 return False
86
87 @classmethod
88 def get_status(self):
89 """Allows `hw_proxy.Proxy` to retrieve the status of the scanners"""
90 status = 'connected' if any(iot_devices[d].device_type == "scanner" for d in iot_devices) else 'disconnected'
91 return {'status': status, 'messages': ''}
92
93 @classmethod
94 @helpers.require_db
95 def send_layouts_list(cls, server_url=None):
96 try:
97 response = requests.post(
98 server_url + '/iot/keyboard_layouts',
99 data={'available_layouts': json.dumps(cls.available_layouts)}, timeout=5
100 )
101 response.raise_for_status()
102 except requests.exceptions.RequestException:
103 _logger.exception('Could not reach configured server to send available layouts')
104
105 @classmethod
106 def load_layouts_list(cls):
107 tree = etree.parse("/usr/share/X11/xkb/rules/base.xml", etree.XMLParser(ns_clean=True, recover=True))
108 layouts = tree.xpath("//layout")
109 for layout in layouts:
110 layout_name = layout.xpath("./configItem/name")[0].text
111 layout_description = layout.xpath("./configItem/description")[0].text
112 KeyboardUSBDriver.available_layouts.append({
113 'name': layout_description,
114 'layout': layout_name,
115 })
116 for variant in layout.xpath("./variantList/variant"):
117 variant_name = variant.xpath("./configItem/name")[0].text
118 variant_description = variant.xpath("./configItem/description")[0].text
119 KeyboardUSBDriver.available_layouts.append({
120 'name': variant_description,
121 'layout': layout_name,
122 'variant': variant_name,
123 })
124
125 def _set_name(self):
126 try:
127 manufacturer = util.get_string(self.dev, self.dev.iManufacturer)
128 product = util.get_string(self.dev, self.dev.iProduct)
129 if manufacturer and product:
130 return re.sub(r"[^\w \-+/*&]", '', "%s - %s" % (manufacturer, product))
131 except ValueError as e:
132 _logger.warning(e)
133 return 'Unknown input device'
134
135 def run(self):
136 try:
137 for device in self.input_devices:
138 for event in device.read_loop():
139 if self._stopped.is_set():
140 break
141 if event.type == evdev.ecodes.EV_KEY:
142 data = evdev.categorize(event)
143
144 modifier_name = self._scancode_to_modifier.get(data.scancode)
145 if modifier_name:
146 if modifier_name in ('caps_lock', 'num_lock'):
147 if data.keystate == 1:
148 self._tracked_modifiers[modifier_name] = not self._tracked_modifiers[modifier_name]
149 else:
150 self._tracked_modifiers[modifier_name] = bool(data.keystate) # 1 for keydown, 0 for keyup
151 elif data.keystate == 1:
152 self.key_input(data.scancode)
153
154 except Exception as err: # noqa: BLE001
155 _logger.warning(err)
156
157 def _change_keyboard_layout(self, new_layout):
158 """Change the layout of the current device to what is specified in
159 new_layout.
160
161 Args:
162 new_layout (dict): A dict containing two keys:
163 - layout (str): The layout code
164 - variant (str): An optional key to represent the variant of the
165 selected layout
166 """
167 if hasattr(self, 'keyboard_layout'):
168 KeyboardUSBDriver.keyboard_layout_groups.remove(self.keyboard_layout)
169
170 if new_layout:
171 self.keyboard_layout = new_layout.get('layout') or 'us'
172 if new_layout.get('variant'):
173 self.keyboard_layout += "(%s)" % new_layout['variant']
174 else:
175 self.keyboard_layout = 'us'
176
177 KeyboardUSBDriver.keyboard_layout_groups.append(self.keyboard_layout)
178 subprocess.call(["setxkbmap", "-display", ":0.0", ",".join(KeyboardUSBDriver.keyboard_layout_groups)])
179
180 # Close then re-open display to refresh the mapping
181 xlib.XCloseDisplay(KeyboardUSBDriver.display)
182 KeyboardUSBDriver.display = xlib.XOpenDisplay(bytes(":0.0", "utf-8"))
183
184 def save_layout(self, layout):
185 """Save the layout to a file on the box to read it when restarting it.
186 We need that in order to keep the selected layout after a reboot.
187
188 Args:
189 new_layout (dict): A dict containing two keys:
190 - layout (str): The layout code
191 - variant (str): An optional key to represent the variant of the
192 selected layout
193 """
194 file_path = helpers.path_file('odoo-keyboard-layouts.conf')
195 if file_path.exists():
196 data = json.loads(file_path.read_text())
197 else:
198 data = {}
199 data[self.device_identifier] = layout
200 helpers.write_file('odoo-keyboard-layouts.conf', json.dumps(data))
201
202 def load_layout(self):
203 """Read the layout from the saved filed and set it as current layout.
204 If no file or no layout is found we use 'us' by default.
205 """
206 file_path = helpers.path_file('odoo-keyboard-layouts.conf')
207 if file_path.exists():
208 data = json.loads(file_path.read_text())
209 layout = data.get(self.device_identifier, {'layout': 'us'})
210 else:
211 layout = {'layout': 'us'}
212 self._change_keyboard_layout(layout)
213
214 def _action_default(self, data):
215 self.data['value'] = ''
216
217 def _is_scanner(self):
218 """Read the device type from the saved filed and set it as current type.
219 If no file or no device type is found we try to detect it automatically.
220 """
221 device_name = self.device_name.lower()
222 scanner_name = ['barcode', 'scanner', 'reader']
223 is_scanner = any(x in device_name for x in scanner_name) or self.dev.interface_protocol == '0'
224
225 file_path = helpers.path_file('odoo-keyboard-is-scanner.conf')
226 if file_path.exists():
227 data = json.loads(file_path.read_text())
228 is_scanner = data.get(self.device_identifier, {}).get('is_scanner', is_scanner)
229 return is_scanner
230
231 def _keyboard_input(self, scancode):
232 """Deal with a keyboard input. Send the character corresponding to the
233 pressed key represented by its scancode to the connected Odoo instance.
234
235 Args:
236 scancode (int): The scancode of the pressed key.
237 """
238 self.data['value'] = self._scancode_to_char(scancode)
239 if self.data['value']:
240 event_manager.device_changed(self)
241
242 def _barcode_scanner_input(self, scancode):
243 """Deal with a barcode scanner input. Add the new character scanned to
244 the current barcode or complete the barcode if "Return" is pressed.
245 When a barcode is completed, two tasks are performed:
246 - Send a device_changed update to the event manager to notify the
247 listeners that the value has changed (used in Enterprise).
248 - Add the barcode to the list barcodes that are being queried in
249 Community.
250
251 Args:
252 scancode (int): The scancode of the pressed key.
253 """
254 if scancode == 28: # Return
255 self.data['value'] = self._current_barcode
256 event_manager.device_changed(self)
257 self._barcodes.put((time.time(), self._current_barcode))
258 self._current_barcode = ''
259 else:
260 self._current_barcode += self._scancode_to_char(scancode)
261
262 def _save_is_scanner(self, data):
263 """Save the type of device.
264 We need that in order to keep the selected type of device after a reboot.
265 """
266 is_scanner = {'is_scanner': data.get('is_scanner')}
267 file_path = helpers.path_file('odoo-keyboard-is-scanner.conf')
268 if file_path.exists():
269 data = json.loads(file_path.read_text())
270 else:
271 data = {}
272 data[self.device_identifier] = is_scanner
273 helpers.write_file('odoo-keyboard-is-scanner.conf', json.dumps(data))
274 self._set_device_type('scanner') if is_scanner.get('is_scanner') else self._set_device_type()
275
276 def _update_layout(self, data):
277 layout = {
278 'layout': data.get('layout'),
279 'variant': data.get('variant'),
280 }
281 self._change_keyboard_layout(layout)
282 self.save_layout(layout)
283
284 def _set_device_type(self, device_type='keyboard'):
285 """Modify the device type between 'keyboard' and 'scanner'
286
287 Args:
288 type (string): Type wanted to switch
289 """
290 if device_type == 'scanner':
291 self.device_type = 'scanner'
292 self.key_input = self._barcode_scanner_input
293 self._barcodes = Queue()
294 self._current_barcode = ''
295 for device in self.input_devices:
296 device.grab()
297 self.read_barcode_lock = Lock()
298 else:
299 self.device_type = 'keyboard'
300 self.key_input = self._keyboard_input
301 self.load_layout()
302
303 def _scancode_to_char(self, scancode):
304 """Translate a received scancode to a character depending on the
305 selected keyboard layout and the current state of the keyboard's
306 modifiers.
307
308 Args:
309 scancode (int): The scancode of the pressed key, to be translated to
310 a character
311
312 Returns:
313 str: The translated scancode.
314 """
315 # Scancode -> Keysym : Depends on the keyboard layout
316 group = KeyboardUSBDriver.keyboard_layout_groups.index(self.keyboard_layout)
317 modifiers = self._get_active_modifiers(scancode)
318 keysym = ctypes.c_int(xlib.XkbKeycodeToKeysym(KeyboardUSBDriver.display, scancode + 8, group, modifiers))
319
320 # Translate Keysym to a character
321 key_pressed = ctypes.create_string_buffer(5)
322 xlib.XkbTranslateKeySym(KeyboardUSBDriver.display, ctypes.byref(keysym), 0, ctypes.byref(key_pressed), 5, ctypes.byref(ctypes.c_int()))
323 if key_pressed.value:
324 return key_pressed.value.decode('utf-8')
325 return ''
326
327 def _get_active_modifiers(self, scancode):
328 """Get the state of currently active modifiers.
329
330 Args:
331 scancode (int): The scancode of the key being translated
332
333 Returns:
334 int: The current state of the modifiers:
335 0 -- Lowercase
336 1 -- Highercase or (NumLock + key pressed on keypad)
337 2 -- AltGr
338 3 -- Highercase + AltGr
339 """
340 modifiers = 0
341 uppercase = (self._tracked_modifiers['right_shift'] or self._tracked_modifiers['left_shift']) ^ self._tracked_modifiers['caps_lock']
342 if uppercase or (scancode in [71, 72, 73, 75, 76, 77, 79, 80, 81, 82, 83] and self._tracked_modifiers['num_lock']):
343 modifiers += 1
344
345 if self._tracked_modifiers['alt_gr']:
346 modifiers += 2
347
348 return modifiers
349
350 def read_next_barcode(self):
351 """Get the value of the last barcode that was scanned but not sent yet
352 and not older than 5 seconds. This function is used in Community, when
353 we don't have access to the IoTLongpolling.
354
355 Returns:
356 str: The next barcode to be read or an empty string.
357 """
358
359 # Previous query still running, stop it by sending a fake barcode
360 if self.read_barcode_lock.locked():
361 self._barcodes.put((time.time(), ""))
362
363 with self.read_barcode_lock:
364 try:
365 timestamp, barcode = self._barcodes.get(True, 55)
366 if timestamp > time.time() - 5:
367 return barcode
368 except Empty:
369 return ''
370
371
372 proxy_drivers['scanner'] = KeyboardUSBDriver
373
374
375 class KeyboardUSBController(http.Controller):
376 @route.iot_route('/hw_proxy/scanner', type='jsonrpc', cors='*')
377 def get_barcode(self):
378 scanners = [iot_devices[d] for d in iot_devices if iot_devices[d].device_type == "scanner"]
379 if scanners:
380 return scanners[0].read_next_barcode()
381 time.sleep(5)
382 return None