refactoring

This commit is contained in:
Maxim Devaev
2024-09-18 04:37:43 +03:00
parent 45270a09d7
commit 7a53f14456
83 changed files with 517 additions and 516 deletions

View File

@@ -76,7 +76,7 @@ class Plugin(BaseAtx): # pylint: disable=too-many-instance-attributes
self.__notifier = aiotools.AioNotifier()
self.__region = aiotools.AioExclusiveRegion(AtxIsBusyError, self.__notifier)
self.__line_request: (gpiod.LineRequest | None) = None
self.__line_req: (gpiod.LineRequest | None) = None
self.__reader = aiogp.AioReader(
path=self.__device_path,
@@ -108,8 +108,8 @@ class Plugin(BaseAtx): # pylint: disable=too-many-instance-attributes
}
def sysprep(self) -> None:
assert self.__line_request is None
self.__line_request = gpiod.request_lines(
assert self.__line_req is None
self.__line_req = gpiod.request_lines(
self.__device_path,
consumer="kvmd::atx",
config={
@@ -143,9 +143,9 @@ class Plugin(BaseAtx): # pylint: disable=too-many-instance-attributes
await self.__reader.poll()
async def cleanup(self) -> None:
if self.__line_request:
if self.__line_req:
try:
self.__line_request.release()
self.__line_req.release()
except Exception:
pass
@@ -196,11 +196,11 @@ class Plugin(BaseAtx): # pylint: disable=too-many-instance-attributes
@aiotools.atomic_fg
async def __inner_click(self, name: str, pin: int, delay: float) -> None:
assert self.__line_request
assert self.__line_req
try:
self.__line_request.set_value(pin, gpiod.line.Value(True))
self.__line_req.set_value(pin, gpiod.line.Value(True))
await asyncio.sleep(delay)
finally:
self.__line_request.set_value(pin, gpiod.line.Value(False))
self.__line_req.set_value(pin, gpiod.line.Value(False))
await asyncio.sleep(1)
get_logger(0).info("Clicked ATX button %r", name)

View File

@@ -85,8 +85,8 @@ class Plugin(BaseAuthService):
"User-Agent": htclient.make_user_agent("KVMD"),
"X-KVMD-User": user,
},
) as response:
htclient.raise_not_200(response)
) as resp:
htclient.raise_not_200(resp)
return True
except Exception:
get_logger().exception("Failed HTTP auth request for user %r", user)

View File

@@ -100,10 +100,10 @@ class Plugin(BaseAuthService):
return True
except ldap.INVALID_CREDENTIALS:
pass
except ldap.SERVER_DOWN as err:
get_logger().error("LDAP server is down: %s", tools.efmt(err))
except Exception as err:
get_logger().error("Unexpected LDAP error: %s", tools.efmt(err))
except ldap.SERVER_DOWN as ex:
get_logger().error("LDAP server is down: %s", tools.efmt(ex))
except Exception as ex:
get_logger().error("Unexpected LDAP error: %s", tools.efmt(ex))
finally:
if conn is not None:
try:

View File

@@ -435,10 +435,10 @@ class Plugin(BaseAuthService):
timeout=self.__timeout,
dict=dct,
)
request = client.CreateAuthPacket(code=pyrad.packet.AccessRequest, User_Name=user)
request["User-Password"] = request.PwCrypt(passwd)
response = client.SendPacket(request)
return (response.code == pyrad.packet.AccessAccept)
req = client.CreateAuthPacket(code=pyrad.packet.AccessRequest, User_Name=user)
req["User-Password"] = req.PwCrypt(passwd)
resp = client.SendPacket(req)
return (resp.code == pyrad.packet.AccessAccept)
except Exception:
get_logger().exception("Failed RADIUS auth request for user %r", user)
return False

View File

