8000 Use voluptuous for BloomSky by fabaff · Pull Request #3096 · home-assistant/core · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

Use voluptuous for BloomSky #3096

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 2, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 22 additions & 16 deletions homeassistant/components/binary_sensor/bloomsky.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,32 +6,38 @@
"""
import logging

from homeassistant.components.binary_sensor import BinarySensorDevice
import voluptuous as vol

from homeassistant.components.binary_sensor import (
BinarySensorDevice, PLATFORM_SCHEMA)
from homeassistant.const import CONF_MONITORED_CONDITIONS
from homeassistant.loader import get_component
import homeassistant.helpers.config_validation as cv

_LOGGER = logging.getLogger(__name__)

DEPENDENCIES = ["bloomsky"]
DEPENDENCIES = ['bloomsky']

# These are the available sensors mapped to binary_sensor class
SENSOR_TYPES = {
"Rain": "moisture",
"Night": None,
'Rain': 'moisture',
'Night': None,
}

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Optional(CONF_MONITORED_CONDITIONS, default=SENSOR_TYPES):
vol.All(cv.ensure_list, [vol.In(SENSOR_TYPES)]),
})


def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the available BloomSky weather binary sensors."""
logger = logging.getLogger(__name__)
bloomsky = get_component('bloomsky')
sensors = config.get('monitored_conditions', SENSOR_TYPES)
sensors = config.get(CONF_MONITORED_CONDITIONS)

for device in bloomsky.BLOOMSKY.devices.values():
for variable in sensors:
if variable in SENSOR_TYPES:
add_devices([BloomSkySensor(bloomsky.BLOOMSKY,
device,
variable)])
else:
logger.error("Cannot find definition for device: %s", variable)
add_devices([BloomSkySensor(bloomsky.BLOOMSKY, device, variable)])


class BloomSkySensor(BinarySensorDevice):
Expand All @@ -40,10 +46,10 @@ class BloomSkySensor(BinarySensorDevice):
def __init__(self, bs, device, sensor_name):
"""Initialize a BloomSky binary sensor."""
self._bloomsky = bs
self._device_id = device["DeviceID"]
self._device_id = device['DeviceID']
self._sensor_name = sensor_name
self._name = "{} {}".format(device["DeviceName"], sensor_name)
self._unique_id = "bloomsky_binary_sensor {}".format(self._name)
self._name = '{} {}'.format(device['DeviceName'], sensor_name)
self._unique_id = 'bloomsky_binary_sensor {}'.format(self._name)
self.update()

@property
Expand Down Expand Up @@ -71,4 +77,4 @@ def update(self):
self._bloomsky.refresh_devices()

self._state = \
self._bloomsky.devices[self._device_id]["Data"][self._sensor_name]
self._bloomsky.devices[self._device_id]['Data'][self._sensor_name]
32 changes: 18 additions & 14 deletions homeassistant/components/bloomsky.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,30 +8,34 @@
from datetime import timedelta

import requests
import voluptuous as vol

from homeassistant.const import CONF_API_KEY
from homeassistant.helpers import validate_config, discovery
from homeassistant.helpers import discovery
from homeassistant.util import Throttle
import homeassistant.helpers.config_validation as cv

_LOGGER = logging.getLogger(__name__)

DOMAIN = "bloomsky"
BLOOMSKY = None
BLOOMSKY_TYPE = ['camera', 'binary_sensor', 'sensor']

_LOGGER = logging.getLogger(__name__)
DOMAIN = 'bloomsky'

# The BloomSky only updates every 5-8 minutes as per the API spec so there's
# no point in polling the API more frequently
MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=300)

CONFIG_SCHEMA = vol.Schema({
DOMAIN: vol.Schema({
vol.Required(CONF_API_KEY): cv.string,
}),
}, extra=vol.ALLOW_EXTRA)


# pylint: disable=unused-argument,too-few-public-methods
def setup(hass, config):
"""Setup BloomSky component."""
if not validate_config(
config,
{DOMAIN: [CONF_API_KEY]},
_LOGGER):
return False

api_key = config[DOMAIN][CONF_API_KEY]

global BLOOMSKY
Expand All @@ -40,7 +44,7 @@ def setup(hass, config):
except RuntimeError:
return False

for component in 'camera', 'binary_sensor', 'sensor':
for component in BLOOMSKY_TYPE:
discovery.load_platform(hass, component, DOMAIN, {}, config)

return True
Expand All @@ -50,19 +54,19 @@ class BloomSky(object):
"""Handle all communication with the BloomSky API."""

