Repository: home-assistant/core
Pull request: Delete subscription on shutdown of SmartThings
<!--
  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.
-->
So SmartThings currently has an issue where we create too many subscriptions, and SmartThings now has a limit on the concurrent subscriptions. So we agreed on deleting the old subscription when we shut down. We currently also store and sync the subscription id in the config entry data, so if we then have the problem that we can't delete the subscription because there's no internet or power got cut off abruptly, we can still delete it on boot, making sure a single instance always keeps a single subscription

https://github.com/pySmartThings/pysmartthings/compare/v2.7.0...v2.7.2

## 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
- [x] Bugfix (non-breaking change which fixes an issue)
- [ ] New integration (thank you!)
- [ ] 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 #139993
- This PR is related to issue: 
- Link to documentation pull request: 
- 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.
-->

- [ ] The code change is tested and works locally.
- [ ] Local tests pass. **Your PR cannot be merged unless tests pass**
- [ ] There is no commented out code in this PR.
- [ ] I have followed the [development checklist][dev-checklist]
- [ ] I have followed the [perfect PR recommendations][perfect-pr]
- [ ] The code has been formatted using Ruff (`ruff format homeassistant tests`)
- [ ] Tests have been added to verify that the new code works.

If user exposed functionality or configuration variables are added/changed:

- [ ] 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:
Smartthing entities stopped updating
### The problem

Since the last HA core release the smart things zigbee temp sensor stopped updating its temp. same with switches, when turned switch on/off in HA, it turned on in real, but no status (on/off) updates from smartthings. Probably it stopped polling ST entities auto for state changes

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

2025.3.0

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

Cant remember

### What type of installation are you running?

Home Assistant Core

### Integration causing the issue

Smartthings

