First of all, there is absolutely no reason why this needs to be duplicated in two different Rules. So let’s just take the second one that works and make it generic so it can work for all your Items.
The first problem is to create a mapping between the MAC IDs and an Item name. Since you are using Rules DSL our options are a little limited. For this I think the easiest will be us a Map.
import java.util.Map
Map<String, String> devices = createHashMap("ff:ff:18:00:91:ff" -> "Person2PresenceProxy",
"ff:ff:af:50:14:8f" -> "Person1PresenceProxy")
Just add more entries to devices when you add new persons to track.
Next, since we are making this generic, we don’t know ahead of time how many people we are tracking so we can’t statically define the timers. So we will use a Map for that too.
import java.util.Map
Map<String, String> devices = createHashMap("ff:ff:18:00:91:ff" -> "Person2PresenceProxy",
"ff:ff:af:50:14:8f" -> "Person1PresenceProxy")
Map<String, Timer> timers = createHashMap
Now for the Rule. We will loop through the keys of devices to see if it’s present in the string. If so we can send the command to the corresponding Item. If not we will create a timer and wait two minutes before completely setting it to OFF.
How important is it that you don’t send duplicate ON commands? If you don’t care the code is really simple. If not, we need to use Design Pattern: Associated Items.
import java.util.Map
import org.eclipse.smarthome.model.script.ScriptServiceUtil
Map<String, String> devices = createHashMap("ff:ff:18:00:91:ff" -> "Person2PresenceProxy",
"ff:ff:af:50:14:8f" -> "Person1PresenceProxy")
Map<String, Timer> timers = createHashMap
rule "PresenceProxy from presenceString"
when
Item presenceString received update
then
// For each device
devices.keys.forEach[ mac |
personProxy = ScriptServiceUtil.getItemRegistry.getItem(devices.get(mac))
// mac is in presenceString
if(presenceString.state.toString.contains(mac)) {
if(personProxy.state == OFF) personProxy.sendCommand(ON)
timers.get(mac)?.cancel()
timers.put(mac, null)
}
// mac isn't in presenceString
else{
if(timers.get(mac) != null) timers.get(mac).cancel
timers.put(mac, createTimer(now.plusMinutes(2), [ |
if(!presenceString.state.toString.contains(mac)){
if(personProxy.state != OFF) personProxy.sendCommand(OFF)
}
timers.put(mac, null)
]
}
]
I just typed in the above so there may be typos but it should be close enough for you to get it to work generically. I based this off of the second Rule so I’ve no idea if there is an error in the first Rule.