Skip to content

Commit

Permalink
debugging an dcode review: param unit added
Browse files Browse the repository at this point in the history
  • Loading branch information
OStrama committed Dec 3, 2024
1 parent beb7021 commit bd73539
Show file tree
Hide file tree
Showing 10 changed files with 96 additions and 106 deletions.
2 changes: 1 addition & 1 deletion custom_components/weishaupt_modbus/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,6 @@ async def async_setup_entry(hass: HomeAssistant, entry: MyConfigEntry) -> bool:
# with your actual devices.
# hass.data.setdefault(DOMAIN, {})[entry.entry_id] = hub.Hub(hass, entry.data["host"])
mbapi = ModbusAPI(config_entry=entry)
await mbapi.connect()

if entry.data[CONF.CB_WEBIF]:
print
Expand Down Expand Up @@ -156,6 +155,7 @@ async def async_migrate_entry(hass: HomeAssistant, config_entry: MyConfigEntry):
new_data[CONF.NAME_TOPIC_PREFIX] = False

if config_entry.version < 5:
new_data[CONF.CB_WEBIF] = False
new_data[CONF.USERNAME] = ""
new_data[CONF.PASSWORD] = ""
hass.config_entries.async_update_entry(
Expand Down
2 changes: 1 addition & 1 deletion custom_components/weishaupt_modbus/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ async def validate_input(data: dict) -> dict[str, Any]:
class ConfigFlow(config_entries.ConfigFlow, domain=CONST.DOMAIN):
"""Class config flow."""

VERSION = 5 # 6
VERSION = 5
# Pick one of the available connection classes in homeassistant/config_entries.py
# This tells HA if it should be asking for updates, or it'll be notified of updates
# automatically. This example uses PUSH, as the dummy hub will notify HA of
Expand Down
28 changes: 11 additions & 17 deletions custom_components/weishaupt_modbus/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,6 @@
CONF_PASSWORD,
CONF_PREFIX,
CONF_USERNAME,
PERCENTAGE,
UnitOfEnergy,
UnitOfPower,
UnitOfTemperature,
UnitOfTime,
UnitOfVolumeFlowRate,
)


Expand Down Expand Up @@ -60,17 +54,17 @@ class MainConstants:
class FormatConstants:
"""Format constants."""

TEMPERATUR = UnitOfTemperature.CELSIUS
ENERGY = UnitOfEnergy.KILO_WATT_HOUR
POWER = UnitOfPower.WATT
PERCENTAGE = PERCENTAGE
NUMBER = ""
STATUS = "Status"
VOLUMENSTROM = UnitOfVolumeFlowRate.CUBIC_METERS_PER_HOUR
KENNLINIE = " " # has to be different from NUMBER we'd have to separate unit strings and format...
TIME_MIN = UnitOfTime.MINUTES
TIME_H = UnitOfTime.HOURS
UNKNOWN = "?"
TEMPERATUR = "temperature"
ENERGY = "energy"
POWER = "power"
PERCENTAGE = "percentage"
NUMBER = "number"
STATUS = "status"
VOLUMENSTROM = "flowrate"
KENNLINIE = "kennlinie"
TIME_MIN = "minutes"
TIME_H = "hours"
UNKNOWN = "unknown"


FORMATS = FormatConstants()
Expand Down
61 changes: 31 additions & 30 deletions custom_components/weishaupt_modbus/coordinator.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,7 @@
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator

from .configentry import MyConfigEntry
from .const import CONF, CONST, FORMATS, TYPES
from .hpconst import DEVICES, PARAMS_STDTEMP
from .const import CONST, TYPES, DEVICES, CONF
from .items import ModbusItem
from .modbusobject import ModbusAPI, ModbusObject
from .webif_object import WebifConnection
Expand All @@ -20,6 +19,27 @@
log = logging.getLogger(__name__)


async def check_configured(
modbus_item: ModbusItem, config_entry: MyConfigEntry
) -> bool:
"""Check if item is configured.
:param modbus_item: definition of modbus item
:type modbus_item: ModbusItem
:param config_entry: HASS config entry
:type config_entry: MyConfigEntry
"""
if modbus_item.device is DEVICES.HZ2:
return config_entry.data[CONF.HK2]
if modbus_item.device is DEVICES.HZ3:
return config_entry.data[CONF.HK3]
if modbus_item.device is DEVICES.HZ4:
return config_entry.data[CONF.HK4]
if modbus_item.device is DEVICES.HZ5:
return config_entry.data[CONF.HK5]
return True


