Skip to content

Commit

Permalink
Merge pull request #5 from gieljnssns/buienalarmdata
Browse files Browse the repository at this point in the history
Buienalarmdata
  • Loading branch information
gieljnssns authored Jun 15, 2020
2 parents 57eaa32 + d381914 commit 034e042
Show file tree
Hide file tree
Showing 6 changed files with 123 additions and 72 deletions.
4 changes: 4 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"python.linting.pylintEnabled": true,
"python.linting.enabled": true
}
10 changes: 6 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
# buienalarm-sensor-homeassistant

Buienalarm custom_component for Home-Assistant

```
```yaml
sensor:
- platform: buienalarm
timeframe: 15
Expand All @@ -15,6 +16,7 @@ sensor:
```
values for next_rain_forecast can be:
- -1 No rain forecast withing timeframe
- 0 It is currently raining
- N Rain is forecast within N minutes
- -1 No rain forecast withing timeframe
- 0 It is currently raining
- N Rain is forecast within N minutes
2 changes: 1 addition & 1 deletion custom_components/buienalarm/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
"""The buienalarm component."""
"""The buienalarm component."""
16 changes: 6 additions & 10 deletions custom_components/buienalarm/manifest.json
Original file line number Diff line number Diff line change
@@ -1,12 +1,8 @@
{
"domain": "buienalarm",
"name": "Buienalarm",
"documentation": "https://github.com/gieljnssns/buienalarm-sensor-homeassistant/tree/master",
"requirements": [
"pybuienalarm==0.0.4"
],
"dependencies": [],
"codeowners": [
"@gieljnssns"
]
"domain": "buienalarm",
"name": "Buienalarm",
"documentation": "https://github.com/gieljnssns/buienalarm-sensor-homeassistant/tree/master",
"requirements": ["pybuienalarm==0.0.5"],
"dependencies": [],
"codeowners": ["@gieljnssns"]
}
155 changes: 102 additions & 53 deletions custom_components/buienalarm/sensor.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,27 @@
"""Support for Buienalarm weather service."""
# import asyncio
# from datetime import datetime, timedelta
# import time
from datetime import timedelta

import logging
import json

# import async_timeout
from buienalarm.pybuienalarm import Buienalarm

import voluptuous as vol

from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (
ATTR_ATTRIBUTION, CONF_LATITUDE, CONF_LONGITUDE, CONF_MONITORED_CONDITIONS,
CONF_NAME, TEMP_CELSIUS)
# from homeassistant.helpers.aiohttp_client import async_get_clientsession
ATTR_ATTRIBUTION,
CONF_LATITUDE,
CONF_LONGITUDE,
CONF_MONITORED_CONDITIONS,
CONF_NAME,
TEMP_CELSIUS,
)
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import Entity
# from homeassistant.helpers.event import async_track_point_in_utc_time
# from homeassistant.util import dt as dt_util
from homeassistant.util import Throttle

MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=60)

_LOGGER = logging.getLogger(__name__)

Expand All @@ -25,38 +30,45 @@


SENSOR_TYPES = {
'temperature': ['Temperature', TEMP_CELSIUS, 'mdi:thermometer'],
'precipitation': ['Precipitation', 'mm/h', 'mdi:weather-pouring'],
'precipitation_forecast_average': ['Precipitation forecast average',
'mm/h', 'mdi:weather-pouring'],
'precipitation_forecast_total': ['Precipitation forecast total',
'mm', 'mdi:weather-pouring'],
'next_rain_forecast': ['Next rain forecast', 'minutes', 'mdi:weather-pouring']
"temperature": ["Temperature", TEMP_CELSIUS, "mdi:thermometer"],
"precipitation": ["Precipitation", "mm/h", "mdi:weather-pouring"],
"precipitation_forecast_average": [
"Precipitation forecast average",
"mm/h",
"mdi:weather-pouring",
],
"precipitation_forecast_total": [
"Precipitation forecast total",
"mm",
"mdi:weather-pouring",
],
"next_rain_forecast": ["Next rain forecast", "minutes", "mdi:weather-pouring"],
}

CONF_TIMEFRAME = 'timeframe'

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Optional(CONF_MONITORED_CONDITIONS,
default=['precipitation']): vol.All(
cv.ensure_list, vol.Length(min=1),
[vol.In(SENSOR_TYPES.keys())]),
vol.Inclusive(CONF_LATITUDE, 'coordinates',
'Latitude and longitude must exist together'): cv.latitude,
vol.Inclusive(CONF_LONGITUDE, 'coordinates',
'Latitude and longitude must exist together'): cv.longitude,
vol.Optional(CONF_TIMEFRAME, default=60):
vol.All(vol.Coerce(int), vol.Range(min=5, max=120)),
vol.Optional(CONF_NAME, default='ba'): cv.string,
})
CONF_TIMEFRAME = "timeframe"

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Optional(CONF_MONITORED_CONDITIONS, default=["precipitation"]): vol.All(
cv.ensure_list, vol.Length(min=1), [vol.In(SENSOR_TYPES.keys())]
),
vol.Inclusive(
CONF_LATITUDE, "coordinates", "Latitude and longitude must exist together"
): cv.latitude,
vol.Inclusive(
CONF_LONGITUDE, "coordinates", "Latitude and longitude must exist together"
): cv.longitude,
vol.Optional(CONF_TIMEFRAME, default=60): vol.All(
vol.Coerce(int), vol.Range(min=5, max=120)
),
vol.Optional(CONF_NAME, default="ba"): cv.string,
}
)


def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up Buienalarm."""

# import buienalarm
from buienalarm.pybuienalarm import Buienalarm

latitude = config.get(CONF_LATITUDE, hass.config.latitude)
longitude = config.get(CONF_LONGITUDE, hass.config.longitude)
timeframe = config.get(CONF_TIMEFRAME, DEFAULT_TIMEFRAME)
Expand All @@ -65,25 +77,25 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
_LOGGER.error("Latitude or longitude not set in HomeAssistant config")
return False

b = Buienalarm(lon=longitude, lat=latitude, timeframe=timeframe)

dev = []

data = BuienalarmData(longitude, latitude, timeframe)

for sensor in config[CONF_MONITORED_CONDITIONS]:
dev.append(BaSensor(b, sensor, timeframe, config.get(CONF_NAME)))
dev.append(BaSensor(data, sensor, config.get(CONF_NAME)))

add_entities(dev)


class BaSensor(Entity):
"""Representation of Buienalarm."""

def __init__(self, ba_data, sensor_type, timeframe, client_name):
def __init__(self, data, sensor_type, client_name):
"""Initialize the sensor."""
self.client_name = client_name
self._name = SENSOR_TYPES[sensor_type][0]
self.type = sensor_type
self.buienalarm = ba_data
self.ba_data = data
self._state = None
self._unit_of_measurement = SENSOR_TYPES[self.type][1]
self._icon = SENSOR_TYPES[self.type][2]
Expand All @@ -92,7 +104,7 @@ def __init__(self, ba_data, sensor_type, timeframe, client_name):
@property
def name(self):
"""Return the name of the sensor."""
return '{} {}'.format(self.client_name, self._name)
return "{} {}".format(self.client_name, self._name)

@property
def state(self):
Expand All @@ -110,26 +122,63 @@ def icon(self):
return self._icon

def update(self):
"""Update buienalarm data."""
if self.type == 'temperature':
self._state = self.buienalarm.get_temperature()
"""Update buienalarm."""
self.ba_data.update()
if self.type == "temperature":
self._state = self.ba_data.temperature

elif self.type == 'precipitation':
self._state = self.buienalarm.get_precipitation_now()
elif self.type == "precipitation":
self._state = self.ba_data.precipitation_now

elif self.type == 'precipitation_forecast_total':
self._state = self.buienalarm.get_precipitation_forecast_total()
elif self.type == "precipitation_forecast_total":
self._state = self.ba_data.precipitation_forecast_total

elif self.type == 'precipitation_forecast_average':
self._state = self.buienalarm.get_precipitation_forecast_average()
elif self.type == "precipitation_forecast_average":
self._state = self.ba_data.precipitation_forecast_average

elif self.type == 'next_rain_forecast':
p_forecast = json.loads(self.buienalarm.get_forecast())
elif self.type == "next_rain_forecast":
p_forecast = self.ba_data.forecast
print(p_forecast)
next_rain_minutes = -1
periods = 0
periods = -1
for precip in p_forecast:
periods += 1
if precip > 0:
next_rain_minutes = 5*periods
next_rain_minutes = 5 * periods
break
self._state = next_rain_minutes


class BuienalarmData:
"""The data from buienalarm."""

def __init__(self, longitude, latitude, timeframe):
"""Initialize the data object."""
self.longitude = longitude
self.latitude = latitude
self.timeframe = timeframe
self.buienalarm = None
self.temperature = None
self.precipitation_now = None
self.precipitation_forecast_total = None
self.precipitation_forecast_average = None
self.forecast = None
self.update()

@Throttle(MIN_TIME_BETWEEN_UPDATES)
def update(self):
"""Update inverter data."""
self.buienalarm = Buienalarm(
lon=self.longitude, lat=self.latitude, timeframe=self.timeframe
)
self.temperature = self.buienalarm.get_temperature()
self.precipitation_now = self.buienalarm.get_precipitation_now()
self.precipitation_forecast_total = (
self.buienalarm.get_precipitation_forecast_total()
)
self.precipitation_forecast_average = (
self.buienalarm.get_precipitation_forecast_average()
)
self.forecast = json.loads(self.buienalarm.get_forecast())

_LOGGER.debug(self.buienalarm)
8 changes: 4 additions & 4 deletions hacs.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"name": "Buienalarm",
"render_readme": true,
"domains": ["sensor"]
}
"name": "Buienalarm",
"render_readme": true,
"domains": ["sensor"]
}

0 comments on commit 034e042

Please sign in to comment.