Is it possible to delay triggering of an event?

That sounds as a good way to do it. Would it be too much asking to see some examples from your openHAB, how you have done? That would likely make it easier for me to understand how things are done.

Btw. I have modified my rule “Send telegram Notification | Garage door 1 open for 30 min.” a bit and initial testings seems positive. Hopefully the “fix” will be stable.

Changed the following - can’t figure out why that should make a difference:

(now.plusMinutes(30)

To

(now.plusSeconds(1800)

BR Søren

I posted this somewhere but can’t find it right not.

Items:

Switch T_Notify_Test
String Notification_Proxy_Info
String Notification_Proxy_Alarm

Rules:

// shows how to use it, useful for testing
rule "Test dispatch notifications"
when
        Item T_Notify_Test received command
then
        Notification_Proxy_Info.postUpdate("This is an Info test")
        Notification_Proxy_Alarm.postUpdate("This is an Alarm test")
end

rule "Dispatch Info Notification"
when
        Item Notification_Proxy_Info received update
then
        val String msg = Notification_Proxy_Info.state.toString
        logInfo("Notification", msg)
        if(TimeOfDay.state != "Night") sendPushToDefaultDevice(msg)
end

rule "Dispatch Alarm Notification"
when
        Item Notification_Proxy_Alarm received update
then
        val String msg = Notification_Proxy_Alarm.state.toString
        logError("Notification", msg)
        if(TimeOfDay.state == "Night") sendPushToDefaultDevice(msg) else sendNotification("my email", msg)
end

I can’t either. They should be the same.

Looking at your log files, java is losing its mind because it’s trying to set something that it doesn’t know how to set. Typically I’ve found that (for myself) that happens when I try and set something that doesn’t exist to something. (For example, trying to reschedule a cancelled timer.)

So if I were you, I’d go with the tried-and-true method of spitting a lot of info to the logs. My suspicion is that your code is getting executed when you’re not expecting it to (PIR doing something unexpected, maybe?), so all the logic we’re using to analyze things doesn’t apply.

i.e. I’d re-write your rules to look something like this:

// This rule sends a telegram notification if garage door has been open for 30 min.
rule "Send telegram Notification | Garage door 1 open for 30 min."
when
	Item Garage_Port_1_State_Closed changed to CLOSED
then
        logInfo("openhab","garage door 1 open for 30 minutes entered.  timer: " + tGarageDoor1)
	if(tGarageDoor1 != null) tGarageDoor1.cancel()            //Terminate timer just for good measure before it is created

       {
                logInfo("openhab","creating timer for garage door 1")
		tGarageDoor1 = createTimer(now.plusMinutes(30), [|
                        logInfo("openhab","destroying timer for garage door 1")
			tGarageDoor1 = null
                        logInfo("openhab","sending telegram for garage door 1")
      		        sendTelegram((TelegramBots), (Message2))
    		   ])
	}
end

rule "Cancel telegram Notification | Garage door 1 open for 30 min."
when
	Item Garage_Port_1_State_Closed changed to OPEN
then
        logInfo("openhab","killing garage door 1 timer (#2).  timer: " + tGarageDoor1)
	if(tGarageDoor1 != null) tGarageDoor1.cancel() //Terminate timer if door is closed before the timer ends
end

then run it for a bit. I’m suspecting you’ll find an instance where you cancel a timer twice in a row, and then java loses its mind immediately after that.

Also when cleaning up your formatting a bit, I noticed you had this:

then
	if(tGarageDoor1 != null) tGarageDoor1.cancel()  {          //Terminate timer just for good measure before it is created
		tGarageDoor1 = createTimer(now.plusMinutes(30), [|
			tGarageDoor1 = null
		sendTelegram((TelegramBots), (Message2))
		])
	}
end

which should run OK, but why do you have a block markers ({}) before tGarageDoor1’s timer creation? There doesn’t seem to be any need for them. As a style thing, I put block markers around all my code in a rule; helps me spot errors and compartmentalizes things. But mixing both block style and non-block style just bugs me, mainly because it can lead to unintended code execution! (i.e. pick a style and stick with it! :wink: )

(In general I don’t like to comment on purely style issues, but since you’re getting odd code execution I thought I’d mention it on the offhand it leads you to find the source of your problem. Forgive me for bringing it up in advance!)

Thanks @rlkoshak I’ll look into this and try and learn from you example how :slight_smile:

Oh well, my “fix” didn’t work.

But I think I found a solution. Been doing some debugging using ‘infoLog’. It is the createTimer that seems to not work everytime but after changing some code, it seems to have become stable.

Replaced this

if(tGarageDoor1 == null || tGarageDoor1.hasTerminated)

With

if(tGarageDoor2 != null) tGarageDoor2.cancel()  {          //Terminate timer if one is already started

So now the complete rule lookes like this

// This rule sends a telegram notification if garage door has been open for 30 min.
rule "Send telegram Notification | Garage door 2 open for 30 min."
when
	Item Garage_Port_2_State_Closed changed to CLOSED
then
	if(tGarageDoor2 != null) tGarageDoor2.cancel()  {          //Terminate timer if one is already started
		tGarageDoor2 = createTimer(now.plusMinutes(1), [|
			tGarageDoor2 = null
		sendTelegram((TelegramBots), (Message4))
		logInfo("TimerEnded", "Send telegram Notification | Garage door 2 open for 30 min.")
		])
		logInfo("TimerStarted", "Will send telegram Notification if garage door 2 is not closed within 30 min.")
	}
end

rule "Cancel telegram Notification | Garage door 2 open for 30 min."
when
	Item Garage_Port_2_State_Closed changed to OPEN
then
	if(tGarageDoor2 != null) tGarageDoor2.cancel() 		//Terminate timer if door is closed before the timer ends
end

I’ll keep an eye on things :slight_smile:

Thanks @TheKorn
I absolutely like the use of ‘logInfo’ you have showed - Been trying to use it myself (as you can see in the above post) to debug and to some extent it was a success. :slight_smile:

I’ll try your code and see what happens :slight_smile:

That I can answer very easy: I do not know what I’m doing. I work with SAP IT operations for a living but do not know anything about coding/programming at all.

In general I have been picking bits and pieces of code found on this forum - and from answers to my posts - and trying to putting it all together to get a working openHAB system.

So in other words I do not (yet) have a “style” on how code should “look”. But all good advice are very welcome, I’m all ears and do not get offended :slight_smile:

BR Søren

ROFLOL! Hey, points for being honest! :smiley:

Here’s a pretty clean example of my style for rules. I religiously use indenting (helps me see what my intent was when editing and I wind up with mismatched ()s, s, and {}s), and I wrap every rule in block markers ( {} ) because I feel that it makes very readable code. I also make all my items in ALL CAPS so they jump out at me when I’m trying to manipulate things.

You’ll find (or steal… :wink: ) your own style soon enough!

I should use logDebug instead. If you set the logging level for the script to DEBUG you can lower the logging level to INFO after troubleshooting. This will prevent flooding your logs after the issue has been resolved and there’s no need to change the code afterwards.

For the label use the rule name to remember where to look for. In this case:

// This rule sends a telegram notification if garage door has been open for 30 min.
rule "Send telegram Notification | Garage door 2 open for 30 min."
when
	Item Garage_Port_2_State_Closed changed to CLOSED
then
	if(tGarageDoor2 != null) tGarageDoor2.cancel()  {          //Terminate timer if one is already started
		tGarageDoor2 = createTimer(now.plusMinutes(1), [|
			tGarageDoor2 = null
		sendTelegram((TelegramBots), (Message4))
		logDebug("GaragePort2Closed30Mins", "Send telegram Notification | Garage door 2 open for 30 min.")
		])
		logDebug("GarageDoor2Closed30Mins", "Will send telegram Notification if garage door 2 is not closed within 30 min.")
	}
end

logback.xml

<logger name="org.openhab.model.script.GarageDoor2Closed30Mins" level="DEBUG"/>

I’m of exactly the opposite opinion. Changing the logging level requires restarting openhab, and that’s the last thing I ever want to do! Changing the rule is a lot easier and rules reload on the fly, so that’s my highly preferred method.

Z[quote=“TheKorn, post:24, topic:10999”]
I’m of exactly the opposite opinion. Changing the logging level requires restarting openhab, and that’s the last thing I ever want to do! Changing the rule is a lot easier and rules reload on the fly, so that’s my highly preferred method.
[/quote]

As far as I have noticed changing the debug level does not require a restart. I am using 1.8.3. I just need to wait a minute or so until the new logging level is used.

Thanks for the suggestion @digineut - I’ll try it out, at least to get a better feel of how things work in openHAB.

Just want to give thanks to all, for your help. It is very much appreciated.

I did some testing last night and as it looks right now everything is working as expected.

I think the “magic” in this script was the change of this line

Replaced this:

if(tGarageDoor1 == null || tGarageDoor1.hasTerminated) 

With

if(tGarageDoor1 != null) tGarageDoor1.cancel()  {          //Terminate timer if one is already started

I like the usage of the ‘infoLog’ parameter. I feel it gives me view of what’s is going on, before I felt I was flying blind :slight_smile:

BR Søren

Depends on how you have mainconfig:referesh set in openhab.cfg. By default, openhab does not have refreshes configured, so changes to logging levels require restarts. (…with good reason, I might add!)

What would be a good reason to require restarts after changing logging levels?

(I can dynamically set logging level in OH2 through Karaf console out of the box)

Causes real havoc with some hardware. My zstick5, for example, royally craps the bed whenever it’s issued a soft reset. (OH has to reset everything to a known state before it can reload the master config file.) Tried it out once for giggles, all hell broke loose once I made a change to openhab.cfg and reset the stick. So no dynamic reloading of the master config file for me! (I believe it’s a driver/firmware issue, so not much OH can really do about it except leave well enough alone by not issuing soft resets.)

Wasn’t aware of that. Do you know if this warning is already documented in a wiki page?

And how about the OH2 way:

log:set DEBUG org.eclipse.smarthome.binding.sonos

in the console will enable debugging on the fly…

Yes and no… the soft reset thing is documented in the zwave wiki. But it was only after reading through the log files after everything broke loose that I connected the dots that reloading the config file sent a soft reset, so that part not really.

As for OH2, I don’t have any experience with it whatsoever so can’t offer any guidance, sorry!

Hi there

Can you please help me? I have found and modify three rules here for a small alarm system and i would like to add a timer in this rule like this: when its in the armaway mode to create a timer that will delay all actions with 15 or 30 sec. I need to do so because this alarm system is made at this moment with only one door contact installed on my front door so if i open the door to enter the house, ill trigger the actions (only one at this moment but later i want to add more). This timer should be also available after arming the system, i mean i need few sec to open and close the door after arming the system and there will be another question here, if i need to reopen the door after arming the system (i forgot the car keys) whats gonna happen? the system will reset the alarm if i enter and exit the house within 30 sec or will start the alarm after 30 sec?
The rules looks like this:
rule "Dispatch Notification"
when
Item Notification_Proxy received update
then
logWarn("Notification", Notification_Proxy.state.toString)
sendMail("dragos.m.constantin@gmail.com", "Security System Alert!",
Notification_Proxy.state.toString)
end

rule "Process door intrusion updates"
Item gDoorSensors changed from CLOSED to OPEN
then
val aState = AlarmSysStatus.state as DecimalType
if(aState == 2 || aState == 3) {
alert.apply(gDoorSensors, "- Intrusion")
}
end

// Alarm Arm and Disarm
rule "rArmState1"
when
Item AlarmArmDisarm received command 3
then
{
if (receivedCommand == 3 && gDoorSensors.state == CLOSED)
{
postUpdate(AlarmSysStatus, 6)
Thread::sleep(30000)
postUpdate(AlarmSysStatus, 3)
logInfo("Security", "SECURITY: Armed Stay!")
sendMail("xxx@gmail.com", "Security: Armed Stay!", "Sistemul este armat in modul Stay!")
executeCommandLine("aplay /opt/openhab/configurations/sounds/armedstay.wav")
executeCommandLine("/opt/openhab/configurations/scripts/armedstay.ssh")
} else {
if (receivedCommand == 3)
logInfo("Security","SECURITY: Unable to Arm Stay!. Please try again.")
sendMail("xxx@gmail.com", "Security: Usa sau geam deschis!", "Sistemul nu s-a putut arma datorita unei usi sau geam deschise! Te rog verifica!.")
postUpdate(AlarmSysStatus, 5)
Thread::sleep(3000)
postUpdate(AlarmSysStatus, 1)
}}}
end

// Alarm Arm and Disarm
rule "rArmState2"
when
Item AlarmArmDisarm received command 2
then
{
if (receivedCommand == 2 && gDoorSensors.state == CLOSED) {
{
postUpdate(AlarmSysStatus, 6)
Thread::sleep(30000)
postUpdate(AlarmSysStatus, 2)
logInfo("Security", "SECURITY: Armed Away!")
sendMail("xxx@gmail.com", "Security: Armed Away!", "Sistemul este armat in modul Away!")
executeCommandLine("aplay /opt/openhab/configurations/sounds/armedaway.wav")
executeCommandLine("/opt/openhab/configurations/scripts/armedaway.ssh")
} else {
if (receivedCommand == 2)
logInfo("Security","SECURITY: Unable to Arm Away!. Please try again.")
sendMail("xxx@gmail.com", "Security: Detectie miscare!", "Sistemul nu s-a putut arma datorita detectiei miscarii. Te rog verifica!")
postUpdate(AlarmSysStatus, 4)
Thread::sleep(3000)
postUpdate(AlarmSysStatus, 1
}}}
end

// Alarm Arm and Disarm
rule "rArmState3"
when
Item AlarmArmDisarm received command 1
then
{
if (receivedCommand == 1)
{
logInfo("Security", "SECURITY: Disarmed")
postUpdate(AlarmSysStatus, 1)
sendMail("dragos.m.constantin@gmail.com", "Security: Disarmed!", "Sistemul este dezarmat!")
executeCommandLine("aplay /opt/openhab/configurations/sounds/disarmed.wav")
executeCommandLine("/opt/openhab/configurations/scripts/disarmed.ssh")
} else {
if (receivedCommand == 1)
postUpdate(AlarmSysStatus, 1)
}}}
end

// Alarm Arm and Disarm
rule "rArmState4"
when
Item AlarmArmDisarm received command 0
then
{
if (receivedCommand == 0)
{
logInfo("Security", "SECURITY: No Update")
}}
end

Alarm System Active Action
rule "rAlarmActivated"
when
Item gDoorSensors changed from CLOSED to OPEN
then
{
if (AlarmSysStatus.state == 2)
{
logInfo("Security", "SECURITY: ARMED-AWAY Motion Intrusion Detected!")
gAllLights.sendCommand(ON)
Thread::sleep(3000)
}
if (AlarmSysStatus.state == 2 && gDoorSensors.state == OPEN)
{
logInfo("Security", "SECURITY: ARMED-AWAY Door Intrusion Detected!")
gAllLights.sendCommand(ON)
Thread::sleep(3000)
}
if (AlarmSysStatus.state == 3 && gDoorSensors.state == OPEN)
{
logInfo("Security", "SECURITY: ARMED-STAY Door Intrusion Detected!")
gAllLights.sendCommand(ON)
Thread::sleep(3000)
}
}}}}
end

