Repository: home-assistant/core
Pull request: Drop upnp options flow
<!--
  You are amazing! Thanks for contributing to our project!
  Please, DO NOT DELETE ANY TEXT from this template! (unless instructed).
-->
## Breaking change
The Options flow is removed!


## 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.
-->

Strip the Options flow from the upnp component. This flow allowed one to set the update interval. Now that the `homeassistant.update_entity` service provides this functionality, the options flow is removed.


## 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)
- [ ] 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 #68899, #66713
- This PR is related to issue: 
- Link to documentation 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] The code has been formatted using Black (`black --fast 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.
- [ ] Untested files have been added to `.coveragerc`.

The integration reached or maintains the following [Integration Quality Scale][quality-scale]:
<!--
  The Integration Quality Scale scores an integration on the code quality
  and user experience. Each level of the quality scale consists of a list
  of requirements. We highly recommend getting your integration scored!
-->

- [ ] No score or internal
- [ ] 🥈 Silver
- [ ] 🥇 Gold
- [ ] 🏆 Platinum

<!--
  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/en/development_checklist.html
[manifest-docs]: https://developers.home-assistant.io/docs/en/creating_integration_manifest.html
[quality-scale]: https://developers.home-assistant.io/docs/en/next/integration_quality_scale_index.html
[docs-repository]: https://github.com/home-assistant/home-assistant.io


Problem statement:
UPnP integration issue since 2022.3.8
### The problem

The UPnP won't load the connection with my router (TP-Link Archer C80). Router config is the same and I just re-checked, UPnP is enabled.

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

core-2022.3.8

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

_No response_

### What type of installation are you running?

Home Assistant Container

### Integration causing the issue

UPnP

### Link to integration documentation on our website

_No response_

### Diagnostics information

```
Logger: aiohttp.server
Source: components/upnp/config_flow.py:295
First occurred: 2:56:46 PM (2 occurrences)
Last logged: 2:56:49 PM

Error handling request
Traceback (most recent call last):
  File "/usr/local/lib/python3.9/site-packages/aiohttp/web_protocol.py", line 435, in _handle_request
    resp = await request_handler(request)
  File "/usr/local/lib/python3.9/site-packages/aiohttp/web_app.py", line 504, in _handle
    resp = await handler(request)
  File "/usr/local/lib/python3.9/site-packages/aiohttp/web_middlewares.py", line 117, in impl
    return await handler(request)
  File "/usr/src/homeassistant/homeassistant/components/http/security_filter.py", line 60, in security_filter_middleware
    return await handler(request)
  File "/usr/src/homeassistant/homeassistant/components/http/forwarded.py", line 100, in forwarded_middleware
    return await handler(request)
  File "/usr/src/homeassistant/homeassistant/components/http/request_context.py", line 28, in request_context_middleware
    return await handler(request)
  File "/usr/src/homeassistant/homeassistant/components/http/ban.py", line 79, in ban_middleware
    return await handler(request)
  File "/usr/src/homeassistant/homeassistant/components/http/auth.py", line 219, in auth_middleware
    return await handler(request)
  File "/usr/src/homeassistant/homeassistant/components/http/view.py", line 137, in handle
    result = await result
  File "/usr/src/homeassistant/homeassistant/components/config/config_entries.py", line 224, in post
    return await super().post(request, flow_id)
  File "/usr/src/homeassistant/homeassistant/components/http/data_validator.py", line 62, in wrapper
    result = await method(view, request, *args, **kwargs)
  File "/usr/src/homeassistant/homeassistant/helpers/data_entry_flow.py", line 111, in post
    result = await self._flow_mgr.async_configure(flow_id, data)
  File "/usr/src/homeassistant/homeassistant/data_entry_flow.py", line 252, in async_configure
    result = await self._async_handle_step(flow, cur_step["step_id"], user_input)
  File "/usr/src/homeassistant/homeassistant/data_entry_flow.py", line 325, in _async_handle_step
    result: FlowResult = await getattr(flow, method)(user_input)
  File "/usr/src/homeassistant/homeassistant/components/upnp/config_flow.py", line 295, in async_step_init
    coordinator = self.hass.data[DOMAIN][self.config_entry.entry_id]
KeyError: '4874c87033421887a7966f72168ae498'
```

### Example YAML snippet

```yaml
None
```


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

_No response_

### Additional information

_No response_

Hints from issue discussion:
Hey there @stevenlooman, @ehendrix23, mind taking a look at this issue as it has been labeled with an integration (`upnp`) you are listed as a [code owner](https://github.com/home-assistant/core/blob/dev/CODEOWNERS#L1081) for? Thanks!
<sub><sup>(message by CodeOwnersMention)</sup></sub>

---

[upnp documentation](https://www.home-assistant.io/integrations/upnp)
[upnp source](https://github.com/home-assistant/core/tree/dev/homeassistant/components/upnp)
<sub><sup>(message by IssueLinks)</sup></sub>
Just found a possible cause, namely the available ports:

- Running in network mode "host" this integration works.
- If I only enable the 8123 port for the HA container this integration stops working.
Thank you for this issue @JoryHogeveen. The network mode always needs to be `host`, as this integration relies on ssdp discovery.  

The error has been reported before but I'm unsure where it is coming from. #67937, #66713 and a few other report the same. Are you able to reproduce this error?
Also, when does this occur? On restart? When you configure the component? Did you change any of the options of the component (the update interval.)

Commit message: Don't try to update the coordinator when it is not there

Patch to review:
diff --git a/homeassistant/components/upnp/config_flow.py b/homeassistant/components/upnp/config_flow.py
index e339c69d5d8b8..346fa50972fac 100644
--- a/homeassistant/components/upnp/config_flow.py
+++ b/homeassistant/components/upnp/config_flow.py
@@ -294,14 +294,22 @@ def __init__(self, config_entry: config_entries.ConfigEntry) -> None:
 
     async def async_step_init(self, user_input: Mapping = None) -> FlowResult:
         """Manage the options."""
+        LOGGER.debug(
+            "UpnpOptionsFlowHandler.async_step_init: user_input: %s", user_input
+        )
         if user_input is not None:
-            coordinator = self.hass.data[DOMAIN][self.config_entry.entry_id]
             update_interval_sec = user_input.get(
                 CONFIG_ENTRY_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL
             )
             update_interval = timedelta(seconds=update_interval_sec)
-            LOGGER.debug("Updating coordinator, update_interval: %s", update_interval)
-            coordinator.update_interval = update_interval
+
+            if self.config_entry.entry_id in self.hass.data[DOMAIN]:
+                coordinator = self.hass.data[DOMAIN][self.config_entry.entry_id]
+                LOGGER.debug(
+                    "Updating coordinator, update_interval: %s", update_interval
+                )
+                coordinator.update_interval = update_interval
+
             return self.async_create_entry(title="", data=user_input)
 
         scan_interval = self.config_entry.options.get(


Code review comments:
diff_hunk: @@ -294,14 +294,22 @@ def __init__(self, config_entry: config_entries.ConfigEntry) -> None:
 
     async def async_step_init(self, user_input: Mapping = None) -> FlowResult:
         """Manage the options."""
+        LOGGER.debug(
+            "UpnpOptionsFlowHandler.async_step_init: user_input: %s", user_input
+        )
         if user_input is not None:
-            coordinator = self.hass.data[DOMAIN][self.config_entry.entry_id]
             update_interval_sec = user_input.get(
                 CONFIG_ENTRY_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL
             )
             update_interval = timedelta(seconds=update_interval_sec)
-            LOGGER.debug("Updating coordinator, update_interval: %s", update_interval)
-            coordinator.update_interval = update_interval
+
+            if self.config_entry.entry_id in self.hass.data[DOMAIN]:
+                coordinator = self.hass.data[DOMAIN][self.config_entry.entry_id]
+                LOGGER.debug(
+                    "Updating coordinator, update_interval: %s", update_interval
+                )
+                coordinator.update_interval = update_interval
path: homeassistant/components/upnp/config_flow.py
text: @user1:
Ideally, we should completely remove the scan interval setting.
We offer the `homeassistant.update_entity` as an alternative.

@author:
Does the `homeassistant.update_entity` service allow one to decrease the poll rate?

@user1:
What you want it to be.  You can call it automation, how often that triggers, or which patterns, maybe skip Sundays and poll slower on a workday. That is up to the implementer. The services offer more freedom.

@author:
This seems fairly loose. It is expected that the integration is updated with a regular interval. Can you point to an integration which uses this? I see the `accuweather` does seem to support it (or at least has tests for it,) but also provides its own (non configurable) update interval.

@user1:
> This seems fairly loose. 

I'm not following that comment? What do you mean by loose? If flexible: Yes. That was the goal.

> Can you point to an integration which uses this?

All of them, it built into the core itself.


@author:
> I'm not following that comment? What do you mean by loose? If flexible: Yes. That was the goal.

The way you bring it somebody can determine it should be polled once on a sunday, perhaps twice on a monday, and once when easter and pentecost are on the same day. This will prevent some of the sensors from working correctly.

> All of them, it built into the core itself.

Thus this integration is also doing it already?

@author:
Joking aside, I've removed the options flow.

@user1:
> The way you bring it somebody can determine it should be polled once on a sunday, perhaps twice on a monday, and once when easter and pentecost are on the same day. This will prevent some of the sensors from working correctly.

Well, we can make that more practical, for example, poll my electric vehicle more often during the day than during the night, so I don't wake up my Tesla at the night and thus prevent the waste of energy by waking it up.

Or: Reducing polling on a paid cloud service when I'm not home or during nights, to save API calls and thus costs.

We've seen many variations on these, in many feature requests throughout the years.