[SOLVED] Do something before alarm clock

Hi! I have alarm clock rule that based on android alarm clock setting:
var Timer timerAlarm = null

rule "Alarm Clock"
when
    Item AlarmClock changed
then
    if (AlarmClock.state as Number == 0) {
        if (timerAlarm !== null) {
            timerAlarm.cancel
            timerAlarm = null
        }
        logInfo("alarm", "All alarms are cancelled")
    } else {
        var epoch = new DateTime((AlarmClock.state as Number).longValue)
        logInfo("alarm", "Scheduling alarm for " +  epoch.toString)

        if (timerAlarm !== null) {
            logInfo("alarm", "Reschedule alarm")
            timerAlarm.reschedule(epoch)
        } else {
            logInfo("alarm", "New Alarm")
            timerAlarm = createTimer(epoch,
                [ k |
                    // Turn on stuff, e.g. radio or light if somebody at home
                    if(gPresent.state == ON){
                    GF_MasterBedroom_Light.sendCommand(ON)
                    }
                    logInfo("alarm", "alarm is expired")
                ]
            )
            
            
        }
    }
end

i need to set my string item heatingMode from “SLEEP” to “NORMAL” 30 minutes before alarm clock, how i can do that in rule?

Would that work?

        var epoch = new DateTime((AlarmClock.state as Number).longValue)
        logInfo("alarm", "Scheduling alarm for " +  epoch.toString)
        var alarm30minBefore = epoch.minusMinutes(30)
        logInfo("alarm", "Scheduling alarm 30 minutes before for " +  alarm30minBefore.toString)

Thanks! so in this way i need two different timers i guess?

Yes you do

You could also reuse the timer.

var Timer timerAlarm = null

rule "Alarm Clock"
when
    Item AlarmClock changed
then
    timerAlarm?.cancel  // only cancel timer if existing, no need to set to null.
    if (AlarmClock.state as Number == 0) {
        logInfo("alarm", "All alarms are cancelled")
    } else {
        var epoch = (new DateTime((AlarmClock.state as Number).longValue)).minusMinutes(30)
        if(now.isAfter(epoch)) {
            epoch = epoch.plusDays(1)  // or something to move the timer forward
        }
        logInfo("alarm", "Scheduling alarm for " +  epoch.toString)
        timerAlarm = createTimer(epoch, [ |
            if(heatingMode.state.toString == "NORMAL") {
                // Turn on stuff, e.g. radio or light if somebody at home
                if(gPresent.state == ON){
                    GF_MasterBedroom_Light.sendCommand(ON)
                }
                logInfo("alarm", "alarm is expired")
            } else {
                heatingMode.sendCommand("NORMAL")
                timerAlarm.reschedule(now.plusMinutes(30))
            }
        ])
    }
end

Of course this does only work if heatingMode can be used as a indicator here. If this is not true, you have to use another global var to differentiate between the first and the second run of the timer.

1 Like