Skip to content

Commit

Permalink
Merge pull request #41 from anand-p-r/develop
Browse files Browse the repository at this point in the history
Consolidate async_updates
  • Loading branch information
anand-p-r authored Jun 20, 2021
2 parents a215429 + dc8a743 commit a7ef02e
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 39 deletions.
13 changes: 7 additions & 6 deletions __init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -279,14 +279,14 @@ def update_lightning_strikes():
loc_time_list = sorted(loc_time_list, key=(lambda item: item[3])) ## distance
loop_end_time = datetime.now()
_LOGGER.debug(f"FMI - Coords retrieved for Lightning Data- {len(loc_time_list)}")

loc_time_list = loc_time_list[:LIGHTNING_LIMIT]

## Second Sort based on date
loc_time_list = sorted(loc_time_list, key=(lambda item: item[2]), reverse=True) ## date

geolocator = Nominatim(user_agent="fmi_hassio_sensor")

## Reverse geocoding
loop_start_time = datetime.now()
op_tuples = []
Expand All @@ -305,7 +305,6 @@ def update_lightning_strikes():
loop_end_time = datetime.now()
self.lightning_data = op_tuples
_LOGGER.debug(f"FMI: Lightning ended")
return

# Update mareo data
def update_mareo_data():
Expand Down Expand Up @@ -335,9 +334,11 @@ def update_mareo_data():
if root_mareo[n][0][2].text == 'SeaLevel':
tuple_to_add = (root_mareo[n][0][1].text, root_mareo[n][0][3].text)
sealevel_tuple_list.append(tuple_to_add)
elif root_mareo[n][0][2].text == 'SeaLevelN2000':
continue
else:
_LOGGER.debug("Sealevel forecast record mismatch - aborting query!")
break
_LOGGER.debug("Sealevel forecast unsupported record: %s", root_mareo[n][0][2].text)
continue
except:
_LOGGER.debug(f"Sealevel forecast records not in expected format for index - {n} of locstring - {loc_string}")

Expand All @@ -347,7 +348,7 @@ def update_mareo_data():
_LOGGER.debug("FMI: Mareo_data updated with data: %s %s", sealevel_tuple_list[0], sealevel_tuple_list[12])
else:
_LOGGER.debug("FMI: Mareo_data not updated. No data available!")

_LOGGER.debug(f"FMI: mareo ended")
return

Expand Down
2 changes: 1 addition & 1 deletion manifest.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"domain": "fmi",
"version": "0.4.4",
"version": "0.4.5",
"name": "Finnish Meteorological Institute",
"documentation": "https://www.home-assistant.io/integrations/fmi/",
"requirements": [
Expand Down
29 changes: 9 additions & 20 deletions sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,10 @@ def name(self):

return self._name

@property
def unique_id(self):
f"{self.coordinator.unique_id}_{self.name}"

@property
def state(self):
"""Return the state of the sensor."""
Expand Down Expand Up @@ -176,14 +180,10 @@ def device_state_attributes(self):

def update(self):
"""Get the latest data from FMI and updates the states."""

if self._fmi is None:
_LOGGER.debug("FMI: Coordinator is not available")
return

# Refresh data from API call.
self._fmi.async_request_refresh()

if self._fmi.current is None:
_LOGGER.debug("FMI: Sensor _FMI Current Forecast is unavailable")
return
Expand Down Expand Up @@ -278,7 +278,6 @@ def __init__(self, name, coordinator, sensor_type):

self.update()


@property
def name(self):
"""Return the name of the sensor."""
Expand Down Expand Up @@ -330,20 +329,16 @@ def device_state_attributes(self):
ATTR_STRIKES: strike.strikes,
ATTR_PEAK_CURRENT: strike.peak_current,
ATTR_CLOUD_COVER: strike.cloud_cover,
ATTR_ELLIPSE_MAJOR: strike.ellipse_major
ATTR_ELLIPSE_MAJOR: strike.ellipse_major,
}
for strike in self.lightning_data[1:]
],
ATTR_ATTRIBUTION: ATTRIBUTION
ATTR_ATTRIBUTION: ATTRIBUTION,
}


def update(self):
"""Get the latest data from FMI and updates the states."""

self._fmi.async_request_refresh()
self.lightning_data = self._fmi.lightning_data

try:
self._state = self.lightning_data[0].location
except:
Expand All @@ -352,6 +347,7 @@ def update(self):

return


class FMIMareoSensor(CoordinatorEntity):
"""Implementation of a FMI sea water level sensor."""

Expand All @@ -373,7 +369,6 @@ def __init__(self, name, coordinator, sensor_type):

self.update()


@property
def name(self):
"""Return the name of the sensor."""
Expand Down Expand Up @@ -423,20 +418,14 @@ def device_state_attributes(self):
return {
ATTR_TIME: mareo_data[0][0],
"FORECASTS": [
{
"time": item[0],
"height": item[1]
}
for item in mareo_data[1:]
{"time": item[0], "height": item[1]} for item in mareo_data[1:]
],
ATTR_ATTRIBUTION: ATTRIBUTION
ATTR_ATTRIBUTION: ATTRIBUTION,
}


def update(self):
"""Get the latest data from FMI and updates the states."""

self._fmi.async_request_refresh()
mareo_data = self._fmi.mareo_data.sea_levels

try:
Expand Down
26 changes: 14 additions & 12 deletions weather.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,11 @@ async def async_setup_entry(hass, config_entry, async_add_entities):

coordinator = hass.data[DOMAIN][config_entry.entry_id][COORDINATOR]

async_add_entities([FMIWeatherEntity(name, coordinator, daily_mode)], False)
entity_list = [FMIWeatherEntity(name, coordinator, False)]
if daily_mode:
entity_list.append(FMIWeatherEntity(f"{name} (daily)", coordinator, True))

async_add_entities(entity_list, False)


class FMIWeatherEntity(CoordinatorEntity, WeatherEntity):
Expand All @@ -51,16 +55,20 @@ def __init__(self, name, coordinator, daily_mode):
self._unit_system = "Metric"
self._fmi = coordinator
self._daily_mode = daily_mode
self._id = (
self.coordinator.unique_id
if not daily_mode
else f"{self.coordinator.unique_id}_daily"
)

@property
def name(self):
"""Return the name of the place based on Lat/Long."""
if self._fmi is None:
return self._name

if self._fmi.current is None:
if self._fmi is None or self._fmi.current is None:
return self._name

if self._daily_mode:
return f"{self._fmi.current.place} (daily)"
return self._fmi.current.place

@property
Expand All @@ -71,7 +79,7 @@ def attribution(self):
@property
def unique_id(self):
"""Return a unique_id for this entity."""
return self.coordinator.unique_id
return self._id

@property
def device_info(self):
Expand Down Expand Up @@ -164,9 +172,6 @@ def forecast(self):
_LOGGER.debug("FMI: Coordinator is not available!")
return None

# Get latest weather data from API call
self._fmi.async_request_refresh()

if self._fmi.forecast is None:
return None

Expand Down Expand Up @@ -205,11 +210,8 @@ def forecast(self):
ATTR_FORECAST_WIND_BEARING: forecast.wind_direction.value,
ATTR_WEATHER_PRESSURE: forecast.pressure.value,
ATTR_WEATHER_HUMIDITY: forecast.humidity.value,

}
for forecast in self._fmi.forecast.forecasts
]

#_LOGGER.debug("FMI: Forecast data: %s", data)

return data

0 comments on commit a7ef02e

Please sign in to comment.