Rule optimization: Window OPEN reminder

To start with, I’d try something like this:

put all your windows that you want a notification for in a group
items file:

Group:Contact:OR(OPEN,CLOSED)    allWindows

Contact DGBadFenster (allWindows)
Contact DGFlurFenster (allWindows)
...

persist that group with, for example, mapdb
mapdb.persist:

allWindows* : strategy = everyChange,restoreOnStartup

add 2 map-files to your transform folder.

windowShortName.map:

DGBadFenster=DG Bad
DGFlurFenster=DG Flur
...
...
...

windowLongName.map:

DGBadFenster=Dachgeschoss Bad
DGFlurFenster=Dachgeschoss Flur
...
...
...

and finally in your rules, do:

import java.util.Map

val Map<String, Timer> OpenWindowTimers = newHashMap

val Functions$Function2<ContactItem, Map<String, Timer>, Boolean> checkOpenWindow = [
  windowItem,
  timerMap |

  val String myTimerKey = windowItem.name.toString

  if (windowItem.state == CLOSED) {
    if (timerMap.get(myTimerKey) !== null) timerMap.get(myTimerKey).cancel()
  } else if ((windowItem.state == OPEN) && (Sommer.state != ON)) {
    timerMap.put(myTimerKey, createTimer(now.plusMinutes(30)) [|
      timerMap.put(myTimerKey, null)

      val String shortName = transform("MAP", "windowShortName.map", windowItem.name.toString)
      val String longName = transform("MAP", "windowLongName.map", windowItem.name.toString)

      logInfo("Rules", "Fenster " + shortName + " 30 Min. offen")
      sendNotification("EMAIL-ADRESS", "Fenster " + shortName + " seit 30 Min. offen")
      EchoDotWZ_Remind.sendCommand("Fenster im " + longName + " ist seit 30 Minuten offen")
    ])
  }

  true
]

rule "Fenster check"
when
  Item allWindows received update
then
  Thread::sleep(100) // this gives the persistence service time to store the last update

  val lastUpdatedWindowItem = allWindows.members.filter[s|s.lastUpdate("mapdb") !== null].sortBy[lastUpdate("mapdb")].last as ContactItem

  checkOpenWindow.apply(lastUpdatedWindowItem, OpenWindowTimers)
end

now you don’t need to add a rule for every window. just add all your windows to the allWindows group and their corresponding (short and long) names to the mapping-files and you’re all set

5 Likes