diff --git a/homeassistant/components/tractive/__init__.py b/homeassistant/components/tractive/__init__.py index 63594c86ed64..54711cec8ba1 100644 --- a/homeassistant/components/tractive/__init__.py +++ b/homeassistant/components/tractive/__init__.py @@ -24,7 +24,9 @@ from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.dispatcher import async_dispatcher_send from .const import ( + ATTR_BUZZER, ATTR_DAILY_GOAL, + ATTR_LED, ATTR_MINUTES_ACTIVE, ATTR_MINUTES_DAY_SLEEP, ATTR_MINUTES_NIGHT_SLEEP, @@ -323,6 +325,13 @@ class TractiveClient: for switch, key in SWITCH_KEY_MAP.items(): if switch_data := event.get(key): payload[switch] = switch_data["active"] + # A timed out LED or buzzer is still reported as active, with + # no time remaining + if ( + switch in (ATTR_BUZZER, ATTR_LED) + and switch_data.get("remaining") == 0 + ): + payload[switch] = False if hardware := event.get("hardware", {}): payload[ATTR_POWER_SAVING] = ( hardware.get("power_saving_zone_id") is not None diff --git a/tests/components/tractive/test_switch.py b/tests/components/tractive/test_switch.py index eb34dcf7e8b2..a98fd85c7d4c 100644 --- a/tests/components/tractive/test_switch.py +++ b/tests/components/tractive/test_switch.py @@ -81,6 +81,51 @@ async def test_switch_on( assert state.state == STATE_ON +@pytest.mark.parametrize( + ("entity_id", "event_key"), + [ + pytest.param("switch.tracker_device_id_123_led", "led_control", id="led"), + pytest.param( + "switch.tracker_device_id_123_buzzer", "buzzer_control", id="buzzer" + ), + ], +) +async def test_timed_switch_off_when_expired( + hass: HomeAssistant, + mock_tractive_client: AsyncMock, + mock_config_entry: MockConfigEntry, + entity_id: str, + event_key: str, +) -> None: + """Test a timed switch turns off once its time ran out.""" + await init_integration(hass, mock_config_entry) + + mock_tractive_client.send_switch_event( + mock_config_entry, + { + "tracker_id": "device_id_123", + event_key: {"active": True, "timeout": 900, "remaining": 896}, + }, + ) + await hass.async_block_till_done() + + assert (state := hass.states.get(entity_id)) + assert state.state == STATE_ON + + # The API keeps reporting the control as active after it timed out + mock_tractive_client.send_switch_event( + mock_config_entry, + { + "tracker_id": "device_id_123", + event_key: {"active": True, "timeout": 900, "remaining": 0}, + }, + ) + await hass.async_block_till_done() + + assert (state := hass.states.get(entity_id)) + assert state.state == STATE_OFF + + async def test_switch_off( hass: HomeAssistant, mock_tractive_client: AsyncMock,