Add SyncThru binary sensors (#48114)

Co-authored-by: Martin Hjelmare <marhje52@gmail.com>
This commit is contained in:
Niels Mündler 2021-05-04 08:28:45 +02:00 committed by GitHub
parent 809c1394d4
commit 2eae87fb1b
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
7 changed files with 247 additions and 94 deletions

View file

@ -2,13 +2,17 @@
import logging
from pysyncthru import SYNCTHRU_STATE_HUMAN, SyncThru
from pysyncthru import SyncThru, SyncthruState
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity
from homeassistant.config_entries import SOURCE_IMPORT
from homeassistant.const import CONF_NAME, CONF_RESOURCE, CONF_URL, PERCENTAGE
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.update_coordinator import (
CoordinatorEntity,
DataUpdateCoordinator,
)
from . import device_identifiers
from .const import DEFAULT_MODEL, DEFAULT_NAME_TEMPLATE, DOMAIN
@ -26,6 +30,16 @@ DEFAULT_MONITORED_CONDITIONS.extend([f"drum_{key}" for key in DRUM_COLORS])
DEFAULT_MONITORED_CONDITIONS.extend([f"tray_{key}" for key in TRAYS])
DEFAULT_MONITORED_CONDITIONS.extend([f"output_tray_{key}" for key in OUTPUT_TRAYS])
SYNCTHRU_STATE_HUMAN = {
SyncthruState.INVALID: "invalid",
SyncthruState.OFFLINE: "unreachable",
SyncthruState.NORMAL: "normal",
SyncthruState.UNKNOWN: "unknown",
SyncthruState.WARNING: "warning",
SyncthruState.TESTING: "testing",
SyncthruState.ERROR: "error",
}
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_RESOURCE): cv.url,
@ -58,7 +72,8 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info=
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up from config entry."""
printer = hass.data[DOMAIN][config_entry.entry_id]
coordinator: DataUpdateCoordinator = hass.data[DOMAIN][config_entry.entry_id]
printer: SyncThru = coordinator.data
supp_toner = printer.toner_status(filter_supported=True)
supp_drum = printer.drum_status(filter_supported=True)
@ -66,28 +81,27 @@ async def async_setup_entry(hass, config_entry, async_add_entities):
supp_output_tray = printer.output_tray_status()
name = config_entry.data[CONF_NAME]
devices = [SyncThruMainSensor(printer, name)]
entities = [SyncThruMainSensor(coordinator, name)]
for key in supp_toner:
devices.append(SyncThruTonerSensor(printer, name, key))
entities.append(SyncThruTonerSensor(coordinator, name, key))
for key in supp_drum:
devices.append(SyncThruDrumSensor(printer, name, key))
entities.append(SyncThruDrumSensor(coordinator, name, key))
for key in supp_tray:
devices.append(SyncThruInputTraySensor(printer, name, key))
entities.append(SyncThruInputTraySensor(coordinator, name, key))
for key in supp_output_tray:
devices.append(SyncThruOutputTraySensor(printer, name, key))
entities.append(SyncThruOutputTraySensor(coordinator, name, key))
async_add_entities(devices, True)
async_add_entities(entities)
class SyncThruSensor(SensorEntity):
class SyncThruSensor(CoordinatorEntity, SensorEntity):
"""Implementation of an abstract Samsung Printer sensor platform."""
def __init__(self, syncthru, name):
def __init__(self, coordinator, name):
"""Initialize the sensor."""
self.syncthru: SyncThru = syncthru
self._attributes = {}
self._state = None
super().__init__(coordinator)
self.syncthru: SyncThru = coordinator.data
self._name = name
self._icon = "mdi:printer"
self._unit_of_measurement = None
@ -97,18 +111,13 @@ class SyncThruSensor(SensorEntity):
def unique_id(self):
"""Return unique ID for the sensor."""
serial = self.syncthru.serial_number()
return serial + self._id_suffix if serial else super().unique_id
return f"{serial}{self._id_suffix}" if serial else None
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def state(self):
"""Return the state of the device."""
return self._state
@property
def icon(self):
"""Return the icon of the device."""
@ -119,11 +128,6 @@ class SyncThruSensor(SensorEntity):
"""Return the unit of measuremnt."""
return self._unit_of_measurement
@property
def extra_state_attributes(self):
"""Return the state attributes of the device."""
return self._attributes
@property
def device_info(self):
"""Return device information."""
@ -131,50 +135,56 @@ class SyncThruSensor(SensorEntity):
class SyncThruMainSensor(SyncThruSensor):
"""Implementation of the main sensor, conducting the actual polling."""
"""
Implementation of the main sensor, conducting the actual polling.
def __init__(self, syncthru, name):
It also shows the detailed state and presents
the displayed current status message.
"""
def __init__(self, coordinator, name):
"""Initialize the sensor."""
super().__init__(syncthru, name)
super().__init__(coordinator, name)
self._id_suffix = "_main"
self._active = True
async def async_update(self):
"""Get the latest data from SyncThru and update the state."""
if not self._active:
return
try:
await self.syncthru.update()
except ValueError:
# if an exception is thrown, printer does not support syncthru
_LOGGER.warning(
"Configured printer at %s does not support SyncThru. "
"Consider changing your configuration",
self.syncthru.url,
)
self._active = False
self._state = SYNCTHRU_STATE_HUMAN[self.syncthru.device_status()]
self._attributes = {"display_text": self.syncthru.device_status_details()}
@property
def state(self):
"""Set state to human readable version of syncthru status."""
return SYNCTHRU_STATE_HUMAN[self.syncthru.device_status()]
@property
def extra_state_attributes(self):
"""Show current printer display text."""
return {
"display_text": self.syncthru.device_status_details(),
}
@property
def entity_registry_enabled_default(self) -> bool:
"""Disable entity by default."""
return False
class SyncThruTonerSensor(SyncThruSensor):
"""Implementation of a Samsung Printer toner sensor platform."""
def __init__(self, syncthru, name, color):
def __init__(self, coordinator, name, color):
"""Initialize the sensor."""
super().__init__(syncthru, name)
super().__init__(coordinator, name)
self._name = f"{name} Toner {color}"
self._color = color
self._unit_of_measurement = PERCENTAGE
self._id_suffix = f"_toner_{color}"
def update(self):
"""Get the latest data from SyncThru and update the state."""
# Data fetching is taken care of through the Main sensor
@property
def extra_state_attributes(self):
"""Show all data returned for this toner."""
return self.syncthru.toner_status().get(self._color, {})
if self.syncthru.is_online():
self._attributes = self.syncthru.toner_status().get(self._color, {})
self._state = self._attributes.get("remaining")
@property
def state(self):
"""Show amount of remaining toner."""
return self.syncthru.toner_status().get(self._color, {}).get("remaining")
class SyncThruDrumSensor(SyncThruSensor):
@ -188,13 +198,15 @@ class SyncThruDrumSensor(SyncThruSensor):
self._unit_of_measurement = PERCENTAGE
self._id_suffix = f"_drum_{color}"
def update(self):
"""Get the latest data from SyncThru and update the state."""
# Data fetching is taken care of through the Main sensor
@property
def extra_state_attributes(self):
"""Show all data returned for this drum."""
return self.syncthru.drum_status().get(self._color, {})
if self.syncthru.is_online():
self._attributes = self.syncthru.drum_status().get(self._color, {})
self._state = self._attributes.get("remaining")
@property
def state(self):
"""Show amount of remaining drum."""
return self.syncthru.drum_status().get(self._color, {}).get("remaining")
class SyncThruInputTraySensor(SyncThruSensor):
@ -207,15 +219,20 @@ class SyncThruInputTraySensor(SyncThruSensor):
self._number = number
self._id_suffix = f"_tray_{number}"
def update(self):
"""Get the latest data from SyncThru and update the state."""
# Data fetching is taken care of through the Main sensor
@property
def extra_state_attributes(self):
"""Show all data returned for this input tray."""
return self.syncthru.input_tray_status().get(self._number, {})
if self.syncthru.is_online():
self._attributes = self.syncthru.input_tray_status().get(self._number, {})
self._state = self._attributes.get("newError")
if self._state == "":
self._state = "Ready"
@property
def state(self):
"""Display ready unless there is some error, then display error."""
tray_state = (
self.syncthru.input_tray_status().get(self._number, {}).get("newError")
)
if tray_state == "":
tray_state = "Ready"
return tray_state
class SyncThruOutputTraySensor(SyncThruSensor):
@ -228,12 +245,17 @@ class SyncThruOutputTraySensor(SyncThruSensor):
self._number = number
self._id_suffix = f"_output_tray_{number}"
def update(self):
"""Get the latest data from SyncThru and update the state."""
# Data fetching is taken care of through the Main sensor
@property
def extra_state_attributes(self):
"""Show all data returned for this output tray."""
return self.syncthru.output_tray_status().get(self._number, {})
if self.syncthru.is_online():
self._attributes = self.syncthru.output_tray_status().get(self._number, {})
self._state = self._attributes.get("status")
if self._state == "":
self._state = "Ready"
@property
def state(self):
"""Display ready unless there is some error, then display error."""
tray_state = (
self.syncthru.output_tray_status().get(self._number, {}).get("status")
)
if tray_state == "":
tray_state = "Ready"
return tray_state