Skip to content

Commit

Permalink
feat: add config flow
Browse files Browse the repository at this point in the history
  • Loading branch information
lhw committed Jun 5, 2024
1 parent 2a6cf6c commit 3d60ff3
Show file tree
Hide file tree
Showing 5 changed files with 61 additions and 178 deletions.
39 changes: 4 additions & 35 deletions custom_components/cloudweatherproxy/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant

from .const import DOMAIN
from .const import CONF_DNS_SERVERS, CONF_WEATHERCLOUD_PROXY, CONF_WUNDERGROUND_PROXY, DOMAIN
from .web import WeathercloudReceiver, WundergroundReceiver

PLATFORMS: list[Platform] = [Platform.SENSOR]
Expand All @@ -15,8 +15,10 @@
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up Cloud Weather Proxy from a config entry."""

proxy_enabled = entry.data[CONF_WUNDERGROUND_PROXY] or entry.data[CONF_WEATHERCLOUD_PROXY]
dns_servers = entry.data[CONF_DNS_SERVERS]
cloudweather = hass.data.setdefault(DOMAIN, {})[entry.entry_id] = (
CloudWeatherListener()
CloudWeatherListener(proxy_enabled=proxy_enabled, dns_servers=dns_servers.split(","))
)
hass.data[DOMAIN].setdefault("known_sensors", {})

Expand All @@ -25,44 +27,11 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
hass.http.register_view(WundergroundReceiver(cloudweather))
hass.http.register_view(WeathercloudReceiver(cloudweather))

# async def handle_webhook(
# hass: HomeAssistant, webhook_id: str, request: web.Request
# ) -> web.Response:
# """Handle webhook callback."""
# log = logging.getLogger(__name__)

# log.info("Received webhook request")
# log.info(request.path)
# log.info(request.query)

# return await cloudweather.handler(request)

# webhook.async_register(
# hass,
# DOMAIN,
# entry.title,
# entry.data[CONF_WEBHOOK_ID],
# handle_webhook,
# allowed_methods=["GET"],
# )

# @callback
# def _stop_CloudWeatherProxy(_: Event) -> None:
# """Stop the Cloud Weather Proxy listener."""
# webhook.async_unregister(hass, entry.data[CONF_WEBHOOK_ID])

# entry.async_on_unload(
# hass.bus.async_listen_once(
# EVENT_HOMEASSISTANT_STOP, _stop_CloudWeatherProxy
# )
# )

return True


async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload a config entry."""
# webhook.async_unregister(hass, entry.data[CONF_WEBHOOK_ID])

if unload_ok := await hass.config_entries.async_unload_platforms(entry, PLATFORMS):
hass.data[DOMAIN].pop(entry.entry_id)
Expand Down
77 changes: 41 additions & 36 deletions custom_components/cloudweatherproxy/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,59 +4,64 @@

from typing import Any

import voluptuous as vol


from yarl import URL

from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
from homeassistant.exceptions import HomeAssistantError
from homeassistant.core import HomeAssistant
from homeassistant.helpers.network import get_url

from .const import DOMAIN
from .const import CONF_WUNDERGROUND_PROXY, CONF_WEATHERCLOUD_PROXY, CONF_DNS_SERVERS, DOMAIN


class CloudWeatherProxyConfigFlow(ConfigFlow, domain=DOMAIN):
"""Config flow for the Ecowitt."""
"""Config flow for the Cloud Weather Proxy."""

VERSION = 1
# _webhook_id: str

async def validate_input(hself, ass: HomeAssistant, data: dict[str, Any]) -> dict[str, Any]:
if not data[CONF_DNS_SERVERS].split(",") > 0:
raise InvalidInput()
return {}

async def async_step_user(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Handle the initial step."""
if user_input is None:
# self._webhook_id = secrets.token_hex(16)
return self.async_show_form(
step_id="user",
# data_schema=vol.Schema(
# {
# vol.Required("provider"): selector(
# {
# "select": {
# "options": ["Wunderground", "Weathercloud"],
# }
# }
# )
# }
# ),
)

base_url = URL(get_url(self.hass))
assert base_url.host

return self.async_create_entry(
title="Cloud Weather Proxy",
data={
# CONF_WEBHOOK_ID: self._webhook_id,
# "provider": user_input["provider"],
},
description_placeholders={
# "path": webhook.async_generate_path(self._webhook_id),
# "server": base_url.host,
# "port": str(base_url.port),
# "provider": user_input["provider"],
},
errors: dict[str, str] = {}
if user_input is not None:
try:
info = await self.validate_input(self.hass, user_input)
except InvalidInput:
errors["base"] = "invalid_input"
else:
base_url = URL(get_url(self.hass))
assert base_url.host

return self.async_create_entry(
title="Cloud Weather Proxy",
data=user_input,
description_placeholders={
"server": base_url.host,
"port": str(base_url.port),
},
)

return self.async_show_form(
step_id="user",
data_schema=vol.Schema(
{
vol.Required(CONF_WUNDERGROUND_PROXY): bool,
vol.Required(CONF_WEATHERCLOUD_PROXY): bool,
vol.Optional(CONF_DNS_SERVERS, default="9.9.9.9"): str,
}
),
errors=errors,
)


class InvalidPort(HomeAssistantError):
class InvalidInput(HomeAssistantError):
"""Error to indicate there port is not usable."""
104 changes: 0 additions & 104 deletions custom_components/cloudweatherproxy/config_flow.py.example

This file was deleted.

4 changes: 4 additions & 0 deletions custom_components/cloudweatherproxy/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,3 +124,7 @@
state_class=SensorStateClass.MEASUREMENT,
),
}

CONF_WUNDERGROUND_PROXY = "weatherunderground_proxy"
CONF_WEATHERCLOUD_PROXY = "weathercloud_proxy"
CONF_DNS_SERVERS = "dns_servers"
15 changes: 12 additions & 3 deletions custom_components/cloudweatherproxy/strings.json
Original file line number Diff line number Diff line change
@@ -1,10 +1,19 @@
{
"config": {
"step": {
"user": {}
"user": {
"title": "Select desired proxy options",
"description": "Select the services to proxy and which DNS servers to query.",
"data": {
"weatherunderground_proxy": "Proxy Weather Underground",
"weathercloud_proxy": "Proxy Weathercloud",
"dns_servers": "DNS Servers"
}
}
},
"abort": {
"already_configured": "[%key:common::config_flow::abort::already_configured_device%]"
"already_configured": "[%key:common::config_flow::abort::already_configured_device%]",
"invalid_input": "[%key:common::config_flow::abort::invalid_input%]"
}
}
}
}

0 comments on commit 3d60ff3

Please sign in to comment.