Improve type hint in cups sensor entity (#77030)

This commit is contained in:
epenet 2022-08-20 08:37:47 +02:00 committed by GitHub
parent 09ab07921a
commit b88e71762d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -4,6 +4,7 @@ from __future__ import annotations
from datetime import timedelta from datetime import timedelta
import importlib import importlib
import logging import logging
from typing import Any
import voluptuous as vol import voluptuous as vol
@ -62,10 +63,10 @@ def setup_platform(
discovery_info: DiscoveryInfoType | None = None, discovery_info: DiscoveryInfoType | None = None,
) -> None: ) -> None:
"""Set up the CUPS sensor.""" """Set up the CUPS sensor."""
host = config[CONF_HOST] host: str = config[CONF_HOST]
port = config[CONF_PORT] port: int = config[CONF_PORT]
printers = config[CONF_PRINTERS] printers: list[str] = config[CONF_PRINTERS]
is_cups = config[CONF_IS_CUPS_SERVER] is_cups: bool = config[CONF_IS_CUPS_SERVER]
if is_cups: if is_cups:
data = CupsData(host, port, None) data = CupsData(host, port, None)
@ -73,6 +74,7 @@ def setup_platform(
if data.available is False: if data.available is False:
_LOGGER.error("Unable to connect to CUPS server: %s:%s", host, port) _LOGGER.error("Unable to connect to CUPS server: %s:%s", host, port)
raise PlatformNotReady() raise PlatformNotReady()
assert data.printers is not None
dev: list[SensorEntity] = [] dev: list[SensorEntity] = []
for printer in printers: for printer in printers:
@ -108,17 +110,14 @@ def setup_platform(
class CupsSensor(SensorEntity): class CupsSensor(SensorEntity):
"""Representation of a CUPS sensor.""" """Representation of a CUPS sensor."""
def __init__(self, data, printer): _attr_icon = ICON_PRINTER
def __init__(self, data: CupsData, printer_name: str) -> None:
"""Initialize the CUPS sensor.""" """Initialize the CUPS sensor."""
self.data = data self.data = data
self._name = printer self._attr_name = printer_name
self._printer = None self._printer: dict[str, Any] | None = None
self._available = False self._attr_available = False
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property @property
def native_value(self): def native_value(self):
@ -129,16 +128,6 @@ class CupsSensor(SensorEntity):
key = self._printer["printer-state"] key = self._printer["printer-state"]
return PRINTER_STATES.get(key, key) return PRINTER_STATES.get(key, key)
@property
def available(self):
"""Return True if entity is available."""
return self._available
@property
def icon(self):
"""Return the icon to use in the frontend, if any."""
return ICON_PRINTER
@property @property
def extra_state_attributes(self): def extra_state_attributes(self):
"""Return the state attributes of the sensor.""" """Return the state attributes of the sensor."""
@ -160,8 +149,10 @@ class CupsSensor(SensorEntity):
def update(self) -> None: def update(self) -> None:
"""Get the latest data and updates the states.""" """Get the latest data and updates the states."""
self.data.update() self.data.update()
self._printer = self.data.printers.get(self._name) assert self.name is not None
self._available = self.data.available assert self.data.printers is not None
self._printer = self.data.printers.get(self.name)
self._attr_available = self.data.available
class IPPSensor(SensorEntity): class IPPSensor(SensorEntity):
@ -170,28 +161,20 @@ class IPPSensor(SensorEntity):
This sensor represents the status of the printer. This sensor represents the status of the printer.
""" """
def __init__(self, data, name): _attr_icon = ICON_PRINTER
def __init__(self, data: CupsData, printer_name: str) -> None:
"""Initialize the sensor.""" """Initialize the sensor."""
self.data = data self.data = data
self._name = name self._printer_name = printer_name
self._attributes = None self._attributes = None
self._available = False self._attr_available = False
@property @property
def name(self): def name(self):
"""Return the name of the sensor.""" """Return the name of the sensor."""
return self._attributes["printer-make-and-model"] return self._attributes["printer-make-and-model"]
@property
def icon(self):
"""Return the icon to use in the frontend."""
return ICON_PRINTER
@property
def available(self):
"""Return True if entity is available."""
return self._available
@property @property
def native_value(self): def native_value(self):
"""Return the state of the sensor.""" """Return the state of the sensor."""
@ -237,8 +220,8 @@ class IPPSensor(SensorEntity):
def update(self) -> None: def update(self) -> None:
"""Fetch new state data for the sensor.""" """Fetch new state data for the sensor."""
self.data.update() self.data.update()
self._attributes = self.data.attributes.get(self._name) self._attributes = self.data.attributes.get(self._printer_name)
self._available = self.data.available self._attr_available = self.data.available
class MarkerSensor(SensorEntity): class MarkerSensor(SensorEntity):
@ -247,24 +230,17 @@ class MarkerSensor(SensorEntity):
This sensor represents the percentage of ink or toner. This sensor represents the percentage of ink or toner.
""" """
def __init__(self, data, printer, name, is_cups): _attr_icon = ICON_MARKER
_attr_native_unit_of_measurement = PERCENTAGE
def __init__(self, data: CupsData, printer: str, name: str, is_cups: bool) -> None:
"""Initialize the sensor.""" """Initialize the sensor."""
self.data = data self.data = data
self._name = name self._attr_name = name
self._printer = printer self._printer = printer
self._index = data.attributes[printer]["marker-names"].index(name) self._index = data.attributes[printer]["marker-names"].index(name)
self._is_cups = is_cups self._is_cups = is_cups
self._attributes = None self._attributes: dict[str, Any] | None = None
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def icon(self):
"""Return the icon to use in the frontend."""
return ICON_MARKER
@property @property
def native_value(self): def native_value(self):
@ -274,11 +250,6 @@ class MarkerSensor(SensorEntity):
return self._attributes[self._printer]["marker-levels"][self._index] return self._attributes[self._printer]["marker-levels"][self._index]
@property
def native_unit_of_measurement(self):
"""Return the unit of measurement."""
return PERCENTAGE
@property @property
def extra_state_attributes(self): def extra_state_attributes(self):
"""Return the state attributes of the sensor.""" """Return the state attributes of the sensor."""
@ -318,17 +289,17 @@ class MarkerSensor(SensorEntity):
class CupsData: class CupsData:
"""Get the latest data from CUPS and update the state.""" """Get the latest data from CUPS and update the state."""
def __init__(self, host, port, ipp_printers): def __init__(self, host: str, port: int, ipp_printers: list[str] | None) -> None:
"""Initialize the data object.""" """Initialize the data object."""
self._host = host self._host = host
self._port = port self._port = port
self._ipp_printers = ipp_printers self._ipp_printers = ipp_printers
self.is_cups = ipp_printers is None self.is_cups = ipp_printers is None
self.printers = None self.printers: dict[str, dict[str, Any]] | None = None
self.attributes = {} self.attributes: dict[str, Any] = {}
self.available = False self.available = False
def update(self): def update(self) -> None:
"""Get the latest data from CUPS.""" """Get the latest data from CUPS."""
cups = importlib.import_module("cups") cups = importlib.import_module("cups")
@ -336,9 +307,11 @@ class CupsData:
conn = cups.Connection(host=self._host, port=self._port) conn = cups.Connection(host=self._host, port=self._port)
if self.is_cups: if self.is_cups:
self.printers = conn.getPrinters() self.printers = conn.getPrinters()
assert self.printers is not None
for printer in self.printers: for printer in self.printers:
self.attributes[printer] = conn.getPrinterAttributes(name=printer) self.attributes[printer] = conn.getPrinterAttributes(name=printer)
else: else:
assert self._ipp_printers is not None
for ipp_printer in self._ipp_printers: for ipp_printer in self._ipp_printers:
self.attributes[ipp_printer] = conn.getPrinterAttributes( self.attributes[ipp_printer] = conn.getPrinterAttributes(
uri=f"ipp://{self._host}:{self._port}/{ipp_printer}" uri=f"ipp://{self._host}:{self._port}/{ipp_printer}"