Time-based lambda condition

I’m trying to use a time-based condition in a lambda form to activate a switch but It doesn’t really work. It compiles fine and gives no errors but nothing really happens:

time:
  - platform: homeassistant
    id: homeassistant_time
    timezone: Europe/Amsterdam

switch:
  - platform: template
    name: "time_switch"
    id: "time_switch"
    turn_on_action:
      then:
        if:
          condition:
            - lambda: 'return id(homeassistant_time).now().hour < 12;'
          then:
            - switch.turn_on: time_switch
    turn_off_action:
      then:
        if:
          condition:
            - lambda: 'return id(homeassistant_time).now().hour > 12;'
          then:
            - switch.turn_off: time_switch

Do I have to setup something on the HA-end or does it automatically extract the time from HA?

Do you have api: in the configuration file? That might be necessary for the home assistant time.

The turn_on_action: and turn_off_action: triggers get executed when the switch state changes. So they would only get executed if some other logic in the configuration or HA changes the state. The time logic needs to be in the lambda: trigger for the template switch. It will get evaluated periodically and the switch state will change based on the return statement.

switch:
  - platform: template
    name: "time_switch"
    id: "time_switch"
    lambda:  'return id(homeassistant_time).now().hour < 12;'
1 Like

Ah, that must be it (api). I’m using MQTT to communicate since the ESP is on a different net. Any way to broadcast the time from HA to my MQTT-server?

The SNTP Time Source — ESPHome could be used if the device can reach a NTP server. Might be able to configure router or the MQTT-server for this. If there are only a few times of interest, could just publish a MQTT topic for each state.

That did the trick. I’ve setup a text sensor that indicates the state and activates the switch at a certain time. Code below if someone else might need it:

time:
  - platform: sntp
    id: sntp_time

text_sensor:
  - platform: template
    id: time_text
    lambda:
      if (id(sntp_time).now().hour == 10 &  id(sntp_time).now().minute > 41) {
        id(time_switch).turn_on();
        return {"on"};
      } else {
        return {"off"};
      }
    update_interval: 1s

  - platform: template
    name: "time_switch"
    id: "time_switch"
    optimistic: TRUE

1 Like