Skip to content

Commit

Permalink
ZONT: the method of selecting the device class has been changed
Browse files Browse the repository at this point in the history
  • Loading branch information
Михаил Шутов committed May 13, 2024
1 parent 5661c32 commit 5af61d2
Show file tree
Hide file tree
Showing 6 changed files with 78 additions and 18 deletions.
31 changes: 27 additions & 4 deletions custom_components/zont_ha/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,15 +37,29 @@
'power_source': UnitOfElectricPotential.VOLT,
'discrete': UnitOfElectricPotential.VOLT,
'dhw_speed': 'л/мин',
'txt': None,
'rssi': SIGNAL_STRENGTH_DECIBELS_MILLIWATT,
'err': None,
'signal_strength': SIGNAL_STRENGTH_DECIBELS_MILLIWATT,
'бар': UnitOfPressure.BAR,
'°': UnitOfTemperature.CELSIUS,
'%': PERCENTAGE,
'В': UnitOfElectricPotential.VOLT,
'battery': PERCENTAGE
}

BINARY_SENSOR_TYPES = ('leakage', 'smoke', 'opening', 'motion')
VALID_TYPE_SENSOR = {
'pressure': 'бар',
'temperature': '°',
'speed': 'км/ч',
'volume': 'л',
'volume_flow_rate': ('л/ч', 'м³/ч'),
'frequency': ('Гц', 'об/мин'),
'power': ('Вт', 'ВА'),
'reactive_power': 'ВАР',
'volatile_organic_compounds_parts': 'ppm',
'energy': 'кВт•ч'
}

BINARY_SENSOR_TYPES = ('leakage', 'smoke', 'opening', 'motion', 'discrete')

MIN_TEMP_AIR = 5
MAX_TEMP_AIR = 35
Expand Down Expand Up @@ -94,7 +108,7 @@

HEATING_MODES = {
'комфорт': 'mdi:emoticon-happy-outline',
'эконом': 'mdi:leaf-circle-outline',
'эко': 'mdi:leaf-circle-outline',
'лето': 'mdi:weather-sunny',
'расписание': 'mdi:clock-outline',
'выкл': 'mdi:power',
Expand All @@ -103,3 +117,12 @@
'не дома': 'mdi:home-off-outline',
'гвс': 'mdi:water-boiler',
}

PERCENT_BATTERY = {
3.0: 90,
2.9: 80,
2.8: 70,
2.7: 60,
2.6: 50,
2.5: 40
}
2 changes: 1 addition & 1 deletion custom_components/zont_ha/core/models_zont.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ class DeviceZONT(BaseEntityZONT):
online: bool
widget_type: str | None
heating_circuits: list[HeatingCircuitZONT] = []
heating_modes: list[HeatingModeZONT] | None
heating_modes: list[HeatingModeZONT] = []
boiler_circuits: list[BoilerCircuitZONT] = []
boiler_modes: list[BoilerModeZONT] = []
sensors: list[SensorZONT] = []
Expand Down
25 changes: 23 additions & 2 deletions custom_components/zont_ha/core/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
from aiohttp import ClientResponse

from .exceptions import ResponseZontError
from ..const import HEATING_MODES, VALID_UNITS
from ..const import HEATING_MODES, VALID_UNITS, VALID_TYPE_SENSOR
from .models_zont import SensorZONT

_LOGGER = logging.getLogger(__name__)

Expand Down Expand Up @@ -66,8 +67,28 @@ def get_icon(name_mode: str) -> str:
return 'mdi:refresh-circle'


def get_unit_sensor(type_sensor, unit_sensor):
def get_unit_sensor(type_sensor, unit_sensor) -> str:
try:
return VALID_UNITS[unit_sensor]
except KeyError:
return VALID_UNITS[type_sensor]


def get_devise_class_by_name(name: str) -> str | None:
if 'мощн' in name.lower():
return 'power_factor'
elif 'влажн' in name.lower():
return 'humidity'
else:
return None


def get_devise_class_sensor(sensor: SensorZONT) -> str:
if sensor.type == 'voltage' and sensor.unit != 'В':
if sensor.unit == '%':
return get_devise_class_by_name(sensor.name)
for device_class, unit in VALID_TYPE_SENSOR.items():
if sensor.unit in unit:
return device_class
else:
return sensor.type
28 changes: 20 additions & 8 deletions custom_components/zont_ha/core/zont.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
MIN_TEMP_AIR, MAX_TEMP_AIR, MIN_TEMP_GVS, MAX_TEMP_GVS, MIN_TEMP_FLOOR,
MAX_TEMP_FLOOR, MATCHES_GVS, MATCHES_FLOOR, URL_TRIGGER_CUSTOM_BUTTON,
URL_SET_GUARD, BINARY_SENSOR_TYPES, URL_SEND_COMMAND_ZONT,
URL_GET_DEVICES_OLD, NO_ERROR, URL_ACTIVATE_HEATING_MODE,
URL_GET_DEVICES_OLD, NO_ERROR, URL_ACTIVATE_HEATING_MODE, PERCENT_BATTERY,
)