@@ -91,7 +91,7 @@ class _TempRequestError(_RequestError):
# =====
class BasePhyConnection:
def send(self, request: bytes) -> bytes:
def send(self, req: bytes) -> bytes:
raise NotImplementedError
@@ -374,7 +374,7 @@ class BaseMcuHid(BaseHid, multiprocessing.Process): # pylint: disable=too-many-
self.__set_state_online(False)
return False
def __process_request(self, conn: BasePhyConnection, request: bytes) -> bool: # pylint: disable=too-many-branches
def __process_request(self, conn: BasePhyConnection, req: bytes) -> bool: # pylint: disable=too-many-branches
logger = get_logger()
error_messages: list[str] = []
live_log_errors = False
@@ -384,47 +384,47 @@ class BaseMcuHid(BaseHid, multiprocessing.Process): # pylint: disable=too-many-
error_retval = False
while self.__gpio.is_powered() and common_retries and read_retries:
response = (RESPONSE_LEGACY_OK if self.__noop else conn.send(request))
resp = (RESPONSE_LEGACY_OK if self.__noop else conn.send(req))
try:
if len(response) < 4:
if len(resp) < 4:
read_retries -= 1
raise _TempRequestError(f"No response from HID: request={request!r}")
raise _TempRequestError(f"No response from HID: request={req!r}")
if not check_response(response):
request = REQUEST_REPEAT
if not check_response(resp):
req = REQUEST_REPEAT
raise _TempRequestError("Invalid response CRC; requesting response again ...")
code = response[1]
code = resp[1]
if code == 0x48: # Request timeout # pylint: disable=no-else-raise
raise _TempRequestError(f"Got request timeout from HID: request={request!r}")
raise _TempRequestError(f"Got request timeout from HID: request={req!r}")
elif code == 0x40: # CRC Error
raise _TempRequestError(f"Got CRC error of request from HID: request={request!r}")
raise _TempRequestError(f"Got CRC error of request from HID: request={req!r}")
elif code == 0x45: # Unknown command
raise _PermRequestError(f"HID did not recognize the request={request!r}")
raise _PermRequestError(f"HID did not recognize the request={req!r}")
elif code == 0x24: # Rebooted?
raise _PermRequestError("No previous command state inside HID, seems it was rebooted")
elif code == 0x20: # Legacy done
self.__set_state_online(True)
return True
elif code & 0x80: # Pong/Done with state
self.__set_state_pong(response)
self.__set_state_pong(resp)
return True
raise _TempRequestError(f"Invalid response from HID: request={request!r}, response=0x{response!r}")
raise _TempRequestError(f"Invalid response from HID: request={req!r}, response=0x{resp!r}")
except _RequestError as err:
except _RequestError as ex:
common_retries -= 1
if live_log_errors:
logger.error(err.msg)
logger.error(ex.msg)
else:
error_messages.append(err.msg)
error_messages.append(ex.msg)
if len(error_messages) > self.__errors_threshold:
for msg in error_messages:
logger.error(msg)
error_messages = []
live_log_errors = True
if isinstance(err, _PermRequestError):
if isinstance(ex, _PermRequestError):
error_retval = True
break
@@ -440,7 +440,7 @@ class BaseMcuHid(BaseHid, multiprocessing.Process): # pylint: disable=too-many-
for msg in error_messages:
logger.error(msg)
if not (common_retries and read_retries):
logger.error("Can't process HID request due many errors: %r", request)
logger.error("Can't process HID request due many errors: %r", req)
return error_retval
def __set_state_online(self, online: bool) -> None:
@@ -449,11 +449,11 @@ class BaseMcuHid(BaseHid, multiprocessing.Process): # pylint: disable=too-many-
def __set_state_busy(self, busy: bool) -> None:
self.__state_flags.update(busy=int(busy))
def __set_state_pong(self, response: bytes) -> None:
status = response[1] << 16
if len(response) > 4:
status |= (response[2] << 8) | response[3]
reset_required = (1 if response[1] & 0b01000000 else 0)
def __set_state_pong(self, resp: bytes) -> None:
status = resp[1] << 16
if len(resp) > 4:
status |= (resp[2] << 8) | resp[3]
reset_required = (1 if resp[1] & 0b01000000 else 0)
self.__state_flags.update(online=1, busy=reset_required, status=status)
if reset_required:
if self.__reset_self:

View File

