Skip to content

Commit

Permalink
Finished release 1.0
Browse files Browse the repository at this point in the history
  • Loading branch information
briis committed Jan 24, 2024
1 parent 9d1d75f commit 2a5d7f3
Show file tree
Hide file tree
Showing 7 changed files with 466 additions and 9 deletions.
127 changes: 127 additions & 0 deletions custom_components/meteobridgesql/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
"""Meteobridge SQL Platform."""
from __future__ import annotations

from datetime import timedelta
import logging
from random import randrange
from types import MappingProxyType
from typing import Any, Self

from pymeteobridgesql import (
MeteobridgeSQLDatabaseConnectionError,
MeteobridgeSQLDataError,
MeteobridgeSQL,
RealtimeData,
StationData,
)

from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
CONF_HOST,
CONF_MAC,
CONF_PASSWORD,
CONF_PORT,
CONF_USERNAME,
Platform,
)
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError, ConfigEntryNotReady, Unauthorized
from homeassistant.helpers import device_registry as dr
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed

from .const import (
CONF_DATABASE,
DOMAIN,
)

PLATFORMS = [Platform.SENSOR]

_LOGGER = logging.getLogger(__name__)

async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool:
"""Set up MeteobridgeSQL as config entry."""

coordinator = MeteobridgeSQLDataUpdateCoordinator(hass, config_entry)
await coordinator.async_config_entry_first_refresh()

hass.data.setdefault(DOMAIN, {})
hass.data[DOMAIN][config_entry.entry_id] = coordinator

config_entry.async_on_unload(config_entry.add_update_listener(async_update_entry))

await hass.config_entries.async_forward_entry_setups(config_entry, PLATFORMS)

return True


async def async_unload_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool:
"""Unload a config entry."""

unload_ok = await hass.config_entries.async_unload_platforms(
config_entry, PLATFORMS
)

hass.data[DOMAIN].pop(config_entry.entry_id)

return unload_ok

async def async_update_entry(hass: HomeAssistant, config_entry: ConfigEntry):
"""Reload MeteobridgeSQL component when options changed."""
await hass.config_entries.async_reload(config_entry.entry_id)

class CannotConnect(HomeAssistantError):
"""Unable to connect to the web site."""

class MeteobridgeSQLDataUpdateCoordinator(DataUpdateCoordinator["MeteobridgeSQLData"]):
"""Class to manage fetching WeatherFlow data."""

def __init__(self, hass: HomeAssistant, config_entry: ConfigEntry) -> None:
"""Initialize global MeteobridgeSQL data updater."""
self.weather = MeteobridgeSQLData(hass, config_entry.data)
self.weather.initialize_data()
self.hass = hass
self.config_entry = config_entry

update_interval = timedelta(minutes=1)

super().__init__(hass, _LOGGER, name=DOMAIN, update_interval=update_interval)


async def _async_update_data(self) -> MeteobridgeSQLData:
"""Fetch data from MeteobridgeSQL."""
try:
return await self.weather.fetch_data()
except Exception as err:
raise UpdateFailed(f"Update failed: {err}") from err

class MeteobridgeSQLData:
"""Keep data for MeteobridgeSQL entity data."""

def __init__(self, hass: HomeAssistant, config: MappingProxyType[str, Any]) -> None:
"""Initialise the weather entity data."""
self.hass = hass
self._config = config
self._weather_data: MeteobridgeSQL
self.sensor_data: RealtimeData

def initialize_data(self) -> bool:
"""Establish connection to API."""

self._weather_data = MeteobridgeSQL(self._config[CONF_HOST], self._config[CONF_USERNAME], self._config[CONF_PASSWORD], self._config[CONF_DATABASE], self._config[CONF_PORT])

return True

async def fetch_data(self) -> Self:
"""Fetch data from API - (current weather and forecast)."""

try:
await self._weather_data.async_init()
self.sensor_data: RealtimeData = await self._weather_data.async_get_realtime_data(self._config[CONF_MAC])
except MeteobridgeSQLDatabaseConnectionError as unauthorized:
_LOGGER.debug(unauthorized)
raise Unauthorized from unauthorized
except MeteobridgeSQLDataError as notreadyerror:
_LOGGER.debug(notreadyerror)
raise ConfigEntryNotReady from notreadyerror

return self
12 changes: 9 additions & 3 deletions custom_components/meteobridgesql/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
)
from homeassistant.core import callback
from homeassistant.data_entry_flow import FlowResult
from pymeteobridgesql import MeteobridgeSQL
from pymeteobridgesql import MeteobridgeSQL, MeteobridgeSQLDatabaseConnectionError
from .const import (CONF_DATABASE, DEFAULT_PORT, DOMAIN)

_LOGGER = logging.getLogger(__name__)
Expand All @@ -38,8 +38,13 @@ async def async_step_user(self, user_input: dict[str, Any] | None = None) -> Flo

errors = {}

meteobridge = MeteobridgeSQL(host=user_input[CONF_HOST],user=user_input[CONF_USERNAME],password=user_input[CONF_PASSWORD], database=user_input[CONF_DATABASE])
meteobridge.async_init()
try:
meteobridge = MeteobridgeSQL(host=user_input[CONF_HOST],user=user_input[CONF_USERNAME],password=user_input[CONF_PASSWORD], database=user_input[CONF_DATABASE])
await meteobridge.async_init()
except MeteobridgeSQLDatabaseConnectionError as error:
_LOGGER.error("Error connecting to MySQL Database: %s", error)
errors["base"] = "cannot_connect"
return await self._show_setup_form(errors)

await self.async_set_unique_id(user_input[CONF_MAC])
self._abort_if_unique_id_configured
Expand Down Expand Up @@ -71,6 +76,7 @@ async def _show_setup_form(self, errors=None):
}
),
errors=errors or {},

)

class WeatherFlowForecastOptionsFlowHandler(config_entries.OptionsFlow):
Expand Down
10 changes: 10 additions & 0 deletions custom_components/meteobridgesql/const.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,16 @@
"""Constants for Meteobridge SQL component."""

ATTR_ATTRIBUTION= "Data provided by Meteobridge"
ATTR_MAX_SOLARRAD_TODAY = "max_solar_radiation_today"
ATTR_MAX_TEMP_TODAY = "max_temperature_today"
ATTR_MAX_UV_TODAY = "max_uv_today"
ATTR_MIN_TEMP_TODAY = "min_temperature_today"
ATTR_PRESSURE_TREND = "pressure_trend"
ATTR_TEMP_15_MIN = "temperature_15_min_ago"

CONF_DATABASE = "database"

DEFAULT_PORT = 3306
DOMAIN = "meteobridgesql"

MANUFACTURER = "Meteobridge"
2 changes: 1 addition & 1 deletion custom_components/meteobridgesql/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
"iot_class": "cloud_polling",
"issue_tracker": "https://github.com/briis/meteobridgesql/issues",
"requirements": [
"pymeteobridgesql==1.0.0"
"pymeteobridgesql==1.0.1"
],
"version": "1.0.0"
}
Loading

0 comments on commit 2a5d7f3

Please sign in to comment.