_LOGGER = logging.getLogger(__name__)
Expand All @@ -36,7 +36,7 @@
)

TypeBinarySensorZont = namedtuple('TypeBinarySensorZont', [
'leakage', 'smoke', 'opening', 'motion'
'leakage', 'smoke', 'opening', 'motion', 'discrete'
])

type_binary_sensor = TypeBinarySensorZont(*BINARY_SENSOR_TYPES)
Expand Down Expand Up @@ -95,8 +95,7 @@ def _create_sensors(self):
self._create_radio_sensors(device)
self._create_error_boiler_sensors(device)

@staticmethod
def _create_radio_sensors(device: DeviceZONT):
def _create_radio_sensors(self, device: DeviceZONT):
"""
Создает дополнительные сенсоры
уровня батареи и связи для радио датчиков
Expand All @@ -107,18 +106,29 @@ def _create_radio_sensors(device: DeviceZONT):
device.sensors.append(SensorZONT(
id=f'{sensor.id}_rssi',
name=f'{sensor.name}_rssi',
type='rssi',
type='signal_strength',
status='ok',
value=sensor.rssi
))
device.sensors.append(SensorZONT(
id=f'{sensor.id}_battery',
name=f'{sensor.name}_battery',
type='voltage',
type='battery',
status='ok',
value=sensor.battery
value=self._convert_value_battery(sensor.battery)
))

@staticmethod
def _convert_value_battery(value: float) -> int:
"""Преобразовывает напряжение батарейки в уровень заряда в %"""
value = round(value, 1)
if value > 3.0:
return 100
elif value < 2.5:
return 0
else:
return PERCENT_BATTERY[value]

@staticmethod
def _create_error_boiler_sensors(device: DeviceZONT):
"""Создаёт дополнительные сенсоры ошибок котла"""
Expand All @@ -131,7 +141,7 @@ def _create_error_boiler_sensors(device: DeviceZONT):
device.sensors.append(SensorZONT(
id=f'{boiler.id}_boiler',
name=f'{boiler.name}_ошибка',
type='txt',
type='err',
status='ok',
value=code_err + text
))
Expand Down Expand Up @@ -243,6 +253,8 @@ def is_on_binary(self, device: DeviceZONT, sensor: SensorZONT) -> bool:
return self._is_on_smoke(voltage, current_value)
case type_binary_sensor.opening | type_binary_sensor.motion:
return self._is_on_contact(voltage, current_value)
case type_binary_sensor.discrete:
return bool(sensor.value)
case _:
_LOGGER.warning(f"Unknown sensor type: {sensor.type}")
return False
Expand Down
2 changes: 1 addition & 1 deletion custom_components/zont_ha/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,5 @@
"integration_type": "hub",
"dependencies": ["http", "zeroconf"],
"requirements": [],
"version": "0.5.2"
"version": "0.5.2-beta"
}
8 changes: 6 additions & 2 deletions custom_components/zont_ha/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
from .const import DOMAIN, BINARY_SENSOR_TYPES
from .core.exceptions import SensorNotFoundError
from .core.models_zont import SensorZONT, DeviceZONT, OTSensorZONT
from .core.utils import get_unit_sensor
from .core.utils import get_unit_sensor, get_devise_class_sensor

_LOGGER = logging.getLogger(__name__)

Expand Down Expand Up @@ -51,6 +51,8 @@ def __init__(
self._sensor = sensor
self._unique_id = unique_id
self._attr_device_info = coordinator.devices_info(device.id)
if sensor.type == 'err':
self._attr_icon = 'mdi:wrench-outline'

@property
def name(self) -> str:
Expand All @@ -59,6 +61,8 @@ def name(self) -> str:
@property
def native_value(self) -> float | str:
"""Возвращает состояние сенсора"""
if self._sensor.type == 'battery':
return int(self._sensor.value)
return self._sensor.value

@property
Expand All @@ -72,7 +76,7 @@ def unique_id(self) -> str:

@property
def device_class(self) -> str | None:
return self._sensor.type
return get_devise_class_sensor(self._sensor)

def __repr__(self) -> str:
if not self.hass:
Expand Down

0 comments on commit 5af61d2

Please sign in to comment.