Simple script to brighten or dim a light, then return to last level.
Python Script
""" Brighten a light, then return to previous brightness state """
# Get Params
entity_id = data.get('entity_id')
action = data.get('action')
level = int(data.get('level'))
# Get current brightness value
states = hass.states.get(entity_id)
brightness = states.attributes.get('brightness') or 0
# Set new brightness value
if action == 'dim_up' : dim = (brightness + level)
if action == 'dim_down' : dim = (brightness - level)
if dim <= 0 : dim = 0
if dim >= 254 : dim = 254
# Call service
if dim == 0 :
logger.info('Tuning off ' + str(entity_id))
data = { "entity_id" : entity_id }
hass.services.call('light', 'turn_off', data)
else :
logger.info('Dimming' + str(entity_id) + 'from : ' + str(brightness) + ' to ' + str(dim))
data = { "entity_id" : entity_id, "brightness" : dim }
hass.services.call('light', 'turn_on', data)
Automation Example
Brighten stairway light when motion detected, restore last level when no motion
nice thanks!
Bit new to python… some question about this…
if the light state is like 150, and it turns on whit 150 more…(=300 in my head) max is 255? right? then it goes lower than previous state when it dims back down?.. 105?
//F
Nice idea and great use of Python Script to drive the automation!
Personally I would have just one automation and either pass the Motion sensor state as a param, or even more simply just query the motion sensor state from the python script. This can dramatically help with debugging since the script doesn’t require any restart to see changes.
Also, I think that working with percentages using “brightness_pct” would be easier to manage and would be more intuitive. It could also help make the automations easier tou understand to show level as “level_pct” to note how much to raise/lower from the current state . . .
Just some thoughts as I ponder a good use of this for my home – Thanks for sharing!
#
# Expose Python scripts in config/python_scripts as services
#
python_script:
Then put name-of-your-service.py files in the directory. Restart. Then you can call scripts. I think new scripts don’t need reload of HA, just edit automation to add service call or use GUI to call service script.
I like using the bright/dim method. This makes sure I can go up and down from whatever the previous brightness was.
So, I can manually set a “not too bright” resting level, and be sure that +100 or +150, etc. is the right increase when the service is triggered. And when the timer or trigger event happens to turn it down again, we get back to whatever the original was.