new typing style

This commit is contained in:
Maxim Devaev
2022-09-04 18:08:40 +03:00
parent 4b75221e94
commit ee3e224e39
129 changed files with 593 additions and 941 deletions

View File

@@ -20,12 +20,8 @@
# ========================================================================== #
from typing import Tuple
from typing import Dict
from typing import Iterable
from typing import AsyncGenerator
from typing import Type
from typing import Optional
from .. import BasePlugin
from .. import get_plugin_class
@@ -36,10 +32,10 @@ class BaseHid(BasePlugin):
def sysprep(self) -> None:
raise NotImplementedError
async def get_state(self) -> Dict:
async def get_state(self) -> dict:
raise NotImplementedError
async def poll_state(self) -> AsyncGenerator[Dict, None]:
async def poll_state(self) -> AsyncGenerator[dict, None]:
yield {}
raise NotImplementedError
@@ -51,7 +47,7 @@ class BaseHid(BasePlugin):
# =====
def send_key_events(self, keys: Iterable[Tuple[str, bool]]) -> None:
def send_key_events(self, keys: Iterable[tuple[str, bool]]) -> None:
raise NotImplementedError
def send_mouse_button_event(self, button: str, state: bool) -> None:
@@ -68,7 +64,7 @@ class BaseHid(BasePlugin):
def send_mouse_wheel_event(self, delta_x: int, delta_y: int) -> None:
raise NotImplementedError
def set_params(self, keyboard_output: Optional[str]=None, mouse_output: Optional[str]=None) -> None:
def set_params(self, keyboard_output: (str | None)=None, mouse_output: (str | None)=None) -> None:
_ = keyboard_output
_ = mouse_output
@@ -80,5 +76,5 @@ class BaseHid(BasePlugin):
# =====
def get_hid_class(name: str) -> Type[BaseHid]:
def get_hid_class(name: str) -> type[BaseHid]:
return get_plugin_class("hid", name) # type: ignore

View File

@@ -25,13 +25,9 @@ import contextlib
import queue
import time
from typing import Tuple
from typing import List
from typing import Dict
from typing import Iterable
from typing import Generator
from typing import AsyncGenerator
from typing import Optional
from ....logging import get_logger
@@ -144,7 +140,7 @@ class BaseMcuHid(BaseHid, multiprocessing.Process): # pylint: disable=too-many-
self.__stop_event = multiprocessing.Event()
@classmethod
def get_plugin_options(cls) -> Dict:
def get_plugin_options(cls) -> dict:
return {
"gpio_device": Option("/dev/gpiochip0", type=valid_abs_path, unpack_as="gpio_device_path"),
"reset_pin": Option(4, type=valid_gpio_pin_optional),
@@ -162,7 +158,7 @@ class BaseMcuHid(BaseHid, multiprocessing.Process): # pylint: disable=too-many-
get_logger(0).info("Starting HID daemon ...")
self.start()
async def get_state(self) -> Dict:
async def get_state(self) -> dict:
state = await self.__state_flags.get()
online = bool(state["online"])
pong = (state["status"] >> 16) & 0xFF
@@ -174,8 +170,8 @@ class BaseMcuHid(BaseHid, multiprocessing.Process): # pylint: disable=too-many-
if online and active_mouse in ["usb_rel", "ps2"]:
absolute = False
keyboard_outputs: Dict = {"available": [], "active": ""}
mouse_outputs: Dict = {"available": [], "active": ""}
keyboard_outputs: dict = {"available": [], "active": ""}
mouse_outputs: dict = {"available": [], "active": ""}
if outputs1 & 0b10000000: # Dynamic
if outputs2 & 0b00000001: # USB
@@ -222,8 +218,8 @@ class BaseMcuHid(BaseHid, multiprocessing.Process): # pylint: disable=too-many-
},
}
async def poll_state(self) -> AsyncGenerator[Dict, None]:
prev_state: Dict = {}
async def poll_state(self) -> AsyncGenerator[dict, None]:
prev_state: dict = {}
while True:
state = await self.get_state()
if state != prev_state:
@@ -244,7 +240,7 @@ class BaseMcuHid(BaseHid, multiprocessing.Process): # pylint: disable=too-many-
# =====
def send_key_events(self, keys: Iterable[Tuple[str, bool]]) -> None:
def send_key_events(self, keys: Iterable[tuple[str, bool]]) -> None:
for (key, state) in keys:
self.__queue_event(KeyEvent(key, state))
@@ -260,8 +256,8 @@ class BaseMcuHid(BaseHid, multiprocessing.Process): # pylint: disable=too-many-
def send_mouse_wheel_event(self, delta_x: int, delta_y: int) -> None:
self.__queue_event(MouseWheelEvent(delta_x, delta_y))
def set_params(self, keyboard_output: Optional[str]=None, mouse_output: Optional[str]=None) -> None:
events: List[BaseEvent] = []
def set_params(self, keyboard_output: (str | None)=None, mouse_output: (str | None)=None) -> None:
events: list[BaseEvent] = []
if keyboard_output is not None:
events.append(SetKeyboardOutputEvent(keyboard_output))
if mouse_output is not None:
@@ -346,7 +342,7 @@ class BaseMcuHid(BaseHid, multiprocessing.Process): # pylint: disable=too-many-
def __process_request(self, conn: BasePhyConnection, request: bytes) -> bool: # pylint: disable=too-many-branches
logger = get_logger()
error_messages: List[str] = []
error_messages: list[str] = []
live_log_errors = False
common_retries = self.__common_retries