class MyCoordinator(DataUpdateCoordinator):
"""My custom coordinator."""

Expand All @@ -44,7 +64,7 @@ def __init__(
always_update=True,
)
self._modbus_api = my_api
self._device = None #: MyDevice | None = None
self._device = None
self._modbusitems = api_items
self._number_of_items = len(api_items)
self._config_entry = p_config_entry
Expand All @@ -54,37 +74,17 @@ async def get_value(self, modbus_item: ModbusItem):
mbo = ModbusObject(self._modbus_api, modbus_item)
if mbo is None:
modbus_item.state = None
modbus_item.state = await mbo.value
log.debug("Get value:%s from item:%s",str(modbus_item.state), modbus_item.translation_key)
else:
modbus_item.state = await mbo.value
return modbus_item.state

def get_value_from_item(self, translation_key: str) -> int:
"""Read a value from another modbus item"""
for _useless, item in enumerate(self._modbusitems):
if item.translation_key == translation_key:
log.debug("Get calc value:%s from item:%s",str(item.state), item.translation_key)
return item.state
return None

async def check_configured(self, modbus_item: ModbusItem) -> bool:
"""Check if item is configured."""
if self._config_entry.data[CONF.HK2] is False:
if modbus_item.device is DEVICES.HZ2:
return False

if self._config_entry.data[CONF.HK3] is False:
if modbus_item.device is DEVICES.HZ3:
return False

if self._config_entry.data[CONF.HK4] is False:
if modbus_item.device is DEVICES.HZ4:
return False

if self._config_entry.data[CONF.HK5] is False:
if modbus_item.device is DEVICES.HZ5:
return False
return True

async def _async_setup(self):
"""Set up the coordinator.
Expand All @@ -94,7 +94,7 @@ async def _async_setup(self):
This method will be called automatically during
coordinator.async_config_entry_first_refresh.
"""
await self.fetch_data()
await self._modbus_api.connect()

async def fetch_data(self, idx=None):
"""Fetch all values from the modbus."""
Expand All @@ -112,8 +112,9 @@ async def fetch_data(self, idx=None):
# await self._modbus_api.connect()
for index in to_update:
item = self._modbusitems[index]
# At setup the coordinator has to be called before buildentitylist. Therefore check if we should add HZ2,3,4,5...
if await self.check_configured(item) is True:
# At setup the coordinator has to be called before buildentitylist.
# Therefore check if we should add HZ2,3,4,5...
if await check_configured(item, self._config_entry) is True:
match item.type:
# here the entities are created with the parameters provided
# by the ModbusItem object
Expand All @@ -139,8 +140,8 @@ async def _async_update_data(self):
# Note: using context is not required if there is no need or ability to limit
# data retrieved from API.
try:
listening_idx = set(self.async_contexts())
return await self.fetch_data() #listening_idx)
# listening_idx = set(self.async_contexts())
return await self.fetch_data() # !!!!!using listening_idx will result in some entities nevwer updated !!!!!
except ModbusException:
log.warning("connection to the heatpump failed")

