Skip to content

Commit

Permalink
Retroactive review changes for #443
Browse files Browse the repository at this point in the history
  • Loading branch information
basnijholt committed Mar 27, 2023
1 parent 6974e9c commit 0e4410c
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 64 deletions.
86 changes: 45 additions & 41 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -132,12 +132,12 @@ adaptive_lighting:

`adaptive_lighting.change_switch_settings` (new in 1.7.0) Change any of the above configuration options of Adaptive Lighting (such as `sunrise_time` or `prefer_rgb_color`) with a service call directly from your script/automation.

| DISALLOWED service data | Description |
| ------------------------- | --------------------------------------------------------------------------------------------------- |
| `entity_id` | You cannot change the switch's unique_id, it's already been registered |
| `lights` | See above, you may call adaptive_lighting.apply() with your lights or create a new config instead |
| `name` | See above. You can already rename your switch's display name in Home Assistant's UI. |
| `interval` | Nope. The interval is only used once when the config loads. A config change and restart is required |
| DISALLOWED service data | Description |
| ----------------------- | --------------------------------------------------------------------------------------------------- |
| `entity_id` | You cannot change the switch's unique_id, it's already been registered |
| `lights` | See above, you may call adaptive_lighting.apply() with your lights or create a new config instead |
| `name` | See above. You can already rename your switch's display name in Home Assistant's UI. |
| `interval` | Nope. The interval is only used once when the config loads. A config change and restart is required |

## Automation examples

Expand Down Expand Up @@ -186,42 +186,46 @@ Set your sunrise and sunset time based on your alarm. The below script sets suns
iphone_carly_wakeup:
alias: iPhone Carly Wakeup
sequence:
- condition: state
entity_id: input_boolean.carly_iphone_wakeup
state: 'off'
- service: input_datetime.set_datetime
target:
entity_id: input_datetime.carly_iphone_wakeup
data:
time: '{{ now().strftime("%H:%M:%S") }}'
- service: input_boolean.turn_on
target:
- condition: state
entity_id: input_boolean.carly_iphone_wakeup
- repeat:
count: '{{ (states.switch | map(attribute=''entity_id'') | select(">","switch.adaptive_lighting_al_") |
select("<", "switch.adaptive_lighting_al_z") | join(",")).split(",")|length
}}'
sequence:
- service: adaptive_lighting.change_switch_settings
data:
entity_id: switch.adaptive_lighting_al_den_ceilingfan_lights
sunrise_time: '{{ now().strftime("%H:%M:%S") }}'
sunset_time: '{{ (as_timestamp(now()) + 12*60*60) | timestamp_custom("%H:%M:%S")
}}'
- service: script.turn_on
target:
entity_id: script.run_wakeup_routine
- service: input_boolean.turn_off
target:
entity_id:
- input_boolean.carly_iphone_winddown
- input_boolean.carly_iphone_bedtime
- service: input_datetime.set_datetime
target:
entity_id: input_datetime.wakeup_time
data:
time: '{{ now().strftime("%H:%M:%S") }}'
- service: script.adaptive_lighting_disable_sleep_mode
state: "off"
- service: input_datetime.set_datetime
target:
entity_id: input_datetime.carly_iphone_wakeup
data:
time: '{{ now().strftime("%H:%M:%S") }}'
- service: input_boolean.turn_on
target:
entity_id: input_boolean.carly_iphone_wakeup
- repeat:
count: >
{{ (states.switch
| map(attribute="entity_id")
| select(">","switch.adaptive_lighting_al_")
| select("<", "switch.adaptive_lighting_al_z")
| join(",")
).split(",") | length }}
sequence:
- service: adaptive_lighting.change_switch_settings
data:
entity_id: switch.adaptive_lighting_al_den_ceilingfan_lights
sunrise_time: '{{ now().strftime("%H:%M:%S") }}'
sunset_time: >
{{ (as_timestamp(now()) + 12*60*60) | timestamp_custom("%H:%M:%S") }}
- service: script.turn_on
target:
entity_id: script.run_wakeup_routine
- service: input_boolean.turn_off
target:
entity_id:
- input_boolean.carly_iphone_winddown
- input_boolean.carly_iphone_bedtime
- service: input_datetime.set_datetime
target:
entity_id: input_datetime.wakeup_time
data:
time: '{{ now().strftime("%H:%M:%S") }}'
- service: script.adaptive_lighting_disable_sleep_mode
mode: queued
icon: mdi:weather-sunset
max: 10
Expand Down
3 changes: 0 additions & 3 deletions custom_components/adaptive_lighting/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,6 @@ async def async_setup(hass: HomeAssistant, config: dict[str, Any]):
# This will reload any changes the user made to any YAML configurations.
await async_setup_reload_service(hass, DOMAIN, PLATFORMS)

