Design Pattern: Motion Sensor Timer

Some ideas:

If you use a lambda you can avoid duplicating the same code for each Sonos (if I understand your comment correctly).

If you use a Map you can drastically reduce the code in your rule. You can populate it using a HashMap but I prefer to use the MAP transform:

sonos.map

0=P4 Radio Norge
1=Korean Pop
2=Liberdade
3=Jazz
4=P5
5=Radio Sørlandet
6=Nrk MP3
7=BuddaBar
8=Something
9=Something else
rule "Sonos Bad1"
when
    Item Bad1VDSonos received update ON
then
    if(Bad1VDSonosOverride.state == OFF && Bad1_Sonos_State.state != "PLAYING"){
        Bad1_Sonos_Volume.sendCommand(Bad1VDSonosVolume.state as Number)
        Thread::sleep(100)
        Bad1_Sonos_PlayPlaylist.sendCommand(transform("MAP", sonos.map, Bad1SonosSelector.state.toString))
    }
end

rule"Sonos OFF"
when
    Item Bad1VDSonos received update OFF
then 
    if (Bad1_Sonos_State.state!="STOPPED"){
        Bad1_Sonos_Stop.sendCommand(ON)
    } 
end

With this approach not only is your Rule shorter, you can add and remove channels by simply editing the map file and you don’t have to touch your Rules. Note, it is better to call the method on the Item than to call the sendCommand Actions.

1 Like