Improve blue current integration code (#114004)

This commit is contained in:
Floris272 2024-03-24 09:35:53 +01:00 committed by GitHub
parent ba5a4a17c4
commit d14a442ac3
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
8 changed files with 79 additions and 57 deletions

View File

@ -111,9 +111,9 @@ class Connector:
entry[EVSE_ID], entry[MODEL_TYPE], entry[ATTR_NAME] entry[EVSE_ID], entry[MODEL_TYPE], entry[ATTR_NAME]
) )
for entry in charge_points_data for entry in charge_points_data
),
self.client.get_grid_status(charge_points_data[0][EVSE_ID]),
) )
)
await self.client.get_grid_status(charge_points_data[0][EVSE_ID])
async def handle_charge_point(self, evse_id: str, model: str, name: str) -> None: async def handle_charge_point(self, evse_id: str, model: str, name: str) -> None:
"""Add the chargepoint and request their data.""" """Add the chargepoint and request their data."""
@ -127,22 +127,26 @@ class Connector:
def update_charge_point(self, evse_id: str, data: dict) -> None: def update_charge_point(self, evse_id: str, data: dict) -> None:
"""Update the charge point data.""" """Update the charge point data."""
self.charge_points[evse_id].update(data) self.charge_points[evse_id].update(data)
self.dispatch_value_update_signal(evse_id) self.dispatch_charge_point_update_signal(evse_id)
def dispatch_value_update_signal(self, evse_id: str) -> None: def dispatch_charge_point_update_signal(self, evse_id: str) -> None:
"""Dispatch a value signal.""" """Dispatch a charge point update signal."""
async_dispatcher_send(self.hass, f"{DOMAIN}_value_update_{evse_id}") async_dispatcher_send(self.hass, f"{DOMAIN}_charge_point_update_{evse_id}")
def dispatch_grid_update_signal(self) -> None: def dispatch_grid_update_signal(self) -> None:
"""Dispatch a grid signal.""" """Dispatch a grid update signal."""
async_dispatcher_send(self.hass, f"{DOMAIN}_grid_update") async_dispatcher_send(self.hass, f"{DOMAIN}_grid_update")
async def on_open(self) -> None:
"""Fetch data when connection is established."""
await self.client.get_charge_points()
async def run_task(self) -> None: async def run_task(self) -> None:
"""Start the receive loop.""" """Start the receive loop."""
try: try:
while True: while True:
try: try:
await self.client.connect(self.on_data) await self.client.connect(self.on_data, self.on_open)
except RequestLimitReached: except RequestLimitReached:
LOGGER.warning( LOGGER.warning(
"Request limit reached. reconnecting at 00:00 (Europe/Amsterdam)" "Request limit reached. reconnecting at 00:00 (Europe/Amsterdam)"
@ -160,7 +164,7 @@ class Connector:
def _on_disconnect(self) -> None: def _on_disconnect(self) -> None:
"""Dispatch signals to update entity states.""" """Dispatch signals to update entity states."""
for evse_id in self.charge_points: for evse_id in self.charge_points:
self.dispatch_value_update_signal(evse_id) self.dispatch_charge_point_update_signal(evse_id)
self.dispatch_grid_update_signal() self.dispatch_grid_update_signal()
async def _disconnect(self) -> None: async def _disconnect(self) -> None:

View File

@ -53,7 +53,7 @@ class ChargepointEntity(BlueCurrentEntity):
def __init__(self, connector: Connector, evse_id: str) -> None: def __init__(self, connector: Connector, evse_id: str) -> None:
"""Initialize the entity.""" """Initialize the entity."""
super().__init__(connector, f"{DOMAIN}_value_update_{evse_id}") super().__init__(connector, f"{DOMAIN}_charge_point_update_{evse_id}")
chargepoint_name = connector.charge_points[evse_id][ATTR_NAME] chargepoint_name = connector.charge_points[evse_id][ATTR_NAME]

View File

@ -6,5 +6,5 @@
"documentation": "https://www.home-assistant.io/integrations/blue_current", "documentation": "https://www.home-assistant.io/integrations/blue_current",
"iot_class": "cloud_push", "iot_class": "cloud_push",
"loggers": ["bluecurrent_api"], "loggers": ["bluecurrent_api"],
"requirements": ["bluecurrent-api==1.2.2"] "requirements": ["bluecurrent-api==1.2.3"]
} }

View File

@ -571,7 +571,7 @@ blinkpy==0.22.6
blockchain==1.4.4 blockchain==1.4.4
# homeassistant.components.blue_current # homeassistant.components.blue_current
bluecurrent-api==1.2.2 bluecurrent-api==1.2.3
# homeassistant.components.bluemaestro # homeassistant.components.bluemaestro
bluemaestro-ble==0.2.3 bluemaestro-ble==0.2.3

View File

@ -490,7 +490,7 @@ blebox-uniapi==2.2.2
blinkpy==0.22.6 blinkpy==0.22.6
# homeassistant.components.blue_current # homeassistant.components.blue_current
bluecurrent-api==1.2.2 bluecurrent-api==1.2.3
# homeassistant.components.bluemaestro # homeassistant.components.bluemaestro
bluemaestro-ble==0.2.3 bluemaestro-ble==0.2.3

View File

