Help combining rules with the same trigger

For one use proper indentation. Every time you have a { all the following lines should be indented until the }.

Avoid putting } on the same line and make them line up with the line for the matching }.

The same goes for [ and ].

This makes it MUCH easier to see which lines are inside which if statements and which lines are inside the Timer lambda.

Remember, your first goal should be to write code that is easy for humans to read. The computer doesn’t care.

Look at Design Pattern: How to Structure a Rule. Most of the code in the two clauses are the same with differing parameters. So first calculate the parameters then you only have to send the commands and create the timers once.

var Timer timer1 = null
var Timer timer2 = null

rule "Motion Detection"
when
    Item Motion received command ON
then
    // 1. Always run the rule

    // 2. Calculate what needs to be done
    var volume = 60
    var sound = "motionalarm.mp3"
    var volTimer = 5
    val nightTime = now.isAfter(now.withTimeAtStartOfDay) && now.isBefore(now.withTimeAtStartOfDay.plusHours(18)
    
    if(Watch_Dog.state == ON) {
        volume = 80
        sound = "dog_barking.mp3"
        volTimer = 30
    }

    // 3. Do it
    HeyGoogle_Volume.sendCommand(volume)
    playSound(sound)
    Motion.sendCommand(OFF)

    timer1?.cancel
    timer1 = createTimer(now.plusSeconds(volTimer), [ |
        HeyGoogle_Volume.sendCommand(30)
        timer1 = null
    ])

    if(Watch_Dog.state != ON && nightTime) {
       SW2_01_1.sendCommand(ON)
        timer2?.cancel
        timer2 = createTimer(now.plusSeconds(120), [|
            SW2_01_1.sendCommand(OFF)
            timer2 = null
        ])
    }
end