### 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:
Hey there @joostlek, mind taking a look at this issue as it has been labeled with an integration (`smartthings`) you are listed as a [code owner](https://github.com/home-assistant/core/blob/dev/CODEOWNERS#L1404) for? Thanks!

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


Code owners of `smartthings` 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 smartthings` 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>

---

[smartthings documentation](https://www.home-assistant.io/integrations/smartthings)
[smartthings source](https://github.com/home-assistant/core/tree/dev/homeassistant/components/smartthings)
<sub><sup>(message by IssueLinks)</sup></sub>
Hi, not sure I understand. I am not a code owner, I am just reporting an issue with smartthings integration. Btw the basic one, entities statuses updating. 
Experiencing the same issue, although I just installed the integration in the newest version so I haven't been able to get it working. The problem is 'solved' momentarily once I open the smartthings app on my android phone. This strikes me as weird to say the least, but I'm no expert. Once I close the app (leave it in the background), the issue returns.
Can you enable debug logs and do some tests and share the logs?
Sure, debug enabled for smartthing integration. Please guide me further. 
Do stuff to trigger an update (like how it would've worked normally) and maybe give it some time and check the logs afterwards to see if you have updates
Done. I see nothing is working. If you turn any switch on in HA, it turns on in ST in real but no way to switch it off back in HA as it did not changed the status there.
Can you please share logs and make sure you show the difference between the two cases
Not sure where to download logs from. Settings/system/logs?
Yes, and then download full logs

Commit message: Fix

Patch to review:
diff --git a/homeassistant/components/smartthings/__init__.py b/homeassistant/components/smartthings/__init__.py
index 3e0e66e890f56..d7c26e3a51d98 100644
--- a/homeassistant/components/smartthings/__init__.py
+++ b/homeassistant/components/smartthings/__init__.py
@@ -2,6 +2,7 @@
 
 from __future__ import annotations
 
+import asyncio
 from collections.abc import Callable
 from dataclasses import dataclass
 import logging
@@ -18,6 +19,7 @@
     SmartThingsAuthenticationFailedError,
     Status,
 )
+from pysmartthings.exceptions import SmartThingsForbiddenError, SmartThingsSinkError
 
 from homeassistant.config_entries import ConfigEntry
 from homeassistant.const import CONF_ACCESS_TOKEN, CONF_TOKEN, Platform
@@ -33,6 +35,7 @@
 from .const import (
     CONF_INSTALLED_APP_ID,
     CONF_LOCATION_ID,
+    CONF_SUBSCRIPTION_URL,
     DOMAIN,
     EVENT_BUTTON,
     MAIN,
@@ -100,6 +103,27 @@ async def _refresh_token() -> str:
 
     client.refresh_token_function = _refresh_token
 
+    def _handle_new_subscription_url(url: str) -> None:
+        """Handle a new subscription URL."""
+        hass.config_entries.async_update_entry(
+            entry, data={**entry.data, CONF_SUBSCRIPTION_URL: url}
+        )
+
+    client.refresh_subscription_url_function = _handle_new_subscription_url
+
+    async def subscribe() -> None:
+        """Subscribe to the SmartThings event stream."""
+        try:
+            await client.subscribe(
+                entry.data[CONF_LOCATION_ID],
+                entry.data[CONF_TOKEN][CONF_INSTALLED_APP_ID],
+                entry.data.get(CONF_SUBSCRIPTION_URL),
+            )
+        except (SmartThingsSinkError, SmartThingsForbiddenError) as err:
+            _LOGGER.error("Error subscribing: %s", err)
+            await asyncio.sleep(300)
+            hass.config_entries.async_schedule_reload(entry.entry_id)
+
     device_status: dict[str, FullDevice] = {}
     try:
         rooms = {
@@ -107,9 +131,16 @@ async def _refresh_token() -> str:
             for room in await client.get_rooms(location_id=entry.data[CONF_LOCATION_ID])
         }
         devices = await client.get_devices()
+        entry.async_create_background_task(
+            hass,
+            subscribe(),
+            "smartthings_socket",
+        )
         for device in devices:
             status = process_status(await client.get_device_status(device.device_id))
             device_status[device.device_id] = FullDevice(device=device, status=status)
+    except SmartThingsSinkError as err:
+        raise ConfigEntryNotReady from err
     except SmartThingsAuthenticationFailedError as err:
         raise ConfigEntryAuthFailed from err
 
@@ -171,14 +202,6 @@ def handle_button_press(event: DeviceEvent) -> None:
         client.add_unspecified_device_event_listener(handle_button_press)
     )
 
-    entry.async_create_background_task(
-        hass,
-        client.subscribe(
-            entry.data[CONF_LOCATION_ID], entry.data[CONF_TOKEN][CONF_INSTALLED_APP_ID]
-        ),
-        "smartthings_webhook",
-    )
-
     await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
 
     device_entries = dr.async_entries_for_config_entry(device_registry, entry.entry_id)
diff --git a/homeassistant/components/smartthings/const.py b/homeassistant/components/smartthings/const.py
index a6d028aed06de..ca1c3ac4f57a0 100644
--- a/homeassistant/components/smartthings/const.py
+++ b/homeassistant/components/smartthings/const.py
@@ -33,4 +33,5 @@
 MAIN = "main"
 OLD_DATA = "old_data"
 
+CONF_SUBSCRIPTION_URL = "subscription_url"
 EVENT_BUTTON = "smartthings.button"
diff --git a/homeassistant/components/smartthings/manifest.json b/homeassistant/components/smartthings/manifest.json
index 2a4e79bff58e2..f7a4bdf8eef94 100644
--- a/homeassistant/components/smartthings/manifest.json
+++ b/homeassistant/components/smartthings/manifest.json
@@ -29,5 +29,7 @@
   "documentation": "https://www.home-assistant.io/integrations/smartthings",
   "iot_class": "cloud_push",
   "loggers": ["pysmartthings"],
-  "requirements": ["pysmartthings==2.7.0"]
+  "requirements": [
+    "git+https://github.com/joostlek/pysmartthings.git@see-fix#pysmartthings==0.0.0"
+  ]
 }


Code review comments:
diff_hunk: @@ -100,16 +103,44 @@ async def _refresh_token() -> str:
 
     client.refresh_token_function = _refresh_token
 
+    def _handle_new_subscription_url(url: str) -> None:
+        """Handle a new subscription URL."""
+        hass.config_entries.async_update_entry(
+            entry, data={**entry.data, CONF_SUBSCRIPTION_URL: url}
+        )
+
+    client.refresh_subscription_url_function = _handle_new_subscription_url
+
+    async def subscribe() -> None:
+        """Subscribe to the SmartThings event stream."""
+        try:
+            await client.subscribe(
+                entry.data[CONF_LOCATION_ID],
+                entry.data[CONF_TOKEN][CONF_INSTALLED_APP_ID],
+                entry.data.get(CONF_SUBSCRIPTION_URL),
+            )
+        except (SmartThingsSinkError, SmartThingsForbiddenError) as err:
+            _LOGGER.error("Error subscribing: %s", err)
+            await asyncio.sleep(300)
path: homeassistant/components/smartthings/__init__.py
text: @user1:
Should we add a random extra time to avoid a retry storm?

@author:
One thing that irritates me with this approach is that we can't properly show the user that the integration couldn't set up. Because this is coming from a background task, it doesn't block startup either.