forked from home-assistant/core
Compare commits
59 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4f134f339c | ||
|
|
264d18bc83 | ||
|
|
4c1d978aa4 | ||
|
|
b10149c2a0 | ||
|
|
2b82830eb1 | ||
|
|
ff1dba3529 | ||
|
|
257a91d929 | ||
|
|
a7e98f12f4 | ||
|
|
f55ab9d4ea | ||
|
|
23cc4d1453 | ||
|
|
f613cd38fc | ||
|
|
45238295df | ||
|
|
65bd308491 | ||
|
|
30345489e6 | ||
|
|
1135446de4 | ||
|
|
a262d0f9e4 | ||
|
|
d425aabae3 | ||
|
|
8d44b721c6 | ||
|
|
baa1801e13 | ||
|
|
965e47eb6a | ||
|
|
16c0301227 | ||
|
|
37096a2b65 | ||
|
|
bead08840e | ||
|
|
b7b55f941c | ||
|
|
4231775e04 | ||
|
|
14d90b5484 | ||
|
|
afa48c54e9 | ||
|
|
6603b3eccd | ||
|
|
e2bf3ac095 | ||
|
|
ced96775fe | ||
|
|
f65e57bf7b | ||
|
|
88cda043ac | ||
|
|
404fbe388c | ||
|
|
a0bc96c20d | ||
|
|
e98476e026 | ||
|
|
aa45ff83bd | ||
|
|
029d006beb | ||
|
|
e94eb686a6 | ||
|
|
2da5a02285 | ||
|
|
e3b1008511 | ||
|
|
cb874fefbb | ||
|
|
0454a5fa3f | ||
|
|
d8f6331318 | ||
|
|
d7459c73e0 | ||
|
|
fa9fe4067a | ||
|
|
55aaa894c3 | ||
|
|
18bc772cbb | ||
|
|
a5072f0fe4 | ||
|
|
76c26da4cb | ||
|
|
3528d865b7 | ||
|
|
e6c224fa40 | ||
|
|
048f219a7f | ||
|
|
945b84a7df | ||
|
|
393ada0312 | ||
|
|
da160066c3 | ||
|
|
ff9427d463 | ||
|
|
3eb646eb0d | ||
|
|
578fe371c6 | ||
|
|
1b03a35fa1 |
@@ -310,7 +310,15 @@ class ManualAlarm(alarm.AlarmControlPanel, RestoreEntity):
|
||||
|
||||
async def async_added_to_hass(self):
|
||||
"""Run when entity about to be added to hass."""
|
||||
await super().async_added_to_hass()
|
||||
state = await self.async_get_last_state()
|
||||
if state:
|
||||
self._state = state.state
|
||||
self._state_ts = state.last_updated
|
||||
if state.state == STATE_ALARM_PENDING and \
|
||||
hasattr(state, 'attributes') and \
|
||||
state.attributes['pre_pending_state']:
|
||||
# If in pending state, we return to the pre_pending_state
|
||||
self._state = state.attributes['pre_pending_state']
|
||||
self._state_ts = dt_util.utcnow()
|
||||
else:
|
||||
self._state = state.state
|
||||
self._state_ts = state.last_updated
|
||||
|
||||
@@ -504,6 +504,20 @@ class _AlexaColorTemperatureController(_AlexaInterface):
|
||||
def name(self):
|
||||
return 'Alexa.ColorTemperatureController'
|
||||
|
||||
def properties_supported(self):
|
||||
return [{'name': 'colorTemperatureInKelvin'}]
|
||||
|
||||
def properties_retrievable(self):
|
||||
return True
|
||||
|
||||
def get_property(self, name):
|
||||
if name != 'colorTemperatureInKelvin':
|
||||
raise _UnsupportedProperty(name)
|
||||
if 'color_temp' in self.entity.attributes:
|
||||
return color_util.color_temperature_mired_to_kelvin(
|
||||
self.entity.attributes['color_temp'])
|
||||
return 0
|
||||
|
||||
|
||||
class _AlexaPercentageController(_AlexaInterface):
|
||||
"""Implements Alexa.PercentageController.
|
||||
|
||||
@@ -16,7 +16,7 @@ from homeassistant.helpers import discovery
|
||||
from homeassistant.helpers.aiohttp_client import async_get_clientsession
|
||||
import homeassistant.helpers.config_validation as cv
|
||||
|
||||
REQUIREMENTS = ['pyatv==0.3.11']
|
||||
REQUIREMENTS = ['pyatv==0.3.12']
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ from homeassistant.const import (
|
||||
from homeassistant.helpers import config_validation as cv
|
||||
from homeassistant.helpers.discovery import async_load_platform
|
||||
|
||||
REQUIREMENTS = ['aioasuswrt==1.1.13']
|
||||
REQUIREMENTS = ['aioasuswrt==1.1.15']
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@@ -423,9 +423,7 @@ class XiaomiButton(XiaomiBinarySensor):
|
||||
})
|
||||
self._last_action = click_type
|
||||
|
||||
if value in ['long_click_press', 'long_click_release']:
|
||||
return True
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
class XiaomiCube(XiaomiBinarySensor):
|
||||
|
||||
@@ -59,15 +59,21 @@ async def async_setup_platform(hass, config, async_add_entities,
|
||||
|
||||
def extract_image_from_mjpeg(stream):
|
||||
"""Take in a MJPEG stream object, return the jpg from it."""
|
||||
data = bytes()
|
||||
data_start = b"\xff\xd8"
|
||||
data_end = b"\xff\xd9"
|
||||
for chunk in stream:
|
||||
end_idx = chunk.find(data_end)
|
||||
if end_idx != -1:
|
||||
return data[data.find(data_start):] + chunk[:end_idx + 2]
|
||||
data = b''
|
||||
|
||||
for chunk in stream:
|
||||
data += chunk
|
||||
jpg_end = data.find(b'\xff\xd9')
|
||||
|
||||
if jpg_end == -1:
|
||||
continue
|
||||
|
||||
jpg_start = data.find(b'\xff\xd8')
|
||||
|
||||
if jpg_start == -1:
|
||||
continue
|
||||
|
||||
return data[jpg_start:jpg_end + 2]
|
||||
|
||||
|
||||
class MjpegCamera(Camera):
|
||||
|
||||
@@ -252,8 +252,7 @@ class Cloud:
|
||||
return json.loads(file.read())
|
||||
|
||||
info = await self.hass.async_add_job(load_config)
|
||||
|
||||
await self.prefs.async_initialize(bool(info))
|
||||
await self.prefs.async_initialize()
|
||||
|
||||
if info is None:
|
||||
return
|
||||
|
||||
@@ -16,19 +16,17 @@ class CloudPreferences:
|
||||
self._store = hass.helpers.storage.Store(STORAGE_VERSION, STORAGE_KEY)
|
||||
self._prefs = None
|
||||
|
||||
async def async_initialize(self, logged_in):
|
||||
async def async_initialize(self):
|
||||
"""Finish initializing the preferences."""
|
||||
prefs = await self._store.async_load()
|
||||
|
||||
if prefs is None:
|
||||
# Backwards compat: we enable alexa/google if already logged in
|
||||
prefs = {
|
||||
PREF_ENABLE_ALEXA: logged_in,
|
||||
PREF_ENABLE_GOOGLE: logged_in,
|
||||
PREF_ENABLE_ALEXA: True,
|
||||
PREF_ENABLE_GOOGLE: True,
|
||||
PREF_GOOGLE_ALLOW_UNLOCK: False,
|
||||
PREF_CLOUDHOOKS: {}
|
||||
}
|
||||
await self._store.async_save(prefs)
|
||||
|
||||
self._prefs = prefs
|
||||
|
||||
|
||||
@@ -88,7 +88,7 @@ async def websocket_get_entity(hass, connection, msg):
|
||||
|
||||
@async_response
|
||||
async def websocket_update_entity(hass, connection, msg):
|
||||
"""Handle get camera thumbnail websocket command.
|
||||
"""Handle update entity websocket command.
|
||||
|
||||
Async friendly.
|
||||
"""
|
||||
@@ -104,8 +104,12 @@ async def websocket_update_entity(hass, connection, msg):
|
||||
if 'name' in msg:
|
||||
changes['name'] = msg['name']
|
||||
|
||||
if 'new_entity_id' in msg:
|
||||
if 'new_entity_id' in msg and msg['new_entity_id'] != msg['entity_id']:
|
||||
changes['new_entity_id'] = msg['new_entity_id']
|
||||
if hass.states.get(msg['new_entity_id']) is not None:
|
||||
connection.send_message(websocket_api.error_message(
|
||||
msg['id'], 'invalid_info', 'Entity is already registered'))
|
||||
return
|
||||
|
||||
try:
|
||||
if changes:
|
||||
|
||||
@@ -383,7 +383,6 @@ class DeviceTracker:
|
||||
for device in self.devices.values():
|
||||
if (device.track and device.last_update_home) and \
|
||||
device.stale(now):
|
||||
device.mark_stale()
|
||||
self.hass.async_create_task(device.async_update_ha_state(True))
|
||||
|
||||
async def async_setup_tracked_device(self):
|
||||
|
||||
@@ -316,14 +316,19 @@ async def async_handle_waypoints_message(hass, context, message):
|
||||
@HANDLERS.register('encrypted')
|
||||
async def async_handle_encrypted_message(hass, context, message):
|
||||
"""Handle an encrypted message."""
|
||||
plaintext_payload = _decrypt_payload(context.secret, message['topic'],
|
||||
if 'topic' not in message and isinstance(context.secret, dict):
|
||||
_LOGGER.error("You cannot set per topic secrets when using HTTP")
|
||||
return
|
||||
|
||||
plaintext_payload = _decrypt_payload(context.secret, message.get('topic'),
|
||||
message['data'])
|
||||
|
||||
if plaintext_payload is None:
|
||||
return
|
||||
|
||||
decrypted = json.loads(plaintext_payload)
|
||||
decrypted['topic'] = message['topic']
|
||||
if 'topic' in message and 'topic' not in decrypted:
|
||||
decrypted['topic'] = message['topic']
|
||||
|
||||
await async_handle_message(hass, context, decrypted)
|
||||
|
||||
|
||||
@@ -24,7 +24,7 @@ from homeassistant.core import callback
|
||||
from homeassistant.helpers.translation import async_get_translations
|
||||
from homeassistant.loader import bind_hass
|
||||
|
||||
REQUIREMENTS = ['home-assistant-frontend==20181205.0']
|
||||
REQUIREMENTS = ['home-assistant-frontend==20181211.2']
|
||||
|
||||
DOMAIN = 'frontend'
|
||||
DEPENDENCIES = ['api', 'websocket_api', 'http', 'system_log',
|
||||
@@ -250,8 +250,7 @@ async def async_setup(hass, config):
|
||||
await asyncio.wait(
|
||||
[async_register_built_in_panel(hass, panel) for panel in (
|
||||
'dev-event', 'dev-info', 'dev-service', 'dev-state',
|
||||
'dev-template', 'dev-mqtt', 'kiosk', 'lovelace',
|
||||
'states', 'profile')],
|
||||
'dev-template', 'dev-mqtt', 'kiosk', 'states', 'profile')],
|
||||
loop=hass.loop)
|
||||
|
||||
hass.data[DATA_FINALIZE_PANEL] = async_finalize_panel
|
||||
|
||||
@@ -19,8 +19,6 @@ DEFAULT_EXPOSED_DOMAINS = [
|
||||
'media_player', 'scene', 'script', 'switch', 'vacuum', 'lock',
|
||||
]
|
||||
DEFAULT_ALLOW_UNLOCK = False
|
||||
CLIMATE_MODE_HEATCOOL = 'heatcool'
|
||||
CLIMATE_SUPPORTED_MODES = {'heat', 'cool', 'off', 'on', CLIMATE_MODE_HEATCOOL}
|
||||
|
||||
PREFIX_TYPES = 'action.devices.types.'
|
||||
TYPE_LIGHT = PREFIX_TYPES + 'LIGHT'
|
||||
|
||||
@@ -48,7 +48,7 @@ def async_register_http(hass, cfg):
|
||||
entity_config.get(entity.entity_id, {}).get(CONF_EXPOSE)
|
||||
|
||||
domain_exposed_by_default = \
|
||||
expose_by_default or entity.domain in exposed_domains
|
||||
expose_by_default and entity.domain in exposed_domains
|
||||
|
||||
# Expose an entity if the entity's domain is exposed by default and
|
||||
# the configuration doesn't explicitly exclude it from being
|
||||
|
||||
@@ -518,6 +518,9 @@ class TemperatureSettingTrait(_Trait):
|
||||
climate.STATE_COOL: 'cool',
|
||||
climate.STATE_OFF: 'off',
|
||||
climate.STATE_AUTO: 'heatcool',
|
||||
climate.STATE_FAN_ONLY: 'fan-only',
|
||||
climate.STATE_DRY: 'dry',
|
||||
climate.STATE_ECO: 'eco'
|
||||
}
|
||||
google_to_hass = {value: key for key, value in hass_to_google.items()}
|
||||
|
||||
@@ -588,8 +591,11 @@ class TemperatureSettingTrait(_Trait):
|
||||
max_temp = self.state.attributes[climate.ATTR_MAX_TEMP]
|
||||
|
||||
if command == COMMAND_THERMOSTAT_TEMPERATURE_SETPOINT:
|
||||
temp = temp_util.convert(params['thermostatTemperatureSetpoint'],
|
||||
TEMP_CELSIUS, unit)
|
||||
temp = temp_util.convert(
|
||||
params['thermostatTemperatureSetpoint'], TEMP_CELSIUS,
|
||||
unit)
|
||||
if unit == TEMP_FAHRENHEIT:
|
||||
temp = round(temp)
|
||||
|
||||
if temp < min_temp or temp > max_temp:
|
||||
raise SmartHomeError(
|
||||
@@ -607,6 +613,8 @@ class TemperatureSettingTrait(_Trait):
|
||||
temp_high = temp_util.convert(
|
||||
params['thermostatTemperatureSetpointHigh'], TEMP_CELSIUS,
|
||||
unit)
|
||||
if unit == TEMP_FAHRENHEIT:
|
||||
temp_high = round(temp_high)
|
||||
|
||||
if temp_high < min_temp or temp_high > max_temp:
|
||||
raise SmartHomeError(
|
||||
@@ -615,7 +623,10 @@ class TemperatureSettingTrait(_Trait):
|
||||
"{} and {}".format(min_temp, max_temp))
|
||||
|
||||
temp_low = temp_util.convert(
|
||||
params['thermostatTemperatureSetpointLow'], TEMP_CELSIUS, unit)
|
||||
params['thermostatTemperatureSetpointLow'], TEMP_CELSIUS,
|
||||
unit)
|
||||
if unit == TEMP_FAHRENHEIT:
|
||||
temp_low = round(temp_low)
|
||||
|
||||
if temp_low < min_temp or temp_low > max_temp:
|
||||
raise SmartHomeError(
|
||||
|
||||
@@ -18,8 +18,8 @@ from homeassistant.components.ihc.const import (
|
||||
SERVICE_SET_RUNTIME_VALUE_FLOAT, SERVICE_SET_RUNTIME_VALUE_INT)
|
||||
from homeassistant.config import load_yaml_config_file
|
||||
from homeassistant.const import (
|
||||
CONF_BINARY_SENSORS, CONF_ID, CONF_LIGHTS, CONF_NAME, CONF_PASSWORD,
|
||||
CONF_SENSORS, CONF_SWITCHES, CONF_TYPE, CONF_UNIT_OF_MEASUREMENT, CONF_URL,
|
||||
CONF_ID, CONF_NAME, CONF_PASSWORD,
|
||||
CONF_TYPE, CONF_UNIT_OF_MEASUREMENT, CONF_URL,
|
||||
CONF_USERNAME, TEMP_CELSIUS)
|
||||
from homeassistant.helpers import discovery
|
||||
import homeassistant.helpers.config_validation as cv
|
||||
@@ -49,7 +49,7 @@ DEVICE_SCHEMA = vol.Schema({
|
||||
vol.Optional(CONF_NAME): cv.string,
|
||||
vol.Optional(CONF_POSITION): cv.string,
|
||||
vol.Optional(CONF_NOTE): cv.string
|
||||
}, extra=vol.ALLOW_EXTRA)
|
||||
})
|
||||
|
||||
|
||||
SWITCH_SCHEMA = DEVICE_SCHEMA.extend({
|
||||
@@ -75,31 +75,31 @@ IHC_SCHEMA = vol.Schema({
|
||||
vol.Required(CONF_PASSWORD): cv.string,
|
||||
vol.Optional(CONF_AUTOSETUP, default=True): cv.boolean,
|
||||
vol.Optional(CONF_INFO, default=True): cv.boolean,
|
||||
vol.Optional(CONF_BINARY_SENSORS, default=[]):
|
||||
vol.Optional(CONF_BINARY_SENSOR, default=[]):
|
||||
vol.All(cv.ensure_list, [
|
||||
vol.All(
|
||||
BINARY_SENSOR_SCHEMA,
|
||||
validate_name)
|
||||
]),
|
||||
vol.Optional(CONF_LIGHTS, default=[]):
|
||||
vol.Optional(CONF_LIGHT, default=[]):
|
||||
vol.All(cv.ensure_list, [
|
||||
vol.All(
|
||||
LIGHT_SCHEMA,
|
||||
validate_name)
|
||||
]),
|
||||
vol.Optional(CONF_SENSORS, default=[]):
|
||||
vol.Optional(CONF_SENSOR, default=[]):
|
||||
vol.All(cv.ensure_list, [
|
||||
vol.All(
|
||||
SENSOR_SCHEMA,
|
||||
validate_name)
|
||||
]),
|
||||
vol.Optional(CONF_SWITCHES, default=[]):
|
||||
vol.Optional(CONF_SWITCH, default=[]):
|
||||
vol.All(cv.ensure_list, [
|
||||
vol.All(
|
||||
SWITCH_SCHEMA,
|
||||
validate_name)
|
||||
]),
|
||||
}, extra=vol.ALLOW_EXTRA)
|
||||
})
|
||||
|
||||
CONFIG_SCHEMA = vol.Schema({
|
||||
DOMAIN: vol.Schema(vol.All(
|
||||
@@ -224,7 +224,8 @@ def get_manual_configuration(hass, config, conf, ihc_controller,
|
||||
'type': sensor_cfg.get(CONF_TYPE),
|
||||
'inverting': sensor_cfg.get(CONF_INVERTING),
|
||||
'dimmable': sensor_cfg.get(CONF_DIMMABLE),
|
||||
'unit': sensor_cfg.get(CONF_UNIT_OF_MEASUREMENT)
|
||||
'unit_of_measurement': sensor_cfg.get(
|
||||
CONF_UNIT_OF_MEASUREMENT)
|
||||
}
|
||||
}
|
||||
discovery_info[name] = device
|
||||
|
||||
@@ -8,7 +8,7 @@ from homeassistant.components.light import DOMAIN as LIGHT_DOMAIN
|
||||
|
||||
|
||||
DOMAIN = 'lifx'
|
||||
REQUIREMENTS = ['aiolifx==0.6.6']
|
||||
REQUIREMENTS = ['aiolifx==0.6.7']
|
||||
|
||||
CONF_SERVER = 'server'
|
||||
CONF_BROADCAST = 'broadcast'
|
||||
|
||||
@@ -42,7 +42,7 @@ class LutronLight(LutronDevice, Light):
|
||||
def __init__(self, area_name, lutron_device, controller):
|
||||
"""Initialize the light."""
|
||||
self._prev_brightness = None
|
||||
super().__init__(self, area_name, lutron_device, controller)
|
||||
super().__init__(area_name, lutron_device, controller)
|
||||
|
||||
@property
|
||||
def supported_features(self):
|
||||
@@ -75,8 +75,7 @@ class LutronLight(LutronDevice, Light):
|
||||
@property
|
||||
def device_state_attributes(self):
|
||||
"""Return the state attributes."""
|
||||
attr = {}
|
||||
attr['lutron_integration_id'] = self._lutron_device.id
|
||||
attr = {'lutron_integration_id': self._lutron_device.id}
|
||||
return attr
|
||||
|
||||
@property
|
||||
|
||||
@@ -29,8 +29,9 @@ SERVICE_CLEAR_USERCODE = 'clear_usercode'
|
||||
POLYCONTROL = 0x10E
|
||||
DANALOCK_V2_BTZE = 0x2
|
||||
POLYCONTROL_DANALOCK_V2_BTZE_LOCK = (POLYCONTROL, DANALOCK_V2_BTZE)
|
||||
WORKAROUND_V2BTZE = 'v2btze'
|
||||
WORKAROUND_DEVICE_STATE = 'state'
|
||||
WORKAROUND_V2BTZE = 1
|
||||
WORKAROUND_DEVICE_STATE = 2
|
||||
WORKAROUND_TRACK_MESSAGE = 4
|
||||
|
||||
DEVICE_MAPPINGS = {
|
||||
POLYCONTROL_DANALOCK_V2_BTZE_LOCK: WORKAROUND_V2BTZE,
|
||||
@@ -43,7 +44,7 @@ DEVICE_MAPPINGS = {
|
||||
# Yale YRD220 (as reported by adrum in PR #17386)
|
||||
(0x0109, 0x0000): WORKAROUND_DEVICE_STATE,
|
||||
# Schlage BE469
|
||||
(0x003B, 0x5044): WORKAROUND_DEVICE_STATE,
|
||||
(0x003B, 0x5044): WORKAROUND_DEVICE_STATE | WORKAROUND_TRACK_MESSAGE,
|
||||
# Schlage FE599NX
|
||||
(0x003B, 0x504C): WORKAROUND_DEVICE_STATE,
|
||||
}
|
||||
@@ -51,13 +52,15 @@ DEVICE_MAPPINGS = {
|
||||
LOCK_NOTIFICATION = {
|
||||
'1': 'Manual Lock',
|
||||
'2': 'Manual Unlock',
|
||||
'3': 'RF Lock',
|
||||
'4': 'RF Unlock',
|
||||
'5': 'Keypad Lock',
|
||||
'6': 'Keypad Unlock',
|
||||
'11': 'Lock Jammed',
|
||||
'254': 'Unknown Event'
|
||||
}
|
||||
NOTIFICATION_RF_LOCK = '3'
|
||||
NOTIFICATION_RF_UNLOCK = '4'
|
||||
LOCK_NOTIFICATION[NOTIFICATION_RF_LOCK] = 'RF Lock'
|
||||
LOCK_NOTIFICATION[NOTIFICATION_RF_UNLOCK] = 'RF Unlock'
|
||||
|
||||
LOCK_ALARM_TYPE = {
|
||||
'9': 'Deadbolt Jammed',
|
||||
@@ -66,8 +69,6 @@ LOCK_ALARM_TYPE = {
|
||||
'19': 'Unlocked with Keypad by user ',
|
||||
'21': 'Manually Locked ',
|
||||
'22': 'Manually Unlocked ',
|
||||
'24': 'Locked by RF',
|
||||
'25': 'Unlocked by RF',
|
||||
'27': 'Auto re-lock',
|
||||
'33': 'User deleted: ',
|
||||
'112': 'Master code changed or User added: ',
|
||||
@@ -79,6 +80,10 @@ LOCK_ALARM_TYPE = {
|
||||
'168': 'Critical Battery Level',
|
||||
'169': 'Battery too low to operate'
|
||||
}
|
||||
ALARM_RF_LOCK = '24'
|
||||
ALARM_RF_UNLOCK = '25'
|
||||
LOCK_ALARM_TYPE[ALARM_RF_LOCK] = 'Locked by RF'
|
||||
LOCK_ALARM_TYPE[ALARM_RF_UNLOCK] = 'Unlocked by RF'
|
||||
|
||||
MANUAL_LOCK_ALARM_LEVEL = {
|
||||
'1': 'by Key Cylinder or Inside thumb turn',
|
||||
@@ -229,6 +234,8 @@ class ZwaveLock(zwave.ZWaveDeviceEntity, LockDevice):
|
||||
self._lock_status = None
|
||||
self._v2btze = None
|
||||
self._state_workaround = False
|
||||
self._track_message_workaround = False
|
||||
self._previous_message = None
|
||||
|
||||
# Enable appropriate workaround flags for our device
|
||||
# Make sure that we have values for the key before converting to int
|
||||
@@ -237,26 +244,30 @@ class ZwaveLock(zwave.ZWaveDeviceEntity, LockDevice):
|
||||
specific_sensor_key = (int(self.node.manufacturer_id, 16),
|
||||
int(self.node.product_id, 16))
|
||||
if specific_sensor_key in DEVICE_MAPPINGS:
|
||||
if DEVICE_MAPPINGS[specific_sensor_key] == WORKAROUND_V2BTZE:
|
||||
workaround = DEVICE_MAPPINGS[specific_sensor_key]
|
||||
if workaround & WORKAROUND_V2BTZE:
|
||||
self._v2btze = 1
|
||||
_LOGGER.debug("Polycontrol Danalock v2 BTZE "
|
||||
"workaround enabled")
|
||||
if DEVICE_MAPPINGS[specific_sensor_key] == \
|
||||
WORKAROUND_DEVICE_STATE:
|
||||
if workaround & WORKAROUND_DEVICE_STATE:
|
||||
self._state_workaround = True
|
||||
_LOGGER.debug(
|
||||
"Notification device state workaround enabled")
|
||||
if workaround & WORKAROUND_TRACK_MESSAGE:
|
||||
self._track_message_workaround = True
|
||||
_LOGGER.debug("Message tracking workaround enabled")
|
||||
self.update_properties()
|
||||
|
||||
def update_properties(self):
|
||||
"""Handle data changes for node values."""
|
||||
self._state = self.values.primary.data
|
||||
_LOGGER.debug("Lock state set from Bool value and is %s", self._state)
|
||||
_LOGGER.debug("lock state set to %s", self._state)
|
||||
if self.values.access_control:
|
||||
notification_data = self.values.access_control.data
|
||||
self._notification = LOCK_NOTIFICATION.get(str(notification_data))
|
||||
if self._state_workaround:
|
||||
self._state = LOCK_STATUS.get(str(notification_data))
|
||||
_LOGGER.debug("workaround: lock state set to %s", self._state)
|
||||
if self._v2btze:
|
||||
if self.values.v2btze_advanced and \
|
||||
self.values.v2btze_advanced.data == CONFIG_ADVANCED:
|
||||
@@ -265,16 +276,37 @@ class ZwaveLock(zwave.ZWaveDeviceEntity, LockDevice):
|
||||
"Lock state set from Access Control value and is %s, "
|
||||
"get=%s", str(notification_data), self.state)
|
||||
|
||||
if self._track_message_workaround:
|
||||
this_message = self.node.stats['lastReceivedMessage'][5]
|
||||
|
||||
if this_message == zwave.const.COMMAND_CLASS_DOOR_LOCK:
|
||||
self._state = self.values.primary.data
|
||||
_LOGGER.debug("set state to %s based on message tracking",
|
||||
self._state)
|
||||
if self._previous_message == \
|
||||
zwave.const.COMMAND_CLASS_DOOR_LOCK:
|
||||
if self._state:
|
||||
self._notification = \
|
||||
LOCK_NOTIFICATION[NOTIFICATION_RF_LOCK]
|
||||
self._lock_status = \
|
||||
LOCK_ALARM_TYPE[ALARM_RF_LOCK]
|
||||
else:
|
||||
self._notification = \
|
||||
LOCK_NOTIFICATION[NOTIFICATION_RF_UNLOCK]
|
||||
self._lock_status = \
|
||||
LOCK_ALARM_TYPE[ALARM_RF_UNLOCK]
|
||||
return
|
||||
|
||||
self._previous_message = this_message
|
||||
|
||||
if not self.values.alarm_type:
|
||||
return
|
||||
|
||||
alarm_type = self.values.alarm_type.data
|
||||
_LOGGER.debug("Lock alarm_type is %s", str(alarm_type))
|
||||
if self.values.alarm_level:
|
||||
alarm_level = self.values.alarm_level.data
|
||||
else:
|
||||
alarm_level = None
|
||||
_LOGGER.debug("Lock alarm_level is %s", str(alarm_level))
|
||||
|
||||
if not alarm_type:
|
||||
return
|
||||
|
||||
@@ -60,7 +60,8 @@ CONFIG_SCHEMA = vol.Schema({
|
||||
ALL_EVENT_TYPES = [
|
||||
EVENT_STATE_CHANGED, EVENT_LOGBOOK_ENTRY,
|
||||
EVENT_HOMEASSISTANT_START, EVENT_HOMEASSISTANT_STOP,
|
||||
EVENT_ALEXA_SMART_HOME, EVENT_HOMEKIT_CHANGED
|
||||
EVENT_ALEXA_SMART_HOME, EVENT_HOMEKIT_CHANGED,
|
||||
EVENT_AUTOMATION_TRIGGERED, EVENT_SCRIPT_STARTED
|
||||
]
|
||||
|
||||
LOG_MESSAGE_SCHEMA = vol.Schema({
|
||||
@@ -468,6 +469,14 @@ def _exclude_events(events, entities_filter):
|
||||
domain = event.data.get(ATTR_DOMAIN)
|
||||
entity_id = event.data.get(ATTR_ENTITY_ID)
|
||||
|
||||
elif event.event_type == EVENT_AUTOMATION_TRIGGERED:
|
||||
domain = 'automation'
|
||||
entity_id = event.data.get(ATTR_ENTITY_ID)
|
||||
|
||||
elif event.event_type == EVENT_SCRIPT_STARTED:
|
||||
domain = 'script'
|
||||
entity_id = event.data.get(ATTR_ENTITY_ID)
|
||||
|
||||
elif event.event_type == EVENT_ALEXA_SMART_HOME:
|
||||
domain = 'alexa'
|
||||
|
||||
|
||||
@@ -7,500 +7,139 @@ at https://www.home-assistant.io/lovelace/
|
||||
from functools import wraps
|
||||
import logging
|
||||
import os
|
||||
from typing import Dict, List, Union
|
||||
import time
|
||||
import uuid
|
||||
|
||||
import voluptuous as vol
|
||||
|
||||
from homeassistant.components import websocket_api
|
||||
from homeassistant.exceptions import HomeAssistantError
|
||||
import homeassistant.util.ruamel_yaml as yaml
|
||||
from homeassistant.util.yaml import load_yaml
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
DOMAIN = 'lovelace'
|
||||
LOVELACE_DATA = 'lovelace'
|
||||
STORAGE_KEY = DOMAIN
|
||||
STORAGE_VERSION = 1
|
||||
CONF_MODE = 'mode'
|
||||
MODE_YAML = 'yaml'
|
||||
MODE_STORAGE = 'storage'
|
||||
|
||||
CONFIG_SCHEMA = vol.Schema({
|
||||
DOMAIN: vol.Schema({
|
||||
vol.Optional(CONF_MODE, default=MODE_STORAGE):
|
||||
vol.All(vol.Lower, vol.In([MODE_YAML, MODE_STORAGE])),
|
||||
}),
|
||||
}, extra=vol.ALLOW_EXTRA)
|
||||
|
||||
|
||||
LOVELACE_CONFIG_FILE = 'ui-lovelace.yaml'
|
||||
JSON_TYPE = Union[List, Dict, str] # pylint: disable=invalid-name
|
||||
|
||||
FORMAT_YAML = 'yaml'
|
||||
FORMAT_JSON = 'json'
|
||||
|
||||
OLD_WS_TYPE_GET_LOVELACE_UI = 'frontend/lovelace_config'
|
||||
WS_TYPE_GET_LOVELACE_UI = 'lovelace/config'
|
||||
WS_TYPE_MIGRATE_CONFIG = 'lovelace/config/migrate'
|
||||
WS_TYPE_SAVE_CONFIG = 'lovelace/config/save'
|
||||
|
||||
WS_TYPE_GET_CARD = 'lovelace/config/card/get'
|
||||
WS_TYPE_UPDATE_CARD = 'lovelace/config/card/update'
|
||||
WS_TYPE_ADD_CARD = 'lovelace/config/card/add'
|
||||
WS_TYPE_MOVE_CARD = 'lovelace/config/card/move'
|
||||
WS_TYPE_DELETE_CARD = 'lovelace/config/card/delete'
|
||||
|
||||
WS_TYPE_GET_VIEW = 'lovelace/config/view/get'
|
||||
WS_TYPE_UPDATE_VIEW = 'lovelace/config/view/update'
|
||||
WS_TYPE_ADD_VIEW = 'lovelace/config/view/add'
|
||||
WS_TYPE_MOVE_VIEW = 'lovelace/config/view/move'
|
||||
WS_TYPE_DELETE_VIEW = 'lovelace/config/view/delete'
|
||||
|
||||
SCHEMA_GET_LOVELACE_UI = websocket_api.BASE_COMMAND_MESSAGE_SCHEMA.extend({
|
||||
vol.Required('type'):
|
||||
vol.Any(WS_TYPE_GET_LOVELACE_UI, OLD_WS_TYPE_GET_LOVELACE_UI),
|
||||
})
|
||||
|
||||
SCHEMA_MIGRATE_CONFIG = websocket_api.BASE_COMMAND_MESSAGE_SCHEMA.extend({
|
||||
vol.Required('type'): WS_TYPE_MIGRATE_CONFIG,
|
||||
vol.Required('type'): WS_TYPE_GET_LOVELACE_UI,
|
||||
vol.Optional('force', default=False): bool,
|
||||
})
|
||||
|
||||
SCHEMA_SAVE_CONFIG = websocket_api.BASE_COMMAND_MESSAGE_SCHEMA.extend({
|
||||
vol.Required('type'): WS_TYPE_SAVE_CONFIG,
|
||||
vol.Required('config'): vol.Any(str, dict),
|
||||
vol.Optional('format', default=FORMAT_JSON):
|
||||
vol.Any(FORMAT_JSON, FORMAT_YAML),
|
||||
})
|
||||
|
||||
SCHEMA_GET_CARD = websocket_api.BASE_COMMAND_MESSAGE_SCHEMA.extend({
|
||||
vol.Required('type'): WS_TYPE_GET_CARD,
|
||||
vol.Required('card_id'): str,
|
||||
vol.Optional('format', default=FORMAT_YAML):
|
||||
vol.Any(FORMAT_JSON, FORMAT_YAML),
|
||||
})
|
||||
|
||||
SCHEMA_UPDATE_CARD = websocket_api.BASE_COMMAND_MESSAGE_SCHEMA.extend({
|
||||
vol.Required('type'): WS_TYPE_UPDATE_CARD,
|
||||
vol.Required('card_id'): str,
|
||||
vol.Required('card_config'): vol.Any(str, dict),
|
||||
vol.Optional('format', default=FORMAT_YAML):
|
||||
vol.Any(FORMAT_JSON, FORMAT_YAML),
|
||||
})
|
||||
|
||||
SCHEMA_ADD_CARD = websocket_api.BASE_COMMAND_MESSAGE_SCHEMA.extend({
|
||||
vol.Required('type'): WS_TYPE_ADD_CARD,
|
||||
vol.Required('view_id'): str,
|
||||
vol.Required('card_config'): vol.Any(str, dict),
|
||||
vol.Optional('position'): int,
|
||||
vol.Optional('format', default=FORMAT_YAML):
|
||||
vol.Any(FORMAT_JSON, FORMAT_YAML),
|
||||
})
|
||||
|
||||
SCHEMA_MOVE_CARD = websocket_api.BASE_COMMAND_MESSAGE_SCHEMA.extend({
|
||||
vol.Required('type'): WS_TYPE_MOVE_CARD,
|
||||
vol.Required('card_id'): str,
|
||||
vol.Optional('new_position'): int,
|
||||
vol.Optional('new_view_id'): str,
|
||||
})
|
||||
|
||||
SCHEMA_DELETE_CARD = websocket_api.BASE_COMMAND_MESSAGE_SCHEMA.extend({
|
||||
vol.Required('type'): WS_TYPE_DELETE_CARD,
|
||||
vol.Required('card_id'): str,
|
||||
})
|
||||
|
||||
SCHEMA_GET_VIEW = websocket_api.BASE_COMMAND_MESSAGE_SCHEMA.extend({
|
||||
vol.Required('type'): WS_TYPE_GET_VIEW,
|
||||
vol.Required('view_id'): str,
|
||||
vol.Optional('format', default=FORMAT_YAML): vol.Any(FORMAT_JSON,
|
||||
FORMAT_YAML),
|
||||
})
|
||||
|
||||
SCHEMA_UPDATE_VIEW = websocket_api.BASE_COMMAND_MESSAGE_SCHEMA.extend({
|
||||
vol.Required('type'): WS_TYPE_UPDATE_VIEW,
|
||||
vol.Required('view_id'): str,
|
||||
vol.Required('view_config'): vol.Any(str, dict),
|
||||
vol.Optional('format', default=FORMAT_YAML): vol.Any(FORMAT_JSON,
|
||||
FORMAT_YAML),
|
||||
})
|
||||
|
||||
SCHEMA_ADD_VIEW = websocket_api.BASE_COMMAND_MESSAGE_SCHEMA.extend({
|
||||
vol.Required('type'): WS_TYPE_ADD_VIEW,
|
||||
vol.Required('view_config'): vol.Any(str, dict),
|
||||
vol.Optional('position'): int,
|
||||
vol.Optional('format', default=FORMAT_YAML): vol.Any(FORMAT_JSON,
|
||||
FORMAT_YAML),
|
||||
})
|
||||
|
||||
SCHEMA_MOVE_VIEW = websocket_api.BASE_COMMAND_MESSAGE_SCHEMA.extend({
|
||||
vol.Required('type'): WS_TYPE_MOVE_VIEW,
|
||||
vol.Required('view_id'): str,
|
||||
vol.Required('new_position'): int,
|
||||
})
|
||||
|
||||
SCHEMA_DELETE_VIEW = websocket_api.BASE_COMMAND_MESSAGE_SCHEMA.extend({
|
||||
vol.Required('type'): WS_TYPE_DELETE_VIEW,
|
||||
vol.Required('view_id'): str,
|
||||
})
|
||||
|
||||
|
||||
class CardNotFoundError(HomeAssistantError):
|
||||
"""Card not found in data."""
|
||||
|
||||
|
||||
class ViewNotFoundError(HomeAssistantError):
|
||||
"""View not found in data."""
|
||||
|
||||
|
||||
class DuplicateIdError(HomeAssistantError):
|
||||
"""Duplicate ID's."""
|
||||
|
||||
|
||||
def load_config(hass) -> JSON_TYPE:
|
||||
"""Load a YAML file."""
|
||||
fname = hass.config.path(LOVELACE_CONFIG_FILE)
|
||||
|
||||
# Check for a cached version of the config
|
||||
if LOVELACE_DATA in hass.data:
|
||||
config, last_update = hass.data[LOVELACE_DATA]
|
||||
modtime = os.path.getmtime(fname)
|
||||
if config and last_update > modtime:
|
||||
return config
|
||||
|
||||
config = yaml.load_yaml(fname, False)
|
||||
seen_card_ids = set()
|
||||
seen_view_ids = set()
|
||||
for view in config.get('views', []):
|
||||
view_id = view.get('id')
|
||||
if view_id:
|
||||
view_id = str(view_id)
|
||||
if view_id in seen_view_ids:
|
||||
raise DuplicateIdError(
|
||||
'ID `{}` has multiple occurances in views'.format(view_id))
|
||||
seen_view_ids.add(view_id)
|
||||
for card in view.get('cards', []):
|
||||
card_id = card.get('id')
|
||||
if card_id:
|
||||
card_id = str(card_id)
|
||||
if card_id in seen_card_ids:
|
||||
raise DuplicateIdError(
|
||||
'ID `{}` has multiple occurances in cards'
|
||||
.format(card_id))
|
||||
seen_card_ids.add(card_id)
|
||||
hass.data[LOVELACE_DATA] = (config, time.time())
|
||||
return config
|
||||
|
||||
|
||||
def migrate_config(fname: str) -> None:
|
||||
"""Add id to views and cards if not present and check duplicates."""
|
||||
config = yaml.load_yaml(fname, True)
|
||||
updated = False
|
||||
seen_card_ids = set()
|
||||
seen_view_ids = set()
|
||||
index = 0
|
||||
for view in config.get('views', []):
|
||||
view_id = str(view.get('id', ''))
|
||||
if not view_id:
|
||||
updated = True
|
||||
view.insert(0, 'id', index, comment="Automatically created id")
|
||||
else:
|
||||
if view_id in seen_view_ids:
|
||||
raise DuplicateIdError(
|
||||
'ID `{}` has multiple occurrences in views'.format(
|
||||
view_id))
|
||||
seen_view_ids.add(view_id)
|
||||
for card in view.get('cards', []):
|
||||
card_id = str(card.get('id', ''))
|
||||
if not card_id:
|
||||
updated = True
|
||||
card.insert(0, 'id', uuid.uuid4().hex,
|
||||
comment="Automatically created id")
|
||||
else:
|
||||
if card_id in seen_card_ids:
|
||||
raise DuplicateIdError(
|
||||
'ID `{}` has multiple occurrences in cards'
|
||||
.format(card_id))
|
||||
seen_card_ids.add(card_id)
|
||||
index += 1
|
||||
if updated:
|
||||
yaml.save_yaml(fname, config)
|
||||
|
||||
|
||||
def save_config(fname: str, config, data_format: str = FORMAT_JSON) -> None:
|
||||
"""Save config to file."""
|
||||
if data_format == FORMAT_YAML:
|
||||
config = yaml.yaml_to_object(config)
|
||||
yaml.save_yaml(fname, config)
|
||||
|
||||
|
||||
def get_card(fname: str, card_id: str, data_format: str = FORMAT_YAML)\
|
||||
-> JSON_TYPE:
|
||||
"""Load a specific card config for id."""
|
||||
round_trip = data_format == FORMAT_YAML
|
||||
|
||||
config = yaml.load_yaml(fname, round_trip)
|
||||
|
||||
for view in config.get('views', []):
|
||||
for card in view.get('cards', []):
|
||||
if str(card.get('id', '')) != card_id:
|
||||
continue
|
||||
if data_format == FORMAT_YAML:
|
||||
return yaml.object_to_yaml(card)
|
||||
return card
|
||||
|
||||
raise CardNotFoundError(
|
||||
"Card with ID: {} was not found in {}.".format(card_id, fname))
|
||||
|
||||
|
||||
def update_card(fname: str, card_id: str, card_config: str,
|
||||
data_format: str = FORMAT_YAML) -> None:
|
||||
"""Save a specific card config for id."""
|
||||
config = yaml.load_yaml(fname, True)
|
||||
for view in config.get('views', []):
|
||||
for card in view.get('cards', []):
|
||||
if str(card.get('id', '')) != card_id:
|
||||
continue
|
||||
if data_format == FORMAT_YAML:
|
||||
card_config = yaml.yaml_to_object(card_config)
|
||||
card.clear()
|
||||
card.update(card_config)
|
||||
yaml.save_yaml(fname, config)
|
||||
return
|
||||
|
||||
raise CardNotFoundError(
|
||||
"Card with ID: {} was not found in {}.".format(card_id, fname))
|
||||
|
||||
|
||||
def add_card(fname: str, view_id: str, card_config: str,
|
||||
position: int = None, data_format: str = FORMAT_YAML) -> None:
|
||||
"""Add a card to a view."""
|
||||
config = yaml.load_yaml(fname, True)
|
||||
for view in config.get('views', []):
|
||||
if str(view.get('id', '')) != view_id:
|
||||
continue
|
||||
cards = view.get('cards', [])
|
||||
if not cards and 'cards' in view:
|
||||
del view['cards']
|
||||
if data_format == FORMAT_YAML:
|
||||
card_config = yaml.yaml_to_object(card_config)
|
||||
if 'id' not in card_config:
|
||||
card_config['id'] = uuid.uuid4().hex
|
||||
if position is None:
|
||||
cards.append(card_config)
|
||||
else:
|
||||
cards.insert(position, card_config)
|
||||
if 'cards' not in view:
|
||||
view['cards'] = cards
|
||||
yaml.save_yaml(fname, config)
|
||||
return
|
||||
|
||||
raise ViewNotFoundError(
|
||||
"View with ID: {} was not found in {}.".format(view_id, fname))
|
||||
|
||||
|
||||
def move_card(fname: str, card_id: str, position: int = None) -> None:
|
||||
"""Move a card to a different position."""
|
||||
if position is None:
|
||||
raise HomeAssistantError(
|
||||
'Position is required if view is not specified.')
|
||||
config = yaml.load_yaml(fname, True)
|
||||
for view in config.get('views', []):
|
||||
for card in view.get('cards', []):
|
||||
if str(card.get('id', '')) != card_id:
|
||||
continue
|
||||
cards = view.get('cards')
|
||||
cards.insert(position, cards.pop(cards.index(card)))
|
||||
yaml.save_yaml(fname, config)
|
||||
return
|
||||
|
||||
raise CardNotFoundError(
|
||||
"Card with ID: {} was not found in {}.".format(card_id, fname))
|
||||
|
||||
|
||||
def move_card_view(fname: str, card_id: str, view_id: str,
|
||||
position: int = None) -> None:
|
||||
"""Move a card to a different view."""
|
||||
config = yaml.load_yaml(fname, True)
|
||||
for view in config.get('views', []):
|
||||
if str(view.get('id', '')) == view_id:
|
||||
destination = view.get('cards')
|
||||
for card in view.get('cards'):
|
||||
if str(card.get('id', '')) != card_id:
|
||||
continue
|
||||
origin = view.get('cards')
|
||||
card_to_move = card
|
||||
|
||||
if 'destination' not in locals():
|
||||
raise ViewNotFoundError(
|
||||
"View with ID: {} was not found in {}.".format(view_id, fname))
|
||||
if 'card_to_move' not in locals():
|
||||
raise CardNotFoundError(
|
||||
"Card with ID: {} was not found in {}.".format(card_id, fname))
|
||||
|
||||
origin.pop(origin.index(card_to_move))
|
||||
|
||||
if position is None:
|
||||
destination.append(card_to_move)
|
||||
else:
|
||||
destination.insert(position, card_to_move)
|
||||
|
||||
yaml.save_yaml(fname, config)
|
||||
|
||||
|
||||
def delete_card(fname: str, card_id: str) -> None:
|
||||
"""Delete a card from view."""
|
||||
config = yaml.load_yaml(fname, True)
|
||||
for view in config.get('views', []):
|
||||
for card in view.get('cards', []):
|
||||
if str(card.get('id', '')) != card_id:
|
||||
continue
|
||||
cards = view.get('cards')
|
||||
cards.pop(cards.index(card))
|
||||
yaml.save_yaml(fname, config)
|
||||
return
|
||||
|
||||
raise CardNotFoundError(
|
||||
"Card with ID: {} was not found in {}.".format(card_id, fname))
|
||||
|
||||
|
||||
def get_view(fname: str, view_id: str, data_format: str = FORMAT_YAML) -> None:
|
||||
"""Get view without it's cards."""
|
||||
round_trip = data_format == FORMAT_YAML
|
||||
config = yaml.load_yaml(fname, round_trip)
|
||||
found = None
|
||||
for view in config.get('views', []):
|
||||
if str(view.get('id', '')) == view_id:
|
||||
found = view
|
||||
break
|
||||
if found is None:
|
||||
raise ViewNotFoundError(
|
||||
"View with ID: {} was not found in {}.".format(view_id, fname))
|
||||
|
||||
del found['cards']
|
||||
if data_format == FORMAT_YAML:
|
||||
return yaml.object_to_yaml(found)
|
||||
return found
|
||||
|
||||
|
||||
def update_view(fname: str, view_id: str, view_config, data_format:
|
||||
str = FORMAT_YAML) -> None:
|
||||
"""Update view."""
|
||||
config = yaml.load_yaml(fname, True)
|
||||
found = None
|
||||
for view in config.get('views', []):
|
||||
if str(view.get('id', '')) == view_id:
|
||||
found = view
|
||||
break
|
||||
if found is None:
|
||||
raise ViewNotFoundError(
|
||||
"View with ID: {} was not found in {}.".format(view_id, fname))
|
||||
if data_format == FORMAT_YAML:
|
||||
view_config = yaml.yaml_to_object(view_config)
|
||||
if not view_config.get('cards') and found.get('cards'):
|
||||
view_config['cards'] = found.get('cards', [])
|
||||
if not view_config.get('badges') and found.get('badges'):
|
||||
view_config['badges'] = found.get('badges', [])
|
||||
found.clear()
|
||||
found.update(view_config)
|
||||
yaml.save_yaml(fname, config)
|
||||
|
||||
|
||||
def add_view(fname: str, view_config: str,
|
||||
position: int = None, data_format: str = FORMAT_YAML) -> None:
|
||||
"""Add a view."""
|
||||
config = yaml.load_yaml(fname, True)
|
||||
views = config.get('views', [])
|
||||
if data_format == FORMAT_YAML:
|
||||
view_config = yaml.yaml_to_object(view_config)
|
||||
if 'id' not in view_config:
|
||||
view_config['id'] = uuid.uuid4().hex
|
||||
if position is None:
|
||||
views.append(view_config)
|
||||
else:
|
||||
views.insert(position, view_config)
|
||||
if 'views' not in config:
|
||||
config['views'] = views
|
||||
yaml.save_yaml(fname, config)
|
||||
|
||||
|
||||
def move_view(fname: str, view_id: str, position: int) -> None:
|
||||
"""Move a view to a different position."""
|
||||
config = yaml.load_yaml(fname, True)
|
||||
views = config.get('views', [])
|
||||
found = None
|
||||
for view in views:
|
||||
if str(view.get('id', '')) == view_id:
|
||||
found = view
|
||||
break
|
||||
if found is None:
|
||||
raise ViewNotFoundError(
|
||||
"View with ID: {} was not found in {}.".format(view_id, fname))
|
||||
|
||||
views.insert(position, views.pop(views.index(found)))
|
||||
yaml.save_yaml(fname, config)
|
||||
|
||||
|
||||
def delete_view(fname: str, view_id: str) -> None:
|
||||
"""Delete a view."""
|
||||
config = yaml.load_yaml(fname, True)
|
||||
views = config.get('views', [])
|
||||
found = None
|
||||
for view in views:
|
||||
if str(view.get('id', '')) == view_id:
|
||||
found = view
|
||||
break
|
||||
if found is None:
|
||||
raise ViewNotFoundError(
|
||||
"View with ID: {} was not found in {}.".format(view_id, fname))
|
||||
|
||||
views.pop(views.index(found))
|
||||
yaml.save_yaml(fname, config)
|
||||
class ConfigNotFound(HomeAssistantError):
|
||||
"""When no config available."""
|
||||
|
||||
|
||||
async def async_setup(hass, config):
|
||||
"""Set up the Lovelace commands."""
|
||||
# Backwards compat. Added in 0.80. Remove after 0.85
|
||||
hass.components.websocket_api.async_register_command(
|
||||
OLD_WS_TYPE_GET_LOVELACE_UI, websocket_lovelace_config,
|
||||
SCHEMA_GET_LOVELACE_UI)
|
||||
# Pass in default to `get` because defaults not set if loaded as dep
|
||||
mode = config.get(DOMAIN, {}).get(CONF_MODE, MODE_STORAGE)
|
||||
|
||||
await hass.components.frontend.async_register_built_in_panel(
|
||||
DOMAIN, config={
|
||||
'mode': mode
|
||||
})
|
||||
|
||||
if mode == MODE_YAML:
|
||||
hass.data[DOMAIN] = LovelaceYAML(hass)
|
||||
else:
|
||||
hass.data[DOMAIN] = LovelaceStorage(hass)
|
||||
|
||||
hass.components.websocket_api.async_register_command(
|
||||
WS_TYPE_GET_LOVELACE_UI, websocket_lovelace_config,
|
||||
SCHEMA_GET_LOVELACE_UI)
|
||||
|
||||
hass.components.websocket_api.async_register_command(
|
||||
WS_TYPE_MIGRATE_CONFIG, websocket_lovelace_migrate_config,
|
||||
SCHEMA_MIGRATE_CONFIG)
|
||||
|
||||
hass.components.websocket_api.async_register_command(
|
||||
WS_TYPE_SAVE_CONFIG, websocket_lovelace_save_config,
|
||||
SCHEMA_SAVE_CONFIG)
|
||||
|
||||
hass.components.websocket_api.async_register_command(
|
||||
WS_TYPE_GET_CARD, websocket_lovelace_get_card, SCHEMA_GET_CARD)
|
||||
|
||||
hass.components.websocket_api.async_register_command(
|
||||
WS_TYPE_UPDATE_CARD, websocket_lovelace_update_card,
|
||||
SCHEMA_UPDATE_CARD)
|
||||
|
||||
hass.components.websocket_api.async_register_command(
|
||||
WS_TYPE_ADD_CARD, websocket_lovelace_add_card, SCHEMA_ADD_CARD)
|
||||
|
||||
hass.components.websocket_api.async_register_command(
|
||||
WS_TYPE_MOVE_CARD, websocket_lovelace_move_card, SCHEMA_MOVE_CARD)
|
||||
|
||||
hass.components.websocket_api.async_register_command(
|
||||
WS_TYPE_DELETE_CARD, websocket_lovelace_delete_card,
|
||||
SCHEMA_DELETE_CARD)
|
||||
|
||||
hass.components.websocket_api.async_register_command(
|
||||
WS_TYPE_GET_VIEW, websocket_lovelace_get_view, SCHEMA_GET_VIEW)
|
||||
|
||||
hass.components.websocket_api.async_register_command(
|
||||
WS_TYPE_UPDATE_VIEW, websocket_lovelace_update_view,
|
||||
SCHEMA_UPDATE_VIEW)
|
||||
|
||||
hass.components.websocket_api.async_register_command(
|
||||
WS_TYPE_ADD_VIEW, websocket_lovelace_add_view, SCHEMA_ADD_VIEW)
|
||||
|
||||
hass.components.websocket_api.async_register_command(
|
||||
WS_TYPE_MOVE_VIEW, websocket_lovelace_move_view, SCHEMA_MOVE_VIEW)
|
||||
|
||||
hass.components.websocket_api.async_register_command(
|
||||
WS_TYPE_DELETE_VIEW, websocket_lovelace_delete_view,
|
||||
SCHEMA_DELETE_VIEW)
|
||||
|
||||
return True
|
||||
|
||||
|
||||
class LovelaceStorage:
|
||||
"""Class to handle Storage based Lovelace config."""
|
||||
|
||||
def __init__(self, hass):
|
||||
"""Initialize Lovelace config based on storage helper."""
|
||||
self._store = hass.helpers.storage.Store(STORAGE_VERSION, STORAGE_KEY)
|
||||
self._data = None
|
||||
|
||||
async def async_load(self, force):
|
||||
"""Load config."""
|
||||
if self._data is None:
|
||||
data = await self._store.async_load()
|
||||
self._data = data if data else {'config': None}
|
||||
|
||||
config = self._data['config']
|
||||
|
||||
if config is None:
|
||||
raise ConfigNotFound
|
||||
|
||||
return config
|
||||
|
||||
async def async_save(self, config):
|
||||
"""Save config."""
|
||||
self._data['config'] = config
|
||||
await self._store.async_save(self._data)
|
||||
|
||||
|
||||
class LovelaceYAML:
|
||||
"""Class to handle YAML-based Lovelace config."""
|
||||
|
||||
def __init__(self, hass):
|
||||
"""Initialize the YAML config."""
|
||||
self.hass = hass
|
||||
self._cache = None
|
||||
|
||||
async def async_load(self, force):
|
||||
"""Load config."""
|
||||
return await self.hass.async_add_executor_job(self._load_config, force)
|
||||
|
||||
def _load_config(self, force):
|
||||
"""Load the actual config."""
|
||||
fname = self.hass.config.path(LOVELACE_CONFIG_FILE)
|
||||
# Check for a cached version of the config
|
||||
if not force and self._cache is not None:
|
||||
config, last_update = self._cache
|
||||
modtime = os.path.getmtime(fname)
|
||||
if config and last_update > modtime:
|
||||
return config
|
||||
|
||||
try:
|
||||
config = load_yaml(fname)
|
||||
except FileNotFoundError:
|
||||
raise ConfigNotFound from None
|
||||
|
||||
self._cache = (config, time.time())
|
||||
return config
|
||||
|
||||
async def async_save(self, config):
|
||||
"""Save config."""
|
||||
raise HomeAssistantError('Not supported')
|
||||
|
||||
|
||||
def handle_yaml_errors(func):
|
||||
"""Handle error with WebSocket calls."""
|
||||
@wraps(func)
|
||||
@@ -511,19 +150,8 @@ def handle_yaml_errors(func):
|
||||
message = websocket_api.result_message(
|
||||
msg['id'], result
|
||||
)
|
||||
except FileNotFoundError:
|
||||
error = ('file_not_found',
|
||||
'Could not find ui-lovelace.yaml in your config dir.')
|
||||
except yaml.UnsupportedYamlError as err:
|
||||
error = 'unsupported_error', str(err)
|
||||
except yaml.WriteError as err:
|
||||
error = 'write_error', str(err)
|
||||
except DuplicateIdError as err:
|
||||
error = 'duplicate_id', str(err)
|
||||
except CardNotFoundError as err:
|
||||
error = 'card_not_found', str(err)
|
||||
except ViewNotFoundError as err:
|
||||
error = 'view_not_found', str(err)
|
||||
except ConfigNotFound:
|
||||
error = 'config_not_found', 'No config found.'
|
||||
except HomeAssistantError as err:
|
||||
error = 'error', str(err)
|
||||
|
||||
@@ -539,116 +167,11 @@ def handle_yaml_errors(func):
|
||||
@handle_yaml_errors
|
||||
async def websocket_lovelace_config(hass, connection, msg):
|
||||
"""Send Lovelace UI config over WebSocket configuration."""
|
||||
return await hass.async_add_executor_job(load_config, hass)
|
||||
|
||||
|
||||
@websocket_api.async_response
|
||||
@handle_yaml_errors
|
||||
async def websocket_lovelace_migrate_config(hass, connection, msg):
|
||||
"""Migrate Lovelace UI configuration."""
|
||||
return await hass.async_add_executor_job(
|
||||
migrate_config, hass.config.path(LOVELACE_CONFIG_FILE))
|
||||
return await hass.data[DOMAIN].async_load(msg['force'])
|
||||
|
||||
|
||||
@websocket_api.async_response
|
||||
@handle_yaml_errors
|
||||
async def websocket_lovelace_save_config(hass, connection, msg):
|
||||
"""Save Lovelace UI configuration."""
|
||||
return await hass.async_add_executor_job(
|
||||
save_config, hass.config.path(LOVELACE_CONFIG_FILE), msg['config'],
|
||||
msg.get('format', FORMAT_JSON))
|
||||
|
||||
|
||||
@websocket_api.async_response
|
||||
@handle_yaml_errors
|
||||
async def websocket_lovelace_get_card(hass, connection, msg):
|
||||
"""Send Lovelace card config over WebSocket configuration."""
|
||||
return await hass.async_add_executor_job(
|
||||
get_card, hass.config.path(LOVELACE_CONFIG_FILE), msg['card_id'],
|
||||
msg.get('format', FORMAT_YAML))
|
||||
|
||||
|
||||
@websocket_api.async_response
|
||||
@handle_yaml_errors
|
||||
async def websocket_lovelace_update_card(hass, connection, msg):
|
||||
"""Receive Lovelace card configuration over WebSocket and save."""
|
||||
return await hass.async_add_executor_job(
|
||||
update_card, hass.config.path(LOVELACE_CONFIG_FILE),
|
||||
msg['card_id'], msg['card_config'], msg.get('format', FORMAT_YAML))
|
||||
|
||||
|
||||
@websocket_api.async_response
|
||||
@handle_yaml_errors
|
||||
async def websocket_lovelace_add_card(hass, connection, msg):
|
||||
"""Add new card to view over WebSocket and save."""
|
||||
return await hass.async_add_executor_job(
|
||||
add_card, hass.config.path(LOVELACE_CONFIG_FILE),
|
||||
msg['view_id'], msg['card_config'], msg.get('position'),
|
||||
msg.get('format', FORMAT_YAML))
|
||||
|
||||
|
||||
@websocket_api.async_response
|
||||
@handle_yaml_errors
|
||||
async def websocket_lovelace_move_card(hass, connection, msg):
|
||||
"""Move card to different position over WebSocket and save."""
|
||||
if 'new_view_id' in msg:
|
||||
return await hass.async_add_executor_job(
|
||||
move_card_view, hass.config.path(LOVELACE_CONFIG_FILE),
|
||||
msg['card_id'], msg['new_view_id'], msg.get('new_position'))
|
||||
|
||||
return await hass.async_add_executor_job(
|
||||
move_card, hass.config.path(LOVELACE_CONFIG_FILE),
|
||||
msg['card_id'], msg.get('new_position'))
|
||||
|
||||
|
||||
@websocket_api.async_response
|
||||
@handle_yaml_errors
|
||||
async def websocket_lovelace_delete_card(hass, connection, msg):
|
||||
"""Delete card from Lovelace over WebSocket and save."""
|
||||
return await hass.async_add_executor_job(
|
||||
delete_card, hass.config.path(LOVELACE_CONFIG_FILE), msg['card_id'])
|
||||
|
||||
|
||||
@websocket_api.async_response
|
||||
@handle_yaml_errors
|
||||
async def websocket_lovelace_get_view(hass, connection, msg):
|
||||
"""Send Lovelace view config over WebSocket config."""
|
||||
return await hass.async_add_executor_job(
|
||||
get_view, hass.config.path(LOVELACE_CONFIG_FILE), msg['view_id'],
|
||||
msg.get('format', FORMAT_YAML))
|
||||
|
||||
|
||||
@websocket_api.async_response
|
||||
@handle_yaml_errors
|
||||
async def websocket_lovelace_update_view(hass, connection, msg):
|
||||
"""Receive Lovelace card config over WebSocket and save."""
|
||||
return await hass.async_add_executor_job(
|
||||
update_view, hass.config.path(LOVELACE_CONFIG_FILE),
|
||||
msg['view_id'], msg['view_config'], msg.get('format', FORMAT_YAML))
|
||||
|
||||
|
||||
@websocket_api.async_response
|
||||
@handle_yaml_errors
|
||||
async def websocket_lovelace_add_view(hass, connection, msg):
|
||||
"""Add new view over WebSocket and save."""
|
||||
return await hass.async_add_executor_job(
|
||||
add_view, hass.config.path(LOVELACE_CONFIG_FILE),
|
||||
msg['view_config'], msg.get('position'),
|
||||
msg.get('format', FORMAT_YAML))
|
||||
|
||||
|
||||
@websocket_api.async_response
|
||||
@handle_yaml_errors
|
||||
async def websocket_lovelace_move_view(hass, connection, msg):
|
||||
"""Move view to different position over WebSocket and save."""
|
||||
return await hass.async_add_executor_job(
|
||||
move_view, hass.config.path(LOVELACE_CONFIG_FILE),
|
||||
msg['view_id'], msg['new_position'])
|
||||
|
||||
|
||||
@websocket_api.async_response
|
||||
@handle_yaml_errors
|
||||
async def websocket_lovelace_delete_view(hass, connection, msg):
|
||||
"""Delete card from Lovelace over WebSocket and save."""
|
||||
return await hass.async_add_executor_job(
|
||||
delete_view, hass.config.path(LOVELACE_CONFIG_FILE), msg['view_id'])
|
||||
await hass.data[DOMAIN].async_save(msg['config'])
|
||||
|
||||
@@ -18,7 +18,7 @@ from .config_flow import CONF_SECRET
|
||||
|
||||
DOMAIN = "owntracks"
|
||||
REQUIREMENTS = ['libnacl==1.6.1']
|
||||
DEPENDENCIES = ['device_tracker', 'webhook']
|
||||
DEPENDENCIES = ['webhook']
|
||||
|
||||
CONF_MAX_GPS_ACCURACY = 'max_gps_accuracy'
|
||||
CONF_WAYPOINT_IMPORT = 'waypoints'
|
||||
@@ -118,9 +118,18 @@ async def async_connect_mqtt(hass, component):
|
||||
|
||||
|
||||
async def handle_webhook(hass, webhook_id, request):
|
||||
"""Handle webhook callback."""
|
||||
"""Handle webhook callback.
|
||||
|
||||
iOS sets the "topic" as part of the payload.
|
||||
Android does not set a topic but adds headers to the request.
|
||||
"""
|
||||
context = hass.data[DOMAIN]['context']
|
||||
message = await request.json()
|
||||
|
||||
try:
|
||||
message = await request.json()
|
||||
except ValueError:
|
||||
_LOGGER.warning('Received invalid JSON from OwnTracks')
|
||||
return json_response([])
|
||||
|
||||
# Android doesn't populate topic
|
||||
if 'topic' not in message:
|
||||
@@ -128,15 +137,15 @@ async def handle_webhook(hass, webhook_id, request):
|
||||
user = headers.get('X-Limit-U')
|
||||
device = headers.get('X-Limit-D', user)
|
||||
|
||||
if user is None:
|
||||
_LOGGER.warning('Set a username in Connection -> Identification')
|
||||
return json_response(
|
||||
{'error': 'You need to supply username.'},
|
||||
status=400
|
||||
)
|
||||
if user:
|
||||
topic_base = re.sub('/#$', '', context.mqtt_topic)
|
||||
message['topic'] = '{}/{}/{}'.format(topic_base, user, device)
|
||||
|
||||
topic_base = re.sub('/#$', '', context.mqtt_topic)
|
||||
message['topic'] = '{}/{}/{}'.format(topic_base, user, device)
|
||||
elif message['_type'] != 'encrypted':
|
||||
_LOGGER.warning('No topic or user found in message. If on Android,'
|
||||
' set a username in Connection -> Identification')
|
||||
# Keep it as a 200 response so the incorrect packet is discarded
|
||||
return json_response([])
|
||||
|
||||
hass.helpers.dispatcher.async_dispatcher_send(
|
||||
DOMAIN, hass, context, message)
|
||||
|
||||
@@ -4,8 +4,11 @@ Support for Harmony Hub devices.
|
||||
For more details about this platform, please refer to the documentation at
|
||||
https://home-assistant.io/components/remote.harmony/
|
||||
"""
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import time
|
||||
from datetime import timedelta
|
||||
from pathlib import Path
|
||||
|
||||
import voluptuous as vol
|
||||
|
||||
@@ -19,11 +22,17 @@ import homeassistant.helpers.config_validation as cv
|
||||
from homeassistant.exceptions import PlatformNotReady
|
||||
from homeassistant.util import slugify
|
||||
|
||||
REQUIREMENTS = ['pyharmony==1.0.20']
|
||||
# REQUIREMENTS = ['pyharmony==1.0.22']
|
||||
REQUIREMENTS = [
|
||||
'https://github.com/home-assistant/pyharmony/archive/'
|
||||
'31efd339a3c39e7b8f58e823a0eddb59013e03ae.zip'
|
||||
'#pyharmony==1.0.21b1'
|
||||
]
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
DEFAULT_PORT = 5222
|
||||
DEFAULT_PORT = 8088
|
||||
SCAN_INTERVAL = timedelta(seconds=5)
|
||||
DEVICES = []
|
||||
CONF_DEVICE_CACHE = 'harmony_device_cache'
|
||||
|
||||
@@ -43,7 +52,8 @@ HARMONY_SYNC_SCHEMA = vol.Schema({
|
||||
})
|
||||
|
||||
|
||||
def setup_platform(hass, config, add_entities, discovery_info=None):
|
||||
async def async_setup_platform(hass, config, async_add_entities,
|
||||
discovery_info=None):
|
||||
"""Set up the Harmony platform."""
|
||||
host = None
|
||||
activity = None
|
||||
@@ -95,7 +105,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
|
||||
device = HarmonyRemote(
|
||||
name, address, port, activity, harmony_conf_file, delay_secs)
|
||||
DEVICES.append(device)
|
||||
add_entities([device])
|
||||
async_add_entities([device])
|
||||
register_services(hass)
|
||||
except (ValueError, AttributeError):
|
||||
raise PlatformNotReady
|
||||
@@ -103,12 +113,12 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
|
||||
|
||||
def register_services(hass):
|
||||
"""Register all services for harmony devices."""
|
||||
hass.services.register(
|
||||
hass.services.async_register(
|
||||
DOMAIN, SERVICE_SYNC, _sync_service,
|
||||
schema=HARMONY_SYNC_SCHEMA)
|
||||
|
||||
|
||||
def _apply_service(service, service_func, *service_func_args):
|
||||
async def _apply_service(service, service_func, *service_func_args):
|
||||
"""Handle services to apply."""
|
||||
entity_ids = service.data.get('entity_id')
|
||||
|
||||
@@ -119,12 +129,12 @@ def _apply_service(service, service_func, *service_func_args):
|
||||
_devices = DEVICES
|
||||
|
||||
for device in _devices:
|
||||
service_func(device, *service_func_args)
|
||||
await service_func(device, *service_func_args)
|
||||
device.schedule_update_ha_state(True)
|
||||
|
||||
|
||||
def _sync_service(service):
|
||||
_apply_service(service, HarmonyRemote.sync)
|
||||
async def _sync_service(service):
|
||||
await _apply_service(service, HarmonyRemote.sync)
|
||||
|
||||
|
||||
class HarmonyRemote(remote.RemoteDevice):
|
||||
@@ -132,8 +142,7 @@ class HarmonyRemote(remote.RemoteDevice):
|
||||
|
||||
def __init__(self, name, host, port, activity, out_path, delay_secs):
|
||||
"""Initialize HarmonyRemote class."""
|
||||
import pyharmony
|
||||
from pathlib import Path
|
||||
import pyharmony.client as harmony_client
|
||||
|
||||
_LOGGER.debug("HarmonyRemote device init started for: %s", name)
|
||||
self._name = name
|
||||
@@ -142,23 +151,30 @@ class HarmonyRemote(remote.RemoteDevice):
|
||||
self._state = None
|
||||
self._current_activity = None
|
||||
self._default_activity = activity
|
||||
self._client = pyharmony.get_client(host, port, self.new_activity)
|
||||
# self._client = pyharmony.get_client(host, port, self.new_activity)
|
||||
self._client = harmony_client.HarmonyClient(host)
|
||||
self._config_path = out_path
|
||||
self._config = self._client.get_config()
|
||||
if not Path(self._config_path).is_file():
|
||||
_LOGGER.debug("Writing harmony configuration to file: %s",
|
||||
out_path)
|
||||
pyharmony.ha_write_config_file(self._config, self._config_path)
|
||||
self._delay_secs = delay_secs
|
||||
_LOGGER.debug("HarmonyRemote device init completed for: %s", name)
|
||||
|
||||
async def async_added_to_hass(self):
|
||||
"""Complete the initialization."""
|
||||
self.hass.bus.async_listen_once(
|
||||
EVENT_HOMEASSISTANT_STOP,
|
||||
lambda event: self._client.disconnect(wait=True))
|
||||
_LOGGER.debug("HarmonyRemote added for: %s", self._name)
|
||||
|
||||
async def shutdown(event):
|
||||
"""Close connection on shutdown."""
|
||||
await self._client.disconnect()
|
||||
|
||||
self.hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, shutdown)
|
||||
|
||||
_LOGGER.debug("Connecting.")
|
||||
await self._client.connect()
|
||||
await self._client.get_config()
|
||||
if not Path(self._config_path).is_file():
|
||||
self.write_config_file()
|
||||
|
||||
# Poll for initial state
|
||||
self.new_activity(self._client.get_current_activity())
|
||||
self.new_activity(await self._client.get_current_activity())
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
@@ -168,7 +184,7 @@ class HarmonyRemote(remote.RemoteDevice):
|
||||
@property
|
||||
def should_poll(self):
|
||||
"""Return the fact that we should not be polled."""
|
||||
return False
|
||||
return True
|
||||
|
||||
@property
|
||||
def device_state_attributes(self):
|
||||
@@ -180,52 +196,101 @@ class HarmonyRemote(remote.RemoteDevice):
|
||||
"""Return False if PowerOff is the current activity, otherwise True."""
|
||||
return self._current_activity not in [None, 'PowerOff']
|
||||
|
||||
async def async_update(self):
|
||||
"""Retrieve current activity from Hub."""
|
||||
_LOGGER.debug("Updating Harmony.")
|
||||
if not self._client.config:
|
||||
await self._client.get_config()
|
||||
|
||||
activity_id = await self._client.get_current_activity()
|
||||
activity_name = self._client.get_activity_name(activity_id)
|
||||
_LOGGER.debug("%s activity reported as: %s", self._name, activity_name)
|
||||
self._current_activity = activity_name
|
||||
self._state = bool(self._current_activity != 'PowerOff')
|
||||
return
|
||||
|
||||
def new_activity(self, activity_id):
|
||||
"""Call for updating the current activity."""
|
||||
import pyharmony
|
||||
activity_name = pyharmony.activity_name(self._config, activity_id)
|
||||
activity_name = self._client.get_activity_name(activity_id)
|
||||
_LOGGER.debug("%s activity reported as: %s", self._name, activity_name)
|
||||
self._current_activity = activity_name
|
||||
self._state = bool(self._current_activity != 'PowerOff')
|
||||
self.schedule_update_ha_state()
|
||||
|
||||
def turn_on(self, **kwargs):
|
||||
async def async_turn_on(self, **kwargs):
|
||||
"""Start an activity from the Harmony device."""
|
||||
import pyharmony
|
||||
activity = kwargs.get(ATTR_ACTIVITY, self._default_activity)
|
||||
|
||||
if activity:
|
||||
activity_id = pyharmony.activity_id(self._config, activity)
|
||||
self._client.start_activity(activity_id)
|
||||
activity_id = None
|
||||
if activity.isdigit() or activity == '-1':
|
||||
_LOGGER.debug("Activity is numeric")
|
||||
if self._client.get_activity_name(int(activity)):
|
||||
activity_id = activity
|
||||
|
||||
if not activity_id:
|
||||
_LOGGER.debug("Find activity ID based on name")
|
||||
activity_id = self._client.get_activity_id(
|
||||
str(activity).strip())
|
||||
|
||||
if not activity_id:
|
||||
_LOGGER.error("Activity %s is invalid", activity)
|
||||
return
|
||||
|
||||
await self._client.start_activity(activity_id)
|
||||
self._state = True
|
||||
else:
|
||||
_LOGGER.error("No activity specified with turn_on service")
|
||||
|
||||
def turn_off(self, **kwargs):
|
||||
async def async_turn_off(self, **kwargs):
|
||||
"""Start the PowerOff activity."""
|
||||
self._client.power_off()
|
||||
await self._client.power_off()
|
||||
|
||||
# pylint: disable=arguments-differ
|
||||
def send_command(self, commands, **kwargs):
|
||||
async def async_send_command(self, command, **kwargs):
|
||||
"""Send a list of commands to one device."""
|
||||
device = kwargs.get(ATTR_DEVICE)
|
||||
if device is None:
|
||||
_LOGGER.error("Missing required argument: device")
|
||||
return
|
||||
|
||||
device_id = None
|
||||
if device.isdigit():
|
||||
_LOGGER.debug("Device is numeric")
|
||||
if self._client.get_device_name(int(device)):
|
||||
device_id = device
|
||||
|
||||
if not device_id:
|
||||
_LOGGER.debug("Find device ID based on device name")
|
||||
device_id = self._client.get_activity_id(str(device).strip())
|
||||
|
||||
if not device_id:
|
||||
_LOGGER.error("Device %s is invalid", device)
|
||||
return
|
||||
|
||||
num_repeats = kwargs.get(ATTR_NUM_REPEATS)
|
||||
delay_secs = kwargs.get(ATTR_DELAY_SECS, self._delay_secs)
|
||||
|
||||
for _ in range(num_repeats):
|
||||
for command in commands:
|
||||
self._client.send_command(device, command)
|
||||
time.sleep(delay_secs)
|
||||
for single_command in command:
|
||||
_LOGGER.debug("Sending command %s", single_command)
|
||||
await self._client.send_command(device, single_command)
|
||||
await asyncio.sleep(delay_secs)
|
||||
|
||||
def sync(self):
|
||||
async def sync(self):
|
||||
"""Sync the Harmony device with the web service."""
|
||||
import pyharmony
|
||||
_LOGGER.debug("Syncing hub with Harmony servers")
|
||||
self._client.sync()
|
||||
self._config = self._client.get_config()
|
||||
await self._client.sync()
|
||||
await self._client.get_config()
|
||||
await self.hass.async_add_executor_job(self.write_config_file)
|
||||
|
||||
def write_config_file(self):
|
||||
"""Write Harmony configuration file."""
|
||||
_LOGGER.debug("Writing hub config to file: %s", self._config_path)
|
||||
pyharmony.ha_write_config_file(self._config, self._config_path)
|
||||
try:
|
||||
with open(self._config_path, 'w+', encoding='utf-8') as file_out:
|
||||
json.dump(self._client.json_config, file_out,
|
||||
sort_keys=True, indent=4)
|
||||
except IOError as exc:
|
||||
_LOGGER.error("Unable to write HUB configuration to %s: %s",
|
||||
self._config_path, exc)
|
||||
|
||||
@@ -14,7 +14,7 @@ from homeassistant.const import (
|
||||
import homeassistant.helpers.config_validation as cv
|
||||
from homeassistant.helpers.entity import Entity
|
||||
|
||||
REQUIREMENTS = ['skybellpy==0.1.2']
|
||||
REQUIREMENTS = ['skybellpy==0.2.0']
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@ from homeassistant.const import (EVENT_HOMEASSISTANT_STOP, CONF_ACCESS_TOKEN,
|
||||
from homeassistant.helpers import discovery
|
||||
from homeassistant.helpers.aiohttp_client import async_get_clientsession
|
||||
|
||||
REQUIREMENTS = ['pyTibber==0.8.5']
|
||||
REQUIREMENTS = ['pyTibber==0.8.6']
|
||||
|
||||
DOMAIN = 'tibber'
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ For more details about this component, please refer to the documentation at
|
||||
https://home-assistant.io/components/tts.amazon_polly/
|
||||
"""
|
||||
import logging
|
||||
|
||||
import voluptuous as vol
|
||||
|
||||
from homeassistant.components.tts import Provider, PLATFORM_SCHEMA
|
||||
@@ -56,7 +57,7 @@ SUPPORTED_VOICES = [
|
||||
'Cristiano', 'Ines', # Portuguese, European
|
||||
'Carmen', # Romanian
|
||||
'Maxim', 'Tatyana', # Russian
|
||||
'Enrique', 'Conchita', 'Lucia' # Spanish European
|
||||
'Enrique', 'Conchita', 'Lucia', # Spanish European
|
||||
'Mia', # Spanish Mexican
|
||||
'Miguel', 'Penelope', # Spanish US
|
||||
'Astrid', # Swedish
|
||||
|
||||
@@ -100,6 +100,6 @@ class ZhaEntity(entity.Entity):
|
||||
'identifiers': {(DOMAIN, ieee)},
|
||||
'manufacturer': self._endpoint.manufacturer,
|
||||
'model': self._endpoint.model,
|
||||
'name': self._device_state_attributes['friendly_name'],
|
||||
'name': self._device_state_attributes.get('friendly_name', ieee),
|
||||
'via_hub': (DOMAIN, self.hass.data[DATA_ZHA][DATA_ZHA_BRIDGE_ID]),
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"""Constants used by Home Assistant components."""
|
||||
MAJOR_VERSION = 0
|
||||
MINOR_VERSION = 84
|
||||
PATCH_VERSION = '0b0'
|
||||
PATCH_VERSION = '5'
|
||||
__short_version__ = '{}.{}'.format(MAJOR_VERSION, MINOR_VERSION)
|
||||
__version__ = '{}.{}'.format(__short_version__, PATCH_VERSION)
|
||||
REQUIRED_PYTHON_VER = (3, 5, 3)
|
||||
|
||||
@@ -1098,9 +1098,11 @@ class ServiceRegistry:
|
||||
raise ServiceNotFound(domain, service) from None
|
||||
|
||||
if handler.schema:
|
||||
service_data = handler.schema(service_data)
|
||||
processed_data = handler.schema(service_data)
|
||||
else:
|
||||
processed_data = service_data
|
||||
|
||||
service_call = ServiceCall(domain, service, service_data, context)
|
||||
service_call = ServiceCall(domain, service, processed_data, context)
|
||||
|
||||
self._hass.bus.async_fire(EVENT_CALL_SERVICE, {
|
||||
ATTR_DOMAIN: domain.lower(),
|
||||
|
||||
@@ -297,7 +297,8 @@ class EntityPlatform:
|
||||
self.domain, self.platform_name, entity.unique_id,
|
||||
suggested_object_id=suggested_object_id,
|
||||
config_entry_id=config_entry_id,
|
||||
device_id=device_id)
|
||||
device_id=device_id,
|
||||
known_object_ids=self.entities.keys())
|
||||
|
||||
if entry.disabled:
|
||||
self.logger.info(
|
||||
|
||||
@@ -117,7 +117,7 @@ class EntityRegistry:
|
||||
@callback
|
||||
def async_get_or_create(self, domain, platform, unique_id, *,
|
||||
suggested_object_id=None, config_entry_id=None,
|
||||
device_id=None):
|
||||
device_id=None, known_object_ids=None):
|
||||
"""Get entity. Create if it doesn't exist."""
|
||||
entity_id = self.async_get_entity_id(domain, platform, unique_id)
|
||||
if entity_id:
|
||||
@@ -126,7 +126,8 @@ class EntityRegistry:
|
||||
device_id=device_id)
|
||||
|
||||
entity_id = self.async_generate_entity_id(
|
||||
domain, suggested_object_id or '{}_{}'.format(platform, unique_id))
|
||||
domain, suggested_object_id or '{}_{}'.format(platform, unique_id),
|
||||
known_object_ids)
|
||||
|
||||
entity = RegistryEntry(
|
||||
entity_id=entity_id,
|
||||
|
||||
@@ -87,7 +87,7 @@ abodepy==0.14.0
|
||||
afsapi==0.0.4
|
||||
|
||||
# homeassistant.components.asuswrt
|
||||
aioasuswrt==1.1.13
|
||||
aioasuswrt==1.1.15
|
||||
|
||||
# homeassistant.components.device_tracker.automatic
|
||||
aioautomatic==0.6.5
|
||||
@@ -112,7 +112,7 @@ aiohue==1.5.0
|
||||
aioimaplib==0.7.13
|
||||
|
||||
# homeassistant.components.lifx
|
||||
aiolifx==0.6.6
|
||||
aiolifx==0.6.7
|
||||
|
||||
# homeassistant.components.light.lifx
|
||||
aiolifx_effects==0.2.1
|
||||
@@ -493,7 +493,7 @@ hole==0.3.0
|
||||
holidays==0.9.8
|
||||
|
||||
# homeassistant.components.frontend
|
||||
home-assistant-frontend==20181205.0
|
||||
home-assistant-frontend==20181211.2
|
||||
|
||||
# homeassistant.components.zwave
|
||||
homeassistant-pyozw==0.1.1
|
||||
@@ -508,6 +508,9 @@ homematicip==0.9.8
|
||||
# homeassistant.components.remember_the_milk
|
||||
httplib2==0.10.3
|
||||
|
||||
# homeassistant.components.remote.harmony
|
||||
https://github.com/home-assistant/pyharmony/archive/31efd339a3c39e7b8f58e823a0eddb59013e03ae.zip#pyharmony==1.0.21b1
|
||||
|
||||
# homeassistant.components.huawei_lte
|
||||
huawei-lte-api==1.0.16
|
||||
|
||||
@@ -834,7 +837,7 @@ pyRFXtrx==0.23
|
||||
pySwitchmate==0.4.4
|
||||
|
||||
# homeassistant.components.tibber
|
||||
pyTibber==0.8.5
|
||||
pyTibber==0.8.6
|
||||
|
||||
# homeassistant.components.switch.dlink
|
||||
pyW215==0.6.0
|
||||
@@ -861,7 +864,7 @@ pyarlo==0.2.2
|
||||
pyatmo==1.4
|
||||
|
||||
# homeassistant.components.apple_tv
|
||||
pyatv==0.3.11
|
||||
pyatv==0.3.12
|
||||
|
||||
# homeassistant.components.device_tracker.bbox
|
||||
# homeassistant.components.sensor.bbox
|
||||
@@ -965,9 +968,6 @@ pygogogate2==0.1.1
|
||||
# homeassistant.components.sensor.gtfs
|
||||
pygtfs-homeassistant==0.1.3.dev0
|
||||
|
||||
# homeassistant.components.remote.harmony
|
||||
pyharmony==1.0.20
|
||||
|
||||
# homeassistant.components.sensor.version
|
||||
pyhaversion==2.0.3
|
||||
|
||||
@@ -1431,7 +1431,7 @@ simplisafe-python==3.1.14
|
||||
sisyphus-control==2.1
|
||||
|
||||
# homeassistant.components.skybell
|
||||
skybellpy==0.1.2
|
||||
skybellpy==0.2.0
|
||||
|
||||
# homeassistant.components.notify.slack
|
||||
slacker==0.11.0
|
||||
|
||||
@@ -101,7 +101,7 @@ hdate==0.7.5
|
||||
holidays==0.9.8
|
||||
|
||||
# homeassistant.components.frontend
|
||||
home-assistant-frontend==20181205.0
|
||||
home-assistant-frontend==20181211.2
|
||||
|
||||
# homeassistant.components.homematicip_cloud
|
||||
homematicip==0.9.8
|
||||
|
||||
@@ -209,7 +209,7 @@ def gather_modules():
|
||||
for req in module.REQUIREMENTS:
|
||||
if req in IGNORE_REQ:
|
||||
continue
|
||||
if '://' in req:
|
||||
if '://' in req and 'pyharmony' not in req:
|
||||
errors.append(
|
||||
"{}[Only pypi dependencies are allowed: {}]".format(
|
||||
package, req))
|
||||
|
||||
@@ -1354,6 +1354,25 @@ async def test_report_colored_light_state(hass):
|
||||
})
|
||||
|
||||
|
||||
async def test_report_colored_temp_light_state(hass):
|
||||
"""Test ColorTemperatureController reports color temp correctly."""
|
||||
hass.states.async_set(
|
||||
'light.test_on', 'on', {'friendly_name': "Test light On",
|
||||
'color_temp': 240,
|
||||
'supported_features': 2})
|
||||
hass.states.async_set(
|
||||
'light.test_off', 'off', {'friendly_name': "Test light Off",
|
||||
'supported_features': 2})
|
||||
|
||||
properties = await reported_properties(hass, 'light.test_on')
|
||||
properties.assert_equal('Alexa.ColorTemperatureController',
|
||||
'colorTemperatureInKelvin', 4166)
|
||||
|
||||
properties = await reported_properties(hass, 'light.test_off')
|
||||
properties.assert_equal('Alexa.ColorTemperatureController',
|
||||
'colorTemperatureInKelvin', 0)
|
||||
|
||||
|
||||
async def reported_properties(hass, endpoint):
|
||||
"""Use ReportState to get properties and return them.
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ def mock_cloudhooks(hass):
|
||||
cloud.iot = Mock(async_send_message=Mock(return_value=mock_coro()))
|
||||
cloud.cloudhook_create_url = 'https://webhook-create.url'
|
||||
cloud.prefs = prefs.CloudPreferences(hass)
|
||||
hass.loop.run_until_complete(cloud.prefs.async_initialize(True))
|
||||
hass.loop.run_until_complete(cloud.prefs.async_initialize())
|
||||
return cloudhooks.Cloudhooks(cloud)
|
||||
|
||||
|
||||
|
||||
@@ -411,7 +411,7 @@ async def test_refresh_token_expired(hass):
|
||||
async def test_webhook_msg(hass):
|
||||
"""Test webhook msg."""
|
||||
cloud = Cloud(hass, MODE_DEV, None, None)
|
||||
await cloud.prefs.async_initialize(True)
|
||||
await cloud.prefs.async_initialize()
|
||||
await cloud.prefs.async_update(cloudhooks={
|
||||
'hello': {
|
||||
'webhook_id': 'mock-webhook-id',
|
||||
|
||||
@@ -277,6 +277,8 @@ def setup_comp(hass):
|
||||
"""Initialize components."""
|
||||
mock_component(hass, 'group')
|
||||
mock_component(hass, 'zone')
|
||||
hass.loop.run_until_complete(async_setup_component(
|
||||
hass, 'device_tracker', {}))
|
||||
hass.loop.run_until_complete(async_mock_mqtt_component(hass))
|
||||
|
||||
hass.states.async_set(
|
||||
|
||||
@@ -62,7 +62,7 @@ def test_lock_value_changed(mock_openzwave):
|
||||
assert device.is_locked
|
||||
|
||||
|
||||
def test_lock_value_changed_workaround(mock_openzwave):
|
||||
def test_lock_state_workaround(mock_openzwave):
|
||||
"""Test value changed for Z-Wave lock using notification state."""
|
||||
node = MockNode(manufacturer_id='0090', product_id='0440')
|
||||
values = MockEntityValues(
|
||||
@@ -78,6 +78,50 @@ def test_lock_value_changed_workaround(mock_openzwave):
|
||||
assert not device.is_locked
|
||||
|
||||
|
||||
def test_track_message_workaround(mock_openzwave):
|
||||
"""Test value changed for Z-Wave lock by alarm-clearing workaround."""
|
||||
node = MockNode(manufacturer_id='003B', product_id='5044',
|
||||
stats={'lastReceivedMessage': [0] * 6})
|
||||
values = MockEntityValues(
|
||||
primary=MockValue(data=True, node=node),
|
||||
access_control=None,
|
||||
alarm_type=None,
|
||||
alarm_level=None,
|
||||
)
|
||||
|
||||
# Here we simulate an RF lock. The first zwave.get_device will call
|
||||
# update properties, simulating the first DoorLock report. We then trigger
|
||||
# a change, simulating the openzwave automatic refreshing behavior (which
|
||||
# is enabled for at least the lock that needs this workaround)
|
||||
node.stats['lastReceivedMessage'][5] = const.COMMAND_CLASS_DOOR_LOCK
|
||||
device = zwave.get_device(node=node, values=values)
|
||||
value_changed(values.primary)
|
||||
assert device.is_locked
|
||||
assert device.device_state_attributes[zwave.ATTR_NOTIFICATION] == 'RF Lock'
|
||||
|
||||
# Simulate a keypad unlock. We trigger a value_changed() which simulates
|
||||
# the Alarm notification received from the lock. Then, we trigger
|
||||
# value_changed() to simulate the automatic refreshing behavior.
|
||||
values.access_control = MockValue(data=6, node=node)
|
||||
values.alarm_type = MockValue(data=19, node=node)
|
||||
values.alarm_level = MockValue(data=3, node=node)
|
||||
node.stats['lastReceivedMessage'][5] = const.COMMAND_CLASS_ALARM
|
||||
value_changed(values.access_control)
|
||||
node.stats['lastReceivedMessage'][5] = const.COMMAND_CLASS_DOOR_LOCK
|
||||
values.primary.data = False
|
||||
value_changed(values.primary)
|
||||
assert not device.is_locked
|
||||
assert device.device_state_attributes[zwave.ATTR_LOCK_STATUS] == \
|
||||
'Unlocked with Keypad by user 3'
|
||||
|
||||
# Again, simulate an RF lock.
|
||||
device.lock()
|
||||
node.stats['lastReceivedMessage'][5] = const.COMMAND_CLASS_DOOR_LOCK
|
||||
value_changed(values.primary)
|
||||
assert device.is_locked
|
||||
assert device.device_state_attributes[zwave.ATTR_NOTIFICATION] == 'RF Lock'
|
||||
|
||||
|
||||
def test_v2btze_value_changed(mock_openzwave):
|
||||
"""Test value changed for v2btze Z-Wave lock."""
|
||||
node = MockNode(manufacturer_id='010e', product_id='0002')
|
||||
|
||||
@@ -1,748 +1,98 @@
|
||||
"""Test the Lovelace initialization."""
|
||||
from unittest.mock import patch
|
||||
from ruamel.yaml import YAML
|
||||
|
||||
from homeassistant.exceptions import HomeAssistantError
|
||||
from homeassistant.setup import async_setup_component
|
||||
from homeassistant.components.websocket_api.const import TYPE_RESULT
|
||||
from homeassistant.components.lovelace import migrate_config
|
||||
from homeassistant.util.ruamel_yaml import UnsupportedYamlError
|
||||
|
||||
TEST_YAML_A = """\
|
||||
title: My Awesome Home
|
||||
# Include external resources
|
||||
resources:
|
||||
- url: /local/my-custom-card.js
|
||||
type: js
|
||||
- url: /local/my-webfont.css
|
||||
type: css
|
||||
|
||||
# Exclude entities from "Unused entities" view
|
||||
excluded_entities:
|
||||
- weblink.router
|
||||
views:
|
||||
# View tab title.
|
||||
- title: Example
|
||||
# Optional unique id for direct access /lovelace/${id}
|
||||
id: example
|
||||
# Optional background (overwrites the global background).
|
||||
background: radial-gradient(crimson, skyblue)
|
||||
# Each view can have a different theme applied.
|
||||
theme: dark-mode
|
||||
# The cards to show on this view.
|
||||
cards:
|
||||
# The filter card will filter entities for their state
|
||||
- type: entity-filter
|
||||
entities:
|
||||
- device_tracker.paulus
|
||||
- device_tracker.anne_there
|
||||
state_filter:
|
||||
- 'home'
|
||||
card:
|
||||
type: glance
|
||||
title: People that are home
|
||||
|
||||
# The picture entity card will represent an entity with a picture
|
||||
- type: picture-entity
|
||||
image: https://www.home-assistant.io/images/default-social.png
|
||||
entity: light.bed_light
|
||||
|
||||
# Specify a tab icon if you want the view tab to be an icon.
|
||||
- icon: mdi:home-assistant
|
||||
# Title of the view. Will be used as the tooltip for tab icon
|
||||
title: Second view
|
||||
cards:
|
||||
- id: test
|
||||
type: entities
|
||||
title: Test card
|
||||
# Entities card will take a list of entities and show their state.
|
||||
- type: entities
|
||||
# Title of the entities card
|
||||
title: Example
|
||||
# The entities here will be shown in the same order as specified.
|
||||
# Each entry is an entity ID or a map with extra options.
|
||||
entities:
|
||||
- light.kitchen
|
||||
- switch.ac
|
||||
- entity: light.living_room
|
||||
# Override the name to use
|
||||
name: LR Lights
|
||||
|
||||
# The markdown card will render markdown text.
|
||||
- type: markdown
|
||||
title: Lovelace
|
||||
content: >
|
||||
Welcome to your **Lovelace UI**.
|
||||
"""
|
||||
|
||||
TEST_YAML_B = """\
|
||||
title: Home
|
||||
views:
|
||||
- title: Dashboard
|
||||
id: dashboard
|
||||
icon: mdi:home
|
||||
cards:
|
||||
- id: testid
|
||||
type: vertical-stack
|
||||
cards:
|
||||
- type: picture-entity
|
||||
entity: group.sample
|
||||
name: Sample
|
||||
image: /local/images/sample.jpg
|
||||
tap_action: toggle
|
||||
"""
|
||||
|
||||
# Test data that can not be loaded as YAML
|
||||
TEST_BAD_YAML = """\
|
||||
title: Home
|
||||
views:
|
||||
- title: Dashboard
|
||||
icon: mdi:home
|
||||
cards:
|
||||
- id: testid
|
||||
type: vertical-stack
|
||||
"""
|
||||
|
||||
# Test unsupported YAML
|
||||
TEST_UNSUP_YAML = """\
|
||||
title: Home
|
||||
views:
|
||||
- title: Dashboard
|
||||
icon: mdi:home
|
||||
cards: !include cards.yaml
|
||||
"""
|
||||
from homeassistant.components import frontend, lovelace
|
||||
|
||||
|
||||
def test_add_id():
|
||||
"""Test if id is added."""
|
||||
yaml = YAML(typ='rt')
|
||||
async def test_lovelace_from_storage(hass, hass_ws_client, hass_storage):
|
||||
"""Test we load lovelace config from storage."""
|
||||
assert await async_setup_component(hass, 'lovelace', {})
|
||||
assert hass.data[frontend.DATA_PANELS]['lovelace'].config == {
|
||||
'mode': 'storage'
|
||||
}
|
||||
|
||||
fname = "dummy.yaml"
|
||||
with patch('homeassistant.util.ruamel_yaml.load_yaml',
|
||||
return_value=yaml.load(TEST_YAML_A)), \
|
||||
patch('homeassistant.util.ruamel_yaml.save_yaml') \
|
||||
as save_yaml_mock:
|
||||
migrate_config(fname)
|
||||
|
||||
result = save_yaml_mock.call_args_list[0][0][1]
|
||||
assert 'id' in result['views'][0]['cards'][0]
|
||||
assert 'id' in result['views'][1]
|
||||
|
||||
|
||||
def test_id_not_changed():
|
||||
"""Test if id is not changed if already exists."""
|
||||
yaml = YAML(typ='rt')
|
||||
|
||||
fname = "dummy.yaml"
|
||||
with patch('homeassistant.util.ruamel_yaml.load_yaml',
|
||||
return_value=yaml.load(TEST_YAML_B)), \
|
||||
patch('homeassistant.util.ruamel_yaml.save_yaml') \
|
||||
as save_yaml_mock:
|
||||
migrate_config(fname)
|
||||
assert save_yaml_mock.call_count == 0
|
||||
|
||||
|
||||
async def test_deprecated_lovelace_ui(hass, hass_ws_client):
|
||||
"""Test lovelace_ui command."""
|
||||
await async_setup_component(hass, 'lovelace')
|
||||
client = await hass_ws_client(hass)
|
||||
|
||||
with patch('homeassistant.components.lovelace.load_config',
|
||||
return_value={'hello': 'world'}):
|
||||
await client.send_json({
|
||||
'id': 5,
|
||||
'type': 'frontend/lovelace_config',
|
||||
})
|
||||
msg = await client.receive_json()
|
||||
# Fetch data
|
||||
await client.send_json({
|
||||
'id': 5,
|
||||
'type': 'lovelace/config'
|
||||
})
|
||||
response = await client.receive_json()
|
||||
assert not response['success']
|
||||
assert response['error']['code'] == 'config_not_found'
|
||||
|
||||
assert msg['id'] == 5
|
||||
assert msg['type'] == TYPE_RESULT
|
||||
assert msg['success']
|
||||
assert msg['result'] == {'hello': 'world'}
|
||||
# Store new config
|
||||
await client.send_json({
|
||||
'id': 6,
|
||||
'type': 'lovelace/config/save',
|
||||
'config': {
|
||||
'yo': 'hello'
|
||||
}
|
||||
})
|
||||
response = await client.receive_json()
|
||||
assert response['success']
|
||||
assert hass_storage[lovelace.STORAGE_KEY]['data'] == {
|
||||
'config': {'yo': 'hello'}
|
||||
}
|
||||
|
||||
# Load new config
|
||||
await client.send_json({
|
||||
'id': 7,
|
||||
'type': 'lovelace/config'
|
||||
})
|
||||
response = await client.receive_json()
|
||||
assert response['success']
|
||||
|
||||
assert response['result'] == {
|
||||
'yo': 'hello'
|
||||
}
|
||||
|
||||
|
||||
async def test_deprecated_lovelace_ui_not_found(hass, hass_ws_client):
|
||||
"""Test lovelace_ui command cannot find file."""
|
||||
await async_setup_component(hass, 'lovelace')
|
||||
async def test_lovelace_from_yaml(hass, hass_ws_client):
|
||||
"""Test we load lovelace config from yaml."""
|
||||
assert await async_setup_component(hass, 'lovelace', {
|
||||
'lovelace': {
|
||||
'mode': 'YAML'
|
||||
}
|
||||
})
|
||||
assert hass.data[frontend.DATA_PANELS]['lovelace'].config == {
|
||||
'mode': 'yaml'
|
||||
}
|
||||
|
||||
client = await hass_ws_client(hass)
|
||||
|
||||
with patch('homeassistant.components.lovelace.load_config',
|
||||
side_effect=FileNotFoundError):
|
||||
# Fetch data
|
||||
await client.send_json({
|
||||
'id': 5,
|
||||
'type': 'lovelace/config'
|
||||
})
|
||||
response = await client.receive_json()
|
||||
assert not response['success']
|
||||
|
||||
assert response['error']['code'] == 'config_not_found'
|
||||
|
||||
# Store new config not allowed
|
||||
await client.send_json({
|
||||
'id': 6,
|
||||
'type': 'lovelace/config/save',
|
||||
'config': {
|
||||
'yo': 'hello'
|
||||
}
|
||||
})
|
||||
response = await client.receive_json()
|
||||
assert not response['success']
|
||||
|
||||
# Patch data
|
||||
with patch('homeassistant.components.lovelace.load_yaml', return_value={
|
||||
'hello': 'yo'
|
||||
}):
|
||||
await client.send_json({
|
||||
'id': 5,
|
||||
'type': 'frontend/lovelace_config',
|
||||
'id': 7,
|
||||
'type': 'lovelace/config'
|
||||
})
|
||||
msg = await client.receive_json()
|
||||
response = await client.receive_json()
|
||||
|
||||
assert msg['id'] == 5
|
||||
assert msg['type'] == TYPE_RESULT
|
||||
assert msg['success'] is False
|
||||
assert msg['error']['code'] == 'file_not_found'
|
||||
|
||||
|
||||
async def test_deprecated_lovelace_ui_load_err(hass, hass_ws_client):
|
||||
"""Test lovelace_ui command cannot find file."""
|
||||
await async_setup_component(hass, 'lovelace')
|
||||
client = await hass_ws_client(hass)
|
||||
|
||||
with patch('homeassistant.components.lovelace.load_config',
|
||||
side_effect=HomeAssistantError):
|
||||
await client.send_json({
|
||||
'id': 5,
|
||||
'type': 'frontend/lovelace_config',
|
||||
})
|
||||
msg = await client.receive_json()
|
||||
|
||||
assert msg['id'] == 5
|
||||
assert msg['type'] == TYPE_RESULT
|
||||
assert msg['success'] is False
|
||||
assert msg['error']['code'] == 'error'
|
||||
|
||||
|
||||
async def test_lovelace_ui(hass, hass_ws_client):
|
||||
"""Test lovelace_ui command."""
|
||||
await async_setup_component(hass, 'lovelace')
|
||||
client = await hass_ws_client(hass)
|
||||
|
||||
with patch('homeassistant.components.lovelace.load_config',
|
||||
return_value={'hello': 'world'}):
|
||||
await client.send_json({
|
||||
'id': 5,
|
||||
'type': 'lovelace/config',
|
||||
})
|
||||
msg = await client.receive_json()
|
||||
|
||||
assert msg['id'] == 5
|
||||
assert msg['type'] == TYPE_RESULT
|
||||
assert msg['success']
|
||||
assert msg['result'] == {'hello': 'world'}
|
||||
|
||||
|
||||
async def test_lovelace_ui_not_found(hass, hass_ws_client):
|
||||
"""Test lovelace_ui command cannot find file."""
|
||||
await async_setup_component(hass, 'lovelace')
|
||||
client = await hass_ws_client(hass)
|
||||
|
||||
with patch('homeassistant.components.lovelace.load_config',
|
||||
side_effect=FileNotFoundError):
|
||||
await client.send_json({
|
||||
'id': 5,
|
||||
'type': 'lovelace/config',
|
||||
})
|
||||
msg = await client.receive_json()
|
||||
|
||||
assert msg['id'] == 5
|
||||
assert msg['type'] == TYPE_RESULT
|
||||
assert msg['success'] is False
|
||||
assert msg['error']['code'] == 'file_not_found'
|
||||
|
||||
|
||||
async def test_lovelace_ui_load_err(hass, hass_ws_client):
|
||||
"""Test lovelace_ui command load error."""
|
||||
await async_setup_component(hass, 'lovelace')
|
||||
client = await hass_ws_client(hass)
|
||||
|
||||
with patch('homeassistant.components.lovelace.load_config',
|
||||
side_effect=HomeAssistantError):
|
||||
await client.send_json({
|
||||
'id': 5,
|
||||
'type': 'lovelace/config',
|
||||
})
|
||||
msg = await client.receive_json()
|
||||
|
||||
assert msg['id'] == 5
|
||||
assert msg['type'] == TYPE_RESULT
|
||||
assert msg['success'] is False
|
||||
assert msg['error']['code'] == 'error'
|
||||
|
||||
|
||||
async def test_lovelace_ui_load_json_err(hass, hass_ws_client):
|
||||
"""Test lovelace_ui command load error."""
|
||||
await async_setup_component(hass, 'lovelace')
|
||||
client = await hass_ws_client(hass)
|
||||
|
||||
with patch('homeassistant.components.lovelace.load_config',
|
||||
side_effect=UnsupportedYamlError):
|
||||
await client.send_json({
|
||||
'id': 5,
|
||||
'type': 'lovelace/config',
|
||||
})
|
||||
msg = await client.receive_json()
|
||||
|
||||
assert msg['id'] == 5
|
||||
assert msg['type'] == TYPE_RESULT
|
||||
assert msg['success'] is False
|
||||
assert msg['error']['code'] == 'unsupported_error'
|
||||
|
||||
|
||||
async def test_lovelace_get_card(hass, hass_ws_client):
|
||||
"""Test get_card command."""
|
||||
await async_setup_component(hass, 'lovelace')
|
||||
client = await hass_ws_client(hass)
|
||||
yaml = YAML(typ='rt')
|
||||
|
||||
with patch('homeassistant.util.ruamel_yaml.load_yaml',
|
||||
return_value=yaml.load(TEST_YAML_A)):
|
||||
await client.send_json({
|
||||
'id': 5,
|
||||
'type': 'lovelace/config/card/get',
|
||||
'card_id': 'test',
|
||||
})
|
||||
msg = await client.receive_json()
|
||||
|
||||
assert msg['id'] == 5
|
||||
assert msg['type'] == TYPE_RESULT
|
||||
assert msg['success']
|
||||
assert msg['result'] == 'id: test\ntype: entities\ntitle: Test card\n'
|
||||
|
||||
|
||||
async def test_lovelace_get_card_not_found(hass, hass_ws_client):
|
||||
"""Test get_card command cannot find card."""
|
||||
await async_setup_component(hass, 'lovelace')
|
||||
client = await hass_ws_client(hass)
|
||||
yaml = YAML(typ='rt')
|
||||
|
||||
with patch('homeassistant.util.ruamel_yaml.load_yaml',
|
||||
return_value=yaml.load(TEST_YAML_A)):
|
||||
await client.send_json({
|
||||
'id': 5,
|
||||
'type': 'lovelace/config/card/get',
|
||||
'card_id': 'not_found',
|
||||
})
|
||||
msg = await client.receive_json()
|
||||
|
||||
assert msg['id'] == 5
|
||||
assert msg['type'] == TYPE_RESULT
|
||||
assert msg['success'] is False
|
||||
assert msg['error']['code'] == 'card_not_found'
|
||||
|
||||
|
||||
async def test_lovelace_get_card_bad_yaml(hass, hass_ws_client):
|
||||
"""Test get_card command bad yaml."""
|
||||
await async_setup_component(hass, 'lovelace')
|
||||
client = await hass_ws_client(hass)
|
||||
|
||||
with patch('homeassistant.util.ruamel_yaml.load_yaml',
|
||||
side_effect=HomeAssistantError):
|
||||
await client.send_json({
|
||||
'id': 5,
|
||||
'type': 'lovelace/config/card/get',
|
||||
'card_id': 'testid',
|
||||
})
|
||||
msg = await client.receive_json()
|
||||
|
||||
assert msg['id'] == 5
|
||||
assert msg['type'] == TYPE_RESULT
|
||||
assert msg['success'] is False
|
||||
assert msg['error']['code'] == 'error'
|
||||
|
||||
|
||||
async def test_lovelace_update_card(hass, hass_ws_client):
|
||||
"""Test update_card command."""
|
||||
await async_setup_component(hass, 'lovelace')
|
||||
client = await hass_ws_client(hass)
|
||||
yaml = YAML(typ='rt')
|
||||
|
||||
with patch('homeassistant.util.ruamel_yaml.load_yaml',
|
||||
return_value=yaml.load(TEST_YAML_A)), \
|
||||
patch('homeassistant.util.ruamel_yaml.save_yaml') \
|
||||
as save_yaml_mock:
|
||||
await client.send_json({
|
||||
'id': 5,
|
||||
'type': 'lovelace/config/card/update',
|
||||
'card_id': 'test',
|
||||
'card_config': 'id: test\ntype: glance\n',
|
||||
})
|
||||
msg = await client.receive_json()
|
||||
|
||||
result = save_yaml_mock.call_args_list[0][0][1]
|
||||
assert result.mlget(['views', 1, 'cards', 0, 'type'],
|
||||
list_ok=True) == 'glance'
|
||||
assert msg['id'] == 5
|
||||
assert msg['type'] == TYPE_RESULT
|
||||
assert msg['success']
|
||||
|
||||
|
||||
async def test_lovelace_update_card_not_found(hass, hass_ws_client):
|
||||
"""Test update_card command cannot find card."""
|
||||
await async_setup_component(hass, 'lovelace')
|
||||
client = await hass_ws_client(hass)
|
||||
yaml = YAML(typ='rt')
|
||||
|
||||
with patch('homeassistant.util.ruamel_yaml.load_yaml',
|
||||
return_value=yaml.load(TEST_YAML_A)):
|
||||
await client.send_json({
|
||||
'id': 5,
|
||||
'type': 'lovelace/config/card/update',
|
||||
'card_id': 'not_found',
|
||||
'card_config': 'id: test\ntype: glance\n',
|
||||
})
|
||||
msg = await client.receive_json()
|
||||
|
||||
assert msg['id'] == 5
|
||||
assert msg['type'] == TYPE_RESULT
|
||||
assert msg['success'] is False
|
||||
assert msg['error']['code'] == 'card_not_found'
|
||||
|
||||
|
||||
async def test_lovelace_update_card_bad_yaml(hass, hass_ws_client):
|
||||
"""Test update_card command bad yaml."""
|
||||
await async_setup_component(hass, 'lovelace')
|
||||
client = await hass_ws_client(hass)
|
||||
yaml = YAML(typ='rt')
|
||||
|
||||
with patch('homeassistant.util.ruamel_yaml.load_yaml',
|
||||
return_value=yaml.load(TEST_YAML_A)), \
|
||||
patch('homeassistant.util.ruamel_yaml.yaml_to_object',
|
||||
side_effect=HomeAssistantError):
|
||||
await client.send_json({
|
||||
'id': 5,
|
||||
'type': 'lovelace/config/card/update',
|
||||
'card_id': 'test',
|
||||
'card_config': 'id: test\ntype: glance\n',
|
||||
})
|
||||
msg = await client.receive_json()
|
||||
|
||||
assert msg['id'] == 5
|
||||
assert msg['type'] == TYPE_RESULT
|
||||
assert msg['success'] is False
|
||||
assert msg['error']['code'] == 'error'
|
||||
|
||||
|
||||
async def test_lovelace_add_card(hass, hass_ws_client):
|
||||
"""Test add_card command."""
|
||||
await async_setup_component(hass, 'lovelace')
|
||||
client = await hass_ws_client(hass)
|
||||
yaml = YAML(typ='rt')
|
||||
|
||||
with patch('homeassistant.util.ruamel_yaml.load_yaml',
|
||||
return_value=yaml.load(TEST_YAML_A)), \
|
||||
patch('homeassistant.util.ruamel_yaml.save_yaml') \
|
||||
as save_yaml_mock:
|
||||
await client.send_json({
|
||||
'id': 5,
|
||||
'type': 'lovelace/config/card/add',
|
||||
'view_id': 'example',
|
||||
'card_config': 'id: test\ntype: added\n',
|
||||
})
|
||||
msg = await client.receive_json()
|
||||
|
||||
result = save_yaml_mock.call_args_list[0][0][1]
|
||||
assert result.mlget(['views', 0, 'cards', 2, 'type'],
|
||||
list_ok=True) == 'added'
|
||||
assert msg['id'] == 5
|
||||
assert msg['type'] == TYPE_RESULT
|
||||
assert msg['success']
|
||||
|
||||
|
||||
async def test_lovelace_add_card_position(hass, hass_ws_client):
|
||||
"""Test add_card command."""
|
||||
await async_setup_component(hass, 'lovelace')
|
||||
client = await hass_ws_client(hass)
|
||||
yaml = YAML(typ='rt')
|
||||
|
||||
with patch('homeassistant.util.ruamel_yaml.load_yaml',
|
||||
return_value=yaml.load(TEST_YAML_A)), \
|
||||
patch('homeassistant.util.ruamel_yaml.save_yaml') \
|
||||
as save_yaml_mock:
|
||||
await client.send_json({
|
||||
'id': 5,
|
||||
'type': 'lovelace/config/card/add',
|
||||
'view_id': 'example',
|
||||
'position': 0,
|
||||
'card_config': 'id: test\ntype: added\n',
|
||||
})
|
||||
msg = await client.receive_json()
|
||||
|
||||
result = save_yaml_mock.call_args_list[0][0][1]
|
||||
assert result.mlget(['views', 0, 'cards', 0, 'type'],
|
||||
list_ok=True) == 'added'
|
||||
assert msg['id'] == 5
|
||||
assert msg['type'] == TYPE_RESULT
|
||||
assert msg['success']
|
||||
|
||||
|
||||
async def test_lovelace_move_card_position(hass, hass_ws_client):
|
||||
"""Test move_card command."""
|
||||
await async_setup_component(hass, 'lovelace')
|
||||
client = await hass_ws_client(hass)
|
||||
yaml = YAML(typ='rt')
|
||||
|
||||
with patch('homeassistant.util.ruamel_yaml.load_yaml',
|
||||
return_value=yaml.load(TEST_YAML_A)), \
|
||||
patch('homeassistant.util.ruamel_yaml.save_yaml') \
|
||||
as save_yaml_mock:
|
||||
await client.send_json({
|
||||
'id': 5,
|
||||
'type': 'lovelace/config/card/move',
|
||||
'card_id': 'test',
|
||||
'new_position': 2,
|
||||
})
|
||||
msg = await client.receive_json()
|
||||
|
||||
result = save_yaml_mock.call_args_list[0][0][1]
|
||||
assert result.mlget(['views', 1, 'cards', 2, 'title'],
|
||||
list_ok=True) == 'Test card'
|
||||
assert msg['id'] == 5
|
||||
assert msg['type'] == TYPE_RESULT
|
||||
assert msg['success']
|
||||
|
||||
|
||||
async def test_lovelace_move_card_view(hass, hass_ws_client):
|
||||
"""Test move_card to view command."""
|
||||
await async_setup_component(hass, 'lovelace')
|
||||
client = await hass_ws_client(hass)
|
||||
yaml = YAML(typ='rt')
|
||||
|
||||
with patch('homeassistant.util.ruamel_yaml.load_yaml',
|
||||
return_value=yaml.load(TEST_YAML_A)), \
|
||||
patch('homeassistant.util.ruamel_yaml.save_yaml') \
|
||||
as save_yaml_mock:
|
||||
await client.send_json({
|
||||
'id': 5,
|
||||
'type': 'lovelace/config/card/move',
|
||||
'card_id': 'test',
|
||||
'new_view_id': 'example',
|
||||
})
|
||||
msg = await client.receive_json()
|
||||
|
||||
result = save_yaml_mock.call_args_list[0][0][1]
|
||||
assert result.mlget(['views', 0, 'cards', 2, 'title'],
|
||||
list_ok=True) == 'Test card'
|
||||
assert msg['id'] == 5
|
||||
assert msg['type'] == TYPE_RESULT
|
||||
assert msg['success']
|
||||
|
||||
|
||||
async def test_lovelace_move_card_view_position(hass, hass_ws_client):
|
||||
"""Test move_card to view with position command."""
|
||||
await async_setup_component(hass, 'lovelace')
|
||||
client = await hass_ws_client(hass)
|
||||
yaml = YAML(typ='rt')
|
||||
|
||||
with patch('homeassistant.util.ruamel_yaml.load_yaml',
|
||||
return_value=yaml.load(TEST_YAML_A)), \
|
||||
patch('homeassistant.util.ruamel_yaml.save_yaml') \
|
||||
as save_yaml_mock:
|
||||
await client.send_json({
|
||||
'id': 5,
|
||||
'type': 'lovelace/config/card/move',
|
||||
'card_id': 'test',
|
||||
'new_view_id': 'example',
|
||||
'new_position': 1,
|
||||
})
|
||||
msg = await client.receive_json()
|
||||
|
||||
result = save_yaml_mock.call_args_list[0][0][1]
|
||||
assert result.mlget(['views', 0, 'cards', 1, 'title'],
|
||||
list_ok=True) == 'Test card'
|
||||
assert msg['id'] == 5
|
||||
assert msg['type'] == TYPE_RESULT
|
||||
assert msg['success']
|
||||
|
||||
|
||||
async def test_lovelace_delete_card(hass, hass_ws_client):
|
||||
"""Test delete_card command."""
|
||||
await async_setup_component(hass, 'lovelace')
|
||||
client = await hass_ws_client(hass)
|
||||
yaml = YAML(typ='rt')
|
||||
|
||||
with patch('homeassistant.util.ruamel_yaml.load_yaml',
|
||||
return_value=yaml.load(TEST_YAML_A)), \
|
||||
patch('homeassistant.util.ruamel_yaml.save_yaml') \
|
||||
as save_yaml_mock:
|
||||
await client.send_json({
|
||||
'id': 5,
|
||||
'type': 'lovelace/config/card/delete',
|
||||
'card_id': 'test',
|
||||
})
|
||||
msg = await client.receive_json()
|
||||
|
||||
result = save_yaml_mock.call_args_list[0][0][1]
|
||||
cards = result.mlget(['views', 1, 'cards'], list_ok=True)
|
||||
assert len(cards) == 2
|
||||
assert cards[0]['title'] == 'Example'
|
||||
assert msg['id'] == 5
|
||||
assert msg['type'] == TYPE_RESULT
|
||||
assert msg['success']
|
||||
|
||||
|
||||
async def test_lovelace_get_view(hass, hass_ws_client):
|
||||
"""Test get_view command."""
|
||||
await async_setup_component(hass, 'lovelace')
|
||||
client = await hass_ws_client(hass)
|
||||
yaml = YAML(typ='rt')
|
||||
|
||||
with patch('homeassistant.util.ruamel_yaml.load_yaml',
|
||||
return_value=yaml.load(TEST_YAML_A)):
|
||||
await client.send_json({
|
||||
'id': 5,
|
||||
'type': 'lovelace/config/view/get',
|
||||
'view_id': 'example',
|
||||
})
|
||||
msg = await client.receive_json()
|
||||
|
||||
assert msg['id'] == 5
|
||||
assert msg['type'] == TYPE_RESULT
|
||||
assert msg['success']
|
||||
assert "".join(msg['result'].split()) == "".join('title: Example\n # \
|
||||
Optional unique id for direct\
|
||||
access /lovelace/${id}\nid: example\n # Optional\
|
||||
background (overwrites the global background).\n\
|
||||
background: radial-gradient(crimson, skyblue)\n\
|
||||
# Each view can have a different theme applied.\n\
|
||||
theme: dark-mode\n'.split())
|
||||
|
||||
|
||||
async def test_lovelace_get_view_not_found(hass, hass_ws_client):
|
||||
"""Test get_card command cannot find card."""
|
||||
await async_setup_component(hass, 'lovelace')
|
||||
client = await hass_ws_client(hass)
|
||||
yaml = YAML(typ='rt')
|
||||
|
||||
with patch('homeassistant.util.ruamel_yaml.load_yaml',
|
||||
return_value=yaml.load(TEST_YAML_A)):
|
||||
await client.send_json({
|
||||
'id': 5,
|
||||
'type': 'lovelace/config/view/get',
|
||||
'view_id': 'not_found',
|
||||
})
|
||||
msg = await client.receive_json()
|
||||
|
||||
assert msg['id'] == 5
|
||||
assert msg['type'] == TYPE_RESULT
|
||||
assert msg['success'] is False
|
||||
assert msg['error']['code'] == 'view_not_found'
|
||||
|
||||
|
||||
async def test_lovelace_update_view(hass, hass_ws_client):
|
||||
"""Test update_view command."""
|
||||
await async_setup_component(hass, 'lovelace')
|
||||
client = await hass_ws_client(hass)
|
||||
yaml = YAML(typ='rt')
|
||||
origyaml = yaml.load(TEST_YAML_A)
|
||||
|
||||
with patch('homeassistant.util.ruamel_yaml.load_yaml',
|
||||
return_value=origyaml), \
|
||||
patch('homeassistant.util.ruamel_yaml.save_yaml') \
|
||||
as save_yaml_mock:
|
||||
await client.send_json({
|
||||
'id': 5,
|
||||
'type': 'lovelace/config/view/update',
|
||||
'view_id': 'example',
|
||||
'view_config': 'id: example2\ntitle: New title\n',
|
||||
})
|
||||
msg = await client.receive_json()
|
||||
|
||||
result = save_yaml_mock.call_args_list[0][0][1]
|
||||
orig_view = origyaml.mlget(['views', 0], list_ok=True)
|
||||
new_view = result.mlget(['views', 0], list_ok=True)
|
||||
assert new_view['title'] == 'New title'
|
||||
assert new_view['cards'] == orig_view['cards']
|
||||
assert 'theme' not in new_view
|
||||
assert msg['id'] == 5
|
||||
assert msg['type'] == TYPE_RESULT
|
||||
assert msg['success']
|
||||
|
||||
|
||||
async def test_lovelace_add_view(hass, hass_ws_client):
|
||||
"""Test add_view command."""
|
||||
await async_setup_component(hass, 'lovelace')
|
||||
client = await hass_ws_client(hass)
|
||||
yaml = YAML(typ='rt')
|
||||
|
||||
with patch('homeassistant.util.ruamel_yaml.load_yaml',
|
||||
return_value=yaml.load(TEST_YAML_A)), \
|
||||
patch('homeassistant.util.ruamel_yaml.save_yaml') \
|
||||
as save_yaml_mock:
|
||||
await client.send_json({
|
||||
'id': 5,
|
||||
'type': 'lovelace/config/view/add',
|
||||
'view_config': 'id: test\ntitle: added\n',
|
||||
})
|
||||
msg = await client.receive_json()
|
||||
|
||||
result = save_yaml_mock.call_args_list[0][0][1]
|
||||
assert result.mlget(['views', 2, 'title'],
|
||||
list_ok=True) == 'added'
|
||||
assert msg['id'] == 5
|
||||
assert msg['type'] == TYPE_RESULT
|
||||
assert msg['success']
|
||||
|
||||
|
||||
async def test_lovelace_add_view_position(hass, hass_ws_client):
|
||||
"""Test add_view command with position."""
|
||||
await async_setup_component(hass, 'lovelace')
|
||||
client = await hass_ws_client(hass)
|
||||
yaml = YAML(typ='rt')
|
||||
|
||||
with patch('homeassistant.util.ruamel_yaml.load_yaml',
|
||||
return_value=yaml.load(TEST_YAML_A)), \
|
||||
patch('homeassistant.util.ruamel_yaml.save_yaml') \
|
||||
as save_yaml_mock:
|
||||
await client.send_json({
|
||||
'id': 5,
|
||||
'type': 'lovelace/config/view/add',
|
||||
'position': 0,
|
||||
'view_config': 'id: test\ntitle: added\n',
|
||||
})
|
||||
msg = await client.receive_json()
|
||||
|
||||
result = save_yaml_mock.call_args_list[0][0][1]
|
||||
assert result.mlget(['views', 0, 'title'],
|
||||
list_ok=True) == 'added'
|
||||
assert msg['id'] == 5
|
||||
assert msg['type'] == TYPE_RESULT
|
||||
assert msg['success']
|
||||
|
||||
|
||||
async def test_lovelace_move_view_position(hass, hass_ws_client):
|
||||
"""Test move_view command."""
|
||||
await async_setup_component(hass, 'lovelace')
|
||||
client = await hass_ws_client(hass)
|
||||
yaml = YAML(typ='rt')
|
||||
|
||||
with patch('homeassistant.util.ruamel_yaml.load_yaml',
|
||||
return_value=yaml.load(TEST_YAML_A)), \
|
||||
patch('homeassistant.util.ruamel_yaml.save_yaml') \
|
||||
as save_yaml_mock:
|
||||
await client.send_json({
|
||||
'id': 5,
|
||||
'type': 'lovelace/config/view/move',
|
||||
'view_id': 'example',
|
||||
'new_position': 1,
|
||||
})
|
||||
msg = await client.receive_json()
|
||||
|
||||
result = save_yaml_mock.call_args_list[0][0][1]
|
||||
assert result.mlget(['views', 1, 'title'],
|
||||
list_ok=True) == 'Example'
|
||||
assert msg['id'] == 5
|
||||
assert msg['type'] == TYPE_RESULT
|
||||
assert msg['success']
|
||||
|
||||
|
||||
async def test_lovelace_delete_view(hass, hass_ws_client):
|
||||
"""Test delete_card command."""
|
||||
await async_setup_component(hass, 'lovelace')
|
||||
client = await hass_ws_client(hass)
|
||||
yaml = YAML(typ='rt')
|
||||
|
||||
with patch('homeassistant.util.ruamel_yaml.load_yaml',
|
||||
return_value=yaml.load(TEST_YAML_A)), \
|
||||
patch('homeassistant.util.ruamel_yaml.save_yaml') \
|
||||
as save_yaml_mock:
|
||||
await client.send_json({
|
||||
'id': 5,
|
||||
'type': 'lovelace/config/view/delete',
|
||||
'view_id': 'example',
|
||||
})
|
||||
msg = await client.receive_json()
|
||||
|
||||
result = save_yaml_mock.call_args_list[0][0][1]
|
||||
views = result.get('views', [])
|
||||
assert len(views) == 1
|
||||
assert views[0]['title'] == 'Second view'
|
||||
assert msg['id'] == 5
|
||||
assert msg['type'] == TYPE_RESULT
|
||||
assert msg['success']
|
||||
assert response['success']
|
||||
assert response['result'] == {'hello': 'yo'}
|
||||
|
||||
@@ -110,7 +110,7 @@ def test_handle_value_error(mock_client):
|
||||
|
||||
|
||||
@asyncio.coroutine
|
||||
def test_returns_error_missing_username(mock_client):
|
||||
def test_returns_error_missing_username(mock_client, caplog):
|
||||
"""Test that an error is returned when username is missing."""
|
||||
resp = yield from mock_client.post(
|
||||
'/api/webhook/owntracks_test',
|
||||
@@ -120,10 +120,29 @@ def test_returns_error_missing_username(mock_client):
|
||||
}
|
||||
)
|
||||
|
||||
assert resp.status == 400
|
||||
|
||||
# Needs to be 200 or OwnTracks keeps retrying bad packet.
|
||||
assert resp.status == 200
|
||||
json = yield from resp.json()
|
||||
assert json == {'error': 'You need to supply username.'}
|
||||
assert json == []
|
||||
assert 'No topic or user found' in caplog.text
|
||||
|
||||
|
||||
@asyncio.coroutine
|
||||
def test_returns_error_incorrect_json(mock_client, caplog):
|
||||
"""Test that an error is returned when username is missing."""
|
||||
resp = yield from mock_client.post(
|
||||
'/api/webhook/owntracks_test',
|
||||
data='not json',
|
||||
headers={
|
||||
'X-Limit-d': 'Pixel',
|
||||
}
|
||||
)
|
||||
|
||||
# Needs to be 200 or OwnTracks keeps retrying bad packet.
|
||||
assert resp.status == 200
|
||||
json = yield from resp.json()
|
||||
assert json == []
|
||||
assert 'invalid JSON' in caplog.text
|
||||
|
||||
|
||||
@asyncio.coroutine
|
||||
|
||||
@@ -265,22 +265,50 @@ class TestComponentLogbook(unittest.TestCase):
|
||||
def test_exclude_automation_events(self):
|
||||
"""Test if automation entries can be excluded by entity_id."""
|
||||
name = 'My Automation Rule'
|
||||
message = 'has been triggered'
|
||||
domain = 'automation'
|
||||
entity_id = 'automation.my_automation_rule'
|
||||
entity_id2 = 'automation.my_automation_rule_2'
|
||||
entity_id2 = 'sensor.blu'
|
||||
|
||||
eventA = ha.Event(logbook.EVENT_LOGBOOK_ENTRY, {
|
||||
eventA = ha.Event(logbook.EVENT_AUTOMATION_TRIGGERED, {
|
||||
logbook.ATTR_NAME: name,
|
||||
logbook.ATTR_MESSAGE: message,
|
||||
logbook.ATTR_DOMAIN: domain,
|
||||
logbook.ATTR_ENTITY_ID: entity_id,
|
||||
})
|
||||
eventB = ha.Event(logbook.EVENT_LOGBOOK_ENTRY, {
|
||||
eventB = ha.Event(logbook.EVENT_AUTOMATION_TRIGGERED, {
|
||||
logbook.ATTR_NAME: name,
|
||||
logbook.ATTR_ENTITY_ID: entity_id2,
|
||||
})
|
||||
|
||||
config = logbook.CONFIG_SCHEMA({
|
||||
ha.DOMAIN: {},
|
||||
logbook.DOMAIN: {logbook.CONF_EXCLUDE: {
|
||||
logbook.CONF_ENTITIES: [entity_id, ]}}})
|
||||
events = logbook._exclude_events(
|
||||
(ha.Event(EVENT_HOMEASSISTANT_STOP), eventA, eventB),
|
||||
logbook._generate_filter_from_config(config[logbook.DOMAIN]))
|
||||
entries = list(logbook.humanify(self.hass, events))
|
||||
|
||||
assert 2 == len(entries)
|
||||
self.assert_entry(
|
||||
entries[0], name='Home Assistant', message='stopped',
|
||||
domain=ha.DOMAIN)
|
||||
self.assert_entry(
|
||||
entries[1], name=name, domain=domain, entity_id=entity_id2)
|
||||
|
||||
def test_exclude_script_events(self):
|
||||
"""Test if script start can be excluded by entity_id."""
|
||||
name = 'My Script Rule'
|
||||
domain = 'script'
|
||||
entity_id = 'script.my_script'
|
||||
entity_id2 = 'script.my_script_2'
|
||||
entity_id2 = 'sensor.blu'
|
||||
|
||||
eventA = ha.Event(logbook.EVENT_SCRIPT_STARTED, {
|
||||
logbook.ATTR_NAME: name,
|
||||
logbook.ATTR_ENTITY_ID: entity_id,
|
||||
})
|
||||
eventB = ha.Event(logbook.EVENT_SCRIPT_STARTED, {
|
||||
logbook.ATTR_NAME: name,
|
||||
logbook.ATTR_MESSAGE: message,
|
||||
logbook.ATTR_DOMAIN: domain,
|
||||
logbook.ATTR_ENTITY_ID: entity_id2,
|
||||
})
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ from unittest.mock import patch, MagicMock
|
||||
from datetime import datetime, timedelta
|
||||
from tempfile import TemporaryDirectory
|
||||
|
||||
import voluptuous as vol
|
||||
import pytz
|
||||
import pytest
|
||||
|
||||
@@ -21,7 +22,7 @@ from homeassistant.const import (
|
||||
__version__, EVENT_STATE_CHANGED, ATTR_FRIENDLY_NAME, CONF_UNIT_SYSTEM,
|
||||
ATTR_NOW, EVENT_TIME_CHANGED, EVENT_TIMER_OUT_OF_SYNC, ATTR_SECONDS,
|
||||
EVENT_HOMEASSISTANT_STOP, EVENT_HOMEASSISTANT_CLOSE,
|
||||
EVENT_SERVICE_REGISTERED, EVENT_SERVICE_REMOVED)
|
||||
EVENT_SERVICE_REGISTERED, EVENT_SERVICE_REMOVED, EVENT_CALL_SERVICE)
|
||||
|
||||
from tests.common import get_test_home_assistant, async_mock_service
|
||||
|
||||
@@ -1000,3 +1001,27 @@ async def test_service_executed_with_subservices(hass):
|
||||
assert len(calls) == 4
|
||||
assert [call.service for call in calls] == [
|
||||
'outer', 'inner', 'inner', 'outer']
|
||||
|
||||
|
||||
async def test_service_call_event_contains_original_data(hass):
|
||||
"""Test that service call event contains original data."""
|
||||
events = []
|
||||
|
||||
@ha.callback
|
||||
def callback(event):
|
||||
events.append(event)
|
||||
|
||||
hass.bus.async_listen(EVENT_CALL_SERVICE, callback)
|
||||
|
||||
calls = async_mock_service(hass, 'test', 'service', vol.Schema({
|
||||
'number': vol.Coerce(int)
|
||||
}))
|
||||
|
||||
await hass.services.async_call('test', 'service', {
|
||||
'number': '23'
|
||||
}, blocking=True)
|
||||
await hass.async_block_till_done()
|
||||
assert len(events) == 1
|
||||
assert events[0].data['service_data']['number'] == '23'
|
||||
assert len(calls) == 1
|
||||
assert calls[0].data['number'] == 23
|
||||
|
||||
Reference in New Issue
Block a user