@@ -47,12 +47,12 @@ class Gpio: # pylint: disable=too-many-instance-attributes
self.__reset_inverted = reset_inverted
self.__reset_delay = reset_delay
self.__line_request: (gpiod.LineRequest | None) = None
self.__line_req: (gpiod.LineRequest | None) = None
self.__last_power: (bool | None) = None
def __enter__(self) -> None:
if self.__power_detect_pin >= 0 or self.__reset_pin >= 0:
assert self.__line_request is None
assert self.__line_req is None
config: dict[int, gpiod.LineSettings] = {}
if self.__power_detect_pin >= 0:
config[self.__power_detect_pin] = gpiod.LineSettings(
@@ -65,7 +65,7 @@ class Gpio: # pylint: disable=too-many-instance-attributes
output_value=gpiod.line.Value(self.__reset_inverted),
)
assert len(config) > 0
self.__line_request = gpiod.request_lines(
self.__line_req = gpiod.request_lines(
self.__device_path,
consumer="kvmd::hid",
config=config,
@@ -78,18 +78,18 @@ class Gpio: # pylint: disable=too-many-instance-attributes
_tb: types.TracebackType,
) -> None:
if self.__line_request:
if self.__line_req:
try:
self.__line_request.release()
self.__line_req.release()
except Exception:
pass
self.__last_power = None
self.__line_request = None
self.__line_req = None
def is_powered(self) -> bool:
if self.__power_detect_pin >= 0:
assert self.__line_request
power = bool(self.__line_request.get_value(self.__power_detect_pin).value)
assert self.__line_req
power = bool(self.__line_req.get_value(self.__power_detect_pin).value)
if power != self.__last_power:
get_logger(0).info("HID power state changed: %s -> %s", self.__last_power, power)
self.__last_power = power
@@ -98,11 +98,11 @@ class Gpio: # pylint: disable=too-many-instance-attributes
def reset(self) -> None:
if self.__reset_pin >= 0:
assert self.__line_request
assert self.__line_req
try:
self.__line_request.set_value(self.__reset_pin, gpiod.line.Value(not self.__reset_inverted))
self.__line_req.set_value(self.__reset_pin, gpiod.line.Value(not self.__reset_inverted))
time.sleep(self.__reset_delay)
finally:
self.__line_request.set_value(self.__reset_pin, gpiod.line.Value(self.__reset_inverted))
self.__line_req.set_value(self.__reset_pin, gpiod.line.Value(self.__reset_inverted))
time.sleep(1)
get_logger(0).info("Reset HID performed")

View File

@@ -184,17 +184,17 @@ class MouseWheelEvent(BaseEvent):
# =====
def check_response(response: bytes) -> bool:
assert len(response) in (4, 8), response
return (bitbang.make_crc16(response[:-2]) == struct.unpack(">H", response[-2:])[0])
def check_response(resp: bytes) -> bool:
assert len(resp) in (4, 8), resp
return (bitbang.make_crc16(resp[:-2]) == struct.unpack(">H", resp[-2:])[0])
def _make_request(command: bytes) -> bytes:
assert len(command) == 5, command
request = b"\x33" + command
request += struct.pack(">H", bitbang.make_crc16(request))
assert len(request) == 8, request
return request
def _make_request(cmd: bytes) -> bytes:
assert len(cmd) == 5, cmd
req = b"\x33" + cmd
req += struct.pack(">H", bitbang.make_crc16(req))
assert len(req) == 8, req
return req
# =====

View File

@@ -182,8 +182,8 @@ class BtServer: # pylint: disable=too-many-instance-attributes
self.__close_client("CTL", client, "ctl_sock")
elif data == b"\x71":
sock.send(b"\x00")
except Exception as err:
get_logger(0).exception("CTL socket error on %s: %s", client.addr, tools.efmt(err))
except Exception as ex:
get_logger(0).exception("CTL socket error on %s: %s", client.addr, tools.efmt(ex))
self.__close_client("CTL", client, "ctl_sock")
continue
@@ -196,8 +196,8 @@ class BtServer: # pylint: disable=too-many-instance-attributes
self.__close_client("INT", client, "int_sock")
elif data[:2] == b"\xA2\x01":
self.__process_leds(data[2])
except Exception as err:
get_logger(0).exception("INT socket error on %s: %s", client.addr, tools.efmt(err))
except Exception as ex:
get_logger(0).exception("INT socket error on %s: %s", client.addr, tools.efmt(ex))
self.__close_client("INT", client, "ctl_sock")
if qr in ready_read:
@@ -279,8 +279,8 @@ class BtServer: # pylint: disable=too-many-instance-attributes
assert client.int_sock is not None
try:
client.int_sock.send(report)
except Exception as err:
get_logger(0).info("Can't send %s report to %s: %s", name, client.addr, tools.efmt(err))
except Exception as ex:
get_logger(0).info("Can't send %s report to %s: %s", name, client.addr, tools.efmt(ex))
self.__close_client_pair(client)
def __clear_modifiers(self) -> None:
@@ -371,13 +371,13 @@ class BtServer: # pylint: disable=too-many-instance-attributes
logger.info("Publishing ..." if public else "Unpublishing ...")
try:
self.__iface.set_public(public)
except Exception as err:
logger.error("Can't change public mode: %s", tools.efmt(err))
except Exception as ex:
logger.error("Can't change public mode: %s", tools.efmt(ex))
def __unpair_client(self, client: _BtClient) -> None:
logger = get_logger(0)
logger.info("Unpairing %s ...", client.addr)
try:
self.__iface.unpair(client.addr)
except Exception as err:
logger.error("Can't unpair %s: %s", client.addr, tools.efmt(err))
except Exception as ex:
logger.error("Can't unpair %s: %s", client.addr, tools.efmt(ex))

View File

@@ -230,9 +230,9 @@ class Plugin(BaseHid, multiprocessing.Process): # pylint: disable=too-many-inst
def __process_cmd(self, conn: ChipConnection, cmd: bytes) -> bool: # pylint: disable=too-many-branches
try:
led_byte = conn.xfer(cmd)
except ChipResponseError as err:
except ChipResponseError as ex:
self.__set_state_online(False)
get_logger(0).info(err)
get_logger(0).error("Invalid chip response: %s", tools.efmt(ex))
time.sleep(2)
else:
if led_byte >= 0:

View File

@@ -192,13 +192,13 @@ class BaseDeviceProcess(multiprocessing.Process): # pylint: disable=too-many-in
else:
logger.error("HID-%s write() error: written (%s) != report length (%d)",
self.__name, written, len(report))
except Exception as err:
if isinstance(err, OSError) and (
except Exception as ex:
if isinstance(ex, OSError) and (
# https://github.com/raspberrypi/linux/commit/61b7f805dc2fd364e0df682de89227e94ce88e25
err.errno == errno.EAGAIN # pylint: disable=no-member
or err.errno == errno.ESHUTDOWN # pylint: disable=no-member
ex.errno == errno.EAGAIN # pylint: disable=no-member
or ex.errno == errno.ESHUTDOWN # pylint: disable=no-member
):
logger.debug("HID-%s busy/unplugged (write): %s", self.__name, tools.efmt(err))
logger.debug("HID-%s busy/unplugged (write): %s", self.__name, tools.efmt(ex))
else:
logger.exception("Can't write report to HID-%s", self.__name)
@@ -216,16 +216,16 @@ class BaseDeviceProcess(multiprocessing.Process): # pylint: disable=too-many-in
while read:
try:
read = bool(select.select([self.__fd], [], [], 0)[0])
except Exception as err:
logger.error("Can't select() for read HID-%s: %s", self.__name, tools.efmt(err))
except Exception as ex:
logger.error("Can't select() for read HID-%s: %s", self.__name, tools.efmt(ex))
break
if read:
try:
report = os.read(self.__fd, self.__read_size)
except Exception as err:
if isinstance(err, OSError) and err.errno == errno.EAGAIN: # pylint: disable=no-member
logger.debug("HID-%s busy/unplugged (read): %s", self.__name, tools.efmt(err))
except Exception as ex:
if isinstance(ex, OSError) and ex.errno == errno.EAGAIN: # pylint: disable=no-member
logger.debug("HID-%s busy/unplugged (read): %s", self.__name, tools.efmt(ex))
else:
logger.exception("Can't read report from HID-%s", self.__name)
else:
@@ -255,9 +255,9 @@ class BaseDeviceProcess(multiprocessing.Process): # pylint: disable=too-many-in
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 Exception as err:
except Exception as ex:
logger.error("Can't open HID-%s device %s: %s",
self.__name, self.__device_path, tools.efmt(err))
self.__name, self.__device_path, tools.efmt(ex))
if self.__fd >= 0:
try:
@@ -268,8 +268,8 @@ class BaseDeviceProcess(multiprocessing.Process): # pylint: disable=too-many-in
else:
# Если запись недоступна, то скорее всего устройство отключено
logger.debug("HID-%s is busy/unplugged (write select)", self.__name)
except Exception as err:
logger.error("Can't select() for write HID-%s: %s", self.__name, tools.efmt(err))
except Exception as ex:
logger.error("Can't select() for write HID-%s: %s", self.__name, tools.efmt(ex))
self.__state_flags.update(online=False)
return False

View File

@@ -44,12 +44,12 @@ class _SerialPhyConnection(BasePhyConnection):
def __init__(self, tty: serial.Serial) -> None:
self.__tty = tty
def send(self, request: bytes) -> bytes:
assert len(request) == 8
assert request[0] == 0x33
def send(self, req: bytes) -> bytes:
assert len(req) == 8
assert req[0] == 0x33
if self.__tty.in_waiting:
self.__tty.read_all()
assert self.__tty.write(request) == 8
assert self.__tty.write(req) == 8
data = self.__tty.read(4)
if len(data) == 4:
if data[0] == 0x34: # New response protocol

View File

@@ -57,9 +57,9 @@ class _SpiPhyConnection(BasePhyConnection):
self.__xfer = xfer
self.__read_timeout = read_timeout
def send(self, request: bytes) -> bytes:
assert len(request) == 8
assert request[0] == 0x33
def send(self, req: bytes) -> bytes:
assert len(req) == 8
assert req[0] == 0x33
deadline_ts = time.monotonic() + self.__read_timeout
dummy = b"\x00" * 10
@@ -70,26 +70,26 @@ class _SpiPhyConnection(BasePhyConnection):
get_logger(0).error("SPI timeout reached while garbage reading")
return b""
self.__xfer(request)
self.__xfer(req)
response: list[int] = []
resp: list[int] = []
deadline_ts = time.monotonic() + self.__read_timeout
found = False
while time.monotonic() < deadline_ts:
for byte in self.__xfer(b"\x00" * (9 - len(response))):
for byte in self.__xfer(b"\x00" * (9 - len(resp))):
if not found:
if byte == 0:
continue
found = True
response.append(byte)
if len(response) == 8:
resp.append(byte)
if len(resp) == 8:
break
if len(response) == 8:
if len(resp) == 8:
break
else:
get_logger(0).error("SPI timeout reached while responce waiting")
return b""
return bytes(response)
return bytes(resp)
class _SpiPhy(BasePhy): # pylint: disable=too-many-instance-attributes

View File

@@ -82,7 +82,7 @@ class Drive:
try:
with open(os.path.join(self.__lun_path, param), "w") as file:
file.write(value + "\n")
except OSError as err:
if err.errno == errno.EBUSY:
except OSError as ex:
if ex.errno == errno.EBUSY:
raise MsdDriveLockedError()
raise

View File

@@ -113,13 +113,13 @@ class Plugin(BaseUserGpioDriver): # pylint: disable=too-many-instance-attribute
while True:
session = self.__ensure_http_session()
try:
async with session.get(f"{self.__url}/strg.cfg") as response:
htclient.raise_not_200(response)
parts = (await response.text()).split(";")
async with session.get(f"{self.__url}/strg.cfg") as resp:
htclient.raise_not_200(resp)
parts = (await resp.text()).split(";")
for pin in self.__state:
self.__state[pin] = (parts[1 + int(pin) * 5] == "1")
except Exception as err:
get_logger().error("Failed ANELPWR bulk GET request: %s", tools.efmt(err))
except Exception as ex:
get_logger().error("Failed ANELPWR bulk GET request: %s", tools.efmt(ex))
self.__state = dict.fromkeys(self.__state, None)
if self.__state != prev_state:
self._notifier.notify()
@@ -143,10 +143,10 @@ class Plugin(BaseUserGpioDriver): # pylint: disable=too-many-instance-attribute
url=f"{self.__url}/ctrl.htm",
data=f"F{pin}={int(state)}",
headers={"Content-Type": "text/plain"},
) as response:
htclient.raise_not_200(response)
except Exception as err:
get_logger().error("Failed ANELPWR POST request to pin %s: %s", pin, tools.efmt(err))
) as resp:
htclient.raise_not_200(resp)
except Exception as ex:
get_logger().error("Failed ANELPWR POST request to pin %s: %s", pin, tools.efmt(ex))
raise GpioDriverOfflineError(self)
self.__update_notifier.notify()