View File

@@ -23,9 +23,6 @@
import types
import time
from typing import Type
from typing import Optional
import gpiod
from ....logging import get_logger
@@ -46,8 +43,8 @@ class Gpio:
self.__reset_inverted = reset_inverted
self.__reset_delay = reset_delay
self.__chip: Optional[gpiod.Chip] = None
self.__reset_line: Optional[gpiod.Line] = None
self.__chip: (gpiod.Chip | None) = None
self.__reset_line: (gpiod.Line | None) = None
def __enter__(self) -> None:
if self.__reset_pin >= 0:
@@ -59,7 +56,7 @@ class Gpio:
def __exit__(
self,
_exc_type: Type[BaseException],
_exc_type: type[BaseException],
_exc: BaseException,
_tb: types.TracebackType,
) -> None:

View File

@@ -23,11 +23,8 @@
import multiprocessing
import time
from typing import Tuple
from typing import Dict
from typing import Iterable
from typing import AsyncGenerator
from typing import Optional
from ....logging import get_logger
@@ -81,7 +78,7 @@ class Plugin(BaseHid): # pylint: disable=too-many-instance-attributes
select_timeout: float,
) -> None:
self.__proc: Optional[multiprocessing.Process] = None
self.__proc: (multiprocessing.Process | None) = None
self.__stop_event = multiprocessing.Event()
self.__notifier = aiomulti.AioProcessNotifier()
@@ -104,7 +101,7 @@ class Plugin(BaseHid): # pylint: disable=too-many-instance-attributes
)
@classmethod
def get_plugin_options(cls) -> Dict:
def get_plugin_options(cls) -> dict:
return {
"manufacturer": Option("PiKVM"),
"product": Option("HID Device"),
@@ -128,9 +125,9 @@ class Plugin(BaseHid): # pylint: disable=too-many-instance-attributes
self.__proc = multiprocessing.Process(target=self.__server_worker, daemon=True)
self.__proc.start()
async def get_state(self) -> Dict:
async def get_state(self) -> dict:
state = await self.__server.get_state()
outputs: Dict = {"available": [], "active": ""}
outputs: dict = {"available": [], "active": ""}
return {
"online": True,
"busy": False,
@@ -151,8 +148,8 @@ class Plugin(BaseHid): # pylint: disable=too-many-instance-attributes
},
}
async def poll_state(self) -> AsyncGenerator[Dict, None]:
prev_state: Dict = {}
async def poll_state(self) -> AsyncGenerator[dict, None]:
prev_state: dict = {}
while True:
state = await self.get_state()
if state != prev_state:
@@ -175,7 +172,7 @@ class Plugin(BaseHid): # pylint: disable=too-many-instance-attributes
# =====
def send_key_events(self, keys: Iterable[Tuple[str, bool]]) -> None:
def send_key_events(self, keys: Iterable[tuple[str, bool]]) -> None:
for (key, state) in keys:
self.__server.queue_event(make_keyboard_event(key, state))

View File

