Get Number of Items in Group with state x

Hello!

I’m sorry if this question might sound stupid but I couldn’t find it in the docs or in the samples:

I want to implement a rule like:

rule "Security State Sensor"
when
  Item Openingcontacts changed or  
  Item Tamperswitches changed
then
  Security_Last_Change.postUpdate( now.toString() )

  if ( Security_Alarmanlage.state == ON ) {
    if ( ( Security_OpenWindows.state <= Openingcontacts.state ) || (Tamperswitches.state >= 1 ) ) { // someone opened a door or window
      logInfo("AlarmanlageRule", "Windows opened during alarm active. Security_OpenWindows: [{}], Openingcontacts: [{}], Tamperswitches: [{}]", Security_OpenWindows.state, Openingcontacts.state, Tamperswitches.state)
      Alarm_Security.postUpdate(ON)
    } else if ( Security_OpenWindows.state >= Openingcontacts.state ) { // someone closed a door or window while the alarm is active
      logInfo("AlarmanlageRule", "Window closed. Security_OpenWindows: [{}], Openingcontacts: [{}], Tamperswitches: [{}]", Security_OpenWindows.state, Openingcontacts.state, Tamperswitches.state)
      Security_OpenWindows.postUpdate(Openingcontacts.state.format("%d"))
    }   
  }
end

//----------------------------------------------------------
// Set how many Windows are open at the time of activation.
//
rule "Alarmanlage wird aktiviert"
when
  Item Security_Alarmanlage changed
then
  if ( Security_Alarmanlage.state == ON) {
    logInfo("AlarmanlageRule", "Security_OpenWindows: [{}], Openingcontacts: [{}]", Security_OpenWindows.state, Openingcontacts)
    Security_OpenWindows.postUpdate(Openingcontacts.state.format("%d"))
  } else {
    Security_OpenWindows.postUpdate(0)
  }
end

Items:

Group:Contact:OR(OPEN, CLOSED)   Security          "Security [(%d)]"             <shield>      (All)
Group:Contact:OR(OPEN, CLOSED)   Openingcontacts    "Öffnungssensoren [(%d)]"  <contact>     (Security)
Group:Contact:OR(OPEN, CLOSED)   Tamperswitches  "Sabotagekontakte [(%d)]"  <contact>     (Security)
Number Security_OpenWindows

I would expect that if the alarm is enabled, the Openingcontacts.state would hold the current number of open windows, but it is OPEN. I saw the $group?.members.filter function but I guess there is a quicker way :smile:

Thanks for your help!

A Group only contains a rollup of the items in the group, particularly when you define the group as a Contact as you have done. To get the count of Items in any given state you need to calculate it yourself.

I think the group?.members.filter.size is the “proper” way to get the count.

I’m not sure what you mean by a quicker way. If you are worried about the runtime performance of filter, I wouldn’t. Unless you have tens of thousands or hundreds of thousands of items in the group the runtime performance of filter will be negligible.

If you are worried about all that typing, I know of no way shorter way to get at the count.

Rich

2 Likes