Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Restore PR #30 and fix deprecated calls to async_track_state_change and async_forward_entry_setup #34

Open
wants to merge 12 commits into
base: main
Choose a base branch
from
Open
9 changes: 5 additions & 4 deletions custom_components/v2c_trydan/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"""The v2c_trydan component."""
from homeassistant.config_entries import SOURCE_IMPORT
from homeassistant.core import HomeAssistant, ServiceCall
from homeassistant.const import CONF_IP_ADDRESS
from homeassistant.const import CONF_IP_ADDRESS, Platform
import logging
import aiohttp
from homeassistant.helpers.aiohttp_client import async_get_clientsession
Expand All @@ -10,7 +10,7 @@

DOMAIN = "v2c_trydan"

PLATFORMS = ["sensor", "switch", "number"]
PLATFORMS = [Platform.SENSOR, Platform.SWITCH, Platform.NUMBER]

async def async_setup(hass: HomeAssistant, config: dict):
hass.data.setdefault(DOMAIN, {})
Expand All @@ -28,8 +28,7 @@ async def async_setup(hass: HomeAssistant, config: dict):
return True

async def async_setup_entry(hass: HomeAssistant, entry):
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)


hass.data[DOMAIN]["ip_address"] = entry.data[CONF_IP_ADDRESS]
ip_address = entry.data[CONF_IP_ADDRESS]

Expand Down Expand Up @@ -150,6 +149,8 @@ async def set_max_intensity_slider(call):
hass.services.async_register(DOMAIN, "set_max_intensity_slider", set_max_intensity_slider)
hass.services.async_register(DOMAIN, "set_dynamic_power_mode_slider", set_dynamic_power_mode_slider)

await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)

return True

async def async_unload_entry(hass: HomeAssistant, entry):
Expand Down
4 changes: 3 additions & 1 deletion custom_components/v2c_trydan/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,6 @@
CONF_IP_ADDRESS = "ip_address"
CONF_KWH_PER_100KM = "kwh_per_100km"
CONF_KM_TO_CHARGE = "km_to_charge"
CONF_PRECIO_LUZ = "precio_luz"
CONF_PRECIO_LUZ = "precio_luz"

DATA_UPDATED = f"{DOMAIN}_update"
42 changes: 37 additions & 5 deletions custom_components/v2c_trydan/number.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
from homeassistant.components.number import NumberEntity
from homeassistant.components.number import NumberEntity, RestoreNumber
from homeassistant.const import DEVICE_DEFAULT_NAME
from homeassistant.core import callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers import config_validation as cv
import logging
from . import DOMAIN
from .const import DOMAIN, DATA_UPDATED

_LOGGER = logging.getLogger(__name__)

Expand Down Expand Up @@ -138,7 +140,7 @@ async def async_set_native_value(self, value):
else:
_LOGGER.error("v2c_dynamic_power_mode must be between 0 and 7")

class KmToChargeNumber(NumberEntity):
class KmToChargeNumber(RestoreNumber):
def __init__(self, hass):
self._hass = hass
self._state = 0
Expand Down Expand Up @@ -178,6 +180,21 @@ async def async_set_native_value(self, value):
else:
_LOGGER.error("v2c_km_to_charge must be between 0 and 1000")

async def async_added_to_hass(self) -> None:
await super().async_added_to_hass()
value = await self.async_get_last_number_data()
if not value:
return
self._state = value.native_value

async_dispatcher_connect(
self._hass, DATA_UPDATED, self._schedule_immediate_update
)

@callback
def _schedule_immediate_update(self):
self.async_schedule_update_ha_state(True)

class IntensityNumber(NumberEntity):
def __init__(self, hass):
self._hass = hass
Expand Down Expand Up @@ -219,7 +236,7 @@ async def async_set_native_value(self, value):
else:
_LOGGER.error("v2c_intensity must be between {} and {}".format(self.native_min_value, self.native_max_value))

class MaxPrice(NumberEntity):
class MaxPrice(RestoreNumber):
def __init__(self, hass):
self._hass = hass
self._state = 0
Expand Down Expand Up @@ -257,4 +274,19 @@ async def async_set_native_value(self, value):
self._state = value
self.async_write_ha_state()
else:
_LOGGER.error("v2c_MaxPrice must be between 0 and 1")
_LOGGER.error("v2c_MaxPrice must be between 0 and 1")

async def async_added_to_hass(self) -> None:
await super().async_added_to_hass()
value = await self.async_get_last_number_data()
if not value:
return
self._state = value.native_value

async_dispatcher_connect(
self._hass, DATA_UPDATED, self._schedule_immediate_update
)

