Often one will have a number of separate Items which are all related to each other in some way. For example, one might have a Contact on a door and a DateTime to represent when the last time the door was opened. This is easy enough to keep track of if there are only one or two such Items, but if one has a lot of similar Items or is using a lot of genetically coded rules where one cannot hard code the names of the associated Items inside the rule mapping between the Items becomes difficult.
By naming Items that are related to each other such that given the name of one Item the name of the associated Item or Items can be constructed. With the associated Item’s name, one can get a reference to that Item by pulling it out of a Group’s members using the
In this example there are two door Contacts and two associated DateTime Items to store the last time the Door was opened or closed. A Rule triggers when one of the Contacts is updated and if it has been.
This example relies upon the gDoor Items being persisted so we can get the lastUpdate. But that is just part of this particular example. The two lines of code where we “Get associated DateTime Item” are the main part of the example.
Group gDoors:Contact Group gDoorsLastUpdate:DateTime Contact Front "Front Door" <frontdoor> (gDoors) DateTime Front_LastUpdate "Front Door Last Update [%1$tm/%1$td %1tH:%1tM]" <clock> (gDoorsLastUpdate) Contact Back "Back Door" <frontdoor> (gDoors) DateTime Back_LastUpdate "Back Door Last Update [%1$tm/%1$td %1tH:%1tM]" <clock> (gDoorsLastUpdate)
rule "A Door's State Changed" Item gDoors received update // NOTE: the rule will trigger multiple times per event when then gDoors.members.forEach[door | // Get the associated DateTime Item val dtStr = door.name + "_LastUpdate" val assocDT = gDoorsLastUpdate.members.filter[dt|dt.name == dtStr].head as DateTimeItem // Update assocDT with the door's lastUpdate assocDT.postUpdate(new DateTimeType(door.lastUpdate)) ] end
The rule loops through all the Items in gDoors, pulls each door’s associated LastUpdate Item and updates that Item with the door’s lastUpdate time.
Note that each LastUpdate Item will be updated every time any door receives an update and the rule will trigger more than once for each update. While this results in a lot of unnecessary work the behavior of the rule doesn’t change.