Skip to content

Commit

Permalink
refactor: Entity initialization
Browse files Browse the repository at this point in the history
  • Loading branch information
davidrapan committed Dec 15, 2024
1 parent 727dc7c commit afa3929
Show file tree
Hide file tree
Showing 13 changed files with 38 additions and 58 deletions.
7 changes: 0 additions & 7 deletions custom_components/solarman/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,10 +145,6 @@ def __init__(self, config: ConfigurationProvider):
self.modbus: PySolarmanAsync = None
self.device_info: dict = {}

@property
def available(self):
return self.state.value > -1

async def load(self):
try:
self.endpoint = await EndPointProvider(self.config).discover()
Expand All @@ -159,9 +155,6 @@ async def load(self):
except BaseException as e:
raise Exception(f"[{self.config.serial}] Device setup failed. [{format_exception(e)}]") from e

def get_entity_descriptions(self):
return (STATE_SENSORS + self.profile.parser.get_entity_descriptions()) if self.profile and self.profile.parser else []

def check(self, lock):
if lock and self._write_lock:
raise UserWarning("Entity is locked!")
Expand Down
20 changes: 7 additions & 13 deletions custom_components/solarman/binary_sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,22 +19,16 @@

_PLATFORM = get_current_file_name(__name__)

def _create_entity(coordinator, description):
if "artificial" in description:
match description["artificial"]:
case "state":
return SolarmanConnectionSensor(coordinator, description)

return SolarmanBinarySensorEntity(coordinator, description)

async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddEntitiesCallback) -> bool:
_LOGGER.debug(f"async_setup_entry: {config_entry.options}")

coordinator, descriptions = get_coordinator(hass, config_entry.entry_id)
coordinator, descriptions = get_coordinator_descriptions(hass, config_entry.entry_id, _PLATFORM)

_LOGGER.debug(f"async_setup_entry: async_add_entities")
_LOGGER.debug(f"async_setup_entry: async_add_entities: {descriptions}")

async_add_entities(create_entity(lambda x: _create_entity(coordinator, x), d) for d in descriptions if is_platform(d, _PLATFORM))
async_add_entities(create_entity(lambda x: SolarmanBinarySensorEntity(coordinator, x), d) for d in descriptions)

async_add_entities([create_entity(lambda _: SolarmanConnectionSensor(coordinator), None)])

return True

Expand All @@ -55,8 +49,8 @@ def is_on(self) -> bool | None:
return (self._attr_state != 0) if not self._sensor_inverted else (self._attr_state == 0)

class SolarmanConnectionSensor(SolarmanBinarySensorEntity):
def __init__(self, coordinator, sensor):
super().__init__(coordinator, sensor)
def __init__(self, coordinator):
super().__init__(coordinator, {"key": "connection_binary_sensor", "name": "Connection"})
self._attr_device_class = BinarySensorDeviceClass.CONNECTIVITY
self._attr_entity_category = EntityCategory.DIAGNOSTIC

Expand Down
6 changes: 3 additions & 3 deletions custom_components/solarman/button.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,11 @@
async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddEntitiesCallback) -> bool:
_LOGGER.debug(f"async_setup_entry: {config_entry.options}")

coordinator, descriptions = get_coordinator(hass, config_entry.entry_id)
coordinator, descriptions = get_coordinator_descriptions(hass, config_entry.entry_id, _PLATFORM)

_LOGGER.debug(f"async_setup_entry: async_add_entities")
_LOGGER.debug(f"async_setup_entry: async_add_entities: {descriptions}")

async_add_entities(create_entity(lambda x: SolarmanButtonEntity(coordinator, x), d) for d in descriptions if is_platform(d, _PLATFORM))
async_add_entities(create_entity(lambda x: SolarmanButtonEntity(coordinator, x), d) for d in descriptions)

return True

Expand Down
7 changes: 2 additions & 5 deletions custom_components/solarman/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,9 @@ def execute_async(x):
loop = asyncio.get_event_loop()
return loop.run_until_complete(x)

def get_coordinator(hass: HomeAssistant, entry_id: str):
def get_coordinator_descriptions(hass: HomeAssistant, entry_id: str, platform: str):
coordinator = hass.data[DOMAIN][entry_id]
return coordinator, coordinator.inverter.get_entity_descriptions()
return coordinator, coordinator.inverter.profile.parser.get_entity_descriptions(platform)