Expand Down
22 changes: 7 additions & 15 deletions custom_components/weishaupt_modbus/entities.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,23 +80,19 @@ def __init__(

self._modbus_api = modbus_api

if self._api_item.format != FORMATS.STATUS:
self._attr_native_unit_of_measurement = self._api_item.format

if self._api_item.format == FORMATS.STATUS:
self._divider = 1
else:
match self._api_item.format:
case FORMATS.ENERGY:
self._attr_state_class = SensorStateClass.TOTAL_INCREASING
case (
FORMATS.TEMPERATUR
| FORMATS.POWER
| FORMATS.PERCENTAGE
| FORMATS.TIME_H
| FORMATS.TIME_MIN
| FORMATS.UNKNOWN
):
case _:
self._attr_state_class = SensorStateClass.MEASUREMENT

if self._api_item.params is not None:
self._attr_native_unit_of_measurement = self._api_item.params.get(
"unit", ""
)
self._attr_native_step = self._api_item.params.get("step", 1)
self._divider = self._api_item.params.get("divider", 1)
self._attr_device_class = self._api_item.params.get("deviceclass", None)
Expand Down Expand Up @@ -204,7 +200,6 @@ def __init__(
def _handle_coordinator_update(self) -> None:
"""Handle updated data from the coordinator."""
self._attr_native_value = self.translate_val(self._api_item.state)
log.debug("Entity update val:%s item:%s",str(self._attr_native_value), self._api_item.translation_key)
self.async_write_ha_state()

@property
Expand Down Expand Up @@ -243,7 +238,6 @@ def __init__(
def _handle_coordinator_update(self) -> None:
"""Handle updated data from the coordinator."""
self._attr_native_value = self.translate_val(self._api_item.state)
log.debug("Entity update val:%s item:%s",str(self._attr_native_value), self._api_item.translation_key)
self.async_write_ha_state()

def translate_val(self, val):
Expand Down Expand Up @@ -334,7 +328,6 @@ def __init__(
def _handle_coordinator_update(self) -> None:
"""Handle updated data from the coordinator."""
self._attr_native_value = self.translate_val(self._api_item.state)
log.debug("Entity update val:%s item:%s",str(self._attr_native_value), self._api_item.translation_key)
self.async_write_ha_state()

async def async_set_native_value(self, value: float) -> None:
Expand Down Expand Up @@ -380,7 +373,6 @@ async def async_select_option(self, option: str) -> None:
"""Write the selected option to modbus and refresh HA."""
self._api_item.state = await self.set_translate_val(option)
self._attr_current_option = self.translate_val(self._api_item.state)
log.debug("Entity update opt:%s item:%s",str(self._attr_current_option), self._api_item.translation_key)
self.async_write_ha_state()

@callback
Expand Down
28 changes: 4 additions & 24 deletions custom_components/weishaupt_modbus/entity_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
from .configentry import MyConfigEntry
from .items import ModbusItem, WebItem
from .modbusobject import ModbusObject
from .const import DEVICES, CONF, TYPES
from .coordinator import MyCoordinator
from .const import TYPES
from .coordinator import MyCoordinator, check_configured
from .entities import MySensorEntity, MyCalcSensorEntity, MyNumberEntity, MySelectEntity

logging.basicConfig()
Expand All @@ -20,28 +20,13 @@ async def check_available(modbus_item: ModbusItem, config_entry: MyConfigEntry)
:param modbus_item: definition of modbus item
:type modbus_item: ModbusItem
"""
log.debug("Check if item %s is available ..", modbus_item.translation_key)
if config_entry.data[CONF.HK2] is False:
if modbus_item.device is DEVICES.HZ2:
return False

if config_entry.data[CONF.HK3] is False:
if modbus_item.device is DEVICES.HZ3:
return False

if config_entry.data[CONF.HK4] is False:
if modbus_item.device is DEVICES.HZ4:
return False

if config_entry.data[CONF.HK5] is False:
if modbus_item.device is DEVICES.HZ5:
return False
if await check_configured(modbus_item, config_entry) is False:
return False

_modbus_api = config_entry.runtime_data.modbus_api
mbo = ModbusObject(_modbus_api, modbus_item)
_useless = await mbo.value
if modbus_item.is_invalid is False:
log.debug("Check availability item %s successful ..", modbus_item.translation_key)
return True
return False

Expand Down Expand Up @@ -73,17 +58,14 @@ async def build_entity_list(
for index, item in enumerate(api_items):
if item.type == item_type:
if await check_available(item, config_entry=config_entry) is True:
log.debug("Add item %s to entity list ..", item.translation_key)
match item_type:
# here the entities are created with the parameters provided
# by the ModbusItem object
case TYPES.SENSOR | TYPES.NUMBER_RO:
log.debug("Add item %s to entity list ..", item.translation_key)
entries.append(
MySensorEntity(config_entry, item, coordinator, index)
)
case TYPES.SENSOR_CALC:
log.debug("Add item %s to entity list ..", item.translation_key)
entries.append(
MyCalcSensorEntity(
config_entry,
Expand All @@ -93,12 +75,10 @@ async def build_entity_list(
)
)
case TYPES.SELECT:
log.debug("Add item %s to entity list ..", item.translation_key)
entries.append(
MySelectEntity(config_entry, item, coordinator, index)
)
case TYPES.NUMBER:
log.debug("Add item %s to entity list ..", item.translation_key)
entries.append(
MyNumberEntity(config_entry, item, coordinator, index)
)
Expand Down
Loading

0 comments on commit bd73539

Please sign in to comment.