External curtains automation via Python Scripting Add-on - update

Hi all,

I had the need of automating external curtains based on three weather conditions like rain, wind gust and illuminance.
I solved the issue with a Python script(via Python Scripting Add-on) as such:

from openhab import rule, Registry, logger
from openhab.triggers import when
from datetime import datetime, timedelta
import scope
import threading


def get_weather_values():
    rain_rate = Registry.getItemState("piezo_rain_rate").floatValue() 
    gust_current = Registry.getItemState("weather_speed_gust").floatValue()
    historic_item = (Registry.getItem("weather_speed_gust").getPersistence()
                     .persistedState(datetime.now() - timedelta(minutes=15)))
    gust_past = historic_item.getState().floatValue()
    logger.info("Current Gust: {}".format(round(gust_current,ndigits=2)))
    logger.info("Past Gust: {}".format(round(gust_past,ndigits=2)))
    irradiance = Registry.getItemState("weather_irradiation_solar").floatValue()
    return rain_rate, gust_current, gust_past, irradiance


def get_target_position(irradiance_opening,irradiance_closing, gust_current_max=16):
    rain_rate, gust_current, gust_past, irradiance = get_weather_values()

    # Logic to determine the target position
    if rain_rate == 0.0 and gust_current <= gust_current_max and gust_past <= 8.0 and irradiance > irradiance_opening:
        return 100 # Curtain opening

    if rain_rate > 0.0 or gust_current > gust_current_max or irradiance < irradiance_closing:
        return 0 # Curtain closing
    return None


def apply_shutter_position(item_name,position):
    target_position = position
    logger.info("{} position: {}".format(item_name,target_position))

    if target_position is None:
        return

    shutter_state = Registry.getItemState(item_name)

    if not isinstance(shutter_state, scope.UnDefType):
        shutter_state = shutter_state.intValue()
        logger.info("Current {} position: {}".format(item_name,shutter_state))

    shutter_item = Registry.getItem(item_name)
    if shutter_state != target_position:
        shutter_item.sendCommand(target_position)
        logger.info("Command sent to {}: {}".format(item_name,target_position))


def job():
    event = threading.Event()
    front_target_position = get_target_position(irradiance_opening=250.0,irradiance_closing=10.0)
    rear_target_position = get_target_position(irradiance_opening=250.0,irradiance_closing=30.0)
    apply_shutter_position(item_name="iTH_shutter", position=front_target_position)
    event.wait(1)
    apply_shutter_position(item_name="iTG_shutter", position=rear_target_position)
    


@rule("Curtains")
@when("Item piezo_rain_rate changed")
@when("Item weather_speed_gust changed")
@when("Item weather_irradiation_solar changed")
def main(module, input):
    job()

I hope this could be useful to anyone needs such a kind of automation logic!
2 Likes