@@ -22,8 +22,6 @@
import types
from typing import Type
from typing import Optional
from typing import Any
import dbus
@@ -56,7 +54,7 @@ class BluezIface:
self.__pairing_required = pairing_required
self.__auth_required = auth_required
self.__bus: Optional[dbus.SystemBus] = None
self.__bus: (dbus.SystemBus | None) = None
def get_address(self) -> str:
return self.__get_prop("Address")
@@ -100,7 +98,7 @@ class BluezIface:
def __exit__(
self,
_exc_type: Type[BaseException],
_exc_type: type[BaseException],
_exc: BaseException,
_tb: types.TracebackType,
) -> None:

View File

@@ -29,11 +29,7 @@ import contextlib
import queue
from typing import Literal
from typing import List
from typing import Dict
from typing import Set
from typing import Generator
from typing import Optional
from ....logging import get_logger
@@ -72,8 +68,8 @@ _SockAttrT = Literal["ctl_sock", "int_sock"]
@dataclasses.dataclass
class _BtClient:
addr: str
ctl_sock: Optional[socket.socket] = None
int_sock: Optional[socket.socket] = None
ctl_sock: (socket.socket | None) = None
int_sock: (socket.socket | None) = None
# =====
@@ -104,8 +100,8 @@ class BtServer: # pylint: disable=too-many-instance-attributes
self.__stop_event = stop_event
self.__clients: Dict[str, _BtClient] = {}
self.__to_read: Set[socket.socket] = set()
self.__clients: dict[str, _BtClient] = {}
self.__to_read: set[socket.socket] = set()
self.__events_queue: "multiprocessing.Queue[BaseEvent]" = multiprocessing.Queue()
@@ -115,8 +111,8 @@ class BtServer: # pylint: disable=too-many-instance-attributes
"scroll": False,
"num": False,
}, notifier)
self.__modifiers: Set[UsbKey] = set()
self.__keys: List[Optional[UsbKey]] = [None] * 6
self.__modifiers: set[UsbKey] = set()
self.__keys: list[UsbKey | None] = [None] * 6
self.__mouse_buttons = 0
def run(self) -> None:
@@ -132,7 +128,7 @@ class BtServer: # pylint: disable=too-many-instance-attributes
self.__close_all_clients(no_change_public=True)
self.__set_public(False)
async def get_state(self) -> Dict:
async def get_state(self) -> dict:
return (await self.__state_flags.get())
def queue_event(self, event: BaseEvent) -> None:

View File

