Hi,
I have written a short Python script but I am not sure about the correctness of that all. I have never ever written a Python script before and also the HA API is new to me. So I’d highle appreciate, if someone could have a look at my script and tell me, where it needs corrections.
Basically, the script will be called by an automation. This automation is triggered by either an open- or a close-event of any of my windows. The automation should give two parameters to the script: the partial name of the entity that triggered the automation (name of the window) as well as the trigger state (on/off).
The script should now control the heating and the covers of the corresponding room/window:
- an open-event should lower the heating and open the cover in case it is lower than a threshold
- a close-event should set the heating to auto and close the cover again to its previous position.
I have already tested this with “normal” automations and only one window. So this generally works.
I just need some assistance in merging all this into one script.
Now here it is:
The automation:
- id: '303427509327'
alias: "Call window automation script"
trigger:
- platform: state
entity_id: binary_sensor.dinning_room
- platform: state
entity_id: binary_sensor.living_room
- platform: state
entity_id: binary_sensor.kitchen
(... six more triggers here... )
action:
- service: python_script.window_automation
data:
entity_id: '{{ trigger.entity_id }}'
sensor_state: '{{ trigger.to_state.state }}'
My window_automation.py contains:
sensor_state = data.get('sensor_state')
entity_id = (data.get('entity_id')).split('.')[1]
current_position = hass.states.get(('cover.' + entity_id).attributes.current_position)
saved_position = (hass.states.get(('input_number.' + entity_id).state) | int)
fresh_air_position = (hass.states.get('input_number.fresh_air').state) | int)
# Window got opened, do the following
# - set heating to "lower"
# - save current cover position
# - open cover until "fresh air"-position is reached
if sensor_state == 'on':
hass.services.call('climate', 'set_operation_mode', { 'entity_id': ('climate.' + entity_id), 'operation_mode': 'lowering'})
if current_position < fresh_air_position:
hass.services.call('input_number', 'set_value', { 'entity_id': ('input_number.' + entity_id), 'value': (current_position | float) })
hass.services.call('cover', 'set_cover_position', {'entity_id': ('cover.' + entity_id), 'position': fresh_air_position })
# Window got closed, do the following
# - set heating to "auto"
# - move cover back to previous position
elif sensor_state == 'off':
hass.services.call('climate', 'set_operation_mode', { 'entity_id': ('climate.' + entity_id), 'operation_mode': 'auto'})
if current_position > saved_position:
hass.services.call('cover', 'set_cover_position', {'entity_id': ('cover.' + entity_id), 'position': saved_position })
Is that something to work with?!
Thanks and greetings!