summaryrefslogtreecommitdiff
path: root/kvmd/plugins/hid
diff options
context:
space:
mode:
authorDevaev Maxim <[email protected]>2020-10-03 09:58:15 +0300
committerDevaev Maxim <[email protected]>2020-10-03 09:58:15 +0300
commit877a0b844100c51ff96f19f4a00abed02dadec89 (patch)
tree0c4b068707931926ecdaab6a9563be9330616b34 /kvmd/plugins/hid
parent971eb1c203e5dfacd55b7c1e215071b3ebd0c153 (diff)
processing udc state
Diffstat (limited to 'kvmd/plugins/hid')
-rw-r--r--kvmd/plugins/hid/otg/__init__.py9
-rw-r--r--kvmd/plugins/hid/otg/device.py34
-rw-r--r--kvmd/plugins/hid/otg/usb.py76
3 files changed, 105 insertions, 14 deletions
diff --git a/kvmd/plugins/hid/otg/__init__.py b/kvmd/plugins/hid/otg/__init__.py
index adbabfb9..95dd34cd 100644
--- a/kvmd/plugins/hid/otg/__init__.py
+++ b/kvmd/plugins/hid/otg/__init__.py
@@ -37,6 +37,7 @@ from ....validators.os import valid_abs_path
from .. import BaseHid
+from .usb import UsbDeviceController
from .keyboard import KeyboardProcess
from .mouse import MouseProcess
@@ -48,12 +49,15 @@ class Plugin(BaseHid):
keyboard: Dict[str, Any],
mouse: Dict[str, Any],
noop: bool,
+ udc: str, # XXX: Not from options, see /kvmd/apps/kvmd/__init__.py for details
) -> None:
self.__notifier = aiomulti.AioProcessNotifier()
- self.__keyboard_proc = KeyboardProcess(noop=noop, notifier=self.__notifier, **keyboard)
- self.__mouse_proc = MouseProcess(noop=noop, notifier=self.__notifier, **mouse)
+ self.__udc = UsbDeviceController(udc)
+
+ self.__keyboard_proc = KeyboardProcess(udc=self.__udc, noop=noop, notifier=self.__notifier, **keyboard)
+ self.__mouse_proc = MouseProcess(udc=self.__udc, noop=noop, notifier=self.__notifier, **mouse)
@classmethod
def get_plugin_options(cls) -> Dict:
@@ -74,6 +78,7 @@ class Plugin(BaseHid):
}
def sysprep(self) -> None:
+ self.__udc.find()
self.__keyboard_proc.start()
self.__mouse_proc.start()
diff --git a/kvmd/plugins/hid/otg/device.py b/kvmd/plugins/hid/otg/device.py
index e44efd5e..08777293 100644
--- a/kvmd/plugins/hid/otg/device.py
+++ b/kvmd/plugins/hid/otg/device.py
@@ -35,6 +35,8 @@ from ....logging import get_logger
from .... import aiomulti
from .... import aioproc
+from .usb import UsbDeviceController
+
# =====
class BaseEvent:
@@ -42,13 +44,15 @@ class BaseEvent:
class BaseDeviceProcess(multiprocessing.Process): # pylint: disable=too-many-instance-attributes
- def __init__(
+ def __init__( # pylint: disable=too-many-arguments
self,
name: str,
read_size: int,
initial_state: Dict,
notifier: aiomulti.AioProcessNotifier,
+ udc: UsbDeviceController,
+
device_path: str,
select_timeout: float,
write_retries: int,
@@ -61,6 +65,8 @@ class BaseDeviceProcess(multiprocessing.Process): # pylint: disable=too-many-in
self.__name = name
self.__read_size = read_size
+ self.__udc = udc
+
self.__device_path = device_path
self.__select_timeout = select_timeout
self.__write_retries = write_retries
@@ -87,7 +93,8 @@ class BaseDeviceProcess(multiprocessing.Process): # pylint: disable=too-many-in
try:
event: BaseEvent = self.__events_queue.get(timeout=0.1)
except queue.Empty:
- pass
+ if not self.__udc.can_operate():
+ self.__close_device()
else:
self._process_event(event)
except Exception:
@@ -216,16 +223,19 @@ class BaseDeviceProcess(multiprocessing.Process): # pylint: disable=too-many-in
logger = get_logger()
if self.__fd < 0:
- try:
- flags = os.O_NONBLOCK
- flags |= (os.O_RDWR if self.__read_size else os.O_WRONLY)
- self.__fd = os.open(self.__device_path, flags)
- except FileNotFoundError:
- logger.error("Missing HID-%s device: %s", self.__name, self.__device_path)
- time.sleep(self.__select_timeout)
- except Exception as err:
- logger.error("Can't open HID-%s device: %s: %s: %s",
- self.__name, self.__device_path, type(err).__name__, err)
+ if self.__udc.can_operate():
+ try:
+ flags = os.O_NONBLOCK
+ flags |= (os.O_RDWR if self.__read_size else os.O_WRONLY)
+ self.__fd = os.open(self.__device_path, flags)
+ except FileNotFoundError:
+ logger.error("Missing HID-%s device: %s", self.__name, self.__device_path)
+ time.sleep(self.__select_timeout)
+ except Exception as err:
+ logger.error("Can't open HID-%s device: %s: %s: %s",
+ self.__name, self.__device_path, type(err).__name__, err)
+ time.sleep(self.__select_timeout)
+ else:
time.sleep(self.__select_timeout)
if self.__fd >= 0:
diff --git a/kvmd/plugins/hid/otg/usb.py b/kvmd/plugins/hid/otg/usb.py
new file mode 100644
index 00000000..35800b0d
--- /dev/null
+++ b/kvmd/plugins/hid/otg/usb.py
@@ -0,0 +1,76 @@
+# ========================================================================== #
+# #
+# KVMD - The main Pi-KVM daemon. #
+# #
+# Copyright (C) 2018 Maxim Devaev <[email protected]> #
+# #
+# This program is free software: you can redistribute it and/or modify #
+# it under the terms of the GNU General Public License as published by #
+# the Free Software Foundation, either version 3 of the License, or #
+# (at your option) any later version. #
+# #
+# This program is distributed in the hope that it will be useful, #
+# but WITHOUT ANY WARRANTY; without even the implied warranty of #
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
+# GNU General Public License for more details. #
+# #
+# You should have received a copy of the GNU General Public License #
+# along with this program. If not, see <https://www.gnu.org/licenses/>. #
+# #
+# ========================================================================== #
+
+
+import os
+
+from ....logging import get_logger
+
+from .... import env
+
+
+# =====
+class UsbDeviceController:
+ # Проблема в том, что устройство может отвечать EAGAIN или ESHUTDOWN,
+ # если оно было отключено физически. См:
+ # - https://github.com/raspberrypi/linux/issues/3870
+ # - https://github.com/raspberrypi/linux/pull/3151
+ # Так что нам нужно проверять состояние контроллера, чтобы не спамить
+ # в устройство и отслеживать его состояние.
+
+ def __init__(self, udc: str) -> None:
+ self.__udc = udc
+ self.__state_path = ""
+
+ def find(self) -> None:
+ logger = get_logger()
+
+ path = f"{env.SYSFS_PREFIX}/sys/class/udc"
+ try:
+ candidates = sorted(os.listdir(path))
+ except Exception as err:
+ logger.error("Can't list %s: %s: %s", path, type(err).__name__, err)
+ return
+
+ udc = ""
+ if not self.__udc:
+ if len(candidates) == 0:
+ logger.warning("Can't find any UDC: ignored")
+ else:
+ udc = candidates[0]
+ elif self.__udc not in candidates:
+ logger.warning("Can't find selected UDC: %s: ignored", self.__udc)
+ else:
+ udc = self.__udc
+
+ if udc:
+ get_logger().info("Using UDC %s", udc)
+ self.__state_path = os.path.join(path, udc, "state")
+
+ def can_operate(self) -> bool:
+ if self.__state_path:
+ try:
+ with open(self.__state_path, "r") as state_file:
+ # https://www.maxlinear.com/Files/Documents/an213_033111.pdf
+ return (state_file.read().strip().lower() == "configured")
+ except Exception:
+ pass
+ return True # При ошибке лучше прикинуться работающим, мало ли что