Deprecate MQTT device tracker state topic and add in_zones support (#172660)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Jan Bouwhuis
2026-12-01 17:10:57 +01:00
committed by GitHub
co-authored by Claude Opus 5.5
parent 0f6a0a7df7
commit 4258c3f85e
5 changed files with 664 additions and 18 deletions
+4
View File
@@ -372,12 +372,16 @@ DEFAULT_WILL = {
ATTR_RETAIN: DEFAULT_RETAIN,
}
DEPRECATED_DEVICE_TRACKER_STATE_TOPIC_ISSUE_PREFIX = (
"deprecated_device_tracker_state_topic_"
)
DEPRECATED_TILT_VALUES_ISSUE_PREFIX = "deprecated_tilt_values_"
DOMAIN = "mqtt"
INVALID_PLATFORM_CONFIG_ISSUE_PREFIX = "invalid_platform_config_"
# Issues of manually configured items, they must be re-created on every setup and
# reload, and need the config_entry_id of the MQTT entry
YAML_ISSUE_PREFIXES = (
DEPRECATED_DEVICE_TRACKER_STATE_TOPIC_ISSUE_PREFIX,
DEPRECATED_TILT_VALUES_ISSUE_PREFIX,
INVALID_PLATFORM_CONFIG_ISSUE_PREFIX,
)
+145 -10
View File
@@ -8,10 +8,12 @@ import probatio
from homeassistant.components import device_tracker
from homeassistant.components.device_tracker import (
DeviceTrackerEntityStateAttribute,
SourceType,
TrackerEntity,
TrackerEntityStateAttribute,
)
from homeassistant.components.zone import DOMAIN as ZONE_DOMAIN
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
CONF_NAME,
@@ -21,7 +23,7 @@ from homeassistant.const import (
EntityStateAttribute,
)
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers import config_validation as cv, issue_registry as ir
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.service_info.mqtt import ReceivePayloadType
from homeassistant.helpers.typing import ConfigType, VolSchemaType
@@ -29,10 +31,13 @@ from homeassistant.helpers.typing import ConfigType, VolSchemaType
from . import subscription
from .config import MQTT_BASE_SCHEMA
from .const import (
ATTR_DISCOVERY_TOPIC,
CONF_JSON_ATTRS_TEMPLATE,
CONF_JSON_ATTRS_TOPIC,
CONF_PAYLOAD_RESET,
CONF_STATE_TOPIC,
DEPRECATED_DEVICE_TRACKER_STATE_TOPIC_ISSUE_PREFIX,
DOMAIN,
)
from .entity import MqttEntity, async_setup_entity_entry_helper
from .models import MqttValueTemplate, ReceiveMessage
@@ -50,6 +55,18 @@ CONF_SOURCE_TYPE = "source_type"
DEFAULT_PAYLOAD_RESET = "None"
DEFAULT_SOURCE_TYPE = SourceType.GPS
DOCS_URL_IN_ZONES = (
"https://www.home-assistant.io/integrations/device_tracker.mqtt/#in_zones"
)
STATE_TOPIC_BREAKS_IN_HA_VERSION = "2027.7.0"
DEPRECATED_STATE_TOPIC_OPTIONS = (
CONF_STATE_TOPIC,
CONF_VALUE_TEMPLATE,
CONF_PAYLOAD_HOME,
CONF_PAYLOAD_NOT_HOME,
CONF_PAYLOAD_RESET,
)
def valid_config(config: ConfigType) -> ConfigType:
"""Check if there is a state topic or json_attributes_topic."""
@@ -67,16 +84,16 @@ PLATFORM_SCHEMA_MODERN_BASE = MQTT_BASE_SCHEMA.extend(
probatio.Optional(CONF_STATE_TOPIC): valid_subscribe_topic,
probatio.Optional(CONF_VALUE_TEMPLATE): cv.template,
probatio.Optional(CONF_NAME): probatio.Any(cv.string, None),
probatio.Optional(CONF_PAYLOAD_HOME, default=STATE_HOME): cv.string,
probatio.Optional(CONF_PAYLOAD_NOT_HOME, default=STATE_NOT_HOME): cv.string,
probatio.Optional(CONF_PAYLOAD_RESET, default=DEFAULT_PAYLOAD_RESET): cv.string,
probatio.Optional(CONF_PAYLOAD_HOME): cv.string,
probatio.Optional(CONF_PAYLOAD_NOT_HOME): cv.string,
probatio.Optional(CONF_PAYLOAD_RESET): cv.string,
probatio.Optional(
CONF_SOURCE_TYPE, default=DEFAULT_SOURCE_TYPE
): probatio.Coerce(SourceType),
},
).extend(MQTT_ENTITY_COMMON_SCHEMA.schema)
PLATFORM_SCHEMA_MODERN = probatio.All(PLATFORM_SCHEMA_MODERN_BASE, valid_config)
PLATFORM_SCHEMA_MODERN = probatio.All(PLATFORM_SCHEMA_MODERN_BASE, valid_config)
DISCOVERY_SCHEMA = probatio.All(
PLATFORM_SCHEMA_MODERN_BASE.extend({}, extra=probatio.REMOVE_EXTRA), valid_config
@@ -106,6 +123,7 @@ class MqttDeviceTracker(MqttEntity, TrackerEntity):
_default_name = None
_entity_id_format = device_tracker.ENTITY_ID_FORMAT
_location_name: str | None = None
_payloads: dict[str, str]
_value_template: Callable[[ReceivePayloadType], ReceivePayloadType]
@staticmethod
@@ -117,10 +135,85 @@ class MqttDeviceTracker(MqttEntity, TrackerEntity):
@override
def _setup_from_config(self, config: ConfigType) -> None:
"""(Re)Setup the entity."""
self._payloads = {
CONF_PAYLOAD_HOME: config.get(CONF_PAYLOAD_HOME, STATE_HOME),
CONF_PAYLOAD_NOT_HOME: config.get(CONF_PAYLOAD_NOT_HOME, STATE_NOT_HOME),
CONF_PAYLOAD_RESET: config.get(CONF_PAYLOAD_RESET, DEFAULT_PAYLOAD_RESET),
}
self._value_template = MqttValueTemplate(
config.get(CONF_VALUE_TEMPLATE), entity=self
).async_render_with_possible_json_value
self._attr_source_type = self._config[CONF_SOURCE_TYPE]
self._attr_source_type = config[CONF_SOURCE_TYPE]
if CONF_STATE_TOPIC not in config:
# Do not keep a location received on a removed state topic
self._attr_location_name = None
@override
async def mqtt_async_added_to_hass(self) -> None:
"""Report the use of the deprecated state topic options."""
if (discovery_data := self._discovery_data) is not None:
if deprecated_options := self._deprecated_state_topic_options():
_LOGGER.warning(
"The MQTT device tracker %s, discovered on topic %s, uses the"
" deprecated option(s) %s, which will stop working in Home"
" Assistant %s. Update the discovery payload to publish the"
" `in_zones` attribute via `json_attributes_topic` instead,"
" see %s",
self.entity_id,
discovery_data[ATTR_DISCOVERY_TOPIC],
", ".join(deprecated_options),
STATE_TOPIC_BREAKS_IN_HA_VERSION,
DOCS_URL_IN_ZONES,
)
return
self._async_update_deprecated_state_topic_issue()
@callback
@override
def async_entity_id_changed(self, old_entity_id: str) -> None:
"""Update the entity ID in the deprecated state topic repair issue."""
super().async_entity_id_changed(old_entity_id)
if self._discovery_data is None:
self._async_update_deprecated_state_topic_issue()
def _deprecated_state_topic_options(self) -> list[str]:
"""Return the deprecated state topic options in the config."""
return [
option
for option in DEPRECATED_STATE_TOPIC_OPTIONS
if option in self._config
]
@callback
def _async_update_deprecated_state_topic_issue(self) -> None:
"""Create or delete the repair issue for a manually configured tracker."""
# Keyed on the registry entry so a rename keeps the ignored state
issue_key = (
self.registry_entry.id
if self.registry_entry is not None
else self.entity_id
)
issue_id = f"{DEPRECATED_DEVICE_TRACKER_STATE_TOPIC_ISSUE_PREFIX}{issue_key}"
if not (deprecated_options := self._deprecated_state_topic_options()):
ir.async_delete_issue(self.hass, DOMAIN, issue_id)
return
ir.async_create_issue(
self.hass,
DOMAIN,
issue_id,
breaks_in_ha_version=STATE_TOPIC_BREAKS_IN_HA_VERSION,
config_entry_id=self._config_entry.entry_id,
is_fixable=False,
issue_domain=device_tracker.DOMAIN,
learn_more_url=DOCS_URL_IN_ZONES,
severity=ir.IssueSeverity.WARNING,
translation_key="deprecated_device_tracker_state_topic",
translation_placeholders={
"entity_id": self.entity_id,
"options": ", ".join(f"`{option}`" for option in deprecated_options),
"breaks_in_ha_version": STATE_TOPIC_BREAKS_IN_HA_VERSION,
},
)
@callback
def _tracker_message_received(self, msg: ReceiveMessage) -> None:
@@ -133,11 +226,11 @@ class MqttDeviceTracker(MqttEntity, TrackerEntity):
msg.topic,
)
return
if payload == self._config[CONF_PAYLOAD_HOME]:
if payload == self._payloads[CONF_PAYLOAD_HOME]:
self._attr_location_name = STATE_HOME
elif payload == self._config[CONF_PAYLOAD_NOT_HOME]:
elif payload == self._payloads[CONF_PAYLOAD_NOT_HOME]:
self._attr_location_name = STATE_NOT_HOME
elif payload == self._config[CONF_PAYLOAD_RESET]:
elif payload == self._payloads[CONF_PAYLOAD_RESET]:
self._attr_location_name = None
else:
if TYPE_CHECKING:
@@ -162,7 +255,7 @@ class MqttDeviceTracker(MqttEntity, TrackerEntity):
def _process_update_extra_state_attributes(
self, extra_state_attributes: dict[str, Any]
) -> None:
"""Extract the location from the extra state attributes."""
"""Extract the location or zone from the extra state attributes."""
if (
EntityStateAttribute.LATITUDE in extra_state_attributes
or EntityStateAttribute.LONGITUDE in extra_state_attributes
@@ -179,10 +272,12 @@ class MqttDeviceTracker(MqttEntity, TrackerEntity):
):
self._attr_latitude = latitude
self._attr_longitude = longitude
self._attr_in_zones = None
else:
# Invalid or incomplete coordinates, reset location
self._attr_latitude = None
self._attr_longitude = None
self._attr_in_zones = None
_LOGGER.warning(
"Extra state attributes received at %s and template %s "
"contain invalid or incomplete location info. Got %s",
@@ -212,6 +307,45 @@ class MqttDeviceTracker(MqttEntity, TrackerEntity):
else:
self._attr_location_accuracy = 0
elif DeviceTrackerEntityStateAttribute.IN_ZONES in extra_state_attributes:
self._attr_latitude = None
self._attr_longitude = None
attr_in_zones: list[str] | Any = extra_state_attributes[
DeviceTrackerEntityStateAttribute.IN_ZONES
]
if not isinstance(attr_in_zones, list):
# Invalid zones, reset location
self._attr_in_zones = None
_LOGGER.warning(
"Extra state attributes received at %s and template %s "
"contains invalid in_zones attribute, "
"expected a list of strings. Got %s",
self._config.get(CONF_JSON_ATTRS_TOPIC),
self._config.get(CONF_JSON_ATTRS_TEMPLATE),
extra_state_attributes,
)
else:
zone_ids = list(dict.fromkeys(str(zone) for zone in attr_in_zones))
# Zones that do not exist yet are skipped by TrackerEntity
self._attr_in_zones = [
zone_id
for zone_id in zone_ids
if zone_id.startswith(f"{ZONE_DOMAIN}.")
]
if unknown_zones := [
zone_id
for zone_id in zone_ids
if zone_id not in self._attr_in_zones
or self.hass.states.get(zone_id) is None
]:
_LOGGER.debug(
"Extra state attributes received at %s and template %s "
"contain in_zones that do not match an existing zone "
"entity ID: %s",
self._config.get(CONF_JSON_ATTRS_TOPIC),
self._config.get(CONF_JSON_ATTRS_TEMPLATE),
unknown_zones,
)
self._attr_extra_state_attributes = {
attribute: value
@@ -219,6 +353,7 @@ class MqttDeviceTracker(MqttEntity, TrackerEntity):
if attribute
not in {
TrackerEntityStateAttribute.GPS_ACCURACY,
DeviceTrackerEntityStateAttribute.IN_ZONES,
EntityStateAttribute.LATITUDE,
EntityStateAttribute.LONGITUDE,
}
+1
View File
@@ -631,6 +631,7 @@ class MqttAttributesMixin(Entity):
self._attributes_message_received,
{
"_attr_extra_state_attributes",
"_attr_in_zones",
"_attr_location_accuracy",
"_attr_latitude",
"_attr_location_name",
@@ -1182,6 +1182,10 @@
"description": "The client certificate that is loaded from `{client_cert_file}` to connect to MQTT broker {broker} expires on {expiry}. The installed private key file `{client_key_file}` cannot be read, or does not contain a valid unencrypted PEM encoded private key. MQTT keeps using the certificate that was loaded, but might not start correctly after a restart. Install a valid private key in `{client_key_file}`. The files are checked once a day. To check them right away after fixing them, reload the MQTT integration.",
"title": "Invalid MQTT private key file installed"
},
"deprecated_device_tracker_state_topic": {
"description": "The manually configured MQTT device tracker `{entity_id}` uses the deprecated option(s) {options}. Setting the location of a device tracker through a state topic is deprecated and will stop working in Home Assistant {breaks_in_ha_version}.\n\nPublish the location as coordinates or as an `in_zones` list of zone entity IDs through `json_attributes_topic` instead. Then remove {options} from the YAML configuration and [reload](/config/tools/yaml) the manually configured MQTT items or restart Home Assistant to fix this issue.",
"title": "MQTT device tracker uses a deprecated state topic"
},
"deprecated_tilt_values": {
"description": "The manually configured MQTT cover `{entity_id}` uses the `tilt_opened_value` or `tilt_closed_value` option. These options are deprecated and will stop working in Home Assistant {breaks_in_ha_version}.\n\nDescribe the slats with `tilt_start_angle` and `tilt_end_angle`, the angles of the slats at `tilt_min` and `tilt_max`, from -90 to 90 degrees. If the angles are not known, set `open_tilt_position` and `closed_tilt_positions` as a percentage instead. Then remove `tilt_opened_value` and `tilt_closed_value` from the YAML configuration and [reload](/config/tools/yaml) the manually configured MQTT items or restart Home Assistant to fix this issue.",
"title": "MQTT cover uses deprecated tilt options"
+510 -8
View File
@@ -1,6 +1,9 @@
"""The tests for the MQTT device_tracker platform."""
from datetime import UTC, datetime
import logging
from typing import Any
from unittest.mock import patch
from freezegun.api import FrozenDateTimeFactory
import pytest
@@ -21,14 +24,18 @@ from homeassistant.components import device_tracker
from homeassistant.components.mqtt.const import DOMAIN
from homeassistant.const import STATE_HOME, STATE_NOT_HOME, STATE_UNKNOWN
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.helpers import (
device_registry as dr,
entity_registry as er,
issue_registry as ir,
)
from homeassistant.setup import async_setup_component
DEFAULT_CONFIG = {
DOMAIN: {
device_tracker.DOMAIN: {
"name": "test",
"state_topic": "test-topic",
"json_attributes_topic": "json-attributes-topic",
}
}
}
@@ -306,9 +313,7 @@ async def test_cleanup_device_tracker(
async def test_setting_device_tracker_value_via_mqtt_message(
hass: HomeAssistant,
mqtt_mock_entry: MqttMockHAClientGenerator,
caplog: pytest.LogCaptureFixture,
hass: HomeAssistant, mqtt_mock_entry: MqttMockHAClientGenerator
) -> None:
"""Test the setting of the value via MQTT."""
await mqtt_mock_entry()
@@ -338,6 +343,294 @@ async def test_setting_device_tracker_value_via_mqtt_message(
assert state.state == STATE_NOT_HOME
@pytest.mark.parametrize(
("discovery_payload", "warning_expected"),
[
pytest.param(
'{"name": "test", "state_topic": "test-topic", '
'"value_template": "{{ value }}", "payload_home": "home", '
'"payload_not_home": "not_home", "payload_reset": "None"}',
True,
id="state_topic",
),
pytest.param(
'{"name": "test", "json_attributes_topic": "attributes-topic"}',
False,
id="json_attributes_topic",
),
],
)
async def test_deprecated_state_topic_discovery_warning(
hass: HomeAssistant,
mqtt_mock_entry: MqttMockHAClientGenerator,
issue_registry: ir.IssueRegistry,
caplog: pytest.LogCaptureFixture,
discovery_payload: str,
warning_expected: bool,
) -> None:
"""Test discovered deprecated options are logged, without a repair issue."""
await mqtt_mock_entry()
async_fire_mqtt_message(
hass, "homeassistant/device_tracker/bla/config", discovery_payload
)
await hass.async_block_till_done()
assert hass.states.get("device_tracker.test") is not None
assert (
"The MQTT device tracker device_tracker.test, discovered on topic "
"homeassistant/device_tracker/bla/config, uses the deprecated option(s) "
"state_topic, value_template, payload_home, payload_not_home, "
"payload_reset, which will stop working in Home Assistant 2027.7.0"
in caplog.text
) is warning_expected
assert not issue_registry.issues
@pytest.mark.parametrize(
("hass_config", "issue_expected"),
[
pytest.param(
{
DOMAIN: {
device_tracker.DOMAIN: {
"name": "test",
"state_topic": "test-topic",
"payload_home": "home",
}
}
},
True,
id="state_topic",
),
pytest.param(DEFAULT_CONFIG, False, id="json_attributes_topic"),
],
)
async def test_deprecated_state_topic_yaml_issue(
hass: HomeAssistant,
mqtt_mock_entry: MqttMockHAClientGenerator,
issue_registry: ir.IssueRegistry,
issue_expected: bool,
) -> None:
"""Test a repair issue is raised for deprecated options in YAML."""
await mqtt_mock_entry()
issue = issue_registry.async_get_issue(
DOMAIN, "deprecated_device_tracker_state_topic_device_tracker.test"
)
assert (issue is not None) is issue_expected
@pytest.mark.parametrize(
"hass_config",
[
{
DOMAIN: {
device_tracker.DOMAIN: {
"name": "test",
"state_topic": "test-topic",
"payload_home": "home",
}
}
}
],
)
async def test_deprecated_state_topic_yaml_issue_details(
hass: HomeAssistant,
mqtt_mock_entry: MqttMockHAClientGenerator,
issue_registry: ir.IssueRegistry,
) -> None:
"""Test the repair issue for deprecated options in YAML."""
await mqtt_mock_entry()
issue = issue_registry.async_get_issue(
DOMAIN, "deprecated_device_tracker_state_topic_device_tracker.test"
)
assert issue is not None
assert issue.breaks_in_ha_version == "2027.7.0"
assert issue.severity is ir.IssueSeverity.WARNING
assert issue.issue_domain == device_tracker.DOMAIN
assert issue.learn_more_url == (
"https://www.home-assistant.io/integrations/device_tracker.mqtt/#in_zones"
)
assert issue.translation_key == "deprecated_device_tracker_state_topic"
assert issue.translation_placeholders == {
"entity_id": "device_tracker.test",
"options": "`state_topic`, `payload_home`",
"breaks_in_ha_version": "2027.7.0",
}
DEPRECATED_YAML_CONFIG = {
DOMAIN: {
device_tracker.DOMAIN: {
"name": "test",
"state_topic": "test-topic",
"payload_home": "home",
}
}
}
DEPRECATED_ISSUE_ID = "deprecated_device_tracker_state_topic_device_tracker.test"
async def _reload_yaml(hass: HomeAssistant, config: dict[str, Any]) -> None:
with patch("homeassistant.config.load_yaml_config_file", return_value=config):
await hass.services.async_call(DOMAIN, "reload", {}, blocking=True)
await hass.async_block_till_done()
@pytest.mark.parametrize("hass_config", [DEPRECATED_YAML_CONFIG])
@pytest.mark.parametrize(
("reload_config", "expected_issue_ids"),
[
pytest.param(
{
DOMAIN: {
device_tracker.DOMAIN: {"name": "test", "state_topic": "test-topic"}
}
},
{DEPRECATED_ISSUE_ID},
id="unchanged",
),
pytest.param(
{
DOMAIN: {
device_tracker.DOMAIN: {
"name": "test",
"json_attributes_topic": "attributes-topic",
}
}
},
set(),
id="migrated",
),
pytest.param({DOMAIN: {}}, set(), id="removed"),
pytest.param(
{
DOMAIN: {
device_tracker.DOMAIN: {
"name": "renamed",
"state_topic": "test-topic",
}
}
},
{"deprecated_device_tracker_state_topic_device_tracker.renamed"},
id="renamed",
),
],
)
async def test_deprecated_state_topic_yaml_issue_refreshed_on_reload(
hass: HomeAssistant,
mqtt_mock_entry: MqttMockHAClientGenerator,
issue_registry: ir.IssueRegistry,
reload_config: dict[str, Any],
expected_issue_ids: set[str],
) -> None:
"""Test the repair issue follows the YAML config on a reload."""
await mqtt_mock_entry()
assert issue_registry.async_get_issue(DOMAIN, DEPRECATED_ISSUE_ID) is not None
await _reload_yaml(hass, reload_config)
assert {
issue_id for domain, issue_id in issue_registry.issues if domain == DOMAIN
} == expected_issue_ids
@pytest.mark.parametrize("hass_config", [DEPRECATED_YAML_CONFIG])
async def test_ignored_deprecated_state_topic_yaml_issue_kept_on_reload(
hass: HomeAssistant,
mqtt_mock_entry: MqttMockHAClientGenerator,
issue_registry: ir.IssueRegistry,
) -> None:
"""Test an ignored repair issue stays ignored when the tracker is unchanged."""
await mqtt_mock_entry()
ir.async_ignore_issue(hass, DOMAIN, DEPRECATED_ISSUE_ID, True)
await _reload_yaml(hass, DEPRECATED_YAML_CONFIG)
issue = issue_registry.async_get_issue(DOMAIN, DEPRECATED_ISSUE_ID)
assert issue is not None
assert issue.dismissed_version is not None
DEPRECATED_YAML_CONFIG_UNIQUE_ID = {
DOMAIN: {
device_tracker.DOMAIN: {
**DEPRECATED_YAML_CONFIG[DOMAIN][device_tracker.DOMAIN],
"unique_id": "veryunique",
}
}
}
@pytest.mark.parametrize("hass_config", [DEPRECATED_YAML_CONFIG_UNIQUE_ID])
async def test_deprecated_state_topic_yaml_issue_follows_entity_id_change(
hass: HomeAssistant,
mqtt_mock_entry: MqttMockHAClientGenerator,
entity_registry: er.EntityRegistry,
issue_registry: ir.IssueRegistry,
) -> None:
"""Test the repair issue of a registered tracker survives an entity ID change."""
await mqtt_mock_entry()
entry = entity_registry.async_get("device_tracker.test")
assert entry is not None
issue_id = f"deprecated_device_tracker_state_topic_{entry.id}"
ir.async_ignore_issue(hass, DOMAIN, issue_id, True)
entity_registry.async_update_entity(
"device_tracker.test", new_entity_id="device_tracker.renamed"
)
await hass.async_block_till_done()
issue = issue_registry.async_get_issue(DOMAIN, issue_id)
assert issue is not None
assert issue.translation_placeholders["entity_id"] == "device_tracker.renamed"
assert issue.dismissed_version is not None
# The registry keeps the new entity ID for the unique ID on a reload
await _reload_yaml(hass, DEPRECATED_YAML_CONFIG_UNIQUE_ID)
assert hass.states.get("device_tracker.renamed") is not None
assert {
issue_id for domain, issue_id in issue_registry.issues if domain == DOMAIN
} == {issue_id}
issue = issue_registry.async_get_issue(DOMAIN, issue_id)
assert issue is not None
assert issue.dismissed_version is not None
async def test_discovery_update_from_state_topic_to_in_zones(
hass: HomeAssistant, mqtt_mock_entry: MqttMockHAClientGenerator
) -> None:
"""Test the location is reset when the state topic is removed."""
await mqtt_mock_entry()
async_fire_mqtt_message(
hass,
"homeassistant/device_tracker/bla/config",
'{"name": "test", "state_topic": "test-topic"}',
)
await hass.async_block_till_done()
async_fire_mqtt_message(hass, "test-topic", "work")
assert hass.states.get("device_tracker.test").state == "work"
async_fire_mqtt_message(
hass,
"homeassistant/device_tracker/bla/config",
'{"name": "test", "json_attributes_topic": "attributes-topic"}',
)
await hass.async_block_till_done()
assert hass.states.get("device_tracker.test").state == STATE_UNKNOWN
async_fire_mqtt_message(hass, "attributes-topic", '{"in_zones": ["zone.home"]}')
state = hass.states.get("device_tracker.test")
assert state.attributes["in_zones"] == ["zone.home"]
assert state.state == STATE_HOME
# The removed state topic is unsubscribed and cannot override in_zones
async_fire_mqtt_message(hass, "test-topic", "work")
assert hass.states.get("device_tracker.test").state == STATE_HOME
async def test_setting_device_tracker_value_via_mqtt_message_and_template(
hass: HomeAssistant, mqtt_mock_entry: MqttMockHAClientGenerator
) -> None:
@@ -444,7 +737,7 @@ async def test_setting_device_tracker_location_via_lat_lon_message(
assert state.attributes["latitude"] == 32.87336
assert state.attributes["longitude"] == -117.22743
assert state.attributes["gps_accuracy"] == 1.5
# assert source_type is overridden by discovery
# assert source_type is overridden with the update
assert state.attributes["source_type"] == "router"
assert state.state == STATE_HOME
@@ -496,7 +789,7 @@ async def test_setting_device_tracker_location_via_lat_lon_message(
assert "latitude" not in state.attributes
assert "longitude" not in state.attributes
assert "gps_accuracy" not in state.attributes
# assert source_type is overridden by discovery
# assert source_type is overridden with the update
assert state.attributes["source_type"] == "router"
assert state.state == STATE_UNKNOWN
@@ -540,6 +833,214 @@ async def test_setting_device_tracker_location_via_lat_lon_message(
assert state.state == STATE_UNKNOWN
async def test_setting_device_tracker_location_via_in_zones_message(
hass: HomeAssistant,
mqtt_mock_entry: MqttMockHAClientGenerator,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test the in_zones setting in combination with GPS coordinates."""
hass.config.latitude = 32.87336
hass.config.longitude = -117.22743
await mqtt_mock_entry()
async_fire_mqtt_message(
hass,
"homeassistant/device_tracker/bla/config",
'{ "name": "test", "json_attributes_topic": "attributes-topic"}',
)
await hass.async_block_till_done()
state = hass.states.get("device_tracker.test")
assert state.attributes["source_type"] == "gps"
assert state.state == STATE_UNKNOWN
# Test in_zones with known `home` zone entity_id
async_fire_mqtt_message(
hass,
"attributes-topic",
'{"in_zones": ["zone.home"],"source_type": "router"}',
)
state = hass.states.get("device_tracker.test")
assert state.attributes["in_zones"] == ["zone.home"]
assert state.attributes.get("latitude") is None
assert state.attributes.get("longitude") is None
assert state.attributes.get("gps_accuracy") is None
# assert source_type is overridden with the update
assert state.attributes["source_type"] == "router"
assert state.state == STATE_HOME
# An invalid in_zones attribute resets the location,
# other attributes are still updated
async_fire_mqtt_message(
hass,
"attributes-topic",
'{"in_zones": "zone.home", "source_type": "gps", "battery": 70}',
)
assert (
"Extra state attributes received at attributes-topic and template "
"None contains invalid in_zones attribute" in caplog.text
)
state = hass.states.get("device_tracker.test")
assert state.attributes["in_zones"] == []
assert state.attributes["source_type"] == "gps"
assert state.attributes["battery"] == 70
assert state.state == STATE_UNKNOWN
# Non zone entity IDs are ignored and logged
caplog.set_level(logging.DEBUG)
async_fire_mqtt_message(
hass,
"attributes-topic",
'{"in_zones": ["sensor.foo", "zone.home"],"source_type": "router"}',
)
state = hass.states.get("device_tracker.test")
assert state.attributes["in_zones"] == ["zone.home"]
assert state.state == STATE_HOME
assert (
"contain in_zones that do not match an existing zone entity ID: "
"['sensor.foo']" in caplog.text
)
async_fire_mqtt_message(
hass,
"attributes-topic",
'{"in_zones": [],"source_type": "router"}',
)
state = hass.states.get("device_tracker.test")
assert state.attributes["in_zones"] == []
# assert source_type is overridden with the update
assert state.attributes["source_type"] == "router"
assert state.attributes.get("latitude") is None
assert state.attributes.get("longitude") is None
assert state.attributes.get("gps_accuracy") is None
assert state.state == STATE_NOT_HOME
# Fire GPS coordinates for an unknown GPS based location
async_fire_mqtt_message(
hass,
"attributes-topic",
'{"latitude":50.1,"longitude": -2.1}',
)
state = hass.states.get("device_tracker.test")
assert state.attributes["in_zones"] == []
assert state.attributes["latitude"] == 50.1
assert state.attributes["longitude"] == -2.1
assert state.attributes["gps_accuracy"] == 0
assert state.attributes["source_type"] == "gps"
assert state.state == STATE_NOT_HOME
# Fire GPS coordinates for the home location
async_fire_mqtt_message(
hass,
"attributes-topic",
'{"latitude":32.87336,"longitude": -117.22743,'
' "gps_accuracy":1.5, "source_type": "gps"}',
)
state = hass.states.get("device_tracker.test")
assert state.attributes["in_zones"] == ["zone.home"]
assert state.attributes["latitude"] == 32.87336
assert state.attributes["longitude"] == -117.22743
assert state.attributes["gps_accuracy"] == 1.5
assert state.attributes["source_type"] == "gps"
assert state.state == STATE_HOME
# Test in_zones with an unknown zone name
async_fire_mqtt_message(
hass,
"attributes-topic",
'{"in_zones": ["unknown"],"source_type": "router"}',
)
state = hass.states.get("device_tracker.test")
assert state.attributes["in_zones"] == []
# assert source_type is overridden with the update
assert state.attributes["source_type"] == "router"
assert state.attributes.get("latitude") is None
assert state.attributes.get("longitude") is None
assert state.attributes.get("gps_accuracy") is None
assert state.state == STATE_NOT_HOME
# Only zone entity_ids are matched, not object_ids or display names
async_fire_mqtt_message(
hass,
"attributes-topic",
'{"in_zones": ["home", "test home"],"source_type": "router"}',
)
state = hass.states.get("device_tracker.test")
assert state.attributes["in_zones"] == []
assert state.attributes["source_type"] == "router"
assert state.attributes.get("latitude") is None
assert state.attributes.get("longitude") is None
assert state.attributes.get("gps_accuracy") is None
assert state.state == STATE_NOT_HOME
# Test in_zones with a known zone entity_id as a list
async_fire_mqtt_message(
hass,
"attributes-topic",
'{"in_zones": ["zone.home"],"source_type": "router"}',
)
state = hass.states.get("device_tracker.test")
assert state.attributes["in_zones"] == ["zone.home"]
# assert source_type is overridden with the update
assert state.attributes["source_type"] == "router"
assert state.attributes.get("latitude") is None
assert state.attributes.get("longitude") is None
assert state.attributes.get("gps_accuracy") is None
assert state.state == STATE_HOME
# Test with a custom zone
hass.states.async_set(
"zone.school",
"zoning",
{
"latitude": 30.0,
"longitude": -100.0,
"radius": 100,
"friendly_name": "School",
},
)
await hass.async_block_till_done()
async_fire_mqtt_message(
hass,
"attributes-topic",
'{"in_zones": ["zone.school"],"source_type": "router"}',
)
state = hass.states.get("device_tracker.test")
assert state.attributes["in_zones"] == ["zone.school"]
# assert source_type is overridden with the update
assert state.attributes["source_type"] == "router"
assert state.attributes.get("latitude") is None
assert state.attributes.get("longitude") is None
assert state.attributes.get("gps_accuracy") is None
assert state.state == "School"
# Invalid coordinates also reset the zones reported via in_zones
async_fire_mqtt_message(
hass,
"attributes-topic",
'{"latitude": null, "longitude": null}',
)
state = hass.states.get("device_tracker.test")
assert state.attributes["in_zones"] == []
assert state.attributes.get("latitude") is None
assert state.attributes.get("longitude") is None
assert state.state == STATE_UNKNOWN
# Coordinates take precedence over in_zones in the same payload
async_fire_mqtt_message(
hass,
"attributes-topic",
'{"latitude": 32.87336, "longitude": -117.22743, "in_zones": []}',
)
state = hass.states.get("device_tracker.test")
assert state.attributes["in_zones"] == ["zone.home"]
assert state.attributes["latitude"] == 32.87336
assert state.attributes["longitude"] == -117.22743
assert state.state == STATE_HOME
async def test_setting_device_tracker_location_via_reset_message(
hass: HomeAssistant, mqtt_mock_entry: MqttMockHAClientGenerator
) -> None:
@@ -727,8 +1228,8 @@ async def test_reloadable(
DEFAULT_CONFIG,
(
{
"state_topic": "test-topic",
"availability_topic": "availability-topic",
"json_attributes_topic": "json-attributes-topic",
},
),
)
@@ -762,6 +1263,7 @@ async def test_skipped_async_ha_write_state(
DEFAULT_CONFIG,
(
{
"state_topic": "test-topic",
"value_template": "{{ value_json.some_var * 1 }}",
},
),