def to_dict(*keys: list):
return {k: k for k in keys}
Expand Down Expand Up @@ -117,9 +117,6 @@ def build_device_info(serial, mac, name, info, filename):

return device_info

def is_platform(description, value):
return (description["platform"] if "platform" in description else "sensor") == value

def all_equals(values, value):
return all(i == value for i in values)

Expand Down
2 changes: 0 additions & 2 deletions custom_components/solarman/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,6 @@

ATTR_ = { CONF_MOD: CONF_MOD, CONF_MPPT: CONF_MPPT, CONF_PHASE: "l" }

STATE_SENSORS = [{"key": "Connection binary_sensor", "name": "Connection", "artificial": "state", "platform": "binary_sensor"}, {"key": "Update Interval sensor", "name": "Update Interval", "artificial": "interval", "platform": "sensor"}]

CONTROL_CODE = types.SimpleNamespace()
CONTROL_CODE.REQUEST = struct.pack("<H", 0x4510)
CONTROL_CODE.RESPONSE = struct.pack("<H", 0x1510)
Expand Down
6 changes: 3 additions & 3 deletions custom_components/solarman/datetime.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,11 @@
async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddEntitiesCallback) -> bool:
_LOGGER.debug(f"async_setup_entry: {config_entry.options}")

coordinator, descriptions = get_coordinator(hass, config_entry.entry_id)
coordinator, descriptions = get_coordinator_descriptions(hass, config_entry.entry_id, _PLATFORM)

_LOGGER.debug(f"async_setup_entry: async_add_entities")
_LOGGER.debug(f"async_setup_entry: async_add_entities: {descriptions}")

async_add_entities(create_entity(lambda x: SolarmanDateTimeEntity(coordinator, x), d) for d in descriptions if is_platform(d, _PLATFORM))
async_add_entities(create_entity(lambda x: SolarmanDateTimeEntity(coordinator, x), d) for d in descriptions)

return True

Expand Down
2 changes: 1 addition & 1 deletion custom_components/solarman/entity.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ def device_name(self) -> str:

@property
def available(self) -> bool:
return self.coordinator.last_update_success and self.coordinator.inverter.available
return self.coordinator.last_update_success and self.coordinator.inverter.state.value > -1

@callback
def _handle_coordinator_update(self) -> None:
Expand Down
6 changes: 3 additions & 3 deletions custom_components/solarman/number.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,11 @@
async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddEntitiesCallback) -> bool:
_LOGGER.debug(f"async_setup_entry: {config_entry.options}")

coordinator, descriptions = get_coordinator(hass, config_entry.entry_id)
coordinator, descriptions = get_coordinator_descriptions(hass, config_entry.entry_id, _PLATFORM)

_LOGGER.debug(f"async_setup_entry: async_add_entities")
_LOGGER.debug(f"async_setup_entry: async_add_entities: {descriptions}")

async_add_entities(create_entity(lambda x: SolarmanNumberEntity(coordinator, x), d) for d in descriptions if is_platform(d, _PLATFORM))
async_add_entities(create_entity(lambda x: SolarmanNumberEntity(coordinator, x), d) for d in descriptions)

return True

Expand Down
4 changes: 2 additions & 2 deletions custom_components/solarman/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,8 @@ def default_from_unit_of_measurement(self, parameters):
def set_state(self, key, state, value = None):
self._result[key] = (state, value)

def get_entity_descriptions(self):
return [i for i in self._items if self.is_valid(i) and not "attribute" in i]
def get_entity_descriptions(self, platform: str):
return [i for i in self._items if self.is_valid(i) and not "attribute" in i and i.get("platform") == platform]

def schedule_requests(self, runtime = 0):
self._result = {}
Expand Down
6 changes: 3 additions & 3 deletions custom_components/solarman/select.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,11 @@
async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddEntitiesCallback) -> bool:
_LOGGER.debug(f"async_setup_entry: {config_entry.options}")

coordinator, descriptions = get_coordinator(hass, config_entry.entry_id)
coordinator, descriptions = get_coordinator_descriptions(hass, config_entry.entry_id, _PLATFORM)

_LOGGER.debug(f"async_setup_entry: async_add_entities")
_LOGGER.debug(f"async_setup_entry: async_add_entities: {descriptions}")

async_add_entities(create_entity(lambda x: SolarmanSelectEntity(coordinator, x), d) for d in descriptions if is_platform(d, _PLATFORM))
async_add_entities(create_entity(lambda x: SolarmanSelectEntity(coordinator, x), d) for d in descriptions)