@ -42,10 +42,10 @@ def create_client_mock(
"""Wait until chargepoints are received.""" """Wait until chargepoints are received."""
await received_charge_points.wait() await received_charge_points.wait()
async def connect(receiver): async def connect(receiver, on_open):
"""Set the receiver and await future.""" """Set the receiver and await future."""
client_mock.receiver = receiver client_mock.receiver = receiver
await client_mock.get_charge_points() await on_open()
started_loop.set() started_loop.set()
started_loop.clear() started_loop.clear()
@ -112,8 +112,9 @@ async def init_integration(
hass, future_container, started_loop, charge_point, status, grid hass, future_container, started_loop, charge_point, status, grid
) )
with patch("homeassistant.components.blue_current.PLATFORMS", [platform]), patch( with (
"homeassistant.components.blue_current.Client", return_value=client_mock patch("homeassistant.components.blue_current.PLATFORMS", [platform]),
patch("homeassistant.components.blue_current.Client", return_value=client_mock),
): ):
config_entry.add_to_hass(hass) config_entry.add_to_hass(hass)

View File

@ -36,15 +36,19 @@ async def test_user(hass: HomeAssistant) -> None:
assert result["errors"] == {} assert result["errors"] == {}
assert result["type"] == FlowResultType.FORM assert result["type"] == FlowResultType.FORM
with patch( with (
patch(
"homeassistant.components.blue_current.config_flow.Client.validate_api_token", "homeassistant.components.blue_current.config_flow.Client.validate_api_token",
return_value="1234", return_value="1234",
), patch( ),
patch(
"homeassistant.components.blue_current.config_flow.Client.get_email", "homeassistant.components.blue_current.config_flow.Client.get_email",
return_value="test@email.com", return_value="test@email.com",
), patch( ),
patch(
"homeassistant.components.blue_current.async_setup_entry", "homeassistant.components.blue_current.async_setup_entry",
return_value=True, return_value=True,
),
): ):
result2 = await hass.config_entries.flow.async_configure( result2 = await hass.config_entries.flow.async_configure(
result["flow_id"], result["flow_id"],
@ -83,15 +87,19 @@ async def test_flow_fails(hass: HomeAssistant, error: Exception, message: str) -
assert result["errors"]["base"] == message assert result["errors"]["base"] == message
assert result["type"] == FlowResultType.FORM assert result["type"] == FlowResultType.FORM
with patch( with (
patch(
"homeassistant.components.blue_current.config_flow.Client.validate_api_token", "homeassistant.components.blue_current.config_flow.Client.validate_api_token",
return_value="1234", return_value="1234",
), patch( ),
patch(
"homeassistant.components.blue_current.config_flow.Client.get_email", "homeassistant.components.blue_current.config_flow.Client.get_email",
return_value="test@email.com", return_value="test@email.com",
), patch( ),
patch(
"homeassistant.components.blue_current.async_setup_entry", "homeassistant.components.blue_current.async_setup_entry",
return_value=True, return_value=True,
),
): ):
result2 = await hass.config_entries.flow.async_configure( result2 = await hass.config_entries.flow.async_configure(
result["flow_id"], result["flow_id"],
@ -121,17 +129,22 @@ async def test_reauth(
expected_api_token: str, expected_api_token: str,
) -> None: ) -> None:
"""Test reauth flow.""" """Test reauth flow."""
with patch( with (
patch(
"homeassistant.components.blue_current.config_flow.Client.validate_api_token", "homeassistant.components.blue_current.config_flow.Client.validate_api_token",
return_value=customer_id, return_value=customer_id,
), patch( ),
patch(
"homeassistant.components.blue_current.config_flow.Client.get_email", "homeassistant.components.blue_current.config_flow.Client.get_email",
return_value="test@email.com", return_value="test@email.com",
), patch( ),
patch(
"homeassistant.components.blue_current.config_flow.Client.wait_for_charge_points", "homeassistant.components.blue_current.config_flow.Client.wait_for_charge_points",
), patch( ),
patch(
"homeassistant.components.blue_current.Client.connect", "homeassistant.components.blue_current.Client.connect",
lambda self, on_data: hass.loop.create_future(), lambda self, on_data, on_open: hass.loop.create_future(),
),
): ):
config_entry.add_to_hass(hass) config_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init( result = await hass.config_entries.flow.async_init(

View File

@ -29,13 +29,14 @@ async def test_load_unload_entry(
hass: HomeAssistant, config_entry: MockConfigEntry hass: HomeAssistant, config_entry: MockConfigEntry
) -> None: ) -> None:
"""Test load and unload entry.""" """Test load and unload entry."""
with patch( with (
"homeassistant.components.blue_current.Client.validate_api_token" patch("homeassistant.components.blue_current.Client.validate_api_token"),
), patch( patch("homeassistant.components.blue_current.Client.wait_for_charge_points"),
"homeassistant.components.blue_current.Client.wait_for_charge_points" patch("homeassistant.components.blue_current.Client.disconnect"),
), patch("homeassistant.components.blue_current.Client.disconnect"), patch( patch(
"homeassistant.components.blue_current.Client.connect", "homeassistant.components.blue_current.Client.connect",
lambda self, on_data: hass.loop.create_future(), lambda self, on_data, on_open: hass.loop.create_future(),
),
): ):
config_entry.add_to_hass(hass) config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(config_entry.entry_id) await hass.config_entries.async_setup(config_entry.entry_id)
@ -61,10 +62,13 @@ async def test_config_exceptions(
config_error: IntegrationError, config_error: IntegrationError,
) -> None: ) -> None:
"""Test if the correct config error is raised when connecting to the api fails.""" """Test if the correct config error is raised when connecting to the api fails."""
with patch( with (
patch(
"homeassistant.components.blue_current.Client.validate_api_token", "homeassistant.components.blue_current.Client.validate_api_token",
side_effect=api_error, side_effect=api_error,
), pytest.raises(config_error): ),
pytest.raises(config_error),
):
config_entry.add_to_hass(hass) config_entry.add_to_hass(hass)
await async_setup_entry(hass, config_entry) await async_setup_entry(hass, config_entry)