@callback
def _schedule_immediate_update(self):
self.async_schedule_update_ha_state(True)
17 changes: 8 additions & 9 deletions custom_components/v2c_trydan/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,11 @@

from homeassistant.const import (
CONF_NAME,
STATE_UNAVAILABLE,
STATE_UNKNOWN,
CONF_IP_ADDRESS,
)
from homeassistant.core import HomeAssistant, callback
from homeassistant.core import Event, EventStateChangedData, HomeAssistant, callback
from homeassistant.components.sensor import (
PLATFORM_SCHEMA,
SensorEntity,
Expand All @@ -24,7 +25,7 @@
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.event import (
async_track_time_interval,
async_track_state_change,
async_track_state_change_event,
async_call_later,
)
from homeassistant.helpers.update_coordinator import (
Expand Down Expand Up @@ -250,11 +251,9 @@ def __init__(self, coordinator, ip_address, kwh_per_100km):
self._kwh_per_100km = kwh_per_100km
self._charging_paused = False

async def async_added_to_hass(self):
await super().async_added_to_hass()
async_track_time_interval(self.hass, self.check_and_pause_charging, timedelta(seconds=10))

async def handle_paused_state_change(self, entity_id, old_state, new_state):
async def handle_paused_state_change(self, event: Event[EventStateChangedData]):
old_state = event.data["old_state"]
new_state = event.data["new_state"]
if new_state is not None and old_state is not None:
if new_state.state == "on" and old_state.state == "off":
#_LOGGER.debug("Charging paused")
Expand Down Expand Up @@ -282,7 +281,7 @@ async def async_set_km_to_charge(self, value):
async def async_added_to_hass(self):
await super().async_added_to_hass()
async_track_time_interval(self.hass, self.check_and_pause_charging, timedelta(seconds=10))
async_track_state_change(self.hass, ["switch.v2c_trydan_switch_paused"], self.handle_paused_state_change)
async_track_state_change_event(self.hass, ["switch.v2c_trydan_switch_paused"], self.handle_paused_state_change)
self.hass.bus.async_listen("state_changed", self.handle_km_to_charge_state_change)


Expand Down Expand Up @@ -452,7 +451,7 @@ async def extract_price_attrs(precio_luz_entity, max_price, current_hour):
return valid_hours, valid_hours_next_day, total_hours

async def pause_or_resume_charging(current_state, max_price, paused_switch, v2c_carga_pvpc_switch):
if v2c_carga_pvpc_switch.is_on:
if v2c_carga_pvpc_switch.is_on and current_state not in (STATE_UNKNOWN, STATE_UNAVAILABLE):
if float(current_state) <= max_price:
await paused_switch.async_turn_off()
else:
Expand Down
25 changes: 21 additions & 4 deletions custom_components/v2c_trydan/switch.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,20 @@
import voluptuous as vol

from homeassistant.components.switch import PLATFORM_SCHEMA, SwitchEntity
from homeassistant.const import CONF_IP_ADDRESS
from homeassistant.core import HomeAssistant
from homeassistant.const import CONF_IP_ADDRESS, STATE_ON
from homeassistant.core import HomeAssistant, callback
from homeassistant.exceptions import PlatformNotReady
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.restore_state import RestoreEntity
from homeassistant.helpers.update_coordinator import (
CoordinatorEntity,
DataUpdateCoordinator,
UpdateFailed,
)

from .coordinator import V2CtrydanDataUpdateCoordinator
from .const import DOMAIN, CONF_PRECIO_LUZ
from .const import DOMAIN, CONF_PRECIO_LUZ, DATA_UPDATED

_LOGGER = logging.getLogger(__name__)

Expand Down Expand Up @@ -82,7 +84,7 @@ async def async_turn_off(self, **kwargs):
except Exception as e:
_LOGGER.error(f"Error turning off switch: {e}")

class V2CCargaPVPCSwitch(SwitchEntity):
class V2CCargaPVPCSwitch(SwitchEntity, RestoreEntity):
def __init__(self, precio_luz_entity):
self._is_on = False
self.precio_luz_entity = precio_luz_entity
Expand All @@ -107,3 +109,18 @@ async def async_turn_on(self, **kwargs):

async def async_turn_off(self, **kwargs):
self._is_on = False

async def async_added_to_hass(self) -> None:
await super().async_added_to_hass()
state = await self.async_get_last_state()
if not state:
return
self._is_on = state.state == STATE_ON

async_dispatcher_connect(
self.hass, DATA_UPDATED, self._schedule_immediate_update
)

@callback
def _schedule_immediate_update(self):
self.async_schedule_update_ha_state(True)
Loading