meteocat 0.1.26 → 0.1.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,3 +1,32 @@
1
+ ## [0.1.28](https://github.com/figorr/meteocat/compare/v0.1.27...v0.1.28) (2024-12-11)
2
+
3
+
4
+ ### Bug Fixes
5
+
6
+ * 0.1.28 ([2c329cb](https://github.com/figorr/meteocat/commit/2c329cb960aa7bd6ec6bec0c6145db791349758f))
7
+ * bump meteocatpy to 0.0.13 ([52c11c6](https://github.com/figorr/meteocat/commit/52c11c66f66b0ebff40fea58a8a5c4d4a74482be))
8
+ * fix entity_id ([fa61841](https://github.com/figorr/meteocat/commit/fa61841ba3857a79d6b97d0e0ed12a543525c205))
9
+ * fix name sensors to include station_id ([7b868fd](https://github.com/figorr/meteocat/commit/7b868fd0eea66f8ec2655e92137d9ab6dd9d0149))
10
+ * ignore test_call_api ([976826a](https://github.com/figorr/meteocat/commit/976826a978889fcec304a8b3620ccf738e1a1946))
11
+ * save variables.json in assets folder ([d2c2234](https://github.com/figorr/meteocat/commit/d2c2234621aaabbbdc65367429b56b304855f710))
12
+ * setup cache folder and new async_remove_entry ([4dfddc0](https://github.com/figorr/meteocat/commit/4dfddc03a64f82582b39eff47870c561d0775d6d))
13
+
14
+ ## [0.1.27](https://github.com/figorr/meteocat/compare/v0.1.26...v0.1.27) (2024-12-10)
15
+
16
+
17
+ ### Bug Fixes
18
+
19
+ * 0.1.27 ([99feff1](https://github.com/figorr/meteocat/commit/99feff14eb85201028c1e6156a13354b05b446c3))
20
+ * bump meteocatpy to 0.0.11 ([03b9485](https://github.com/figorr/meteocat/commit/03b9485b0486a2bef7f0b7f3c0bf9bf1fca3da8c))
21
+ * bump meteocatpy to 0.0.9 ([1fb0de9](https://github.com/figorr/meteocat/commit/1fb0de97181b802494cb8371eb472a37c9a51f40))
22
+ * delete .meteocat_cache ([7941005](https://github.com/figorr/meteocat/commit/79410050e68667ca8162ff6575c0541a5f8b6207))
23
+ * fix python version ([07e3264](https://github.com/figorr/meteocat/commit/07e3264f5dde756c322ca431f4b895a211be998f))
24
+ * fix python version ([32f539b](https://github.com/figorr/meteocat/commit/32f539bb33a343881ebd26eb7ad3f12a58ecbed4))
25
+ * fix python version ([2ff2dfc](https://github.com/figorr/meteocat/commit/2ff2dfcfa597d9fbba0fc59c330f975c6b00a55b))
26
+ * ignore cache tests ([238d148](https://github.com/figorr/meteocat/commit/238d148630a5f84123f8d2d5db66dbd6e6b372f8))
27
+ * set variables cache ([ba77035](https://github.com/figorr/meteocat/commit/ba7703511c4e0604bd5d87f7d07ce487be67bafe))
28
+ * set variables cache ([ba55568](https://github.com/figorr/meteocat/commit/ba55568526fe74e83feaf4d7a0cd5127334ee139))
29
+
1
30
  ## [0.1.26](https://github.com/figorr/meteocat/compare/v0.1.25...v0.1.26) (2024-12-09)
2
31
 
3
32
 
@@ -1,20 +1,32 @@
1
1
  from __future__ import annotations
2
2
 
3
- import os
4
3
  import logging
4
+ from pathlib import Path
5
5
  from homeassistant import core
6
6
  from homeassistant.config_entries import ConfigEntry
7
7
  from homeassistant.core import HomeAssistant
8
8
  from homeassistant.exceptions import HomeAssistantError
9
9
  from homeassistant.helpers.entity_platform import async_get_platforms
10
10
 
11
- from .coordinator import MeteocatSensorCoordinator, MeteocatEntityCoordinator
11
+ from .coordinator import MeteocatSensorCoordinator #, MeteocatEntityCoordinator
12
12
  from .const import DOMAIN, PLATFORMS
13
13
 
14
14
  _LOGGER = logging.getLogger(__name__)
15
15
 
16
16
  # Versión
17
- __version__ = "0.1.26"
17
+ __version__ = "0.1.28"
18
+
19
+ def safe_remove(path: Path, is_folder: bool = False):
20
+ """Elimina de forma segura un archivo o carpeta si existe."""
21
+ try:
22
+ if is_folder and path.exists() and not any(path.iterdir()):
23
+ path.rmdir()
24
+ _LOGGER.info(f"Carpeta {path.name} eliminada correctamente.")
25
+ elif not is_folder and path.exists():
26
+ path.unlink()
27
+ _LOGGER.info(f"Archivo {path.name} eliminado correctamente.")
28
+ except OSError as e:
29
+ _LOGGER.error(f"Error al intentar eliminar {path.name}: {e}")
18
30
 
19
31
 
20
32
  async def async_setup(hass: core.HomeAssistant, config: dict) -> bool:
@@ -45,13 +57,18 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
45
57
  f"Estación '{entry_data['station_name']}' (ID: {entry_data['station_id']})."
46
58
  )
47
59
 
60
+ # Configurar ruta de la caché
61
+ cache_dir = Path(hass.config.path("custom_components", DOMAIN, ".meteocat_cache"))
62
+ cache_dir.mkdir(parents=True, exist_ok=True)
63
+ _LOGGER.debug(f"Directorio de caché configurado en: {cache_dir}")
64
+
48
65
  # Inicializar coordinadores
49
66
  try:
50
67
  sensor_coordinator = MeteocatSensorCoordinator(hass=hass, entry_data=entry_data)
51
- entity_coordinator = MeteocatEntityCoordinator(hass=hass, entry_data=entry_data)
52
-
53
68
  await sensor_coordinator.async_config_entry_first_refresh()
54
- await entity_coordinator.async_config_entry_first_refresh()
69
+
70
+ # entity_coordinator = MeteocatEntityCoordinator(hass=hass, entry_data=entry_data)
71
+ # await entity_coordinator.async_config_entry_first_refresh()
55
72
  except Exception as err: # Capturar todos los errores
56
73
  _LOGGER.exception(f"Error al inicializar los coordinadores: {err}")
57
74
  return False
@@ -60,7 +77,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
60
77
  hass.data.setdefault(DOMAIN, {})
61
78
  hass.data[DOMAIN][entry.entry_id] = {
62
79
  "sensor_coordinator": sensor_coordinator,
63
- "entity_coordinator": entity_coordinator,
80
+ # "entity_coordinator": entity_coordinator,
64
81
  **entry_data,
65
82
  }
66
83
 
@@ -89,48 +106,23 @@ async def async_remove_entry(hass: HomeAssistant, entry: ConfigEntry) -> None:
89
106
  _LOGGER.info(f"Eliminando datos residuales de la integración: {entry.entry_id}")
90
107
 
91
108
  # Definir las rutas de los archivos y carpetas a eliminar
92
- custom_components_path = hass.config.path("custom_components", DOMAIN)
93
- assets_folder = os.path.join(custom_components_path, "assets")
94
- files_folder = os.path.join(custom_components_path, "files")
95
- symbols_file = os.path.join(assets_folder, "symbols.json")
96
- station_data_file = os.path.join(files_folder, "station_data.json")
97
-
98
- # Eliminar el archivo symbols.json si existe
99
- try:
100
- if os.path.exists(symbols_file):
101
- os.remove(symbols_file)
102
- _LOGGER.info("Archivo symbols.json eliminado correctamente.")
103
- else:
104
- _LOGGER.info("El archivo symbols.json no se encontró.")
105
- except OSError as e:
106
- _LOGGER.error(f"Error al intentar eliminar el archivo symbols.json: {e}")
107
-
108
- # Eliminar el archivo station_data.json si existe
109
- try:
110
- if os.path.exists(station_data_file):
111
- os.remove(station_data_file)
112
- _LOGGER.info("Archivo station_data.json eliminado correctamente.")
113
- else:
114
- _LOGGER.info("El archivo station_data.json no se encontró.")
115
- except OSError as e:
116
- _LOGGER.error(f"Error al intentar eliminar el archivo station_data.json: {e}")
117
-
118
- # Eliminar la carpeta assets si está vacía
119
- try:
120
- if os.path.exists(assets_folder) and not os.listdir(assets_folder):
121
- os.rmdir(assets_folder)
122
- _LOGGER.info("Carpeta assets eliminada correctamente.")
123
- elif os.path.exists(assets_folder):
124
- _LOGGER.warning("La carpeta assets no está vacía y no se pudo eliminar.")
125
- except OSError as e:
126
- _LOGGER.error(f"Error al intentar eliminar la carpeta assets: {e}")
127
-
128
- # Eliminar la carpeta files si está vacía
129
- try:
130
- if os.path.exists(files_folder) and not os.listdir(files_folder):
131
- os.rmdir(files_folder)
132
- _LOGGER.info("Carpeta files eliminada correctamente.")
133
- elif os.path.exists(files_folder):
134
- _LOGGER.warning("La carpeta files no está vacía y no se pudo eliminar.")
135
- except OSError as e:
136
- _LOGGER.error(f"Error al intentar eliminar la carpeta files: {e}")
109
+ custom_components_path = Path(hass.config.path("custom_components")) / DOMAIN
110
+ assets_folder = custom_components_path / "assets"
111
+ files_folder = custom_components_path / "files"
112
+ cache_folder = custom_components_path / ".meteocat_cache"
113
+ symbols_file = assets_folder / "symbols.json"
114
+ variables_file = assets_folder / "variables.json"
115
+ station_data_file = files_folder / "station_data.json"
116
+
117
+ # Validar la ruta base
118
+ if not custom_components_path.exists():
119
+ _LOGGER.warning(f"La ruta {custom_components_path} no existe. No se realizará la limpieza.")
120
+ return
121
+
122
+ # Eliminar archivos y carpetas
123
+ safe_remove(symbols_file)
124
+ safe_remove(variables_file)
125
+ safe_remove(station_data_file)
126
+ safe_remove(assets_folder, is_folder=True)
127
+ safe_remove(files_folder, is_folder=True)
128
+ safe_remove(cache_folder, is_folder=True)
@@ -1,5 +1,6 @@
1
1
  from __future__ import annotations
2
2
 
3
+ import os
3
4
  import json
4
5
  import logging
5
6
  from pathlib import Path
@@ -104,6 +105,7 @@ class MeteocatConfigFlow(ConfigFlow, domain=DOMAIN):
104
105
  assets_dir = Path(__file__).parent / "assets"
105
106
  assets_dir.mkdir(parents=True, exist_ok=True)
106
107
  symbols_file = assets_dir / "symbols.json"
108
+ variables_file = assets_dir / "variables.json"
107
109
  symbols_client = MeteocatSymbols(self.api_key)
108
110
 
109
111
  try:
@@ -115,12 +117,20 @@ class MeteocatConfigFlow(ConfigFlow, domain=DOMAIN):
115
117
  errors["base"] = "symbols_download_failed"
116
118
 
117
119
  if not errors:
118
- variables_client = MeteocatVariables(self.api_key)
120
+ # Configurar la ruta para la caché en la carpeta `custom_components/meteocat`
121
+ cache_dir = os.path.join(os.path.dirname(__file__), ".meteocat_cache")
122
+
123
+ # Crear la carpeta de caché si no existe
124
+ os.makedirs(cache_dir, exist_ok=True)
125
+
126
+ variables_client = MeteocatVariables(self.api_key, cache_dir=cache_dir)
119
127
  try:
120
128
  variables_data = await variables_client.get_variables()
121
129
  self.variable_id = next(
122
130
  (v["codi"] for v in variables_data if v["nom"].lower() == "temperatura"), None
123
131
  )
132
+ async with aiofiles.open(variables_file, "w", encoding="utf-8") as file:
133
+ await file.write(json.dumps({"variables": variables_data}, ensure_ascii=False, indent=4))
124
134
  if not self.variable_id:
125
135
  _LOGGER.error("No se encontró la variable 'Temperatura'")
126
136
  errors["base"] = "variable_not_found"
@@ -12,7 +12,7 @@ from homeassistant.helpers.update_coordinator import DataUpdateCoordinator
12
12
  from homeassistant.exceptions import ConfigEntryNotReady
13
13
 
14
14
  from meteocatpy.data import MeteocatStationData
15
- from meteocatpy.forecast import MeteocatForecast
15
+ # from meteocatpy.forecast import MeteocatForecast
16
16
  from meteocatpy.exceptions import (
17
17
  BadRequestError,
18
18
  ForbiddenError,
@@ -119,76 +119,76 @@ class MeteocatSensorCoordinator(DataUpdateCoordinator):
119
119
  )
120
120
  raise
121
121
 
122
- class MeteocatEntityCoordinator(DataUpdateCoordinator):
123
- """Coordinator para manejar la actualización de datos de las entidades de predicción."""
124
-
125
- def __init__(
126
- self,
127
- hass: HomeAssistant,
128
- entry_data: dict,
129
- update_interval: timedelta = DEFAULT_ENTITY_UPDATE_INTERVAL,
130
- ):
131
- """
132
- Inicializa el coordinador de datos para entidades de predicción.
133
-
134
- Args:
135
- hass (HomeAssistant): Instancia de Home Assistant.
136
- entry_data (dict): Datos de configuración obtenidos de core.config_entries.
137
- update_interval (timedelta): Intervalo de actualización.
138
- """
139
- self.api_key = entry_data["api_key"]
140
- self.town_name = entry_data["town_name"]
141
- self.town_id = entry_data["town_id"]
142
- self.station_name = entry_data["station_name"]
143
- self.station_id = entry_data["station_id"]
144
- self.variable_name = entry_data["variable_name"]
145
- self.variable_id = entry_data["variable_id"]
146
- self.meteocat_forecast = MeteocatForecast(self.api_key)
147
-
148
- super().__init__(
149
- hass,
150
- _LOGGER,
151
- name=f"{DOMAIN} Entity Coordinator",
152
- update_interval=update_interval,
153
- )
154
-
155
- async def _async_update_data(self) -> Dict:
156
- """Actualiza los datos de las entidades de predicción desde la API de Meteocat."""
157
- try:
158
- hourly_forecast = await self.meteocat_forecast.get_prediccion_horaria(self.town_id)
159
- daily_forecast = await self.meteocat_forecast.get_prediccion_diaria(self.town_id)
160
- _LOGGER.debug(
161
- "Datos de predicción actualizados exitosamente (Town ID: %s)", self.town_id
162
- )
163
- return {
164
- "hourly_forecast": hourly_forecast,
165
- "daily_forecast": daily_forecast,
166
- }
167
- except ForbiddenError as err:
168
- _LOGGER.error(
169
- "Acceso denegado al obtener datos de predicción (Town ID: %s): %s",
170
- self.town_id,
171
- err,
172
- )
173
- raise ConfigEntryNotReady from err
174
- except TooManyRequestsError as err:
175
- _LOGGER.warning(
176
- "Límite de solicitudes alcanzado al obtener datos de predicción (Town ID: %s): %s",
177
- self.town_id,
178
- err,
179
- )
180
- raise ConfigEntryNotReady from err
181
- except (BadRequestError, InternalServerError, UnknownAPIError) as err:
182
- _LOGGER.error(
183
- "Error al obtener datos de predicción (Town ID: %s): %s",
184
- self.town_id,
185
- err,
186
- )
187
- raise
188
- except Exception as err:
189
- _LOGGER.exception(
190
- "Error inesperado al obtener datos de predicción (Town ID: %s): %s",
191
- self.town_id,
192
- err,
193
- )
194
- raise
122
+ # class MeteocatEntityCoordinator(DataUpdateCoordinator):
123
+ # """Coordinator para manejar la actualización de datos de las entidades de predicción."""
124
+
125
+ # def __init__(
126
+ # self,
127
+ # hass: HomeAssistant,
128
+ # entry_data: dict,
129
+ # update_interval: timedelta = DEFAULT_ENTITY_UPDATE_INTERVAL,
130
+ # ):
131
+ # """
132
+ # Inicializa el coordinador de datos para entidades de predicción.
133
+
134
+ # Args:
135
+ # hass (HomeAssistant): Instancia de Home Assistant.
136
+ # entry_data (dict): Datos de configuración obtenidos de core.config_entries.
137
+ # update_interval (timedelta): Intervalo de actualización.
138
+ # """
139
+ # self.api_key = entry_data["api_key"]
140
+ # self.town_name = entry_data["town_name"]
141
+ # self.town_id = entry_data["town_id"]
142
+ # self.station_name = entry_data["station_name"]
143
+ # self.station_id = entry_data["station_id"]
144
+ # self.variable_name = entry_data["variable_name"]
145
+ # self.variable_id = entry_data["variable_id"]
146
+ # self.meteocat_forecast = MeteocatForecast(self.api_key)
147
+
148
+ # super().__init__(
149
+ # hass,
150
+ # _LOGGER,
151
+ # name=f"{DOMAIN} Entity Coordinator",
152
+ # update_interval=update_interval,
153
+ # )
154
+
155
+ # async def _async_update_data(self) -> Dict:
156
+ # """Actualiza los datos de las entidades de predicción desde la API de Meteocat."""
157
+ # try:
158
+ # hourly_forecast = await self.meteocat_forecast.get_prediccion_horaria(self.town_id)
159
+ # daily_forecast = await self.meteocat_forecast.get_prediccion_diaria(self.town_id)
160
+ # _LOGGER.debug(
161
+ # "Datos de predicción actualizados exitosamente (Town ID: %s)", self.town_id
162
+ # )
163
+ # return {
164
+ # "hourly_forecast": hourly_forecast,
165
+ # "daily_forecast": daily_forecast,
166
+ # }
167
+ # except ForbiddenError as err:
168
+ # _LOGGER.error(
169
+ # "Acceso denegado al obtener datos de predicción (Town ID: %s): %s",
170
+ # self.town_id,
171
+ # err,
172
+ # )
173
+ # raise ConfigEntryNotReady from err
174
+ # except TooManyRequestsError as err:
175
+ # _LOGGER.warning(
176
+ # "Límite de solicitudes alcanzado al obtener datos de predicción (Town ID: %s): %s",
177
+ # self.town_id,
178
+ # err,
179
+ # )
180
+ # raise ConfigEntryNotReady from err
181
+ # except (BadRequestError, InternalServerError, UnknownAPIError) as err:
182
+ # _LOGGER.error(
183
+ # "Error al obtener datos de predicción (Town ID: %s): %s",
184
+ # self.town_id,
185
+ # err,
186
+ # )
187
+ # raise
188
+ # except Exception as err:
189
+ # _LOGGER.exception(
190
+ # "Error inesperado al obtener datos de predicción (Town ID: %s): %s",
191
+ # self.town_id,
192
+ # err,
193
+ # )
194
+ # raise
@@ -1,98 +1,98 @@
1
- from __future__ import annotations
2
-
3
- import asyncio
4
- import logging
5
- from homeassistant.components.weather import WeatherEntity
6
- from homeassistant.const import (
7
- DEGREE,
8
- PERCENTAGE,
9
- UnitOfPressure,
10
- UnitOfSpeed,
11
- UnitOfTemperature,
12
- UnitOfVolumetricFlux,
13
- )
14
-
15
- from .const import (
16
- DOMAIN,
17
- CONF_API_KEY,
18
- TOWN_ID,
19
- TEMPERATURE,
20
- HUMIDITY,
21
- WIND_SPEED,
22
- WIND_DIRECTION,
23
- )
24
- from .condition import get_condition_from_statcel
25
- from .coordinator import MeteocatEntityCoordinator
26
-
27
-
28
- _LOGGER = logging.getLogger(__name__)
29
-
30
- async def async_setup_entry(hass, config_entry, async_add_entities):
31
- """Configura el componente weather basado en una entrada de configuración."""
32
- api_key = config_entry.data[CONF_API_KEY]
33
- town_id = config_entry.data[TOWN_ID]
34
-
35
- # Crear el coordinador
36
- coordinator = MeteocatEntityCoordinator(hass, api_key, town_id)
37
- # Asegurarse de que el coordinador esté actualizado antes de agregar la entidad
38
- await coordinator.async_refresh()
39
-
40
- async_add_entities([MeteocatWeatherEntity(coordinator)], True)
41
-
42
- class MeteocatWeatherEntity(WeatherEntity):
43
- """Entidad de clima para la integración Meteocat."""
44
-
45
- def __init__(self, coordinator: MeteocatEntityCoordinator):
46
- """Inicializa la entidad MeteocatWeather."""
47
- self._coordinator = coordinator
48
- self._attr_temperature_unit = UnitOfTemperature.CELSIUS
49
- self._data = {}
50
-
51
- async def async_update(self):
52
- """Actualiza los datos meteorológicos."""
53
- try:
54
- # Usamos el coordinador para obtener los datos actualizados
55
- if self._coordinator.data:
56
- hourly_forecast = self._coordinator.data["hourly_forecast"]
57
- current_forecast = hourly_forecast["variables"]
58
- codi_estatcel = current_forecast.get("estatCel", {}).get("valor")
59
- is_night = current_forecast.get("is_night", False)
60
- self._data = {
61
- "temperature": current_forecast.get(TEMPERATURE, {}).get("valor"),
62
- "humidity": current_forecast.get(HUMIDITY, {}).get("valor"),
63
- "wind_speed": current_forecast.get(WIND_SPEED, {}).get("valor"),
64
- "wind_bearing": current_forecast.get(WIND_DIRECTION, {}).get("valor"),
65
- "condition": get_condition_from_statcel(codi_estatcel, is_night)["condition"],
66
- }
67
- except Exception as err:
68
- _LOGGER.error("Error al actualizar la predicción de Meteocat: %s", err)
69
-
70
- @property
71
- def name(self):
72
- """Retorna el nombre de la entidad."""
73
- return f"Clima {self._coordinator._town_id}"
74
-
75
- @property
76
- def temperature(self):
77
- """Retorna la temperatura actual."""
78
- return self._data.get("temperature")
79
-
80
- @property
81
- def humidity(self):
82
- """Retorna la humedad relativa actual."""
83
- return self._data.get("humidity")
84
-
85
- @property
86
- def wind_speed(self):
87
- """Retorna la velocidad del viento."""
88
- return self._data.get("wind_speed")
89
-
90
- @property
91
- def wind_bearing(self):
92
- """Retorna la dirección del viento."""
93
- return self._data.get("wind_bearing")
94
-
95
- @property
96
- def condition(self):
97
- """Retorna la condición climática."""
98
- return self._data.get("condition")
1
+ # from __future__ import annotations
2
+
3
+ # import asyncio
4
+ # import logging
5
+ # from homeassistant.components.weather import WeatherEntity
6
+ # from homeassistant.const import (
7
+ # DEGREE,
8
+ # PERCENTAGE,
9
+ # UnitOfPressure,
10
+ # UnitOfSpeed,
11
+ # UnitOfTemperature,
12
+ # UnitOfVolumetricFlux,
13
+ # )
14
+
15
+ # from .const import (
16
+ # DOMAIN,
17
+ # CONF_API_KEY,
18
+ # TOWN_ID,
19
+ # TEMPERATURE,
20
+ # HUMIDITY,
21
+ # WIND_SPEED,
22
+ # WIND_DIRECTION,
23
+ # )
24
+ # from .condition import get_condition_from_statcel
25
+ # from .coordinator import MeteocatEntityCoordinator
26
+
27
+
28
+ # _LOGGER = logging.getLogger(__name__)
29
+
30
+ # async def async_setup_entry(hass, config_entry, async_add_entities):
31
+ # """Configura el componente weather basado en una entrada de configuración."""
32
+ # api_key = config_entry.data[CONF_API_KEY]
33
+ # town_id = config_entry.data[TOWN_ID]
34
+
35
+ # # Crear el coordinador
36
+ # coordinator = MeteocatEntityCoordinator(hass, api_key, town_id)
37
+ # # Asegurarse de que el coordinador esté actualizado antes de agregar la entidad
38
+ # await coordinator.async_refresh()
39
+
40
+ # async_add_entities([MeteocatWeatherEntity(coordinator)], True)
41
+
42
+ # class MeteocatWeatherEntity(WeatherEntity):
43
+ # """Entidad de clima para la integración Meteocat."""
44
+
45
+ # def __init__(self, coordinator: MeteocatEntityCoordinator):
46
+ # """Inicializa la entidad MeteocatWeather."""
47
+ # self._coordinator = coordinator
48
+ # self._attr_temperature_unit = UnitOfTemperature.CELSIUS
49
+ # self._data = {}
50
+
51
+ # async def async_update(self):
52
+ # """Actualiza los datos meteorológicos."""
53
+ # try:
54
+ # # Usamos el coordinador para obtener los datos actualizados
55
+ # if self._coordinator.data:
56
+ # hourly_forecast = self._coordinator.data["hourly_forecast"]
57
+ # current_forecast = hourly_forecast["variables"]
58
+ # codi_estatcel = current_forecast.get("estatCel", {}).get("valor")
59
+ # is_night = current_forecast.get("is_night", False)
60
+ # self._data = {
61
+ # "temperature": current_forecast.get(TEMPERATURE, {}).get("valor"),
62
+ # "humidity": current_forecast.get(HUMIDITY, {}).get("valor"),
63
+ # "wind_speed": current_forecast.get(WIND_SPEED, {}).get("valor"),
64
+ # "wind_bearing": current_forecast.get(WIND_DIRECTION, {}).get("valor"),
65
+ # "condition": get_condition_from_statcel(codi_estatcel, is_night)["condition"],
66
+ # }
67
+ # except Exception as err:
68
+ # _LOGGER.error("Error al actualizar la predicción de Meteocat: %s", err)
69
+
70
+ # @property
71
+ # def name(self):
72
+ # """Retorna el nombre de la entidad."""
73
+ # return f"Clima {self._coordinator._town_id}"
74
+
75
+ # @property
76
+ # def temperature(self):
77
+ # """Retorna la temperatura actual."""
78
+ # return self._data.get("temperature")
79
+
80
+ # @property
81
+ # def humidity(self):
82
+ # """Retorna la humedad relativa actual."""
83
+ # return self._data.get("humidity")
84
+
85
+ # @property
86
+ # def wind_speed(self):
87
+ # """Retorna la velocidad del viento."""
88
+ # return self._data.get("wind_speed")
89
+
90
+ # @property
91
+ # def wind_bearing(self):
92
+ # """Retorna la dirección del viento."""
93
+ # return self._data.get("wind_bearing")
94
+
95
+ # @property
96
+ # def condition(self):
97
+ # """Retorna la condición climática."""
98
+ # return self._data.get("condition")
@@ -7,6 +7,6 @@
7
7
  "iot_class": "cloud_polling",
8
8
  "documentation": "https://gitlab.com/figorr/meteocat",
9
9
  "loggers": ["meteocatpy"],
10
- "requirements": ["meteocatpy==0.0.8", "packaging>=20.3", "wrapt>=1.14.0"],
11
- "version": "0.1.26"
10
+ "requirements": ["meteocatpy==0.0.13", "packaging>=20.3", "wrapt>=1.14.0"],
11
+ "version": "0.1.28"
12
12
  }
@@ -319,7 +319,7 @@ class MeteocatSensor(CoordinatorEntity[MeteocatSensorCoordinator], SensorEntity)
319
319
  """Return the device info."""
320
320
  return DeviceInfo(
321
321
  identifiers={(DOMAIN, self._town_id)},
322
- name=self._town_name,
322
+ name="Meteocat " + self._station_id + " " + self._town_name,
323
323
  manufacturer="Meteocat",
324
324
  model="Meteocat API",
325
325
  )
@@ -1,2 +1,2 @@
1
1
  # version.py
2
- __version__ = "0.1.26"
2
+ __version__ = "0.1.28"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "meteocat",
3
- "version": "0.1.26",
3
+ "version": "0.1.28",
4
4
  "description": "[![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)\r [![Python version compatibility](https://img.shields.io/pypi/pyversions/meteocat)](https://pypi.org/project/meteocat)\r [![pipeline status](https://gitlab.com/figorr/meteocat/badges/master/pipeline.svg)](https://gitlab.com/figorr/meteocat/commits/master)",
5
5
  "main": "index.js",
6
6
  "directories": {