View File

@@ -78,9 +78,9 @@ class Plugin(BaseUserGpioDriver): # pylint: disable=too-many-instance-attribute
proc = await aioproc.log_process(self.__cmd, logger=get_logger(0), prefix=str(self))
if proc.returncode != 0:
raise RuntimeError(f"Custom command error: retcode={proc.returncode}")
except Exception as err:
except Exception as ex:
get_logger(0).error("Can't run custom command [ %s ]: %s",
tools.cmdfmt(self.__cmd), tools.efmt(err))
tools.cmdfmt(self.__cmd), tools.efmt(ex))
raise GpioDriverOfflineError(self)
def __str__(self) -> str:

View File

@@ -71,9 +71,9 @@ class Plugin(BaseUserGpioDriver): # pylint: disable=too-many-instance-attribute
try:
proc = await aioproc.log_process(self.__cmd, logger=get_logger(0), prefix=str(self))
return (proc.returncode == 0)
except Exception as err:
except Exception as ex:
get_logger(0).error("Can't run custom command [ %s ]: %s",
tools.cmdfmt(self.__cmd), tools.efmt(err))
tools.cmdfmt(self.__cmd), tools.efmt(ex))
raise GpioDriverOfflineError(self)
async def write(self, pin: str, state: bool) -> None:

