meteocat 2.2.3 → 2.2.5

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,21 @@
1
+ ## [2.2.5](https://github.com/figorr/meteocat/compare/v2.2.4...v2.2.5) (2025-02-16)
2
+
3
+
4
+ ### Bug Fixes
5
+
6
+ * 2.2.5 ([cd8fb52](https://github.com/figorr/meteocat/commit/cd8fb52c607e3a74308246136b6ac2d47b51e125))
7
+ * fix lightning status sensor native value ([dc3badc](https://github.com/figorr/meteocat/commit/dc3badc7b66d9afbcc14e23da3f0909f845cef2f))
8
+ * fix validity at lightning coordinator and cached data ([d959bc5](https://github.com/figorr/meteocat/commit/d959bc56dfb19a475b2e34a2649bbabd803ab41e))
9
+ * new lighting validity hour ([eab0215](https://github.com/figorr/meteocat/commit/eab0215cc3d68de9f900a4ecf1844ef3c6c22610))
10
+
11
+ ## [2.2.4](https://github.com/figorr/meteocat/compare/v2.2.3...v2.2.4) (2025-02-09)
12
+
13
+
14
+ ### Bug Fixes
15
+
16
+ * 2.2.4 ([59183ea](https://github.com/figorr/meteocat/commit/59183ea082f6d963e46d3f8a51e0867b3f32060d))
17
+ * fix valid lightning data for download from API ([4e4a8ae](https://github.com/figorr/meteocat/commit/4e4a8ae110b72b6e6ff560921f88ea7fb4640a29))
18
+
1
19
  ## [2.2.3](https://github.com/figorr/meteocat/compare/v2.2.2...v2.2.3) (2025-02-08)
2
20
 
3
21
 
@@ -33,7 +33,7 @@ from .const import DOMAIN, PLATFORMS
33
33
  _LOGGER = logging.getLogger(__name__)
34
34
 
35
35
  # Versión
36
- __version__ = "2.2.3"
36
+ __version__ = "2.2.5"
37
37
 
38
38
  # Definir el esquema de configuración CONFIG_SCHEMA
39
39
  CONFIG_SCHEMA = vol.Schema(
@@ -56,6 +56,8 @@ DEFAULT_VALIDITY_MINUTES = 0 # Minutos a partir de los cuales la API tiene la i
56
56
  DEFAULT_ALERT_VALIDITY_TIME = 120 # Minutos a partir de los cuales las alertas están obsoletas y se se debe proceder a una nueva llamada a la API
57
57
  DEFAULT_QUOTES_VALIDITY_TIME = 240 # Minutos a partir de los cuales los datos de cuotas están obsoletos y se se debe proceder a una nueva llamada a la API
58
58
  DEFAULT_LIGHTNING_VALIDITY_TIME = 240 # Minutos a partir de los cuales los datos de rayos están obsoletos y se se debe proceder a una nueva llamada a la API
59
+ DEFAULT_LIGHTNING_VALIDITY_HOURS = 1 # Hora a partir de la cual la API tiene la información actualizada de rayos disponible para descarga
60
+ DEFAULT_LIGHTNING_VALIDITY_MINUTES = 0 # Minutos a partir de los cuales la API tiene la información actualizada de rayos disponible para descarga
59
61
 
60
62
  # Multiplicadores para la duración de validez basada en limit_prediccio
61
63
  ALERT_VALIDITY_MULTIPLIER_100 = 12 # para limit_prediccio <= 100
@@ -43,7 +43,9 @@ from .const import (
43
43
  ALERT_VALIDITY_MULTIPLIER_200,
44
44
  ALERT_VALIDITY_MULTIPLIER_500,
45
45
  ALERT_VALIDITY_MULTIPLIER_DEFAULT,
46
- DEFAULT_LIGHTNING_VALIDITY_TIME
46
+ DEFAULT_LIGHTNING_VALIDITY_TIME,
47
+ DEFAULT_LIGHTNING_VALIDITY_HOURS,
48
+ DEFAULT_LIGHTNING_VALIDITY_MINUTES
47
49
  )
48
50
 
49
51
  _LOGGER = logging.getLogger(__name__)
@@ -1332,7 +1334,7 @@ class MeteocatAlertsCoordinator(DataUpdateCoordinator):
1332
1334
  "Usando datos en caché para las alertas. Última actualización: %s",
1333
1335
  cached_data["actualitzat"]["dataUpdate"],
1334
1336
  )
1335
- return cached_data
1337
+ return {"actualizado": cached_data['actualitzat']['dataUpdate']}
1336
1338
 
1337
1339
  # Si no se puede actualizar ni cargar datos en caché, retornar None
1338
1340
  _LOGGER.error("No se pudo obtener datos actualizados ni cargar datos en caché de alertas.")
@@ -1781,7 +1783,7 @@ class MeteocatQuotesCoordinator(DataUpdateCoordinator):
1781
1783
  cached_data = await load_json_from_file(self.quotes_file)
1782
1784
  if cached_data:
1783
1785
  _LOGGER.warning("Usando datos en caché para las cuotas de la API de Meteocat.")
1784
- return cached_data
1786
+ return {"actualizado": cached_data['actualitzat']['dataUpdate']}
1785
1787
 
1786
1788
  _LOGGER.error("No se pudo obtener datos actualizados ni cargar datos en caché.")
1787
1789
  return None
@@ -1908,15 +1910,21 @@ class MeteocatLightningCoordinator(DataUpdateCoordinator):
1908
1910
  existing_data = await load_json_from_file(self.lightning_file) or {}
1909
1911
 
1910
1912
  # Definir la duración de validez de los datos
1913
+ now = datetime.now(timezone.utc).astimezone(TIMEZONE)
1914
+ current_time = now.time() # Extraer solo la parte de la hora
1915
+ offset = now.utcoffset().total_seconds() / 3600 # Obtener el offset en horas
1916
+
1917
+ # Determinar la hora de validez considerando el offset horario, el horario de verano (+02:00) o invierno (+01:00)
1918
+ validity_start_time = time(int(DEFAULT_LIGHTNING_VALIDITY_HOURS + offset), DEFAULT_LIGHTNING_VALIDITY_MINUTES)
1919
+
1911
1920
  validity_duration = timedelta(minutes=DEFAULT_LIGHTNING_VALIDITY_TIME)
1912
1921
 
1913
1922
  if not existing_data:
1914
1923
  return await self._fetch_and_save_new_data()
1915
1924
  else:
1916
1925
  last_update = datetime.fromisoformat(existing_data['actualitzat']['dataUpdate'])
1917
- now = datetime.now(timezone.utc).astimezone(TIMEZONE)
1918
1926
 
1919
- if now - last_update >= validity_duration:
1927
+ if now - last_update >= validity_duration and current_time >= validity_start_time:
1920
1928
  return await self._fetch_and_save_new_data()
1921
1929
  else:
1922
1930
  _LOGGER.debug("Usando datos existentes de rayos: %s", existing_data)
@@ -1963,7 +1971,7 @@ class MeteocatLightningCoordinator(DataUpdateCoordinator):
1963
1971
  cached_data = await load_json_from_file(self.lightning_file)
1964
1972
  if cached_data:
1965
1973
  _LOGGER.warning("Usando datos en caché para los datos de rayos de la API de Meteocat.")
1966
- return cached_data
1974
+ return {"actualizado": cached_data['actualitzat']['dataUpdate']}
1967
1975
 
1968
1976
  _LOGGER.error("No se pudo obtener datos actualizados ni cargar datos en caché.")
1969
1977
  return None
@@ -2008,20 +2016,20 @@ class MeteocatLightningFileCoordinator(DataUpdateCoordinator):
2008
2016
  if not existing_data:
2009
2017
  _LOGGER.warning("No se encontraron datos en %s.", self.lightning_file)
2010
2018
  return {
2011
- "actualizado": datetime.now(ZoneInfo("Europe/Madrid")).isoformat(),
2019
+ "actualizado": datetime.now(TIMEZONE).isoformat(),
2012
2020
  "region": self._reset_data(),
2013
2021
  "town": self._reset_data()
2014
2022
  }
2015
2023
 
2016
2024
  # Convertir la cadena de fecha a un objeto datetime y ajustar a la zona horaria local
2017
2025
  update_date = datetime.fromisoformat(existing_data.get("actualitzat", {}).get("dataUpdate", ""))
2018
- update_date = update_date.astimezone(ZoneInfo("Europe/Madrid"))
2019
- now = datetime.now(ZoneInfo("Europe/Madrid"))
2026
+ update_date = update_date.astimezone(TIMEZONE)
2027
+ now = datetime.now(TIMEZONE)
2020
2028
 
2021
2029
  if update_date.date() != now.date(): # Si la fecha no es la de hoy
2022
2030
  _LOGGER.info("Los datos de rayos son de un día diferente. Reiniciando valores a cero.")
2023
2031
  region_data = town_data = self._reset_data()
2024
- update_date = datetime.now(ZoneInfo("Europe/Madrid")).isoformat() # Usar la fecha actual
2032
+ update_date = datetime.now(TIMEZONE).isoformat() # Usar la fecha actual
2025
2033
  else:
2026
2034
  region_data = self._process_region_data(existing_data.get("dades", []))
2027
2035
  town_data = self._process_town_data(existing_data.get("dades", []))
@@ -9,5 +9,5 @@
9
9
  "issue_tracker": "https://github.com/figorr/meteocat/issues",
10
10
  "loggers": ["meteocatpy"],
11
11
  "requirements": ["meteocatpy==1.0.1", "packaging>=20.3", "wrapt>=1.14.0"],
12
- "version": "2.2.3"
12
+ "version": "2.2.5"
13
13
  }
@@ -103,6 +103,8 @@ from .const import (
103
103
  ALERT_VALIDITY_MULTIPLIER_500,
104
104
  ALERT_VALIDITY_MULTIPLIER_DEFAULT,
105
105
  DEFAULT_LIGHTNING_VALIDITY_TIME,
106
+ DEFAULT_LIGHTNING_VALIDITY_HOURS,
107
+ DEFAULT_LIGHTNING_VALIDITY_MINUTES,
106
108
  )
107
109
 
108
110
  from .coordinator import (
@@ -1687,29 +1689,40 @@ class MeteocatLightningStatusSensor(CoordinatorEntity[MeteocatLightningCoordinat
1687
1689
  self._attr_entity_category = getattr(description, "entity_category", None)
1688
1690
 
1689
1691
  def _get_data_update(self):
1690
- """Obtiene la fecha de actualización directamente desde el coordinador."""
1692
+ """Obtiene la fecha de actualización directamente desde el coordinador y la convierte a UTC."""
1691
1693
  data_update = self.coordinator.data.get("actualizado")
1692
1694
  if data_update:
1693
1695
  try:
1694
- return datetime.fromisoformat(data_update.rstrip("Z"))
1696
+ local_time = datetime.fromisoformat(data_update) # Ya tiene offset (+01:00 o +02:00)
1697
+ return local_time.astimezone(ZoneInfo("UTC")) # Convertir a UTC
1695
1698
  except ValueError:
1696
1699
  _LOGGER.error("Formato de fecha de actualización inválido: %s", data_update)
1697
1700
  return None
1701
+
1702
+ def _determine_status(self, now, data_update, current_time, validity_start_time, validity_duration):
1703
+ """Determina el estado basado en la fecha de actualización."""
1704
+ if now - data_update > timedelta(days=1):
1705
+ return "obsolete"
1706
+ elif now - data_update < validity_duration or current_time < validity_start_time:
1707
+ return "updated"
1708
+ return "obsolete"
1698
1709
 
1699
1710
  @property
1700
1711
  def native_value(self):
1701
- """Devuelve el estado actual de las alertas basado en la fecha de actualización."""
1712
+ """Devuelve el estado del archivo de rayos basado en la fecha de actualización."""
1702
1713
  data_update = self._get_data_update()
1703
1714
  if not data_update:
1704
1715
  return "unknown"
1705
1716
 
1706
- current_time = datetime.now(ZoneInfo("UTC"))
1717
+ now = datetime.now(timezone.utc).astimezone(TIMEZONE)
1718
+ current_time = now.time() # Extraer solo la parte de la hora
1719
+ offset = now.utcoffset().total_seconds() / 3600 # Obtener el offset en horas
1707
1720
 
1708
- # Comprobar si el archivo de alertas está obsoleto
1709
- if current_time - data_update >= timedelta(minutes=DEFAULT_LIGHTNING_VALIDITY_TIME):
1710
- return "obsolete"
1721
+ # Determinar la hora de validez considerando el offset horario, el horario de verano (+02:00) o invierno (+01:00)
1722
+ validity_start_time = time(int(DEFAULT_LIGHTNING_VALIDITY_HOURS + offset), DEFAULT_LIGHTNING_VALIDITY_MINUTES)
1723
+ validity_duration = timedelta(minutes=DEFAULT_LIGHTNING_VALIDITY_TIME)
1711
1724
 
1712
- return "updated"
1725
+ return self._determine_status(now, data_update, current_time, validity_start_time, validity_duration)
1713
1726
 
1714
1727
  @property
1715
1728
  def extra_state_attributes(self):
@@ -1,2 +1,2 @@
1
1
  # version.py
2
- __version__ = "2.2.3"
2
+ __version__ = "2.2.5"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "meteocat",
3
- "version": "2.2.3",
3
+ "version": "2.2.5",
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": {
package/pyproject.toml CHANGED
@@ -1,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "meteocat"
3
- version = "2.2.3"
3
+ version = "2.2.5"
4
4
  description = "Script para obtener datos meteorológicos de la API de Meteocat"
5
5
  authors = ["figorr <jdcuartero@yahoo.es>"]
6
6
  license = "Apache-2.0"