Repository: home-assistant/core
Pull request: Add configure option to Vodafone Station for consider home
<!--
  You are amazing! Thanks for contributing to our project!
  Please, DO NOT DELETE ANY TEXT from this template! (unless instructed).
-->
## Breaking change
<!--
  If your PR contains a breaking change for existing users, it is important
  to tell them what breaks, how to make it work again and why we did this.
  This piece of text is published with the release notes, so it helps if you
  write it towards our users, not us.
  Note: Remove this section if this PR is NOT a breaking change.
-->


## 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.
-->
Allow users to change the default time ( 180sec ) to consider a device at 'home'.


## 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 #102512
- 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] I have followed the [perfect PR recommendations][perfect-pr]
- [x] 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.
- [ ] Untested files have been added to `.coveragerc`.

<!--
  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:
Vodafone Station 6 shows device trackers as always "home"
### The problem

Installed the integration and it works quite well but the "consider home" parameter setting is missing. Navigated to the cogwheel but there are only the standard settings.

When disconnected, the device trackers remain "home".

### What version of Home Assistant Core has the issue?

core-2023.10.4

### What was the last working version of Home Assistant Core?

core-2023.10.4

### What type of installation are you running?

Home Assistant OS

### Integration causing the issue

Vodafone

### Link to integration documentation on our website

_No response_

### Diagnostics information

_No response_

### Example YAML snippet

_No response_

### Anything in the logs that might be useful for us?

_No response_

### Additional information

_No response_

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

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