View File

@@ -150,9 +150,9 @@ class Plugin(BaseUserGpioDriver): # pylint: disable=too-many-instance-attribute
assert channel is not None
self.__send_channel(tty, channel)
except Exception as err:
except Exception as ex:
self.__channel_queue.put_nowait(None)
if isinstance(err, serial.SerialException) and err.errno == errno.ENOENT: # pylint: disable=no-member
if isinstance(ex, serial.SerialException) and ex.errno == errno.ENOENT: # pylint: disable=no-member
logger.error("Missing %s serial device: %s", self, self.__device_path)
else:
logger.exception("Unexpected %s error", self)

View File

@@ -150,9 +150,9 @@ class Plugin(BaseUserGpioDriver): # pylint: disable=too-many-instance-attribute
assert channel is not None
self.__send_channel(tty, channel)
except Exception as err:
except Exception as ex:
self.__channel_queue.put_nowait(None)
if isinstance(err, serial.SerialException) and err.errno == errno.ENOENT: # pylint: disable=no-member
if isinstance(ex, serial.SerialException) and ex.errno == errno.ENOENT: # pylint: disable=no-member
logger.error("Missing %s serial device: %s", self, self.__device_path)
else:
logger.exception("Unexpected %s error", self)

View File

@@ -54,7 +54,7 @@ class Plugin(BaseUserGpioDriver):
self.__output_pins: dict[int, (bool | None)] = {}
self.__reader: (aiogp.AioReader | None) = None
self.__outputs_request: (gpiod.LineRequest | None) = None
self.__outputs_req: (gpiod.LineRequest | None) = None
@classmethod
def get_plugin_options(cls) -> dict:
@@ -74,7 +74,7 @@ class Plugin(BaseUserGpioDriver):
def prepare(self) -> None:
assert self.__reader is None
assert self.__outputs_request is None
assert self.__outputs_req is None
self.__reader = aiogp.AioReader(
path=self.__device_path,
consumer="kvmd::gpio::inputs",
@@ -82,7 +82,7 @@ class Plugin(BaseUserGpioDriver):
notifier=self._notifier,
)
if self.__output_pins:
self.__outputs_request = gpiod.request_lines(
self.__outputs_req = gpiod.request_lines(
self.__device_path,
consumer="kvmd::gpiod::outputs",
config={
@@ -99,9 +99,9 @@ class Plugin(BaseUserGpioDriver):
await self.__reader.poll()
async def cleanup(self) -> None:
if self.__outputs_request:
if self.__outputs_req:
try:
self.__outputs_request.release()
self.__outputs_req.release()
except Exception:
pass
@@ -110,15 +110,15 @@ class Plugin(BaseUserGpioDriver):
pin_int = int(pin)
if pin_int in self.__input_pins:
return self.__reader.get(pin_int)
assert self.__outputs_request
assert self.__outputs_req
assert pin_int in self.__output_pins
return bool(self.__outputs_request.get_value(pin_int).value)
return bool(self.__outputs_req.get_value(pin_int).value)
async def write(self, pin: str, state: bool) -> None:
assert self.__outputs_request
assert self.__outputs_req
pin_int = int(pin)
assert pin_int in self.__output_pins
self.__outputs_request.set_value(pin_int, gpiod.line.Value(state))
self.__outputs_req.set_value(pin_int, gpiod.line.Value(state))
def __str__(self) -> str:
return f"GPIO({self._instance_name})"

View File

@@ -93,9 +93,9 @@ class Plugin(BaseUserGpioDriver):
try:
with self.__ensure_device("probing"):
pass
except Exception as err:
except Exception as ex:
logger.error("Can't probe %s on %s: %s",
self, self.__device_path, tools.efmt(err))
self, self.__device_path, tools.efmt(ex))
self.__reset_pins()
async def run(self) -> None:
@@ -137,9 +137,9 @@ class Plugin(BaseUserGpioDriver):
pin, state, self, self.__device_path)
try:
self.__inner_write(pin, state)
except Exception as err:
except Exception as ex:
logger.error("Can't reset pin=%d of %s on %s: %s",
pin, self, self.__device_path, tools.efmt(err))
pin, self, self.__device_path, tools.efmt(ex))
def __inner_read(self, pin: int) -> bool:
assert 0 <= pin <= 7
@@ -168,9 +168,9 @@ class Plugin(BaseUserGpioDriver):
get_logger(0).info("Opened %s on %s while %s", self, self.__device_path, context)
try:
yield self.__device
except Exception as err:
except Exception as ex:
get_logger(0).error("Error occured on %s on %s while %s: %s",
self, self.__device_path, context, tools.efmt(err))
self, self.__device_path, context, tools.efmt(ex))
self.__close_device()
raise

