Skip to content

Commit

Permalink
Merge pull request #534 from kylegordon/octopus-energy-v10.3.1
Browse files Browse the repository at this point in the history
Octopus Energy v10.3.1
  • Loading branch information
kylegordon authored May 12, 2024
2 parents 16e5366 + 90b4b52 commit c9703b2
Show file tree
Hide file tree
Showing 85 changed files with 1,000 additions and 3,054 deletions.
82 changes: 16 additions & 66 deletions custom_components/octopus_energy/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,23 +5,18 @@
from homeassistant.helpers import device_registry as dr
from homeassistant.components.recorder import get_instance
from homeassistant.util.dt import (utcnow)
from homeassistant.const import (
EVENT_HOMEASSISTANT_STOP
)

from .coordinators.account import AccountCoordinatorResult, async_setup_account_info_coordinator
from .coordinators.intelligent_dispatches import async_setup_intelligent_dispatches_coordinator
from .coordinators.intelligent_settings import async_setup_intelligent_settings_coordinator
from .coordinators.electricity_rates import async_setup_electricity_rates_coordinator
from .coordinators.saving_sessions import async_setup_saving_sessions_coordinators
from .coordinators.greenness_forecast import async_setup_greenness_forecast_coordinator
from .statistics import get_statistic_ids_to_remove
from .intelligent import async_mock_intelligent_data, get_intelligent_features, is_intelligent_tariff, mock_intelligent_device

from .config.main import async_migrate_main_config
from .config.target_rates import async_migrate_target_config
from .utils import get_active_tariff_code
from .utils.tariff_overrides import async_get_tariff_override

from .const import (
CONFIG_KIND,
Expand All @@ -39,6 +34,8 @@
CONFIG_ACCOUNT_ID,
CONFIG_MAIN_ELECTRICITY_PRICE_CAP,
CONFIG_MAIN_GAS_PRICE_CAP,

CONFIG_TARGET_NAME,

DATA_CLIENT,
DATA_ELECTRICITY_RATES_COORDINATOR_KEY,
Expand Down Expand Up @@ -78,13 +75,6 @@ async def async_migrate_entry(hass, config_entry):

return True

async def _async_close_client(hass, account_id: str):
if account_id in hass.data[DOMAIN] and DATA_CLIENT in hass.data[DOMAIN][account_id]:
_LOGGER.debug('Closing client...')
client: OctopusEnergyApiClient = hass.data[DOMAIN][account_id][DATA_CLIENT]
await client.async_close()
_LOGGER.debug('Client closed.')

async def async_setup_entry(hass, entry):
"""This is called from the config flow."""
hass.data.setdefault(DOMAIN, {})
Expand All @@ -100,22 +90,6 @@ async def async_setup_entry(hass, entry):
if config[CONFIG_KIND] == CONFIG_KIND_ACCOUNT:
await async_setup_dependencies(hass, config)
await hass.config_entries.async_forward_entry_setups(entry, ACCOUNT_PLATFORMS)

async def async_close_connection(_) -> None:
"""Close client."""
await _async_close_client(hass, account_id)

entry.async_on_unload(
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, async_close_connection)
)

# If the main account has been reloaded, then reload all other entries to make sure they're referencing
# the correct references (e.g. rate coordinators)
child_entries = hass.config_entries.async_entries(DOMAIN)
for child_entry in child_entries:
if child_entry.data[CONFIG_KIND] != CONFIG_KIND_ACCOUNT and child_entry.data[CONFIG_ACCOUNT_ID] == account_id:
await hass.config_entries.async_reload(child_entry.entry_id)

elif config[CONFIG_KIND] == CONFIG_KIND_TARGET_RATE:
if DOMAIN not in hass.data or account_id not in hass.data[DOMAIN] or DATA_ACCOUNT not in hass.data[DOMAIN][account_id]:
raise ConfigEntryNotReady("Account has not been setup")
Expand Down Expand Up @@ -174,8 +148,6 @@ async def async_setup_dependencies(hass, config):
_LOGGER.info(f'electricity_price_cap: {electricity_price_cap}')
_LOGGER.info(f'gas_price_cap: {gas_price_cap}')

# Close any existing clients, as our new client may have changed
await _async_close_client(hass, account_id)
client = OctopusEnergyApiClient(config[CONFIG_MAIN_API_KEY], electricity_price_cap, gas_price_cap)
hass.data[DOMAIN][account_id][DATA_CLIENT] = client

Expand All @@ -191,48 +163,31 @@ async def async_setup_dependencies(hass, config):

hass.data[DOMAIN][account_id][DATA_ACCOUNT] = AccountCoordinatorResult(utcnow(), 1, account_info)

