processing udc state

This commit is contained in:
Devaev Maxim 2020-10-03 09:58:15 +03:00
parent 971eb1c203
commit 877a0b8441
4 changed files with 111 additions and 16 deletions

View File

@ -56,12 +56,16 @@ def main(argv: Optional[List[str]]=None) -> None:
msd_kwargs = config.kvmd.msd._unpack(ignore=["type"]) msd_kwargs = config.kvmd.msd._unpack(ignore=["type"])
if config.kvmd.msd.type == "otg": if config.kvmd.msd.type == "otg":
msd_kwargs["gadget"] = config.otg.gadget # XXX: Small crutch to pass gadget name to plugin msd_kwargs["gadget"] = config.otg.gadget # XXX: Small crutch to pass gadget name to the plugin
hid_kwargs = config.kvmd.hid._unpack(ignore=["type", "keymap"])
if config.kvmd.hid.type == "otg":
hid_kwargs["udc"] = config.otg.udc # XXX: Small crutch to pass UDC to the plugin
global_config = config global_config = config
config = config.kvmd config = config.kvmd
hid = get_hid_class(config.hid.type)(**config.hid._unpack(ignore=["type", "keymap"])) hid = get_hid_class(config.hid.type)(**hid_kwargs)
streamer = Streamer(**config.streamer._unpack(ignore=["forever"])) streamer = Streamer(**config.streamer._unpack(ignore=["forever"]))
KvmdServer( KvmdServer(

View File

@ -37,6 +37,7 @@ from ....validators.os import valid_abs_path
from .. import BaseHid from .. import BaseHid
from .usb import UsbDeviceController
from .keyboard import KeyboardProcess from .keyboard import KeyboardProcess
from .mouse import MouseProcess from .mouse import MouseProcess
@ -48,12 +49,15 @@ class Plugin(BaseHid):
keyboard: Dict[str, Any], keyboard: Dict[str, Any],
mouse: Dict[str, Any], mouse: Dict[str, Any],
noop: bool, noop: bool,
udc: str, # XXX: Not from options, see /kvmd/apps/kvmd/__init__.py for details
) -> None: ) -> None:
self.__notifier = aiomulti.AioProcessNotifier() self.__notifier = aiomulti.AioProcessNotifier()
self.__keyboard_proc = KeyboardProcess(noop=noop, notifier=self.__notifier, **keyboard) self.__udc = UsbDeviceController(udc)
self.__mouse_proc = MouseProcess(noop=noop, notifier=self.__notifier, **mouse)
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 @classmethod
def get_plugin_options(cls) -> Dict: def get_plugin_options(cls) -> Dict:
@ -74,6 +78,7 @@ class Plugin(BaseHid):
} }
def sysprep(self) -> None: def sysprep(self) -> None:
self.__udc.find()
self.__keyboard_proc.start() self.__keyboard_proc.start()
self.__mouse_proc.start() self.__mouse_proc.start()

View File

@ -35,6 +35,8 @@ from ....logging import get_logger
from .... import aiomulti from .... import aiomulti
from .... import aioproc from .... import aioproc
from .usb import UsbDeviceController
# ===== # =====
class BaseEvent: class BaseEvent:
@ -42,13 +44,15 @@ class BaseEvent:
class BaseDeviceProcess(multiprocessing.Process): # pylint: disable=too-many-instance-attributes class BaseDeviceProcess(multiprocessing.Process): # pylint: disable=too-many-instance-attributes
def __init__( def __init__( # pylint: disable=too-many-arguments
self, self,
name: str, name: str,
read_size: int, read_size: int,
initial_state: Dict, initial_state: Dict,
notifier: aiomulti.AioProcessNotifier, notifier: aiomulti.AioProcessNotifier,
udc: UsbDeviceController,
device_path: str, device_path: str,
select_timeout: float, select_timeout: float,
write_retries: int, write_retries: int,
@ -61,6 +65,8 @@ class BaseDeviceProcess(multiprocessing.Process): # pylint: disable=too-many-in
self.__name = name self.__name = name
self.__read_size = read_size self.__read_size = read_size
self.__udc = udc
self.__device_path = device_path self.__device_path = device_path
self.__select_timeout = select_timeout self.__select_timeout = select_timeout
self.__write_retries = write_retries self.__write_retries = write_retries
@ -87,7 +93,8 @@ class BaseDeviceProcess(multiprocessing.Process): # pylint: disable=too-many-in
try: try:
event: BaseEvent = self.__events_queue.get(timeout=0.1) event: BaseEvent = self.__events_queue.get(timeout=0.1)
except queue.Empty: except queue.Empty:
pass if not self.__udc.can_operate():
self.__close_device()
else: else:
self._process_event(event) self._process_event(event)
except Exception: except Exception:
@ -216,16 +223,19 @@ class BaseDeviceProcess(multiprocessing.Process): # pylint: disable=too-many-in
logger = get_logger() logger = get_logger()
if self.__fd < 0: if self.__fd < 0:
try: if self.__udc.can_operate():
flags = os.O_NONBLOCK try:
flags |= (os.O_RDWR if self.__read_size else os.O_WRONLY) flags = os.O_NONBLOCK
self.__fd = os.open(self.__device_path, flags) flags |= (os.O_RDWR if self.__read_size else os.O_WRONLY)
except FileNotFoundError: self.__fd = os.open(self.__device_path, flags)
logger.error("Missing HID-%s device: %s", self.__name, self.__device_path) except FileNotFoundError:
time.sleep(self.__select_timeout) logger.error("Missing HID-%s device: %s", self.__name, self.__device_path)
except Exception as err: time.sleep(self.__select_timeout)
logger.error("Can't open HID-%s device: %s: %s: %s", except Exception as err:
self.__name, self.__device_path, type(err).__name__, 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) time.sleep(self.__select_timeout)
if self.__fd >= 0: if self.__fd >= 0:

View File

@ -0,0 +1,76 @@
# ========================================================================== #
# #
# KVMD - The main Pi-KVM daemon. #
# #
# Copyright (C) 2018 Maxim Devaev <mdevaev@gmail.com> #
# #
# 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 # При ошибке лучше прикинуться работающим, мало ли что