return True

Expand Down
18 changes: 8 additions & 10 deletions custom_components/solarman/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,7 @@
_PLATFORM = get_current_file_name(__name__)

def _create_entity(coordinator, description, options):
if "artificial" in description:
match description["artificial"]:
case "interval":
return SolarmanIntervalSensor(coordinator, description)
elif (name := description["name"]) and "Battery" in name and (additional := options.get(CONF_ADDITIONAL_OPTIONS, {})) is not None:
if (name := description["name"]) and "Battery" in name and (additional := options.get(CONF_ADDITIONAL_OPTIONS, {})) is not None:
battery_nominal_voltage = additional.get(CONF_BATTERY_NOMINAL_VOLTAGE, DEFAULT_[CONF_BATTERY_NOMINAL_VOLTAGE])
battery_life_cycle_rating = additional.get(CONF_BATTERY_LIFE_CYCLE_RATING, DEFAULT_[CONF_BATTERY_LIFE_CYCLE_RATING])
if "registers" in description:
Expand All @@ -51,11 +47,13 @@ def _create_entity(coordinator, description, options):
async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddEntitiesCallback) -> bool:
_LOGGER.debug(f"async_setup_entry: {config_entry.options}")

coordinator, descriptions = get_coordinator(hass, config_entry.entry_id)
coordinator, descriptions = get_coordinator_descriptions(hass, config_entry.entry_id, _PLATFORM)

_LOGGER.debug(f"async_setup_entry: async_add_entities")
_LOGGER.debug(f"async_setup_entry: async_add_entities: {descriptions}")

async_add_entities(create_entity(lambda x: _create_entity(coordinator, x, config_entry.options), d) for d in descriptions if is_platform(d, _PLATFORM))
async_add_entities(create_entity(lambda x: _create_entity(coordinator, x, config_entry.options), d) for d in descriptions)

async_add_entities([create_entity(lambda _: SolarmanIntervalSensor(coordinator), None)])

return True

Expand All @@ -71,8 +69,8 @@ def __init__(self, coordinator, sensor):
self._attr_state_class = state_class

class SolarmanIntervalSensor(SolarmanSensorEntity):
def __init__(self, coordinator, sensor):
super().__init__(coordinator, sensor)
def __init__(self, coordinator):
super().__init__(coordinator, {"key": "update_interval_sensor", "name": "Update Interval"})
self._attr_entity_category = EntityCategory.DIAGNOSTIC
self._attr_native_unit_of_measurement = "s"
self._attr_state_class = "duration"
Expand Down
6 changes: 3 additions & 3 deletions custom_components/solarman/switch.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,11 @@
async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddEntitiesCallback) -> bool:
_LOGGER.debug(f"async_setup_entry: {config_entry.options}")

coordinator, descriptions = get_coordinator(hass, config_entry.entry_id)
coordinator, descriptions = get_coordinator_descriptions(hass, config_entry.entry_id, _PLATFORM)

_LOGGER.debug(f"async_setup_entry: async_add_entities")
_LOGGER.debug(f"async_setup_entry: async_add_entities: {descriptions}")

async_add_entities(create_entity(lambda x: SolarmanSwitchEntity(coordinator, x), d) for d in descriptions if is_platform(d, _PLATFORM))
async_add_entities(create_entity(lambda x: SolarmanSwitchEntity(coordinator, x), d) for d in descriptions)

return True

Expand Down
6 changes: 3 additions & 3 deletions custom_components/solarman/time.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,11 @@
async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddEntitiesCallback) -> bool:
_LOGGER.debug(f"async_setup_entry: {config_entry.options}")

coordinator, descriptions = get_coordinator(hass, config_entry.entry_id)
coordinator, descriptions = get_coordinator_descriptions(hass, config_entry.entry_id, _PLATFORM)

_LOGGER.debug(f"async_setup_entry: async_add_entities")
_LOGGER.debug(f"async_setup_entry: async_add_entities: {descriptions}")

async_add_entities(create_entity(lambda x: SolarmanTimeEntity(coordinator, x), d) for d in descriptions if is_platform(d, _PLATFORM))
async_add_entities(create_entity(lambda x: SolarmanTimeEntity(coordinator, x), d) for d in descriptions)

return True

Expand Down

0 comments on commit afa3929

Please sign in to comment.