View File

@@ -111,13 +111,13 @@ class Plugin(BaseUserGpioDriver): # pylint: disable=too-many-instance-attribute
while True:
session = self.__ensure_http_session()
try:
async with session.get(f"{self.__url}/api/{self.__token}/lights") as response:
results = await response.json()
async with session.get(f"{self.__url}/api/{self.__token}/lights") as resp:
results = await resp.json()
for pin in self.__state:
if pin in results:
self.__state[pin] = bool(results[pin]["state"]["on"])
except Exception as err:
get_logger().error("Failed Hue bulk GET request: %s", tools.efmt(err))
except Exception as ex:
get_logger().error("Failed Hue bulk GET request: %s", tools.efmt(ex))
self.__state = dict.fromkeys(self.__state, None)
if self.__state != prev_state:
self._notifier.notify()
@@ -140,10 +140,10 @@ class Plugin(BaseUserGpioDriver): # pylint: disable=too-many-instance-attribute
async with session.put(
url=f"{self.__url}/api/{self.__token}/lights/{pin}/state",
json={"on": state},
) as response:
htclient.raise_not_200(response)
except Exception as err:
get_logger().error("Failed Hue PUT request to pin %s: %s", pin, tools.efmt(err))
) as resp:
htclient.raise_not_200(resp)
except Exception as ex:
get_logger().error("Failed Hue PUT request to pin %s: %s", pin, tools.efmt(ex))
raise GpioDriverOfflineError(self)
self.__update_notifier.notify()