device_registry = dr.async_get(hass)
now = utcnow()

# Remove gas meter devices which had incorrect identifier
if account_info is not None and len(account_info["gas_meter_points"]) > 0:
device_registry = dr.async_get(hass)
for point in account_info["gas_meter_points"]:
mprn = point["mprn"]
for meter in point["meters"]:
serial_number = meter["serial_number"]

tariff_code = get_active_tariff_code(now, point["agreements"])
if tariff_code is None:
gas_device = device_registry.async_get_device(identifiers={(DOMAIN, f"gas_{serial_number}_{mprn}")})
if gas_device is not None:
_LOGGER.debug(f'Removed gas device {serial_number}/{mprn} due to no active tariff')
device_registry.async_remove_device(gas_device.id)

# Remove gas meter devices which had incorrect identifier
gas_device = device_registry.async_get_device(identifiers={(DOMAIN, f"electricity_{serial_number}_{mprn}")})
if gas_device is not None:
device_registry.async_remove_device(gas_device.id)
intelligent_device = device_registry.async_get_device(identifiers={(DOMAIN, f"electricity_{serial_number}_{mprn}")})
if intelligent_device is not None:
device_registry.async_remove_device(intelligent_device.id)

has_intelligent_tariff = False
intelligent_mpan = None
intelligent_serial_number = None
now = utcnow()
for point in account_info["electricity_meter_points"]:
mpan = point["mpan"]
# We only care about points that have active agreements
electricity_tariff_code = get_active_tariff_code(now, point["agreements"])

for meter in point["meters"]:
serial_number = meter["serial_number"]

if electricity_tariff_code is not None:
if electricity_tariff_code is not None:
for meter in point["meters"]:
if meter["is_export"] == False:
if is_intelligent_tariff(electricity_tariff_code):
intelligent_mpan = mpan
intelligent_serial_number = serial_number
intelligent_mpan = point["mpan"]
intelligent_serial_number = meter["serial_number"]
has_intelligent_tariff = True
else:
_LOGGER.debug(f'Removed electricity device {serial_number}/{mpan} due to no active tariff')
electricity_device = device_registry.async_get_device(identifiers={(DOMAIN, f"electricity_{serial_number}_{mpan}")})
if electricity_device is not None:
device_registry.async_remove_device(electricity_device.id)

should_mock_intelligent_data = await async_mock_intelligent_data(hass, account_id)
if should_mock_intelligent_data:
Expand Down Expand Up @@ -267,9 +222,8 @@ async def async_setup_dependencies(hass, config):
serial_number = meter["serial_number"]
is_export_meter = meter["is_export"]
is_smart_meter = meter["is_smart_meter"]
tariff_override = await async_get_tariff_override(hass, mpan, serial_number)
planned_dispatches_supported = get_intelligent_features(intelligent_device["provider"]).planned_dispatches_supported if intelligent_device is not None else True
await async_setup_electricity_rates_coordinator(hass, account_id, mpan, serial_number, is_smart_meter, is_export_meter, planned_dispatches_supported, tariff_override)
await async_setup_electricity_rates_coordinator(hass, account_id, mpan, serial_number, is_smart_meter, is_export_meter, planned_dispatches_supported)

await async_setup_account_info_coordinator(hass, account_id)

Expand All @@ -279,8 +233,6 @@ async def async_setup_dependencies(hass, config):

await async_setup_saving_sessions_coordinators(hass, account_id)

await async_setup_greenness_forecast_coordinator(hass, account_id)

async def options_update_listener(hass, entry):
"""Handle options update."""
await hass.config_entries.async_reload(entry.entry_id)
Expand All @@ -289,12 +241,10 @@ async def async_unload_entry(hass, entry):
"""Unload a config entry."""

unload_ok = False
if entry.data[CONFIG_KIND] == CONFIG_KIND_ACCOUNT:
if CONFIG_MAIN_API_KEY in entry.data:
unload_ok = await hass.config_entries.async_unload_platforms(entry, ACCOUNT_PLATFORMS)
elif entry.data[CONFIG_KIND] == CONFIG_KIND_TARGET_RATE:
elif CONFIG_TARGET_NAME in entry.data:
unload_ok = await hass.config_entries.async_unload_platforms(entry, TARGET_RATE_PLATFORMS)
elif entry.data[CONFIG_KIND] == CONFIG_KIND_COST_TRACKER:
unload_ok = await hass.config_entries.async_unload_platforms(entry, COST_TRACKER_PLATFORMS)

return unload_ok

Expand Down
Loading

0 comments on commit c9703b2

Please sign in to comment.