Skip to content

Commit

Permalink
Async is a fickly beast ...
Browse files Browse the repository at this point in the history
Signed-off-by: stefan <[email protected]>
  • Loading branch information
RustyDust committed Dec 30, 2024
1 parent 386f0d6 commit 6830fd5
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 19 deletions.
16 changes: 10 additions & 6 deletions custom_components/sonnenbatterie/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,14 +65,15 @@
)

async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool:
LOGGER.info(f"setup_entry: {json.dumps(dict(config_entry.data))}\n{json.dumps(dict(config_entry.options))}")
LOGGER.info(f"setup_entry: {config_entry.data}\n{config_entry.options}")
ip_address = config_entry.data["ip_address"]
password = config_entry.data["password"]
username = config_entry.data["username"]

sb = AsyncSonnenBatterie(username, password, ip_address)
await sb.login()
inverter_power = int((await sb.get_batterysystem())['battery_system']['system']['inverter_capacity'])
await sb.logout()

# noinspection PyPep8Naming
SCHEMA_CHARGE_BATTERY = vol.Schema(
Expand All @@ -85,7 +86,7 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> b
await hass.config_entries.async_forward_entry_setups(config_entry, [ Platform.SENSOR ])
# rustydust_241227: this doesn't seem to be needed
# config_entry.add_update_listener(update_listener)
config_entry.async_on_unload(config_entry.add_update_listener(async_reload_entry))
# config_entry.async_on_unload(config_entry.add_update_listener(async_reload_entry))


# service definitions
Expand Down Expand Up @@ -152,6 +153,7 @@ async def set_tou_schedule(call: ServiceCall) -> ServiceResponse:
"schedule": response["EM_ToU_Schedule"],
}

# noinspection PyUnusedLocal
async def get_tou_schedule(call: ServiceCall) -> ServiceResponse:
await sb.login()
response = await sb.sb2.get_tou_schedule_string()
Expand Down Expand Up @@ -218,10 +220,11 @@ async def get_tou_schedule(call: ServiceCall) -> ServiceResponse:
# Done setting up the entry
return True

async def async_reload_entry(hass, entry):
"""Reload config entry."""
await async_unload_entry(hass, entry)
await async_setup_entry(hass, entry)
# rustydust_241230: no longer needed
# async def async_reload_entry(hass, entry):
# """Reload config entry."""
# await async_unload_entry(hass, entry)
# await async_setup_entry(hass, entry)

# rustydust_241227: this doesn't seem to be needed
# async def update_listener(hass, entry):
Expand All @@ -233,4 +236,5 @@ async def async_reload_entry(hass, entry):

async def async_unload_entry(hass, entry):
"""Handle removal of an entry."""
LOGGER.info(f"Unloading config entry: {entry}")
return await hass.config_entries.async_forward_entry_unload(entry, Platform.SENSOR)
24 changes: 18 additions & 6 deletions custom_components/sonnenbatterie/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,10 @@ class SonnenbatterieFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):

CONFIG_SCHEMA_USER = vol.Schema(
{
vol.Required(CONF_IP_ADDRESS, default="127.0.0.1"): str,
vol.Required(CONF_IP_ADDRESS, default="192.168.0.1"): str,
vol.Required(CONF_USERNAME): vol.In(["User", "Installer"]),
vol.Required(CONF_PASSWORD, default="sonnenUser3552"): str,
vol.Required(CONF_SCAN_INTERVAL, default=DEFAULT_SCAN_INTERVAL): vol.Range(min=10, max=3600),
vol.Optional(CONF_SCAN_INTERVAL, default=DEFAULT_SCAN_INTERVAL): int,
vol.Optional(ATTR_SONNEN_DEBUG, default=DEFAULT_SONNEN_DEBUG): cv.boolean,
}
)
Expand All @@ -52,15 +52,21 @@ async def async_step_user(self, user_input=None):
LOGGER.error(f"Unable to connect to sonnenbatterie: {e}")
return self._show_form({"base": "connection_error"})

# async is a fickly beast ...
sb_serial = await my_serial
unique_id = f"{DOMAIN}-{sb_serial}"
await self.async_set_unique_id(unique_id)
self._abort_if_unique_id_configured()

return self.async_create_entry(
title=f"{user_input[CONF_IP_ADDRESS]} ({my_serial})",
title=f"{user_input[CONF_IP_ADDRESS]} ({sb_serial})",
data={
CONF_USERNAME: username,
CONF_PASSWORD: password,
CONF_IP_ADDRESS: ipaddress,
CONF_SCAN_INTERVAL: user_input[CONF_SCAN_INTERVAL],
ATTR_SONNEN_DEBUG: user_input[ATTR_SONNEN_DEBUG],
CONF_SERIAL_NUMBER: my_serial,
CONF_SERIAL_NUMBER: sb_serial,
},
)

Expand Down Expand Up @@ -98,6 +104,7 @@ async def async_step_reconfigure(self, user_input):
)

if user_input is not None:
LOGGER.info(f"Reconfiguring {entry}")
if entry.data.get(CONF_SERIAL_NUMBER):
await self.async_set_unique_id(entry.data[CONF_SERIAL_NUMBER])
self._abort_if_unique_id_configured()
Expand All @@ -119,10 +126,12 @@ async def async_step_reconfigure(self, user_input):
errors={"base": "connection_error"},
)

# async is a fickly beast ...
sb_serial = await my_serial
return self.async_update_reload_and_abort(
self._get_reconfigure_entry(),
data_updates=user_input,
title=f"{user_input[CONF_IP_ADDRESS]} ({my_serial})",
title=f"{user_input[CONF_IP_ADDRESS]} ({sb_serial})",
)


Expand All @@ -135,7 +144,10 @@ async def async_step_reconfigure(self, user_input):
@staticmethod
async def _internal_setup(_username, _password, _ipaddress):
sb_test = AsyncSonnenBatterie(_username, _password, _ipaddress)
return await sb_test.get_systemdata().get("DE_Ticket_Number", "Unknown")
await sb_test.login()
result = (await sb_test.get_systemdata()).get("DE_Ticket_Number", "Unknown")
await sb_test.logout()
return result

@callback
def _show_form(self, errors=None):
Expand Down
6 changes: 2 additions & 4 deletions custom_components/sonnenbatterie/coordinator.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,13 +103,11 @@ async def _async_update_data(self):
self.latestData["system_data"] = await result

except Exception as ex:
if self.debug:
e = traceback.format_exc()
LOGGER.error(e)
LOGGER.info(traceback.format_exc())
if self._last_error is not None:
elapsed = time() - self._last_error
if elapsed > timedelta(seconds=180).total_seconds():
LOGGER.warning(f"Unable to connecto to Sonnenbatteries at {self.ip_address} for {elapsed} seconds. Please check! [{ex}]")
LOGGER.error(f"Unable to connecto to Sonnenbatteries at {self.ip_address} for {elapsed} seconds. Please check! [{ex}]")
else:
self._last_error = time()

Expand Down
3 changes: 0 additions & 3 deletions custom_components/sonnenbatterie/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,6 @@
generate_powermeter_sensors,
)

_LOGGER = logging.getLogger(__name__)


# rustydust_241227: this doesn't seem to be used anywhere
# async def async_unload_entry(hass, entry):
# """Unload a config entry."""
Expand Down

0 comments on commit 6830fd5

Please sign in to comment.