View File

@@ -153,9 +153,9 @@ class Plugin(BaseUserGpioDriver): # pylint: disable=too-many-instance-attribute
proc = await aioproc.log_process(**self.__make_ipmitool_kwargs(action), logger=get_logger(0), prefix=str(self))
if proc.returncode != 0:
raise RuntimeError(f"Ipmitool error: retcode={proc.returncode}")
except Exception as err:
except Exception as ex:
get_logger(0).error("Can't send IPMI power-%s request to %s:%d: %s",
action, self.__host, self.__port, tools.efmt(err))
action, self.__host, self.__port, tools.efmt(ex))
raise GpioDriverOfflineError(self)
# =====
@@ -171,9 +171,9 @@ class Plugin(BaseUserGpioDriver): # pylint: disable=too-many-instance-attribute
self.__online = True
return
raise RuntimeError(f"Invalid ipmitool response: {text}")
except Exception as err:
except Exception as ex:
get_logger(0).error("Can't fetch IPMI power status from %s:%d: %s",
self.__host, self.__port, tools.efmt(err))
self.__host, self.__port, tools.efmt(ex))
self.__power = False
self.__online = False

View File

@@ -53,7 +53,7 @@ class Plugin(BaseUserGpioDriver):
self.__device_path = device_path
self.__tasks: dict[int, (asyncio.Task | None)] = {}
self.__line_request: (gpiod.LineRequest | None) = None
self.__line_req: (gpiod.LineRequest | None) = None
@classmethod
def get_plugin_options(cls) -> dict:
@@ -74,7 +74,7 @@ class Plugin(BaseUserGpioDriver):
self.__tasks[int(pin)] = None
def prepare(self) -> None:
self.__line_request = gpiod.request_lines(
self.__line_req = gpiod.request_lines(
self.__device_path,
consumer="kvmd::locator",
config={
@@ -94,9 +94,9 @@ class Plugin(BaseUserGpioDriver):
for task in tasks:
task.cancel()
await asyncio.gather(*tasks, return_exceptions=True)
if self.__line_request:
if self.__line_req:
try:
self.__line_request.release()
self.__line_req.release()
except Exception:
pass
@@ -115,17 +115,17 @@ class Plugin(BaseUserGpioDriver):
async def __blink(self, pin: int) -> None:
assert pin in self.__tasks
assert self.__line_request
assert self.__line_req
try:
state = True
while True:
self.__line_request.set_value(pin, gpiod.line.Value(state))
self.__line_req.set_value(pin, gpiod.line.Value(state))
state = (not state)
await asyncio.sleep(0.1)
except asyncio.CancelledError:
pass
finally:
self.__line_request.set_value(pin, gpiod.line.Value(False))
self.__line_req.set_value(pin, gpiod.line.Value(False))
def __str__(self) -> str:
return f"Locator({self._instance_name})"

View File

@@ -91,9 +91,9 @@ class Plugin(BaseUserGpioDriver):
try:
with self.__ensure_device("probing"):
pass
except Exception as err:
except Exception as ex:
logger.error("Can't probe %s on %s: %s",
self, self.__device_path, tools.efmt(err))
self, self.__device_path, tools.efmt(ex))
self.__reset_pins()
async def cleanup(self) -> None:
@@ -119,9 +119,9 @@ class Plugin(BaseUserGpioDriver):
pin, state, self, self.__device_path)
try:
self.__inner_write(pin, state)
except Exception as err:
except Exception as ex:
logger.error("Can't reset pin=%d of %s on %s: %s",
pin, self, self.__device_path, tools.efmt(err))
pin, self, self.__device_path, tools.efmt(ex))
def __inner_write(self, pin: int, state: bool) -> None:
assert 0 <= pin <= 7
@@ -144,9 +144,9 @@ class Plugin(BaseUserGpioDriver):
get_logger(0).info("Opened %s on %s while %s", self, self.__device_path, context)
try:
yield self.__device
except Exception as err:
except Exception as ex:
get_logger(0).error("Error occured on %s on %s while %s: %s",
self, self.__device_path, context, tools.efmt(err))
self, self.__device_path, context, tools.efmt(ex))
self.__close_device()
raise