@@ -20,11 +20,8 @@
# ========================================================================== #
from typing import Tuple
from typing import Dict
from typing import Iterable
from typing import AsyncGenerator
from typing import Optional
from typing import Any
from ....logging import get_logger
@@ -49,9 +46,9 @@ from .mouse import MouseProcess
class Plugin(BaseHid): # pylint: disable=too-many-instance-attributes
def __init__( # pylint: disable=super-init-not-called
self,
keyboard: Dict[str, Any],
mouse: Dict[str, Any],
mouse_alt: Dict[str, Any],
keyboard: dict[str, Any],
mouse: dict[str, Any],
mouse_alt: dict[str, Any],
noop: bool,
udc: str, # XXX: Not from options, see /kvmd/apps/kvmd/__init__.py for details
) -> None:
@@ -66,8 +63,8 @@ class Plugin(BaseHid): # pylint: disable=too-many-instance-attributes
self.__keyboard_proc = KeyboardProcess(**common, **keyboard)
self.__mouse_current = self.__mouse_proc = MouseProcess(**common, **mouse)
self.__mouse_alt_proc: Optional[MouseProcess] = None
self.__mouses: Dict[str, MouseProcess] = {}
self.__mouse_alt_proc: (MouseProcess | None) = None
self.__mouses: dict[str, MouseProcess] = {}
if mouse_alt["device_path"]:
self.__mouse_alt_proc = MouseProcess(
absolute=(not mouse["absolute"]),
@@ -84,7 +81,7 @@ class Plugin(BaseHid): # pylint: disable=too-many-instance-attributes
self.__mouses["usb_win98"] = self.__mouses["usb"]
@classmethod
def get_plugin_options(cls) -> Dict:
def get_plugin_options(cls) -> dict:
return {
"keyboard": {
"device": Option("/dev/kvmd-hid-keyboard", type=valid_abs_path, unpack_as="device_path"),
@@ -121,7 +118,7 @@ class Plugin(BaseHid): # pylint: disable=too-many-instance-attributes
if self.__mouse_alt_proc:
self.__mouse_alt_proc.start(udc)
async def get_state(self) -> Dict:
async def get_state(self) -> dict:
keyboard_state = await self.__keyboard_proc.get_state()
mouse_state = await self.__mouse_current.get_state()
return {
@@ -146,8 +143,8 @@ class Plugin(BaseHid): # pylint: disable=too-many-instance-attributes
},
}
async def poll_state(self) -> AsyncGenerator[Dict, None]:
prev_state: Dict = {}
async def poll_state(self) -> AsyncGenerator[dict, None]:
prev_state: dict = {}
while True:
state = await self.get_state()
if state != prev_state:
@@ -173,7 +170,7 @@ class Plugin(BaseHid): # pylint: disable=too-many-instance-attributes
# =====
def send_key_events(self, keys: Iterable[Tuple[str, bool]]) -> None:
def send_key_events(self, keys: Iterable[tuple[str, bool]]) -> None:
self.__keyboard_proc.send_key_events(keys)
def send_mouse_button_event(self, button: str, state: bool) -> None:
@@ -188,7 +185,7 @@ class Plugin(BaseHid): # pylint: disable=too-many-instance-attributes
def send_mouse_wheel_event(self, delta_x: int, delta_y: int) -> None:
self.__mouse_current.send_wheel_event(delta_x, delta_y)
def set_params(self, keyboard_output: Optional[str]=None, mouse_output: Optional[str]=None) -> None:
def set_params(self, keyboard_output: (str | None)=None, mouse_output: (str | None)=None) -> None:
_ = keyboard_output
if mouse_output in self.__mouses and mouse_output != self.__get_current_mouse_mode():
self.__mouse_current.send_clear_event()

View File

@@ -28,9 +28,7 @@ import errno
import logging
import time
from typing import Dict
from typing import Generator
from typing import Optional
from ....logging import get_logger
@@ -48,7 +46,7 @@ class BaseDeviceProcess(multiprocessing.Process): # pylint: disable=too-many-in
self,
name: str,
read_size: int,
initial_state: Dict,
initial_state: dict,
notifier: aiomulti.AioProcessNotifier,
device_path: str,
@@ -76,7 +74,7 @@ class BaseDeviceProcess(multiprocessing.Process): # pylint: disable=too-many-in
self.__stop_event = multiprocessing.Event()
self.__no_device_reported = False
self.__logger: Optional[logging.Logger] = None
self.__logger: (logging.Logger | None) = None
def start(self, udc: str) -> None: # type: ignore # pylint: disable=arguments-differ
self.__udc_state_path = usb.get_udc_path(udc, usb.U_STATE)
@@ -125,7 +123,7 @@ class BaseDeviceProcess(multiprocessing.Process): # pylint: disable=too-many-in
self.__close_device()
async def get_state(self) -> Dict:
async def get_state(self) -> dict:
return (await self.__state_flags.get())
# =====

View File

@@ -23,11 +23,6 @@
import struct
import dataclasses
from typing import List
from typing import Set
from typing import Optional
from typing import Union
from ....keyboard.mappings import UsbKey
from ....keyboard.mappings import KEYMAP
@@ -66,7 +61,7 @@ class ModifierEvent(BaseEvent):
assert self.modifier.is_modifier
def make_keyboard_event(key: str, state: bool) -> Union[KeyEvent, ModifierEvent]:
def make_keyboard_event(key: str, state: bool) -> (KeyEvent | ModifierEvent):
usb_key = KEYMAP[key].usb
if usb_key.is_modifier:
return ModifierEvent(usb_key, state)
@@ -87,8 +82,8 @@ def get_led_num(flags: int) -> bool:
def make_keyboard_report(
pressed_modifiers: Set[UsbKey],
pressed_keys: List[Optional[UsbKey]],
pressed_modifiers: set[UsbKey],
pressed_keys: list[UsbKey | None],
) -> bytes:
modifiers = 0
@@ -168,7 +163,7 @@ def make_mouse_report(
buttons: int,
move_x: int,
move_y: int,
wheel_x: Optional[int],
wheel_x: (int | None),
wheel_y: int,
) -> bytes:

View File

@@ -20,12 +20,8 @@
# ========================================================================== #
from typing import Tuple
from typing import List
from typing import Set
from typing import Iterable
from typing import Generator
from typing import Optional
from typing import Any
from ....logging import get_logger
@@ -56,8 +52,8 @@ class KeyboardProcess(BaseDeviceProcess):
**kwargs,
)
self.__pressed_modifiers: Set[UsbKey] = set()
self.__pressed_keys: List[Optional[UsbKey]] = [None] * 6
self.__pressed_modifiers: set[UsbKey] = set()
self.__pressed_keys: list[UsbKey | None] = [None] * 6
def cleanup(self) -> None:
self._stop()
@@ -72,7 +68,7 @@ class KeyboardProcess(BaseDeviceProcess):
self._clear_queue()
self._queue_event(ResetEvent())
def send_key_events(self, keys: Iterable[Tuple[str, bool]]) -> None:
def send_key_events(self, keys: Iterable[tuple[str, bool]]) -> None:
for (key, state) in keys:
self._queue_event(make_keyboard_event(key, state))

View File

@@ -21,7 +21,6 @@
from typing import Generator
from typing import Optional
from typing import Any
from ....logging import get_logger
@@ -145,8 +144,8 @@ class MouseProcess(BaseDeviceProcess):
def __make_report(
self,
relative_event: Optional[MouseRelativeEvent]=None,
wheel_event: Optional[MouseWheelEvent]=None,
relative_event: (MouseRelativeEvent | None)=None,
wheel_event: (MouseWheelEvent | None)=None,
) -> bytes:
if self.__absolute:

View File

@@ -23,7 +23,6 @@
import os
import contextlib
from typing import Dict
from typing import Generator
from typing import Any
@@ -85,21 +84,21 @@ class _SerialPhy(BasePhy):
# =====
class Plugin(BaseMcuHid):
def __init__(self, **kwargs: Any) -> None:
phy_kwargs: Dict = {
phy_kwargs: dict = {
(option.unpack_as or key): kwargs.pop(option.unpack_as or key)
for (key, option) in self.__get_phy_options().items()
}
super().__init__(phy=_SerialPhy(**phy_kwargs), **kwargs)
@classmethod
def get_plugin_options(cls) -> Dict:
def get_plugin_options(cls) -> dict:
return {
**cls.__get_phy_options(),
**BaseMcuHid.get_plugin_options(),
}
@classmethod
def __get_phy_options(cls) -> Dict:
def __get_phy_options(cls) -> dict:
return {
"device": Option("/dev/kvmd-hid", type=valid_abs_path, unpack_as="device_path"),
"speed": Option(115200, type=valid_tty_speed),

View File

@@ -24,11 +24,8 @@ import os
import contextlib
import time
from typing import List
from typing import Dict
from typing import Generator
from typing import Callable
from typing import Optional
from typing import Any
import spidev
@@ -75,7 +72,7 @@ class _SpiPhyConnection(BasePhyConnection):
self.__xfer(request)
response: List[int] = []
response: list[int] = []
deadline_ts = time.monotonic() + self.__read_timeout
found = False
while time.monotonic() < deadline_ts:
@@ -143,7 +140,7 @@ class _SpiPhy(BasePhy): # pylint: disable=too-many-instance-attributes
)
@contextlib.contextmanager
def __sw_cs_connected(self) -> Generator[Optional[gpiod.Line], None, None]:
def __sw_cs_connected(self) -> Generator[(gpiod.Line | None), None, None]:
if self.__sw_cs_pin > 0:
with contextlib.closing(gpiod.Chip(self.__gpio_device_path)) as chip:
line = chip.get_line(self.__sw_cs_pin)
@@ -156,19 +153,19 @@ class _SpiPhy(BasePhy): # pylint: disable=too-many-instance-attributes
# =====
class Plugin(BaseMcuHid):
def __init__(self, **kwargs: Any) -> None:
phy_kwargs: Dict = {key: kwargs.pop(key) for key in self.__get_phy_options()}
phy_kwargs: dict = {key: kwargs.pop(key) for key in self.__get_phy_options()}
phy_kwargs["gpio_device_path"] = kwargs["gpio_device_path"]
super().__init__(phy=_SpiPhy(**phy_kwargs), **kwargs)
@classmethod
def get_plugin_options(cls) -> Dict:
def get_plugin_options(cls) -> dict:
return {
**cls.__get_phy_options(),
**BaseMcuHid.get_plugin_options(),
}
@classmethod
def __get_phy_options(cls) -> Dict:
def __get_phy_options(cls) -> dict:
return {
"bus": Option(-1, type=valid_int_f0),
"chip": Option(-1, type=valid_int_f0),