Could you please help with this?
Thanks!

Take a look at this topic below;

https://community.openhab.org/t/custom-widget-keypad/18154

It will show you how to create a rule that delays, to let you open the door, get out and close the door before changing the alarm state.

If you forget your keys. During the delay if you type your code again it will cancel the state change.

Change the 5 in the line below to 15 or 30 secs for your desired delay

set_timer = createTimer(now.plusSeconds(5)) [|

Hope that helps

Right now I’m using Rotini app and i have a pin code through i access the alarm items so if i need to arm or disarm i need to enter the pin code so i think i cant use too much info from the link you posted.
I was thinking to add timer in between my rules, not to create different rule… something like this:

var Timer timer = null

//Alarm System Active Action
rule "rAlarmActivated"
when
Item gDoorSensors changed from CLOSED to OPEN
then
{
if (AlarmSysStatus.state == 2)
{
if (timer!=null)
timer.cancel
timer = createTimer(now.plusSeconds(30))[|
logInfo(“Security”, “SECURITY: ARMED-AWAY Motion Intrusion Detected!”)
gAllLights.sendCommand(ON)
Thread::sleep(3000)
}
if (AlarmSysStatus.state == 2 && gDoorSensors.state == OPEN)
{
if (timer!=null)
timer.cancel
timer = createTimer(now.plusSeconds(30))[|
logInfo(“Security”, “SECURITY: ARMED-AWAY Door Intrusion Detected!”)
gAllLights.sendCommand(ON)
Thread::sleep(3000)
}
if (AlarmSysStatus.state == 3 && gDoorSensors.state == OPEN)
{
logInfo(“Security”, “SECURITY: ARMED-STAY Door Intrusion Detected!”)
if (timer!=null)
timer.cancel
timer = createTimer(now.plusSeconds(30))[|
gAllLights.sendCommand(ON)
Thread::sleep(3000)
}
}}}}
end

I didn’t test this because my gateway with the door contact is dead but if this will work i think would solve only the problem related entering the house during the alarmaway mode but not the other problem related to the way of arming an having 30 sec before going out the house.

I would do this using 2 rules to make it clear and easier to work with.
1 st Rule - Setting Alarm
You would just need to remove the first IF statement (from last link provided) in the rule that checks the pin code submitted but the logic for setting and cancelling the alarm would be the same. Just set your AlarmSysStatus.state instead.
2 nd Rule - Alarm Activated
To work with what you have provided, you could then put an IF check in your create timer to see if the alarm state has been turned off during intrusion. If not set your alert, something like;

if (AlarmSysStatus.state == 3 && gDoorSensors.state == OPEN)
{
logInfo("Security", "SECURITY: ARMED-STAY Door Intrusion Detected!")
//set time delay for alarm activation
timer = createTimer(now.plusSeconds(30))[|
   //check if alarm has been disactived
   if (AlarmSysStatus.state == 3){
      // door was opened and alarm is still set '''alarm stuff here'''
      gAllLights.sendCommand(ON)
}else if(AlarmSysStatus.state == 1) {
   // alarm was disabled
   logInfo("Security", "SECURITY: DISARMED")
}
]