Mqtt automation simple switch

Hi

I have seen many automation examples to trigger mtqq light. Here is my typical problem.
In my area we have lots of power cuts. few of my lights runs connected to home inverter, some are directly connected to mains power.

I want to turn on mqtt light which is directly connected to mains power from sunset to night 11 PM.

My issue :

when i turned on light after sunset, if there is any power failure by the time 11 PM, my mqtt client is in disconnected mode. if power comes back at 11:30 PM, my light is still turning on.

how do I solve my problem. my mqtt light is sonoff with tosmota firmware.

Do

  1. I need to trigger mqtt event every sec ( between sun set to 11PM turn on ) and off after that.
  2. something with MQTT configuration ?

Naveen

Have you set retain on in the mqtt broker when publishing the topic? If so you need to turn it off and flush the broker with a publish with retain off, I believe.

Thank you,

But if I turn off retain flag, I have opposite problem.
If there is no power when on at the time of sunset, my light will not glow, when power is back

Naveen

I would use automation but use time as the trigger (every 5 min), mqtt light state and time of day as the condition and turn off light as action. I think the power outage would prevent you using time of day as the trigger.

Thank you Rob,

Your solution is good. Any idea how do I check weather time is in required range ? like
(6PM to 11PM ) then only trigger automation?

try this

TIME CONDITION
The time condition can test if it is after a specified time, before a specified time or if it is a certain day of the week

condition:
  condition: time
  # At least one of the following is required.
  after: '15:00:00'
  before: '02:00:00'
  weekday:
    - mon
    - wed
    - fri

Valid values for weekday are mon, tue, wed, thu, fri, sat, sun. Time condition windows can span across the midnight threshold. In the example above, the condition window is from 3pm to 2am.

Yup thank you very much. I will have a try!!!

Naveen