1
0
mirror of https://github.com/home-assistant/core.git synced 2025-12-24 21:06:19 +00:00
This commit is contained in:
Paulus Schoutsen
2019-07-31 12:25:30 -07:00
parent da05dfe708
commit 4de97abc3a
2676 changed files with 163166 additions and 140084 deletions

View File

@@ -5,33 +5,66 @@ from aiohttp import web
from homeassistant import core
from homeassistant.components import (
climate, cover, fan, light, media_player, scene, script)
climate,
cover,
fan,
light,
media_player,
scene,
script,
)
from homeassistant.components.climate.const import (
SERVICE_SET_TEMPERATURE, SUPPORT_TARGET_TEMPERATURE)
SERVICE_SET_TEMPERATURE,
SUPPORT_TARGET_TEMPERATURE,
)
from homeassistant.components.cover import (
ATTR_CURRENT_POSITION, ATTR_POSITION, SERVICE_SET_COVER_POSITION,
SUPPORT_SET_POSITION)
ATTR_CURRENT_POSITION,
ATTR_POSITION,
SERVICE_SET_COVER_POSITION,
SUPPORT_SET_POSITION,
)
from homeassistant.components.fan import (
ATTR_SPEED, SPEED_HIGH, SPEED_LOW, SPEED_MEDIUM, SPEED_OFF,
SUPPORT_SET_SPEED)
ATTR_SPEED,
SPEED_HIGH,
SPEED_LOW,
SPEED_MEDIUM,
SPEED_OFF,
SUPPORT_SET_SPEED,
)
from homeassistant.components.http import HomeAssistantView
from homeassistant.components.http.const import KEY_REAL_IP
from homeassistant.components.light import (
ATTR_BRIGHTNESS, ATTR_HS_COLOR, SUPPORT_BRIGHTNESS, SUPPORT_COLOR)
ATTR_BRIGHTNESS,
ATTR_HS_COLOR,
SUPPORT_BRIGHTNESS,
SUPPORT_COLOR,
)
from homeassistant.components.media_player.const import (
ATTR_MEDIA_VOLUME_LEVEL, SUPPORT_VOLUME_SET)
ATTR_MEDIA_VOLUME_LEVEL,
SUPPORT_VOLUME_SET,
)
from homeassistant.const import (
ATTR_ENTITY_ID, ATTR_SUPPORTED_FEATURES, ATTR_TEMPERATURE,
HTTP_BAD_REQUEST, HTTP_NOT_FOUND, SERVICE_CLOSE_COVER, SERVICE_OPEN_COVER,
SERVICE_TURN_OFF, SERVICE_TURN_ON, SERVICE_VOLUME_SET, STATE_OFF, STATE_ON)
ATTR_ENTITY_ID,
ATTR_SUPPORTED_FEATURES,
ATTR_TEMPERATURE,
HTTP_BAD_REQUEST,
HTTP_NOT_FOUND,
SERVICE_CLOSE_COVER,
SERVICE_OPEN_COVER,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
SERVICE_VOLUME_SET,
STATE_OFF,
STATE_ON,
)
from homeassistant.util.network import is_local
_LOGGER = logging.getLogger(__name__)
HUE_API_STATE_ON = 'on'
HUE_API_STATE_BRI = 'bri'
HUE_API_STATE_HUE = 'hue'
HUE_API_STATE_SAT = 'sat'
HUE_API_STATE_ON = "on"
HUE_API_STATE_BRI = "bri"
HUE_API_STATE_HUE = "hue"
HUE_API_STATE_SAT = "sat"
HUE_API_STATE_HUE_MAX = 65535.0
HUE_API_STATE_SAT_MAX = 254.0
@@ -45,9 +78,9 @@ STATE_SATURATION = HUE_API_STATE_SAT
class HueUsernameView(HomeAssistantView):
"""Handle requests to create a username for the emulated hue bridge."""
url = '/api'
name = 'emulated_hue:api:create_username'
extra_urls = ['/api/']
url = "/api"
name = "emulated_hue:api:create_username"
extra_urls = ["/api/"]
requires_auth = False
async def post(self, request):
@@ -55,24 +88,22 @@ class HueUsernameView(HomeAssistantView):
try:
data = await request.json()
except ValueError:
return self.json_message('Invalid JSON', HTTP_BAD_REQUEST)
return self.json_message("Invalid JSON", HTTP_BAD_REQUEST)
if 'devicetype' not in data:
return self.json_message('devicetype not specified',
HTTP_BAD_REQUEST)
if "devicetype" not in data:
return self.json_message("devicetype not specified", HTTP_BAD_REQUEST)
if not is_local(request[KEY_REAL_IP]):
return self.json_message('only local IPs allowed',
HTTP_BAD_REQUEST)
return self.json_message("only local IPs allowed", HTTP_BAD_REQUEST)
return self.json([{'success': {'username': '12345678901234567890'}}])
return self.json([{"success": {"username": "12345678901234567890"}}])
class HueAllGroupsStateView(HomeAssistantView):
"""Group handler."""
url = '/api/{username}/groups'
name = 'emulated_hue:all_groups:state'
url = "/api/{username}/groups"
name = "emulated_hue:all_groups:state"
requires_auth = False
def __init__(self, config):
@@ -83,18 +114,16 @@ class HueAllGroupsStateView(HomeAssistantView):
def get(self, request, username):
"""Process a request to make the Brilliant Lightpad work."""
if not is_local(request[KEY_REAL_IP]):
return self.json_message('only local IPs allowed',
HTTP_BAD_REQUEST)
return self.json_message("only local IPs allowed", HTTP_BAD_REQUEST)
return self.json({
})
return self.json({})
class HueGroupView(HomeAssistantView):
"""Group handler to get Logitech Pop working."""
url = '/api/{username}/groups/0/action'
name = 'emulated_hue:groups:state'
url = "/api/{username}/groups/0/action"
name = "emulated_hue:groups:state"
requires_auth = False
def __init__(self, config):
@@ -105,23 +134,26 @@ class HueGroupView(HomeAssistantView):
def put(self, request, username):
"""Process a request to make the Logitech Pop working."""
if not is_local(request[KEY_REAL_IP]):
return self.json_message('only local IPs allowed',
HTTP_BAD_REQUEST)
return self.json_message("only local IPs allowed", HTTP_BAD_REQUEST)
return self.json([{
'error': {
'address': '/groups/0/action/scene',
'type': 7,
'description': 'invalid value, dummy for parameter, scene'
}
}])
return self.json(
[
{
"error": {
"address": "/groups/0/action/scene",
"type": 7,
"description": "invalid value, dummy for parameter, scene",
}
}
]
)
class HueAllLightsStateView(HomeAssistantView):
"""Handle requests for getting and setting info about entities."""
url = '/api/{username}/lights'
name = 'emulated_hue:lights:state'
url = "/api/{username}/lights"
name = "emulated_hue:lights:state"
requires_auth = False
def __init__(self, config):
@@ -132,10 +164,9 @@ class HueAllLightsStateView(HomeAssistantView):
def get(self, request, username):
"""Process a request to get the list of available lights."""
if not is_local(request[KEY_REAL_IP]):
return self.json_message('only local IPs allowed',
HTTP_BAD_REQUEST)
return self.json_message("only local IPs allowed", HTTP_BAD_REQUEST)
hass = request.app['hass']
hass = request.app["hass"]
json_response = {}
for entity in hass.states.async_all():
@@ -143,8 +174,7 @@ class HueAllLightsStateView(HomeAssistantView):
state = get_entity_state(self.config, entity)
number = self.config.entity_id_to_number(entity.entity_id)
json_response[number] = entity_to_json(self.config,
entity, state)
json_response[number] = entity_to_json(self.config, entity, state)
return self.json(json_response)
@@ -152,8 +182,8 @@ class HueAllLightsStateView(HomeAssistantView):
class HueOneLightStateView(HomeAssistantView):
"""Handle requests for getting and setting info about entities."""
url = '/api/{username}/lights/{entity_id}'
name = 'emulated_hue:light:state'
url = "/api/{username}/lights/{entity_id}"
name = "emulated_hue:light:state"
requires_auth = False
def __init__(self, config):
@@ -164,19 +194,18 @@ class HueOneLightStateView(HomeAssistantView):
def get(self, request, username, entity_id):
"""Process a request to get the state of an individual light."""
if not is_local(request[KEY_REAL_IP]):
return self.json_message('only local IPs allowed',
HTTP_BAD_REQUEST)
return self.json_message("only local IPs allowed", HTTP_BAD_REQUEST)
hass = request.app['hass']
hass = request.app["hass"]
entity_id = self.config.number_to_entity_id(entity_id)
entity = hass.states.get(entity_id)
if entity is None:
_LOGGER.error('Entity not found: %s', entity_id)
_LOGGER.error("Entity not found: %s", entity_id)
return web.Response(text="Entity not found", status=404)
if not self.config.is_entity_exposed(entity):
_LOGGER.error('Entity not exposed: %s', entity_id)
_LOGGER.error("Entity not exposed: %s", entity_id)
return web.Response(text="Entity not exposed", status=404)
state = get_entity_state(self.config, entity)
@@ -189,8 +218,8 @@ class HueOneLightStateView(HomeAssistantView):
class HueOneLightChangeView(HomeAssistantView):
"""Handle requests for getting and setting info about entities."""
url = '/api/{username}/lights/{entity_number}/state'
name = 'emulated_hue:light:state'
url = "/api/{username}/lights/{entity_number}/state"
name = "emulated_hue:light:state"
requires_auth = False
def __init__(self, config):
@@ -200,38 +229,37 @@ class HueOneLightChangeView(HomeAssistantView):
async def put(self, request, username, entity_number):
"""Process a request to set the state of an individual light."""
if not is_local(request[KEY_REAL_IP]):
return self.json_message('only local IPs allowed',
HTTP_BAD_REQUEST)
return self.json_message("only local IPs allowed", HTTP_BAD_REQUEST)
config = self.config
hass = request.app['hass']
hass = request.app["hass"]
entity_id = config.number_to_entity_id(entity_number)
if entity_id is None:
_LOGGER.error('Unknown entity number: %s', entity_number)
return self.json_message('Entity not found', HTTP_NOT_FOUND)
_LOGGER.error("Unknown entity number: %s", entity_number)
return self.json_message("Entity not found", HTTP_NOT_FOUND)
entity = hass.states.get(entity_id)
if entity is None:
_LOGGER.error('Entity not found: %s', entity_id)
return self.json_message('Entity not found', HTTP_NOT_FOUND)
_LOGGER.error("Entity not found: %s", entity_id)
return self.json_message("Entity not found", HTTP_NOT_FOUND)
if not config.is_entity_exposed(entity):
_LOGGER.error('Entity not exposed: %s', entity_id)
_LOGGER.error("Entity not exposed: %s", entity_id)
return web.Response(text="Entity not exposed", status=404)
try:
request_json = await request.json()
except ValueError:
_LOGGER.error('Received invalid json')
return self.json_message('Invalid JSON', HTTP_BAD_REQUEST)
_LOGGER.error("Received invalid json")
return self.json_message("Invalid JSON", HTTP_BAD_REQUEST)
# Parse the request into requested "on" status and brightness
parsed = parse_hue_api_put_light_body(request_json, entity)
if parsed is None:
_LOGGER.error('Unable to parse data: %s', request_json)
_LOGGER.error("Unable to parse data: %s", request_json)
return web.Response(text="Bad request", status=400)
# Choose general HA domain
@@ -270,12 +298,12 @@ class HueOneLightChangeView(HomeAssistantView):
# If the requested entity is a script add some variables
elif entity.domain == script.DOMAIN:
data['variables'] = {
'requested_state': STATE_ON if parsed[STATE_ON] else STATE_OFF
data["variables"] = {
"requested_state": STATE_ON if parsed[STATE_ON] else STATE_OFF
}
if parsed[STATE_BRIGHTNESS] is not None:
data['variables']['requested_level'] = parsed[STATE_BRIGHTNESS]
data["variables"]["requested_level"] = parsed[STATE_BRIGHTNESS]
# If the requested entity is a climate, set the temperature
elif entity.domain == climate.DOMAIN:
@@ -297,8 +325,7 @@ class HueOneLightChangeView(HomeAssistantView):
domain = entity.domain
service = SERVICE_VOLUME_SET
# Convert 0-100 to 0.0-1.0
data[ATTR_MEDIA_VOLUME_LEVEL] = \
parsed[STATE_BRIGHTNESS] / 100.0
data[ATTR_MEDIA_VOLUME_LEVEL] = parsed[STATE_BRIGHTNESS] / 100.0
# If the requested entity is a cover, convert to open_cover/close_cover
elif entity.domain == cover.DOMAIN:
@@ -343,27 +370,42 @@ class HueOneLightChangeView(HomeAssistantView):
# Separate call to turn on needed
if turn_on_needed:
hass.async_create_task(hass.services.async_call(
core.DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: entity_id},
blocking=True))
hass.async_create_task(
hass.services.async_call(
core.DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: entity_id},
blocking=True,
)
)
if service is not None:
hass.async_create_task(hass.services.async_call(
domain, service, data, blocking=True))
hass.async_create_task(
hass.services.async_call(domain, service, data, blocking=True)
)
json_response = \
[create_hue_success_response(
entity_id, HUE_API_STATE_ON, parsed[STATE_ON])]
json_response = [
create_hue_success_response(entity_id, HUE_API_STATE_ON, parsed[STATE_ON])
]
if parsed[STATE_BRIGHTNESS] is not None:
json_response.append(create_hue_success_response(
entity_id, HUE_API_STATE_BRI, parsed[STATE_BRIGHTNESS]))
json_response.append(
create_hue_success_response(
entity_id, HUE_API_STATE_BRI, parsed[STATE_BRIGHTNESS]
)
)
if parsed[STATE_HUE] is not None:
json_response.append(create_hue_success_response(
entity_id, HUE_API_STATE_HUE, parsed[STATE_HUE]))
json_response.append(
create_hue_success_response(
entity_id, HUE_API_STATE_HUE, parsed[STATE_HUE]
)
)
if parsed[STATE_SATURATION] is not None:
json_response.append(create_hue_success_response(
entity_id, HUE_API_STATE_SAT, parsed[STATE_SATURATION]))
json_response.append(
create_hue_success_response(
entity_id, HUE_API_STATE_SAT, parsed[STATE_SATURATION]
)
)
return self.json(json_response)
@@ -396,32 +438,32 @@ def parse_hue_api_put_light_body(request_json, entity):
if HUE_API_STATE_HUE in request_json:
try:
# Clamp brightness from 0 to 65535
data[STATE_HUE] = \
max(0, min(int(request_json[HUE_API_STATE_HUE]),
HUE_API_STATE_HUE_MAX))
data[STATE_HUE] = max(
0, min(int(request_json[HUE_API_STATE_HUE]), HUE_API_STATE_HUE_MAX)
)
except ValueError:
return None
if HUE_API_STATE_SAT in request_json:
try:
# Clamp saturation from 0 to 254
data[STATE_SATURATION] = \
max(0, min(int(request_json[HUE_API_STATE_SAT]),
HUE_API_STATE_SAT_MAX))
data[STATE_SATURATION] = max(
0, min(int(request_json[HUE_API_STATE_SAT]), HUE_API_STATE_SAT_MAX)
)
except ValueError:
return None
if HUE_API_STATE_BRI in request_json:
try:
# Clamp brightness from 0 to 255
data[STATE_BRIGHTNESS] = \
max(0, min(int(request_json[HUE_API_STATE_BRI]),
HUE_API_STATE_BRI_MAX))
data[STATE_BRIGHTNESS] = max(
0, min(int(request_json[HUE_API_STATE_BRI]), HUE_API_STATE_BRI_MAX)
)
except ValueError:
return None
if entity.domain == light.DOMAIN:
data[STATE_ON] = (data[STATE_BRIGHTNESS] > 0)
data[STATE_ON] = data[STATE_BRIGHTNESS] > 0
if not entity_features & SUPPORT_BRIGHTNESS:
data[STATE_BRIGHTNESS] = None
@@ -430,8 +472,12 @@ def parse_hue_api_put_light_body(request_json, entity):
data[STATE_ON] = True
elif entity.domain in [
script.DOMAIN, media_player.DOMAIN,
fan.DOMAIN, cover.DOMAIN, climate.DOMAIN]:
script.DOMAIN,
media_player.DOMAIN,
fan.DOMAIN,
cover.DOMAIN,
climate.DOMAIN,
]:
# Convert 0-255 to 0-100
level = (data[STATE_BRIGHTNESS] / HUE_API_STATE_BRI_MAX) * 100
data[STATE_BRIGHTNESS] = round(level)
@@ -447,7 +493,7 @@ def get_entity_state(config, entity):
STATE_BRIGHTNESS: None,
STATE_HUE: None,
STATE_ON: False,
STATE_SATURATION: None
STATE_SATURATION: None,
}
if cached_state is None:
@@ -460,8 +506,7 @@ def get_entity_state(config, entity):
sat = hue_sat[1]
# convert hass hs values back to hue hs values
data[STATE_HUE] = int((hue / 360.0) * HUE_API_STATE_HUE_MAX)
data[STATE_SATURATION] = \
int((sat / 100.0) * HUE_API_STATE_SAT_MAX)
data[STATE_SATURATION] = int((sat / 100.0) * HUE_API_STATE_SAT_MAX)
else:
data[STATE_BRIGHTNESS] = 0
data[STATE_HUE] = 0
@@ -480,10 +525,10 @@ def get_entity_state(config, entity):
data[STATE_BRIGHTNESS] = round(temperature * 255 / 100)
elif entity.domain == media_player.DOMAIN:
level = entity.attributes.get(
ATTR_MEDIA_VOLUME_LEVEL, 1.0 if data[STATE_ON] else 0.0)
ATTR_MEDIA_VOLUME_LEVEL, 1.0 if data[STATE_ON] else 0.0
)
# Convert 0.0-1.0 to 0-255
data[STATE_BRIGHTNESS] = \
round(min(1.0, level) * HUE_API_STATE_BRI_MAX)
data[STATE_BRIGHTNESS] = round(min(1.0, level) * HUE_API_STATE_BRI_MAX)
elif entity.domain == fan.DOMAIN:
speed = entity.attributes.get(ATTR_SPEED, 0)
# Convert 0.0-1.0 to 0-255
@@ -520,35 +565,30 @@ def entity_to_json(config, entity, state):
entity_features = entity.attributes.get(ATTR_SUPPORTED_FEATURES, 0)
if entity_features & SUPPORT_BRIGHTNESS:
return {
'state':
{
"state": {
HUE_API_STATE_ON: state[STATE_ON],
HUE_API_STATE_BRI: state[STATE_BRIGHTNESS],
HUE_API_STATE_HUE: state[STATE_HUE],
HUE_API_STATE_SAT: state[STATE_SATURATION],
'reachable': True
"reachable": True,
},
'type': 'Dimmable light',
'name': config.get_entity_name(entity),
'modelid': 'HASS123',
'uniqueid': entity.entity_id,
'swversion': '123'
}
return {
'state':
{
HUE_API_STATE_ON: state[STATE_ON],
'reachable': True
},
'type': 'On/off light',
'name': config.get_entity_name(entity),
'modelid': 'HASS123',
'uniqueid': entity.entity_id,
'swversion': '123'
"type": "Dimmable light",
"name": config.get_entity_name(entity),
"modelid": "HASS123",
"uniqueid": entity.entity_id,
"swversion": "123",
}
return {
"state": {HUE_API_STATE_ON: state[STATE_ON], "reachable": True},
"type": "On/off light",
"name": config.get_entity_name(entity),
"modelid": "HASS123",
"uniqueid": entity.entity_id,
"swversion": "123",
}
def create_hue_success_response(entity_id, attr, value):
"""Create a success response for an attribute set on a light."""
success_key = '/lights/{}/state/{}'.format(entity_id, attr)
return {'success': {success_key: value}}
success_key = "/lights/{}/state/{}".format(entity_id, attr)
return {"success": {success_key: value}}