View File

@@ -153,9 +153,9 @@ class Plugin(BaseUserGpioDriver): # pylint: disable=too-many-instance-attribute
assert channel is not None
self.__send_channel(tty, channel)
except Exception as err:
except Exception as ex:
self.__channel_queue.put_nowait(None)
if isinstance(err, serial.SerialException) and err.errno == errno.ENOENT: # pylint: disable=no-member
if isinstance(ex, serial.SerialException) and ex.errno == errno.ENOENT: # pylint: disable=no-member
logger.error("Missing %s serial device: %s", self, self.__device_path)
else:
logger.exception("Unexpected %s error", self)

View File

@@ -94,18 +94,18 @@ class Plugin(BaseUserGpioDriver):
pwm.period_ns = self.__period
pwm.duty_cycle_ns = self.__get_duty_cycle(bool(initial))
pwm.enable()
except Exception as err:
except Exception as ex:
logger.error("Can't get PWM chip %d channel %d: %s",
self.__chip, pin, tools.efmt(err))
self.__chip, pin, tools.efmt(ex))
async def cleanup(self) -> None:
for (pin, pwm) in self.__pwms.items():
try:
pwm.disable()
pwm.close()
except Exception as err:
except Exception as ex:
get_logger(0).error("Can't cleanup PWM chip %d channel %d: %s",
self.__chip, pin, tools.efmt(err))
self.__chip, pin, tools.efmt(ex))
async def read(self, pin: str) -> bool:
try:

View File

@@ -146,9 +146,9 @@ class Plugin(BaseUserGpioDriver): # pylint: disable=too-many-instance-attribute
asyncio.ensure_future(self.__reader.readexactly(6)),
timeout=self.__timeout,
))[4]
except Exception as err:
except Exception as ex:
get_logger(0).error("Can't send command to TESmart KVM [%s]:%d: %s",
self.__host, self.__port, tools.efmt(err))
self.__host, self.__port, tools.efmt(ex))
await self.__close_device()
self.__active = -1
raise GpioDriverOfflineError(self)
@@ -168,9 +168,9 @@ class Plugin(BaseUserGpioDriver): # pylint: disable=too-many-instance-attribute
asyncio.ensure_future(asyncio.open_connection(self.__host, self.__port)),
timeout=self.__timeout,
)
except Exception as err:
except Exception as ex:
get_logger(0).error("Can't connect to TESmart KVM [%s]:%d: %s",
self.__host, self.__port, tools.efmt(err))
self.__host, self.__port, tools.efmt(ex))
raise GpioDriverOfflineError(self)
async def __ensure_device_serial(self) -> None:
@@ -179,9 +179,9 @@ class Plugin(BaseUserGpioDriver): # pylint: disable=too-many-instance-attribute
serial_asyncio.open_serial_connection(url=self.__device_path, baudrate=self.__speed),
timeout=self.__timeout,
)
except Exception as err:
except Exception as ex:
get_logger(0).error("Can't connect to TESmart KVM [%s]:%d: %s",
self.__device_path, self.__speed, tools.efmt(err))
self.__device_path, self.__speed, tools.efmt(ex))
raise GpioDriverOfflineError(self)
async def __close_device(self) -> None:

View File

@@ -157,9 +157,9 @@ class Plugin(BaseUserGpioDriver): # pylint: disable=too-many-instance-attribute
if self.__protocol == 2:
self.__channel_queue.put_nowait(channel)
except Exception as err:
except Exception as ex:
self.__channel_queue.put_nowait(None)
if isinstance(err, serial.SerialException) and err.errno == errno.ENOENT: # pylint: disable=no-member
if isinstance(ex, serial.SerialException) and ex.errno == errno.ENOENT: # pylint: disable=no-member
logger.error("Missing %s serial device: %s", self, self.__device_path)
else:
logger.exception("Unexpected %s error", self)