Identify a switching sequence

Easy to use, 100% Lua-based event scripting framework.

Moderator: leecollings

Post Reply
paul402
Posts: 96
Joined: Monday 23 May 2016 23:07
Target OS: Raspberry Pi / ODroid
Domoticz version:
Contact:

Identify a switching sequence

Post by paul402 »

I would like to know if 3 movement sensors are triggered in a sequence with max 5 minutes gap between each of the triggers for the data to be valid.
I not sure how to go about this so would appreciate some hints on how to do it.
I'm not asking someone to do it for me, just give me a clue. For instance do I need to use persistent data or not. Thanks.
User avatar
Ragdag
Posts: 152
Joined: Friday 30 March 2018 13:56
Target OS: Raspberry Pi / ODroid
Domoticz version: Beta
Location: Netherlands
Contact:

Re: Identify a switching sequence

Post by Ragdag »

Asked my trusted ChatGPT :D

Code: Select all

local scriptVar = 'Motion_Sequence_Detection'

-- Sensor configuration
local SENSOR_IDX = {
    MOTION_1 = 1001,  -- Replace with actual Domoticz device IDs
    MOTION_2 = 1002,
    MOTION_3 = 1003
}

-- Constants
local MAX_TIME_GAP = 300  -- 5 minutes (300 seconds)

return {
    on = {
        devices = {SENSOR_IDX.MOTION_1, SENSOR_IDX.MOTION_2, SENSOR_IDX.MOTION_3} -- Trigger on motion sensor activation
    },
    
    logging = {
        level = domoticz.LOG_DEBUG,
        marker = scriptVar,
    },

    data = {
        Motion1Time = { initial = 0 },
        Motion2Time = { initial = 0 },
        Motion3Time = { initial = 0 }
    },

    execute = function(domoticz, item)
        local function logDebug(message)
            domoticz.log(message, domoticz.LOG_DEBUG)
        end

        local function logInfo(message)
            domoticz.log(message, domoticz.LOG_INFO)
        end

        local function triggerAction()
            logInfo("Motion sequence detected! Triggering action.")
            -- Add your action here, e.g., send a notification
            domoticz.notify("Motion Sequence", "All 3 motion sensors triggered in sequence!", domoticz.PRIORITY_NORMAL)
            
            -- Reset timestamps after detection
            domoticz.data.Motion1Time = 0
            domoticz.data.Motion2Time = 0
            domoticz.data.Motion3Time = 0
        end

        local currentTime = os.time()

        if item.idx == SENSOR_IDX.MOTION_1 then
            logDebug("Motion sensor 1 triggered")
            domoticz.data.Motion1Time = currentTime

        elseif item.idx == SENSOR_IDX.MOTION_2 then
            if domoticz.data.Motion1Time > 0 and (currentTime - domoticz.data.Motion1Time) <= MAX_TIME_GAP then
                logDebug("Motion sensor 2 triggered within valid time window")
                domoticz.data.Motion2Time = currentTime
            else
                logDebug("Motion sensor 2 triggered but sequence invalid (resetting)")
                domoticz.data.Motion1Time = 0
                domoticz.data.Motion2Time = 0
                domoticz.data.Motion3Time = 0
            end

        elseif item.idx == SENSOR_IDX.MOTION_3 then
            if domoticz.data.Motion1Time > 0 and domoticz.data.Motion2Time > 0 and 
               (currentTime - domoticz.data.Motion2Time) <= MAX_TIME_GAP then
                logDebug("Motion sensor 3 triggered within valid time window")
                triggerAction() -- All 3 sensors triggered in sequence
            else
                logDebug("Motion sensor 3 triggered but sequence invalid (resetting)")
                domoticz.data.Motion1Time = 0
                domoticz.data.Motion2Time = 0
                domoticz.data.Motion3Time = 0
            end
        end
    end
}
or

Code: Select all

