8000 Use config subentries in nederlandse spoorwegen by Martreides · Pull Request #139857 · home-assistant/core · GitHub
[go: up one dir, main page]

Skip to content

Use config subentries in nederlandse spoorwegen #139857

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 26 commits into
base: dev
Choose a base branch
from

Conversation

Martreides
Copy link
Contributor
@Martreides Martreides commented Mar 5, 2025

Breaking change

Proposed change

Major overhaul of the nederlandse_spoorwegen integration. The integration is currently a legacy one which can only be configured through config.yaml. This PR is intended as a first big step towards a Bronze quality for this integration. It moves the integration from yaml into a config flow. This alone required major changes to the integration including changing function to use asyncio.

Note that the change also implements Config Subentries, that functionality is so fresh that this is currently the only actual integration making use of it.

Type of change

  • Dependency upgrade
  • 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

  • This PR fixes or closes issue: fixes #
  • This PR is related to issue:
  • Link to documentation pull request:
  • Link to developer documentation pull request:
  • Link to frontend pull request:

Checklist

  • 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
  • I have followed the perfect PR recommendations
  • 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:

If the code communicates with devices, web services, or third-party tools:

  • The manifest file 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.

To help with the load of incoming pull requests:

@home-assistant
Copy link
home-assistant bot commented Mar 5, 2025

Hey there @YarmoM, mind taking a look at this pull request as it has been labeled with an integration (nederlandse_spoorwegen) you are listed as a code owner for? Thanks!

Code owner commands

Code owners of nederlandse_spoorwegen can trigger bot actions by commenting:

  • @home-assistant close Closes the pull request.
  • @home-assistant rename Awesome new title Renames the pull request.
  • @home-assistant reopen Reopen the pull request.
  • @home-assistant unassign nederlandse_spoorwegen Removes the current integration label and assignees on the pull request, 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 pull request.
  • @home-assistant remove-label needs-more-information Remove a label (needs-more-information, problem in dependency, problem in custom component) on the pull request.

@Martreides Martreides changed the title Dev ns config flow Improvement of NS integration - Uses Config Subentries Mar 5, 2025
@Martreides Martreides force-pushed the dev-ns-config-flow branch from acbf756 to c8ef47a Compare March 6, 2025 20:48
@Martreides
Copy link
Contributor Author
Martreides commented Mar 8, 2025

The sub entries currently have an annoying issue. After adding one it is nicely added but does not start to show data until after a reboot.

Edit: after making it possible to reload the integration (fe06495) that seems to work as well.

Edit edit: solving this turned out to be quite simple. I have added an update listener that reloads the integration after changes. This works like a charm. Commit: fbc4009.

@MartinHjelmare MartinHjelmare changed the title Improvement of NS integration - Uses Config Subentries Use config subentries in nederlandse spoorwegen Mar 9, 2025
@Martreides Martreides marked this pull request as ready for review March 16, 2025 16:52
@Martreides Martreides requested a review from a team as a code owner March 16, 2025 16:52
@Martreides
Copy link
Contributor Author

Pylint fails due to "Return type should be FlowResult in async_step_user". I think this is unavoidable since this PR makes use of subconfig entries. I'm not entirely sure why Mypy fails, it gives an error about a function not returning a value but that is incorrect. It might be caused by a lack of type hinting in the API being used.

@tr4nt0r tr4nt0r mentioned this pull request Apr 7, 2025
19 tasks
@tr4nt0r
Copy link
Contributor
tr4nt0r commented Apr 23, 2025

@Martreides issue is fixed, if you rebase the CI should pass in your PR, too #143502

Copy link
Member
@joostlek joostlek left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the config flow requires 100% unit tests. Let me know if there is anything I can help you with

Comment on lines +17 to +21
@dataclass
class NederlandseSpoorwegenData:
"""Data structure for runtime data."""

nsapi: ns_api.NSAPI
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this dataclass is not needed

nsapi: ns_api.NSAPI


async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
8000
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

extend ConfigEntry with the type of entry.runtime_data and use that throughout the code

Comment on lines +28 to +31
nsapi = ns_api.NSAPI(entry.data[CONF_API_KEY])
loop = asyncio.get_running_loop()
await loop.run_in_executor(None, nsapi.get_stations)
entry.runtime_data = NederlandseSpoorwegenData(nsapi)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

only keep things in the try block that can raise

try:
nsapi = ns_api.NSAPI(entry.data[CONF_API_KEY])
loop = asyncio.get_running_loop()
await loop.run_in_executor(None, nsapi.get_stations)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please use hass.async_add_executor_job instead

raise ConfigEntryAuthFailed(
"Could not instantiate the Nederlandse Spoorwegen API."
) from ex
else:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

else: can be removed

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we can leave the YAML for a followup

Comment on lines -36 to -76
ROUTE_SCHEMA = vol.Schema(
{
vol.Required(CONF_NAME): cv.string,
vol.Required(CONF_FROM): cv.string,
vol.Required(CONF_TO): cv.string,
vol.Optional(CONF_VIA): cv.string,
vol.Optional(CONF_TIME): cv.time,
}
from .const import (
CONF_STATION_FROM,
CONF_STATION_TO,
CONF_STATION_VIA,
CONF_TIME,
MIN_TIME_BETWEEN_UPDATES,
)

ROUTES_SCHEMA = vol.All(cv.ensure_list, [ROUTE_SCHEMA])

PLATFORM_SCHEMA = SENSOR_PLATFORM_SCHEMA.extend(
{vol.Required(CONF_API_KEY): cv.string, vol.Optional(CONF_ROUTES): ROUTES_SCHEMA}
)
_LOGGER = logging.getLogger(__name__)


def setup_platform(
async def async_setup_entry(
hass: HomeAssistant,
config: ConfigType,
add_entities: AddEntitiesCallback,
discovery_info: DiscoveryInfoType | None = None,
entry: ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up the departure sensor."""

nsapi = ns_api.NSAPI(config[CONF_API_KEY])

try:
stations = nsapi.get_stations()
except (
requests.exceptions.ConnectionError,
requests.exceptions.HTTPError,
) as error:
_LOGGER.error("Could not connect to the internet: %s", error)
raise PlatformNotReady from error
except RequestParametersError as error:
_LOGGER.error("Could not fetch stations, please check configuration: %s", error)
return

sensors = []
for departure in config.get(CONF_ROUTES, {}):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So we still want to import the existing YAML config so the user only has to remove their YAML remnants and they're ready

@Throttle(MIN_TIME_BETWEEN_UPDATES)
def update(self) -> None:
@Throttle(timedelta(seconds=MIN_TIME_BETWEEN_UPDATES))
async def async_update(self) -> None:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is it possible to keep this one untouched?

"""Initialize the sensor."""
self._hass = hass
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
self._hass = hass

self.hass is set once the entity is added to hass

@home-assistant home-assistant bot marked this pull request as draft May 14, 2025 15:47
@home-assistant
Copy link

Please take a look at the requested changes, and use the Ready for review button when you are done, thanks 👍

Learn more about our pull request process.

@Martreides Martreides force-pushed the dev-ns-config-flow branch from b2b6078 to 5be0477 Compare June 1, 2025 14:06
@Martreides
Copy link
Contributor Author

Thanks for the review @joostlek. It will take some time to get through all of the comments, I'll start working on it.

Co-authored-by: Joost Lekkerkerker <joostlek@outlook.com>
@@ -0,0 +1,60 @@
rules:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please make a separate PR with the quality scale addition.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants
0