# API documentation at http://weatherlution.com/bloomsky-api/
API_URL = "https://api.bloomsky.com/api/skydata"
API_URL = 'https://api.bloomsky.com/api/skydata'

def __init__(self, api_key):
"""Initialize the BookSky."""
self._api_key = api_key
self.devices = {}
_LOGGER.debug("Initial bloomsky device load...")
_LOGGER.debug("Initial BloomSky device load...")
self.refresh_devices()

@Throttle(MIN_TIME_BETWEEN_UPDATES)
def refresh_devices(self):
"""Use the API to retreive a list of devices."""
_LOGGER.debug("Fetching bloomsky update")
_LOGGER.debug("Fetching BloomSky update")
response = requests.get(self.API_URL,
headers={"Authorization": self._api_key},
timeout=10)
Expand All @@ -73,5 +77,5 @@ def refresh_devices(self):
return
# Create dictionary keyed off of the device unique id
self.devices.update({
device["DeviceID"]: device for device in response.json()
device['DeviceID']: device for device in response.json()
})
61 changes: 33 additions & 28 deletions homeassistant/components/sensor/bloomsky.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,58 +6,63 @@
"""
import logging

from homeassistant.const import TEMP_FAHRENHEIT
import voluptuous as vol

from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (TEMP_FAHRENHEIT, CONF_MONITORED_CONDITIONS)
from homeassistant.helpers.entity import Entity
from homeassistant.loader import get_component
import homeassistant.helpers.config_validation as cv

_LOGGER = logging.getLogger(__name__)

DEPENDENCIES = ["bloomsky"]
DEPENDENCIES = ['bloomsky']

# These are the available sensors
SENSOR_TYPES = ["Temperature",
"Humidity",
"Pressure",
"Luminance",
"UVIndex",
"Voltage"]
SENSOR_TYPES = ['Temperature',
'Humidity',
'Pressure',
'Luminance',
'UVIndex',
'Voltage']

# Sensor units - these do not currently align with the API documentation
SENSOR_UNITS = {"Temperature": TEMP_FAHRENHEIT,
"Humidity": "%",
"Pressure": "inHg",
"Luminance": "cd/m²",
"Voltage": "mV"}
SENSOR_UNITS = {'Temperature': TEMP_FAHRENHEIT,
'Humidity': '%',
'Pressure': 'inHg',
'Luminance': 'cd/m²',
'Voltage': 'mV'}

# Which sensors to format numerically
FORMAT_NUMBERS = ["Temperature", "Pressure", "Voltage"]
FORMAT_NUMBERS = ['Temperature', 'Pressure', 'Voltage']

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Optional(CONF_MONITORED_CONDITIONS, default=SENSOR_TYPES):
vol.All(cv.ensure_list, [vol.In(SENSOR_TYPES)]),
})


# pylint: disable=unused-argument
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the available BloomSky weather sensors."""
logger = logging.getLogger(__name__)
bloomsky = get_component('bloomsky')
sensors = config.get('monitored_conditions', SENSOR_TYPES)
sensors = config.get(CONF_MONITORED_CONDITIONS)

for device in bloomsky.BLOOMSKY.devices.values():
for variable in sensors:
if variable in SENSOR_TYPES:
add_devices([BloomSkySensor(bloomsky.BLOOMSKY,
device,
variable)])
else:
logger.error("Cannot find definition for device: %s", variable)
add_devices([BloomSkySensor(bloomsky.BLOOMSKY, device, variable)])


class BloomSkySensor(Entity):
"""Representation of a single sensor in a BloomSky device."""

def __init__(self, bs, device, sensor_name):
"""Initialize a bloomsky sensor."""
"""Initialize a BloomSky sensor."""
self._bloomsky = bs
self._device_id = device["DeviceID"]
self._device_id = device['DeviceID']
self._sensor_name = sensor_name
self._name = "{} {}".format(device["DeviceName"], sensor_name)
self._unique_id = "bloomsky_sensor {}".format(self._name)
self._name = '{} {}'.format(device['DeviceName'], sensor_name)
self._unique_id = 'bloomsky_sensor {}'.format(self._name)
self.update()

@property
Expand Down Expand Up @@ -85,9 +90,9 @@ def update(self):
self._bloomsky.refresh_devices()

state = \
self._bloomsky.devices[self._device_id]["Data"][self._sensor_name]
self._bloomsky.devices[self._device_id]['Data'][self._sensor_name]

if self._sensor_name in FORMAT_NUMBERS:
self._state = "{0:.2f}".format(state)
self._state = '{0:.2f}'.format(state)
else:
self._state = state
0