# quickly populate data for change_switch_settings before actually loading integration.
# update_services_yaml()

if DOMAIN in config:
for entry in config[DOMAIN]:
hass.async_create_task(
Expand Down
30 changes: 10 additions & 20 deletions custom_components/adaptive_lighting/switch.py
Original file line number Diff line number Diff line change
Expand Up @@ -365,12 +365,10 @@ async def handle_change_switch_settings(
which = data.get(CONF_USE_DEFAULTS, "current")
if which == "current": # use whatever we're already using.
defaults = switch._current_settings # pylint: disable=protected-access
# not needed since validate() does this part for us
elif which == "factory": # use actual defaults listed in the documentation
defaults = {key: default for key, default, _ in VALIDATION_TUPLES}
elif (
which == "configuration"
): # use whatever's in the config flow or configuration.yaml
elif which == "configuration":
# use whatever's in the config flow or configuration.yaml
defaults = switch._config_backup # pylint: disable=protected-access
else:
defaults = None
Expand All @@ -387,15 +385,13 @@ async def handle_change_switch_settings(

all_lights = switch._lights # pylint: disable=protected-access
switch.turn_on_off_listener.reset(*all_lights, reset_manual_control=False)
# pylint: disable=protected-access
if switch.is_on:
await switch._update_attrs_and_maybe_adapt_lights(
await switch._update_attrs_and_maybe_adapt_lights( # pylint: disable=protected-access
all_lights,
transition=switch._initial_transition,
force=True,
context=switch.create_context("service", parent=service_call.context),
)
# pylint: enable=protected-access


@callback
Expand Down Expand Up @@ -557,8 +553,8 @@ async def handle_set_manual_control(service_call: ServiceCall):

args = {vol.Optional(CONF_USE_DEFAULTS, default="current"): cv.string}
for k, _, valid in VALIDATION_TUPLES:
# Modifying these after initialization isn't possible (yet)
if k != CONF_INTERVAL and k != CONF_NAME and k != CONF_LIGHTS:
# Modifying these after initialization isn't possible
if k not in (CONF_INTERVAL, CONF_NAME, CONF_LIGHTS):
args[vol.Optional(k)] = valid
platform = entity_platform.current_platform.get()
platform.async_register_entity_service(
Expand All @@ -572,20 +568,15 @@ def validate(config_entry: ConfigEntry, **kwargs):
"""Get the options and data from the config_entry and add defaults."""
# defaults and data will exist only if this is called from change_switch_settings
defaults = kwargs.get("defaults")
service_data = kwargs.get("data")
if defaults is None:
defaults = {key: default for key, default, _ in VALIDATION_TUPLES}

data = deepcopy(defaults)
if config_entry is not None:
# Is this deepcopy necessary?
# We're already creating a new array for the defaults variable...
# afterwards defaults is never used again.
data = deepcopy(defaults)
data.update(config_entry.options) # come from options flow
data.update(config_entry.data) # all yaml settings come from data
else:
# no idea how to clear original data from memory
# hopefully it does it automatically, otherwise TODO.
data = deepcopy(defaults)
service_data = kwargs["data"]
data.update(service_data)
data = {key: replace_none_str(value) for key, value in data.items()}
for key, (validate_value, _) in EXTRA_VALIDATION.items():
Expand Down Expand Up @@ -761,7 +752,7 @@ def _set_changeable_settings(
data: dict,
defaults: dict,
):
# Should only contain the settings we want the users to be able to change during runtime.
# Only pass settings users can change during runtime
data = validate(
config_entry=None,
data=data,
Expand Down Expand Up @@ -827,8 +818,7 @@ def __init__(
adapt_brightness_switch: SimpleSwitch,
):
"""Initialize the Adaptive Lighting switch."""
# Set attributes we DON'T want users modifying
# during runtime here.
# Set attributes that can't be modified during runtime
self.hass = hass
self.turn_on_off_listener = turn_on_off_listener
self.sleep_mode_switch = sleep_mode_switch
Expand Down

0 comments on commit 0e4410c

Please sign in to comment.