Repository: home-assistant/core
Pull request: Add sensor platform to backup integration
<!--
  You are amazing! Thanks for contributing to our project!
  Please, DO NOT DELETE ANY TEXT from this template! (unless instructed).
-->
## Proposed change
<!--
  Describe the big picture of your changes here to communicate to the
  maintainers why we should accept this pull request. If it fixes a bug
  or resolves a feature request, be sure to link to that issue in the
  additional information section.
-->
This adds some sensors to the backup platform

![image](https://github.com/user-attachments/assets/0e28cbd6-f72a-4963-a563-64ece5ab2b88)

![image](https://github.com/user-attachments/assets/6baa763d-9cfa-4760-a495-d4f77cb4ad83)

![image](https://github.com/user-attachments/assets/3889f2b4-19d5-47cc-a742-9786353e861f)



**todo**:
- [x] add docs
- [ ] ~~adjust existing tests~~
- [x] add new tests


## Type of change
<!--
  What type of change does your PR introduce to Home Assistant?
  NOTE: Please, check only 1! box!
  If your PR requires multiple boxes to be checked, you'll most likely need to
  split it into multiple PRs. This makes things easier and faster to code review.
-->

- [ ] Dependency upgrade
- [ ] Bugfix (non-breaking change which fixes an issue)
- [ ] New integration (thank you!)
- [x] New feature (which adds functionality to an existing integration)
- [ ] Deprecation (breaking change to happen in the future)
- [ ] Breaking change (fix/feature causing existing functionality to break)
- [ ] Code quality improvements to existing code or addition of tests

## Additional information
<!--
  Details are important, and help maintainers processing your PR.
  Please be sure to fill out additional details, if applicable.
-->

- This PR fixes or closes issue: fixes #138181
- This PR is related to issue: 
- Link to documentation pull request: https://github.com/home-assistant/home-assistant.io/pull/37764
- Link to developer documentation pull request: 
- Link to frontend pull request: 

## Checklist
<!--
  Put an `x` in the boxes that apply. You can also fill these out after
  creating the PR. If you're unsure about any of them, don't hesitate to ask.
  We're here to help! This is simply a reminder of what we are going to look
  for before merging your code.
-->

- [x] The code change is tested and works locally.
- [x] Local tests pass. **Your PR cannot be merged unless tests pass**
- [x] There is no commented out code in this PR.
- [x] I have followed the [development checklist][dev-checklist]
- [x] I have followed the [perfect PR recommendations][perfect-pr]
- [x] The code has been formatted using Ruff (`ruff format homeassistant tests`)
- [x] Tests have been added to verify that the new code works.

If user exposed functionality or configuration variables are added/changed:

- [x] Documentation added/updated for [www.home-assistant.io][docs-repository]

If the code communicates with devices, web services, or third-party tools:

- [ ] The [manifest file][manifest-docs] has all fields filled out correctly.  
      Updated and included derived files by running: `python3 -m script.hassfest`.
- [ ] New or updated dependencies have been added to `requirements_all.txt`.  
      Updated by running `python3 -m script.gen_requirements_all`.
- [ ] For the updated dependencies - a link to the changelog, or at minimum a diff between library versions is added to the PR description.

<!--
  This project is very active and we have a high turnover of pull requests.

  Unfortunately, the number of incoming pull requests is higher than what our
  reviewers can review and merge so there is a long backlog of pull requests
  waiting for review. You can help here!
  
  By reviewing another pull request, you will help raise the code quality of
  that pull request and the final review will be faster. This way the general
  pace of pull request reviews will go up and your wait time will go down.
  
  When picking a pull request to review, try to choose one that hasn't yet
  been reviewed.

  Thanks for helping out!
-->

To help with the load of incoming pull requests:

- [ ] I have reviewed two other [open pull requests][prs] in this repository.

[prs]: https://github.com/home-assistant/core/pulls?q=is%3Aopen+is%3Apr+-author%3A%40me+-draft%3Atrue+-label%3Awaiting-for-upstream+sort%3Acreated-desc+review%3Anone+-status%3Afailure

<!--
  Thank you for contributing <3

  Below, some useful links you could explore:
-->
[dev-checklist]: https://developers.home-assistant.io/docs/development_checklist/
[manifest-docs]: https://developers.home-assistant.io/docs/creating_integration_manifest/
[quality-scale]: https://developers.home-assistant.io/docs/integration_quality_scale_index/
[docs-repository]: https://github.com/home-assistant/home-assistant.io
[perfect-pr]: https://developers.home-assistant.io/docs/review-process/#creating-the-perfect-pr


Problem statement:
I cant found any Sensor for BackUp Status
### The problem

New BackUp - brilliant. But, i cant found any Sensor for plase to Lovelas Card with Status BackUp....

### What version of Home Assistant Core has the issue?

2025.2.1

### What was the last working version of Home Assistant Core?

_No response_

### What type of installation are you running?

Home Assistant Supervised

### Integration causing the issue

BackUp

### Link to integration documentation on our website

_No response_

### Diagnostics information

_No response_

### Example YAML snippet

```yaml

```

### Anything in the logs that might be useful for us?

```txt

```

### Additional information

_No response_

Hints from issue discussion:
I came here looking for the same. There should be a "backups stale" sensor that turns on after 24 hours or something similar, so you know that the backups have failed or are failing. The google drive backup add_on provides this.

Hey there @home-assistant/core, mind taking a look at this issue as it has been labeled with an integration (`backup`) you are listed as a [code owner](https://github.com/home-assistant/core/blob/dev/CODEOWNERS#L183) for? Thanks!

<details>
<summary>Code owner commands</summary>


Code owners of `backup` can trigger bot actions by commenting:

- `@home-assistant close` Closes the issue.
- `@home-assistant rename Awesome new title` Renames the issue.
- `@home-assistant reopen` Reopen the issue.
- `@home-assistant unassign backup` Removes the current integration label and assignees on the issue, add the integration domain after the command.
- `@home-assistant add-label needs-more-information` Add a label (needs-more-information, problem in dependency, problem in custom component) to the issue.
- `@home-assistant remove-label needs-more-information` Remove a label (needs-more-information, problem in dependency, problem in custom component) on the issue.

</details>


<sub><sup>(message by CodeOwnersMention)</sup></sub>

---

[backup documentation](https://www.home-assistant.io/integrations/backup)
[backup source](https://github.com/home-assistant/core/tree/dev/homeassistant/components/backup)
<sub><sup>(message by IssueLinks)</sup></sub>
You should only file an issue if you found a bug. Feature and enhancement requests should go in [the Feature Requests section](https://community.home-assistant.io/c/feature-requests) of our community forum. Thanks!
A backup system with no easy way to check a status or automate a notification of failure is no backup system at all, so this is most definitely a bug.

Commit message: add sensor platform to backup integration

Patch to review:
diff --git a/homeassistant/components/backup/__init__.py b/homeassistant/components/backup/__init__.py
index 71a4f5ea41ab90..fdb4d511a7d9e4 100644
--- a/homeassistant/components/backup/__init__.py
+++ b/homeassistant/components/backup/__init__.py
@@ -1,8 +1,10 @@
 """The Backup integration."""
 
+from homeassistant.config_entries import SOURCE_SYSTEM
+from homeassistant.const import Platform
 from homeassistant.core import HomeAssistant, ServiceCall, callback
 from homeassistant.exceptions import HomeAssistantError
-from homeassistant.helpers import config_validation as cv
+from homeassistant.helpers import config_validation as cv, discovery_flow
 from homeassistant.helpers.hassio import is_hassio
 from homeassistant.helpers.typing import ConfigType
 
@@ -17,6 +19,7 @@
     LocalBackupAgent,
 )
 from .const import DATA_MANAGER, DOMAIN
+from .coordinator import BackupConfigEntry, BackupDataUpdateCoordinator
 from .http import async_register_http_views
 from .manager import (
     BackupManager,
@@ -70,6 +73,8 @@
     "suggested_filename_from_name_date",
 ]
 
+PLATFORMS = [Platform.SENSOR]
+
 CONFIG_SCHEMA = cv.empty_config_schema(DOMAIN)
 
 
@@ -118,9 +123,31 @@ async def async_handle_create_automatic_service(call: ServiceCall) -> None:
 
     async_register_http_views(hass)
 
+    discovery_flow.async_create_flow(
+        hass, DOMAIN, context={"source": SOURCE_SYSTEM}, data={}
+    )
+
     return True
 
 
+async def async_setup_entry(hass: HomeAssistant, entry: BackupConfigEntry) -> bool:
+    """Set up a config entry."""
+    backup_manager: BackupManager = hass.data[DATA_MANAGER]
+    coordinator = BackupDataUpdateCoordinator(hass, entry, backup_manager)
+    await coordinator.async_config_entry_first_refresh()
+
+    entry.runtime_data = coordinator
+
+    await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
+
+    return True
+
+
+async def async_unload_entry(hass: HomeAssistant, entry: BackupConfigEntry) -> bool:
+    """Unload a config entry."""
+    return await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
+
+
 @callback
 def async_get_manager(hass: HomeAssistant) -> BackupManager:
     """Get the backup manager instance.
diff --git a/homeassistant/components/backup/config_flow.py b/homeassistant/components/backup/config_flow.py
new file mode 100644
index 00000000000000..ab1f884ea8658e
--- /dev/null
+++ b/homeassistant/components/backup/config_flow.py
@@ -0,0 +1,21 @@
+"""Config flow for Home Assistant Backup integration."""
+
+from __future__ import annotations
+
+from typing import Any
+
+from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
+
+from .const import DOMAIN
+
+
+class BackupConfigFlow(ConfigFlow, domain=DOMAIN):
+    """Handle a config flow for Home Assistant Backup."""
+
+    VERSION = 1
+
+    async def async_step_system(
+        self, user_input: dict[str, Any] | None = None
+    ) -> ConfigFlowResult:
+        """Handle the initial step."""
+        return self.async_create_entry(title="Backup", data={})
diff --git a/homeassistant/components/backup/coordinator.py b/homeassistant/components/backup/coordinator.py
new file mode 100644
index 00000000000000..a6d9038121bae4
--- /dev/null
+++ b/homeassistant/components/backup/coordinator.py
@@ -0,0 +1,82 @@
+"""Coordinator for Home Assistant Backup integration."""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from datetime import datetime
+import logging
+
+from homeassistant.config_entries import ConfigEntry
+from homeassistant.core import HomeAssistant
+from homeassistant.helpers.update_coordinator import DataUpdateCoordinator
+from homeassistant.util import dt as dt_util
+
+from .const import DOMAIN
+from .manager import (
+    BackupManager,
+    BackupManagerState,
+    BackupPlatformEvent,
+    ManagerStateEvent,
+)
+
+_LOGGER = logging.getLogger(__name__)
+
+type BackupConfigEntry = ConfigEntry[BackupDataUpdateCoordinator]
+
+
+@dataclass
+class BackupCoordinatorData:
+    """Class to hold backup data."""
+
+    backup_manager_state: BackupManagerState
+    last_successful_automatic_backup: datetime | None
+    next_scheduled_automatic_backup: datetime | None
+
+
+class BackupDataUpdateCoordinator(DataUpdateCoordinator[BackupCoordinatorData]):
+    """Class to retrieve backup status."""
+
+    config_entry: ConfigEntry
+
+    def __init__(
+        self,
+        hass: HomeAssistant,
+        config_entry: ConfigEntry,
+        backup_manager: BackupManager,
+    ) -> None:
+        """Initialize coordinator."""
+        super().__init__(
+            hass,
+            _LOGGER,
+            config_entry=config_entry,
+            name=DOMAIN,
+            update_interval=None,
+        )
+        backup_manager.async_subscribe_events(self._on_event)
+        backup_manager.async_subscribe_platform_events(self._on_event)
+        self.backup_manager = backup_manager
+
+    def _on_event(self, event: ManagerStateEvent | BackupPlatformEvent) -> None:
+        """Handle new event."""
+        _LOGGER.debug("Received backup event: %s", event)
+        self.hass.async_create_task(self.async_refresh())
+
+    async def _async_update_data(self) -> BackupCoordinatorData:
+        """Update backup manager data."""
+        backups = await self.backup_manager.async_get_backups()
+        newest_backup_date: datetime | None = None
+        for backup in backups[0].values():
+            if (backup_date := dt_util.parse_datetime(backup.date)) is None:
+                continue
+            if newest_backup_date is None or newest_backup_date < backup_date:
+                newest_backup_date = backup_date
+
+        next_scheduled_automatic_backup = (
+            self.backup_manager.config.data.schedule.next_automatic_backup
+        )
+
+        return BackupCoordinatorData(
+            backup_manager_state=self.backup_manager.state,
+            last_successful_automatic_backup=newest_backup_date,
+            next_scheduled_automatic_backup=next_scheduled_automatic_backup,
+        )
diff --git a/homeassistant/components/backup/entity.py b/homeassistant/components/backup/entity.py
new file mode 100644
index 00000000000000..0752d49cd13da2
--- /dev/null
+++ b/homeassistant/components/backup/entity.py
@@ -0,0 +1,34 @@
+"""Base for backup entities."""
+
+from __future__ import annotations
+
+from homeassistant.const import __version__ as HA_VERSION
+from homeassistant.helpers.device_registry import DeviceEntryType, DeviceInfo
+from homeassistant.helpers.entity import EntityDescription
+from homeassistant.helpers.update_coordinator import CoordinatorEntity
+
+from .const import DOMAIN
+from .coordinator import BackupDataUpdateCoordinator
+
+
+class BackupManagerEntity(CoordinatorEntity[BackupDataUpdateCoordinator]):
+    """Base entity for backup manager."""
+
+    _attr_has_entity_name = True
+
+    def __init__(
+        self,
+        coordinator: BackupDataUpdateCoordinator,
+        entity_description: EntityDescription,
+    ) -> None:
+        """Initialize base entity."""
+        super().__init__(coordinator)
+        self.entity_description = entity_description
+        self._attr_unique_id = f"{DOMAIN}_{entity_description.key}"
+        self._attr_device_info = DeviceInfo(
+            identifiers={(DOMAIN, "backup_manager")},
+            manufacturer="Home Assistant",
+            sw_version=HA_VERSION,
+            name="Home Assistant Backup System",
+            entry_type=DeviceEntryType.SERVICE,
+        )
diff --git a/homeassistant/components/backup/manager.py b/homeassistant/components/backup/manager.py
index 81826ffcb24264..98c9ef56f96d84 100644
--- a/homeassistant/components/backup/manager.py
+++ b/homeassistant/components/backup/manager.py
@@ -114,6 +114,12 @@ class BackupManagerState(StrEnum):
     RESTORE_BACKUP = "restore_backup"
 
 
+class BackupPlatformState(StrEnum):
+    """Backup platform type."""
+
+    LOADED = "loaded"
+
+
 class CreateBackupStage(StrEnum):
     """Create backup stage enum."""
 
@@ -218,6 +224,14 @@ class RestoreBackupEvent(ManagerStateEvent):
     state: RestoreBackupState
 
 
+@dataclass(frozen=True, kw_only=True, slots=True)
+class BackupPlatformEvent:
+    """Backup platform class."""
+
+    domain: str
+    state: BackupPlatformState
+
+
 class BackupPlatformProtocol(Protocol):
     """Define the format that backup platforms can have."""
 
@@ -325,6 +339,9 @@ def __init__(self, hass: HomeAssistant, reader_writer: BackupReaderWriter) -> No
         self.last_event: ManagerStateEvent = IdleEvent()
         self.last_non_idle_event: ManagerStateEvent | None = None
         self._backup_event_subscriptions: list[Callable[[ManagerStateEvent], None]] = []
+        self._backup_platform_event_subscriptions: list[
+            Callable[[BackupPlatformEvent], None]
+        ] = []
 
     async def async_setup(self) -> None:
         """Set up the backup manager."""
@@ -418,6 +435,11 @@ async def _add_platform(
         LOGGER.debug("%s platforms loaded in total", len(self.platforms))
         LOGGER.debug("%s agents loaded in total", len(self.backup_agents))
         LOGGER.debug("%s local agents loaded in total", len(self.local_backup_agents))
+        event = BackupPlatformEvent(
+            domain=integration_domain, state=BackupPlatformState.LOADED
+        )
+        for subscription in self._backup_platform_event_subscriptions:
+            subscription(event)
 
     async def async_pre_backup_actions(self) -> None:
         """Perform pre backup actions."""
@@ -1283,6 +1305,19 @@ def remove_subscription() -> None:
         self._backup_event_subscriptions.append(on_event)
         return remove_subscription
 
+    @callback
+    def async_subscribe_platform_events(
+        self,
+        on_event: Callable[[BackupPlatformEvent], None],
+    ) -> Callable[[], None]:
+        """Subscribe to platform events."""
+
+        def remove_subscription() -> None:
+            self._backup_platform_event_subscriptions.remove(on_event)
+
+        self._backup_platform_event_subscriptions.append(on_event)
+        return remove_subscription
+
     def _update_issue_backup_failed(self) -> None:
         """Update issue registry when a backup fails."""
         ir.async_create_issue(
diff --git a/homeassistant/components/backup/manifest.json b/homeassistant/components/backup/manifest.json
index 6cbfb834c7f08c..4ddac52014f907 100644
--- a/homeassistant/components/backup/manifest.json
+++ b/homeassistant/components/backup/manifest.json
@@ -8,5 +8,6 @@
   "integration_type": "system",
   "iot_class": "calculated",
   "quality_scale": "internal",
-  "requirements": ["cronsim==2.6", "securetar==2025.1.4"]
+  "requirements": ["cronsim==2.6", "securetar==2025.1.4"],
+  "single_config_entry": true
 }
diff --git a/homeassistant/components/backup/sensor.py b/homeassistant/components/backup/sensor.py
new file mode 100644
index 00000000000000..d8b0c856bf090d
--- /dev/null
+++ b/homeassistant/components/backup/sensor.py
@@ -0,0 +1,75 @@
+"""Sensor platform for Home Assistant Backup integration."""
+
+from __future__ import annotations
+
+from collections.abc import Callable
+from dataclasses import dataclass
+from datetime import datetime
+
+from homeassistant.components.sensor import (
+    SensorDeviceClass,
+    SensorEntity,
+    SensorEntityDescription,
+)
+from homeassistant.core import HomeAssistant
+from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
+
+from .coordinator import BackupConfigEntry, BackupCoordinatorData
+from .entity import BackupManagerEntity
+from .manager import BackupManagerState
+
+
+@dataclass(kw_only=True, frozen=True)
+class BackupSensorEntityDescription(SensorEntityDescription):
+    """Description for Acaia sensor entities with dynamic units."""
+
+    value_fn: Callable[[BackupCoordinatorData], str | datetime | None]
+
+
+BACKUP_MANAGER_DESCRIPTIONS = (
+    BackupSensorEntityDescription(
+        key="backup_manager_state",
+        translation_key="backup_manager_state",
+        device_class=SensorDeviceClass.ENUM,
+        options=[state.value for state in BackupManagerState],
+        value_fn=lambda data: data.backup_manager_state,
+    ),
+    BackupSensorEntityDescription(
+        key="next_scheduled_automatic_backup",
+        translation_key="next_scheduled_automatic_backup",
+        device_class=SensorDeviceClass.TIMESTAMP,
+        value_fn=lambda data: data.next_scheduled_automatic_backup,
+    ),
+    BackupSensorEntityDescription(
+        key="last_successful_automatic_backup",
+        translation_key="last_successful_automatic_backup",
+        device_class=SensorDeviceClass.TIMESTAMP,
+        value_fn=lambda data: data.last_successful_automatic_backup,
+    ),
+)
+
+
+async def async_setup_entry(
+    hass: HomeAssistant,
+    config_entry: BackupConfigEntry,
+    async_add_entities: AddConfigEntryEntitiesCallback,
+) -> None:
+    """Sensor set up for backup config entry."""
+
+    coordinator = config_entry.runtime_data
+
+    async_add_entities(
+        BackupManagerSensor(coordinator, description)
+        for description in BACKUP_MANAGER_DESCRIPTIONS
+    )
+
+
+class BackupManagerSensor(BackupManagerEntity, SensorEntity):
+    """Sensor to track backup manager state."""
+
+    entity_description: BackupSensorEntityDescription
+
+    @property
+    def native_value(self) -> str | datetime | None:
+        """Return native value of entity."""
+        return self.entity_description.value_fn(self.coordinator.data)
diff --git a/homeassistant/components/backup/strings.json b/homeassistant/components/backup/strings.json
index 32d76ded049bac..7b05768268b65d 100644
--- a/homeassistant/components/backup/strings.json
+++ b/homeassistant/components/backup/strings.json
@@ -18,5 +18,24 @@
       "name": "Create automatic backup",
       "description": "Creates a new backup with automatic backup settings."
     }
+  },
+  "entity": {
+    "sensor": {
+      "backup_manager_state": {
+        "name": "Backup Manager State",
+        "state": {
+          "idle": "Idle",
+          "create_backup": "Create backup",
+          "receive_backup": "Receive backup",
+          "restore_backup": "Restore backup"
+        }
+      },
+      "next_scheduled_automatic_backup": {
+        "name": "Next scheduled automatic backup"
+      },
+      "last_successful_automatic_backup": {
+        "name": "Last successful automatic backup"
+      }
+    }
   }
 }


Code review comments:
diff_hunk: @@ -18,5 +18,24 @@
       "name": "Create automatic backup",
       "description": "Creates a new backup with automatic backup settings."
     }
+  },
+  "entity": {
+    "sensor": {
+      "backup_manager_state": {
+        "name": "Backup Manager State",
+        "state": {
+          "idle": "Idle",
+          "create_backup": "Create backup",
+          "receive_backup": "Receive backup",
+          "restore_backup": "Restore backup"
path: homeassistant/components/backup/strings.json
text: @user1:
I think those should all be in present participle (Creating, receiving,...)