return {
    -- Trigger on all three motion sensor devices
    on = {
        devices = { "Motion Sensor 1", "Motion Sensor 2", "Motion Sensor 3" }
    },
    -- Persistent data to store the timestamps of triggers
    data = {
        sequence = { initial = {} }
    },
    execute = function(domoticz, device)
        local now = os.time()  -- Current timestamp in seconds
        local seq = domoticz.data.sequence  -- Get the current sequence

        -- If there is already a recorded trigger, check the gap between the last trigger and now
        if #seq > 0 then
            local lastTrigger = seq[#seq]
            if (now - lastTrigger > 300) then  -- 300 seconds = 5 minutes
                domoticz.log("Time gap exceeded 5 minutes. Resetting sequence.", domoticz.LOG_INFO)
                seq = {}  -- Reset the sequence if the gap is too long
            end
        end

        -- Add the current trigger's timestamp to the sequence
        table.insert(seq, now)
        domoticz.data.sequence = seq  -- Save the updated sequence
        domoticz.log("Sensor triggered: " .. device.name .. ". Sequence count: " .. #seq, domoticz.LOG_DEBUG)

        -- Check if we have reached three triggers in valid succession
        if #seq >= 3 then
            domoticz.log("Valid sequence of 3 movement sensor triggers detected!", domoticz.LOG_INFO)
            -- Perform your desired action here. For example, send a notification:
            domoticz.notify(
                "Movement Sequence",
                "Three movement sensors were triggered in sequence with less than 5 minutes between each.",
                domoticz.PRIORITY_NORMAL
            )
            -- Reset the sequence after handling the valid event
            domoticz.data.sequence = {}
        end
    end
}
Last edited by Ragdag on Friday 14 February 2025 15:04, edited 1 time in total.
User avatar
waltervl
Posts: 5853
Joined: Monday 28 January 2019 18:48
Target OS: Linux
Domoticz version: 2024.7
Location: NL
Contact:

Re: Identify a switching sequence

Post by waltervl »

You can ask for the last updated value of those 3 sensors if the last update value is equal to switching. It depends on the integration if last update is the same as last switched.

Code: Select all

if (domoticz.devices('My PIR 1').lastUpdate.minutesAgo < 5 and 
	domoticz.devices('My PIR 2').lastUpdate.minutesAgo < 5 and
	domoticz.devices('My PIR 3').lastUpdate.minutesAgo < 5)
Domoticz running on Udoo X86 (on Ubuntu)
Devices/plugins: ZigbeeforDomoticz (with Xiaomi, Ikea, Tuya devices), Nefit Easy, Midea Airco, Omnik Solar, Goodwe Solar
paul402
Posts: 96
Joined: Monday 23 May 2016 23:07
Target OS: Raspberry Pi / ODroid
Domoticz version:
Contact:

Re: Identify a switching sequence

Post by paul402 »

Wow! Thank you. I never expected so much help!
Can I be cheeky and ask how I would change this if the motion sequence went sensor1, sensor2 and back to sensor1 as the alternative possible exit.
User avatar
waltervl
Posts: 5853
Joined: Monday 28 January 2019 18:48
Target OS: Linux
Domoticz version: 2024.7
Location: NL
Contact:

Re: Identify a switching sequence

Post by waltervl »

I think you have to ask chatgpt..... :)
My solution was only to check if 3 motion sensors were triggered within 5 minutes. Not checking the order. But that could probably done with some simple if-then statements based on last updates (but then with swcondsago instead of minutes ago.
Domoticz running on Udoo X86 (on Ubuntu)
Devices/plugins: ZigbeeforDomoticz (with Xiaomi, Ikea, Tuya devices), Nefit Easy, Midea Airco, Omnik Solar, Goodwe Solar
paul402
Posts: 96
Joined: Monday 23 May 2016 23:07
Target OS: Raspberry Pi / ODroid
Domoticz version:
Contact:

Re: Identify a switching sequence

Post by paul402 »

Thanks. I've never used AI/ChatGPT before how do you phrase a request for code? Do you have an example of what you entered to reply to my initial post?
User avatar
Ragdag
Posts: 152
Joined: Friday 30 March 2018 13:56
Target OS: Raspberry Pi / ODroid
Domoticz version: Beta
Location: Netherlands
Contact:

Re: Identify a switching sequence

Post by Ragdag »

paul402 wrote: Sunday 16 February 2025 6:28 Thanks. I've never used AI/ChatGPT before how do you phrase a request for code? Do you have an example of what you entered to reply to my initial post?
I did something like this
Can you help me with this Domoticz dzvents script?
I would like to know if 3 movement sensors are triggered in a sequence with max 5 minutes gap between each of the triggers for the data to be valid.
I do have the premium ChatGPT this month, so I created a Domoticz dzvents project so that I can attach the dzvents wiki page as a resource, but even without it will likely work
User avatar
Ragdag
Posts: 152
Joined: Friday 30 March 2018 13:56
Target OS: Raspberry Pi / ODroid
Domoticz version: Beta
Location: Netherlands
Contact:

Re: Identify a switching sequence

Post by Ragdag »

Here is an alternative, with both sequences

Code: Select all

--[[
Description:
This script monitors a sequence of three motion sensors. It validates that the triggers occur within a maximum of 5 minutes between each activation.
Additionally, it detects an alternative exit sequence where motion returns to Sensor 1 after Sensor 2.
--]]

-----------------------------------------------------------
-- Constants and Configuration
-----------------------------------------------------------
local scriptName = 'MotionSequenceDetection'
local maxTimeGap = 300 -- 5 minutes (in seconds)

-- Sensor names as configured in Domoticz
local SENSORS = {
    SENSOR1 = 'Motion Sensor 1',
    SENSOR2 = 'Motion Sensor 2',
    SENSOR3 = 'Motion Sensor 3'
}

-----------------------------------------------------------
-- Persistent Data Storage
-----------------------------------------------------------
return {
    on = {
        devices = { SENSORS.SENSOR1, SENSORS.SENSOR2, SENSORS.SENSOR3 }
    },

    data = {
        motionSequence = { initial = {} }
    },

    execute = function(domoticz, device)
        local now = domoticz.time.raw
        local sequence = domoticz.data.motionSequence

        -- Remove expired entries
        local newSequence = {}
        for _, entry in ipairs(sequence) do
            if now - entry.time <= maxTimeGap then
                table.insert(newSequence, entry)
            end
        end
        sequence = newSequence

        -- Add the new motion event
        table.insert(sequence, { sensor = device.name, time = now })
        domoticz.data.motionSequence = sequence

        -- Check if sequence matches predefined patterns
        if #sequence >= 3 then
            if sequence[1].sensor == SENSORS.SENSOR1 and
               sequence[2].sensor == SENSORS.SENSOR2 and
               sequence[3].sensor == SENSORS.SENSOR3 then
                domoticz.log('Valid motion sequence detected: SENSOR1 -> SENSOR2 -> SENSOR3', domoticz.LOG_INFO)
            elseif sequence[1].sensor == SENSORS.SENSOR1 and
                   sequence[2].sensor == SENSORS.SENSOR2 and
                   sequence[3].sensor == SENSORS.SENSOR1 then
                domoticz.log('Alternative exit detected: SENSOR1 -> SENSOR2 -> SENSOR1', domoticz.LOG_INFO)
            end
        end
    end
}

paul402
Posts: 96
Joined: Monday 23 May 2016 23:07
Target OS: Raspberry Pi / ODroid
Domoticz version:
Contact:

Re: Identify a switching sequence

Post by paul402 »

Thank you. I've learned something new!
Much appreciated. Can't wait to try this on another project I have in mind to create a touch screen Raspi with rotating info/photo screens.
Post Reply

Who is online

Users browsing this forum: No registered users and 1 guest