Code owners of `vodafone_station` 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 vodafone_station` Removes the current integration label and assignees on the issue, add the integration domain after the command.

</details>


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

---

[vodafone_station documentation](https://www.home-assistant.io/integrations/vodafone_station)
[vodafone_station source](https://github.com/home-assistant/core/tree/dev/homeassistant/components/vodafone_station)
<sub><sup>(message by IssueLinks)</sup></sub>
Hi @p2923260, the status changes after the default 180s + the scanning interval (60s), so at best after 3m1s and at worst after 4 minutes.

Thanks @chemelli74 for your prompt answer. You did a very useful integration. Are you planning to make it a configurable interval? Possibly via yaml?
> Thanks @chemelli74 for your prompt answer. You did a very useful integration. 

Thank you !

> Are you planning to make it a configurable interval? Possibly via yaml?

YAML is not allowed anymore for any new feature in HA ;-)
But yes, will add the option to change it.


There hasn't been any activity on this issue recently. Due to the high number of incoming GitHub notifications, we have to clean some of the old issues, as many of them have already been resolved with the latest updates.
Please make sure to update to the latest Home Assistant version and check if that solves the issue. Let us know if that works for you by adding a comment 👍
This issue has now been marked as stale and will be closed if no further activity occurs. Thank you for your contributions.

Commit message: add test

Patch to review:
diff --git a/homeassistant/components/vodafone_station/config_flow.py b/homeassistant/components/vodafone_station/config_flow.py
index dc33d0db52b443..21cc4fe5fc35ed 100644
--- a/homeassistant/components/vodafone_station/config_flow.py
+++ b/homeassistant/components/vodafone_station/config_flow.py
@@ -7,9 +7,13 @@
 from aiovodafone import VodafoneStationSercommApi, exceptions as aiovodafone_exceptions
 import voluptuous as vol
 
-from homeassistant import core
-from homeassistant.config_entries import ConfigEntry, ConfigFlow
+from homeassistant.components.device_tracker import (
+    CONF_CONSIDER_HOME,
+    DEFAULT_CONSIDER_HOME,
+)
+from homeassistant.config_entries import ConfigEntry, ConfigFlow, OptionsFlow
 from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME
+from homeassistant.core import HomeAssistant, callback
 from homeassistant.data_entry_flow import FlowResult
 
 from .const import _LOGGER, DEFAULT_HOST, DEFAULT_USERNAME, DOMAIN
@@ -30,9 +34,7 @@ def user_form_schema(user_input: dict[str, Any] | None) -> vol.Schema:
 STEP_REAUTH_DATA_SCHEMA = vol.Schema({vol.Required(CONF_PASSWORD): str})
 
 
-async def validate_input(
-    hass: core.HomeAssistant, data: dict[str, Any]
-) -> dict[str, str]:
+async def validate_input(hass: HomeAssistant, data: dict[str, Any]) -> dict[str, str]:
     """Validate the user input allows us to connect."""
 
     api = VodafoneStationSercommApi(
@@ -54,6 +56,12 @@ class VodafoneStationConfigFlow(ConfigFlow, domain=DOMAIN):
     VERSION = 1
     entry: ConfigEntry | None = None
 
+    @staticmethod
+    @callback
+    def async_get_options_flow(config_entry: ConfigEntry) -> OptionsFlow:
+        """Get the options flow for this handler."""
+        return VodafoneStationOptionsFlowHandler(config_entry)
+
     async def async_step_user(
         self, user_input: dict[str, Any] | None = None
     ) -> FlowResult:
@@ -133,3 +141,31 @@ async def async_step_reauth_confirm(
             data_schema=STEP_REAUTH_DATA_SCHEMA,
             errors=errors,
         )
+
+
+class VodafoneStationOptionsFlowHandler(OptionsFlow):
+    """Handle a option flow."""
+
+    def __init__(self, config_entry: ConfigEntry) -> None:
+        """Initialize options flow."""
+        self.config_entry = config_entry
+
+    async def async_step_init(
+        self, user_input: dict[str, Any] | None = None
+    ) -> FlowResult:
+        """Handle options flow."""
+
+        if user_input is not None:
+            return self.async_create_entry(title="", data=user_input)
+
+        data_schema = vol.Schema(
+            {
+                vol.Optional(
+                    CONF_CONSIDER_HOME,
+                    default=self.config_entry.options.get(
+                        CONF_CONSIDER_HOME, DEFAULT_CONSIDER_HOME.total_seconds()
+                    ),
+                ): vol.All(vol.Coerce(int), vol.Clamp(min=0, max=900))
+            }
+        )
+        return self.async_show_form(step_id="init", data_schema=data_schema)
diff --git a/homeassistant/components/vodafone_station/strings.json b/homeassistant/components/vodafone_station/strings.json
index fab266ac47f86b..8910d7178b737e 100644
--- a/homeassistant/components/vodafone_station/strings.json
+++ b/homeassistant/components/vodafone_station/strings.json
@@ -36,6 +36,15 @@
       "unknown": "[%key:common::config_flow::error::unknown%]"
     }
   },
+  "options": {
+    "step": {
+      "init": {
+        "data": {
+          "consider_home": "Seconds to consider a device at 'home'"
+        }
+      }
+    }
+  },
   "entity": {
     "button": {
       "dsl_reconnect": { "name": "DSL reconnect" },
diff --git a/tests/components/vodafone_station/test_config_flow.py b/tests/components/vodafone_station/test_config_flow.py
index 00b1ae6e72ac56..24a4179830e13f 100644
--- a/tests/components/vodafone_station/test_config_flow.py
+++ b/tests/components/vodafone_station/test_config_flow.py
@@ -4,6 +4,7 @@
 from aiovodafone import exceptions as aiovodafone_exceptions
 import pytest
 
+from homeassistant.components.device_tracker import CONF_CONSIDER_HOME
 from homeassistant.components.vodafone_station.const import DOMAIN
 from homeassistant.config_entries import SOURCE_REAUTH, SOURCE_USER
 from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME
@@ -23,11 +24,7 @@ async def test_user(hass: HomeAssistant) -> None:
         "homeassistant.components.vodafone_station.config_flow.VodafoneStationSercommApi.logout",
     ), patch(
         "homeassistant.components.vodafone_station.async_setup_entry"
-    ) as mock_setup_entry, patch(
-        "requests.get",
-    ) as mock_request_get:
-        mock_request_get.return_value.status_code = 200
-
+    ) as mock_setup_entry:
         result = await hass.config_entries.flow.async_init(
             DOMAIN, context={"source": SOURCE_USER}
         )
@@ -123,11 +120,7 @@ async def test_reauth_successful(hass: HomeAssistant) -> None:
         "homeassistant.components.vodafone_station.config_flow.VodafoneStationSercommApi.logout",
     ), patch(
         "homeassistant.components.vodafone_station.async_setup_entry",
-    ), patch(
-        "requests.get",
-    ) as mock_request_get:
-        mock_request_get.return_value.status_code = 200
-
+    ):
         result = await hass.config_entries.flow.async_init(
             DOMAIN,
             context={"source": SOURCE_REAUTH, "entry_id": mock_config.entry_id},
@@ -216,3 +209,31 @@ async def test_reauth_not_successful(hass: HomeAssistant, side_effect, error) ->
 
         assert result2["type"] == FlowResultType.ABORT
         assert result2["reason"] == "reauth_successful"
+
+
+async def test_options_flow(hass: HomeAssistant) -> None:
+    """Test options flow."""
+
+    mock_config = MockConfigEntry(domain=DOMAIN, data=MOCK_USER_DATA)
+    mock_config.add_to_hass(hass)
+
+    with patch(
+        "homeassistant.components.vodafone_station.config_flow.VodafoneStationSercommApi.login",
+    ), patch(
+        "homeassistant.components.vodafone_station.config_flow.VodafoneStationSercommApi.logout",
+    ), patch(
+        "homeassistant.components.vodafone_station.async_setup_entry",
+    ):
+        result = await hass.config_entries.options.async_init(mock_config.entry_id)
+        assert result["type"] == FlowResultType.FORM
+        assert result["step_id"] == "init"
+
+        result = await hass.config_entries.options.async_init(mock_config.entry_id)
+        result = await hass.config_entries.options.async_configure(
+            result["flow_id"],
+            user_input={
+                CONF_CONSIDER_HOME: 37,
+            },
+        )
+        assert result["type"] == FlowResultType.CREATE_ENTRY
+        assert mock_config.options[CONF_CONSIDER_HOME] == 37


Code review comments:
diff_hunk: @@ -133,3 +141,31 @@ async def async_step_reauth_confirm(
             data_schema=STEP_REAUTH_DATA_SCHEMA,
             errors=errors,
         )
+
+
+class VodafoneStationOptionsFlowHandler(OptionsFlow):
+    """Handle a option flow."""
+
+    def __init__(self, config_entry: ConfigEntry) -> None:
+        """Initialize options flow."""
+        self.config_entry = config_entry
+
+    async def async_step_init(
+        self, user_input: dict[str, Any] | None = None
+    ) -> FlowResult:
+        """Handle options flow."""
+
+        if user_input is not None:
+            return self.async_create_entry(title="", data=user_input)
+
+        data_schema = vol.Schema(
+            {
+                vol.Optional(
+                    CONF_CONSIDER_HOME,
+                    default=self.config_entry.options.get(
path: homeassistant/components/vodafone_station/config_flow.py
text: @user1:
```suggestion
                    default=self.options.get(
```

diff_hunk: @@ -216,3 +209,31 @@ async def test_reauth_not_successful(hass: HomeAssistant, side_effect, error) ->
 
         assert result2["type"] == FlowResultType.ABORT
         assert result2["reason"] == "reauth_successful"
+
+
+async def test_options_flow(hass: HomeAssistant) -> None:
+    """Test options flow."""
+
+    mock_config = MockConfigEntry(domain=DOMAIN, data=MOCK_USER_DATA)
+    mock_config.add_to_hass(hass)
+
+    with patch(
+        "homeassistant.components.vodafone_station.config_flow.VodafoneStationSercommApi.login",
+    ), patch(
+        "homeassistant.components.vodafone_station.config_flow.VodafoneStationSercommApi.logout",
+    ), patch(
+        "homeassistant.components.vodafone_station.async_setup_entry",
+    ):
path: tests/components/vodafone_station/test_config_flow.py
text: @user1:
Please be reminded that currently when you submit the options flow, nothing will happen. If you want to apply the new options directly, you should reload the integration and add proper listeners to that.

In that light I don't want to see the async_setup_entry patched, but rather executed and then tested if we reload them

@author:
Fixed! Will update `fritz` as well once this get merged.

@user1:
This is not fixed as far as I can see

diff_hunk: @@ -216,3 +209,31 @@ async def test_reauth_not_successful(hass: HomeAssistant, side_effect, error) ->
 
         assert result2["type"] == FlowResultType.ABORT
         assert result2["reason"] == "reauth_successful"
+
+
+async def test_options_flow(hass: HomeAssistant) -> None:
+    """Test options flow."""
+
+    mock_config = MockConfigEntry(domain=DOMAIN, data=MOCK_USER_DATA)
+    mock_config.add_to_hass(hass)
+
+    with patch(
+        "homeassistant.components.vodafone_station.config_flow.VodafoneStationSercommApi.login",
+    ), patch(
+        "homeassistant.components.vodafone_station.config_flow.VodafoneStationSercommApi.logout",
+    ), patch(
+        "homeassistant.components.vodafone_station.async_setup_entry",
+    ):
+        result = await hass.config_entries.options.async_init(mock_config.entry_id)
+        assert result["type"] == FlowResultType.FORM
+        assert result["step_id"] == "init"
+
+        result = await hass.config_entries.options.async_init(mock_config.entry_id)
path: tests/components/vodafone_station/test_config_flow.py
text: @user1:
Why are we starting the flow twice?

@author:
Barely copy&paste from `fritz` ;-)
Fixed.

diff_hunk: @@ -133,3 +141,31 @@ async def async_step_reauth_confirm(
             data_schema=STEP_REAUTH_DATA_SCHEMA,
             errors=errors,
         )
+
+
+class VodafoneStationOptionsFlowHandler(OptionsFlow):
+    """Handle a option flow."""
+
+    def __init__(self, config_entry: ConfigEntry) -> None:
+        """Initialize options flow."""
+        self.config_entry = config_entry
path: homeassistant/components/vodafone_station/config_flow.py
text: @user1:
```suggestion
class VodafoneStationOptionsFlowHandler(OptionsFlowWithConfigEntry):
    """Handle an option flow."""
```

@author:
Thx, was not aware of `OptionsFlowWithConfigEntry`