diff --git a/homeassistant/components/growatt_server/coordinator.py b/homeassistant/components/growatt_server/coordinator.py index f5da2779580b3..c9885f16dad56 100644 --- a/homeassistant/components/growatt_server/coordinator.py +++ b/homeassistant/components/growatt_server/coordinator.py @@ -215,14 +215,15 @@ def _sync_update_data(self) -> dict[str, Any]: mix_chart_entries = mix_detail["chartData"] sorted_keys = sorted(mix_chart_entries) - # Create datetime from the latest entry - date_now = dt_util.now().date() - last_updated_time = dt_util.parse_time(str(sorted_keys[-1])) - mix_detail["lastdataupdate"] = datetime.datetime.combine( - date_now, - last_updated_time, # type: ignore[arg-type] - dt_util.get_default_time_zone(), - ) + if sorted_keys: + # Create datetime from the latest entry + date_now = dt_util.now().date() + last_updated_time = dt_util.parse_time(str(sorted_keys[-1])) + mix_detail["lastdataupdate"] = datetime.datetime.combine( + date_now, + last_updated_time, # type: ignore[arg-type] + dt_util.get_default_time_zone(), + ) # Dashboard data for mix system dashboard_data = self.api.dashboard_data(self.plant_id) diff --git a/tests/components/growatt_server/test_sensor.py b/tests/components/growatt_server/test_sensor.py index e64a2a864e2c8..81e31ba5ba989 100644 --- a/tests/components/growatt_server/test_sensor.py +++ b/tests/components/growatt_server/test_sensor.py @@ -127,6 +127,29 @@ async def test_sensors_classic_api( ) +@pytest.mark.freeze_time("2023-10-21") +async def test_mix_empty_chart_data( + hass: HomeAssistant, + mock_growatt_classic_api, + mock_config_entry_classic: MockConfigEntry, +) -> None: + """Test mix device handles empty chart data without crashing.""" + mock_growatt_classic_api.device_list.return_value = [ + {"deviceSn": "MIX123456", "deviceType": "mix"} + ] + mock_growatt_classic_api.mix_detail.return_value = { + "deviceSn": "MIX123456", + "chartData": {}, + } + + with patch("homeassistant.components.growatt_server.PLATFORMS", [Platform.SENSOR]): + await setup_integration(hass, mock_config_entry_classic) + + # Should not crash - entities should still be created + states = hass.states.async_entity_ids("sensor") + assert len(states) > 0 + + async def test_sensor_coordinator_updates( hass: HomeAssistant, mock_growatt_v1_api,