Check Sensors script (dzVents)  [Solved]

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

Moderator: leecollings

User avatar
waaren
Posts: 6028
Joined: Tuesday 03 January 2017 14:18
Target OS: Linux
Domoticz version: Beta
Location: Netherlands
Contact:

Re: Check Sensors script (dzVents)

Post by waaren »

hoeby wrote: Monday 03 June 2019 21:14 I hope somebody can help me.
Have a look at this on how to loop through the results, -select the devices you need and display the lastSeen value from the domoticz api.

Code: Select all

local scriptVar = 'lastSeen'

return {
    on = { timer =  {'every minute'}, httpResponses = { scriptVar }},
    logging = { level   = domoticz.LOG_ERROR, marker  = scriptVar },
    
    execute = function(dz, item)
        if not (item.isHTTPResponse) then
            dz.openURL({ 
                url = dz.settings['Domoticz url'] .. '/json.htm?type=devices&used=true',
                callback = scriptVar })
        else
            local devicesToBeChecked =  {["982"]=1, ["1003"]=1, ["1011"]=1, ["Watermeter"]=1 } -- change to idx / name of the devices you want to check
            local Time = require('Time')
            for _, node in pairs(item.json.result) do
                if devicesToBeChecked[node.idx] or devicesToBeChecked[node.Name] then
                    dz.log('id '..  node.idx .. '(' ..node.Name ..') lastUpdate secondsAgo ==>> ' .. Time(node.LastUpdate).secondsAgo,dz.LOG_FORCE)
                end
            end
        end
    end
}
Debian buster, bullseye on RPI-4, Intel NUC.
dz Beta, Z-Wave, RFLink, RFXtrx433e, P1, Youless, Hue, Yeelight, Xiaomi, MQTT
==>> dzVents wiki
hoeby
Posts: 531
Joined: Saturday 02 June 2018 11:05
Target OS: Raspberry Pi / ODroid
Domoticz version: V2022.1
Location: Echt, Netherlands
Contact:

Re: Check Sensors script (dzVents)

Post by hoeby »

Thanks Waaren,

I made a start with it.
Yes it works, but i can't get it to work for 100%

The script does for _, node in pairs(item.json.result) do
After that i do for deviceName, threshold in pairs(toCheck) do, to get the threshold which is paired with the device.
But when doing this, the script is run Multi-times to many.
I now disabled the like for deviceName, threshold in pairs(toCheck) do and have given a local threshold. One setting for all devices. Than it works. But i prefer to have the option for giving a different threshold to each device.

Some idea's how to do this, or getting me on the road to a solution?

The log, when for deviceName, threshold in pairs(toCheck) do

Code: Select all

2019-06-04 21:00:00.415 Status: dzVents: Info: Handling httpResponse-events for: "lastSeen 
2019-06-04 21:00:00.491 Status: dzVents: 433 
2019-06-04 21:00:00.491 Status: dzVents: !Info: lastSeen: dzCheckSensors Dashboard-webpage-check : 7.21 minutes was last response, threshold=2 days 
2019-06-04 21:00:00.491 Status: dzVents: !Info: lastSeen: dzCheckSensors Test-Deur-Contact-Zigbee : 7.21 minutes was last response, threshold=2 days 
2019-06-04 21:00:00.492 Status: dzVents: !Info: lastSeen: dzCheckSensors Smoke-801414201509-zigbee : 7.21 minutes was last response, threshold=2 days 
2019-06-04 21:00:00.492 Status: dzVents: 43080 
2019-06-04 21:00:00.492 Status: dzVents: !Info: lastSeen: dzCheckSensors Dashboard-webpage-check : 11.9 hours was last response, threshold=2 days 
2019-06-04 21:00:00.492 Status: dzVents: !Info: lastSeen: dzCheckSensors Test-Deur-Contact-Zigbee : 11.9 hours was last response, threshold=2 days 
2019-06-04 21:00:00.493 Status: dzVents: !Info: lastSeen: dzCheckSensors Smoke-801414201509-zigbee : 11.9 hours was last response, threshold=2 days 
2019-06-04 21:00:00.493 Status: dzVents: 1587 
2019-06-04 21:00:00.493 Status: dzVents: !Info: lastSeen: dzCheckSensors Dashboard-webpage-check : 26.4 minutes was last response, threshold=2 days 
2019-06-04 21:00:00.494 Status: dzVents: !Info: lastSeen: dzCheckSensors Test-Deur-Contact-Zigbee : 26.4 minutes was last response, threshold=2 days 
2019-06-04 21:00:00.494 Status: dzVents: !Info: lastSeen: dzCheckSensors Smoke-801414201509-zigbee : 26.4 minutes was last response, threshold=2 days 
2019-06-04 21:00:37.661 Status: EventSystem: reset all events... 
The script, without for deviceName, threshold in pairs(toCheck) do

Code: Select all

local scriptVar = 'lastSeen'

return {
    on = { timer =  {'every minute'}, httpResponses = { scriptVar }},
    logging = { level   = domoticz.LOG_ERROR, marker  = scriptVar },
    
    data = { notified = { initial = {} } },
    
    execute = function(dz, item)
            
            local notifyTime = 'at 10:00' --you can add multiple notification times, i.e. 'at 12:00, at 20:00'
	        local notifyHead = 'dzCheckSensors'
	        local notified   = dz.data.notified -- short reference
	        local teleTok    = 'xxxxxxxxxxxxxxxxxxxxxxxxxxx'
                local chatId     = 'Xxxxxxxxxxxxxxx'
                local domoURL    = 'xxx.xxx.xxx.xxx'
                local domoPORT   = 'xxxx'
        
            
        if dz.devices('opVakantie').state== 'On' then
	        toCheck = {    -- timeout for each device, in seconds (with holiday)
                ['Smoke-801414201509-zigbee']       = 1209600,    -- 2 weken
                ['Test-Deur-Contact-Zigbee']        = 1209600,    -- 2 weken
            }
        else
            toCheck = {    -- timeout for each device, in seconds (no holiday)
                ['Smoke-801414201509-zigbee']       = 172800,     -- 2 dagen
                ['Test-Deur-Contact-Zigbee']        = 172800,     -- 2 dagen
                ['Dashboard-webpage-check']         = 172800,
            }
        end
	
        function writeTime(secs)
            local t
            secs=tonumber(secs)
                if secs == nil then t='NIL'
                    elseif secs >= 86400   then t=string.sub(tostring(secs/24/3600),1,4)..' days'  
                    elseif secs >= 3600    then t=string.sub(tostring(secs/3600),1,4)..' hours' 
                    elseif secs >= 60      then t=string.sub(tostring(secs/60),1,4)..' minutes'
                    else t=secs..' seconds' 
                end
                return t 
            end
        
        for deviceName, lastUpdate in pairs(notified) do
     	    if toCheck[deviceName]==nil then
     	            notified[deviceName]=nil
     	            dz.log (notifyHead .." ".. deviceName.. ' was removed from the notified table, '..writeTime(threshold),99)
            end
        end
        
        if not (item.isHTTPResponse) then
            dz.openURL({ 
                --url = dz.settings['Domoticz url'] .. '/json.htm?type=devices&used=true',
                url = (domoURL..':'..domoPORT..'/json.htm?type=devices&used=true'),
                callback = scriptVar })
        else
            local Time = require('Time')
            for _, node in pairs(item.json.result) do
                if toCheck[node.Name] then
                    --dz.log('id '..  node.idx .. '(' ..node.Name ..') lastUpdate secondsAgo ==>> ' .. Time(node.LastUpdate).secondsAgo,dz.LOG_FORCE)
                    local lastSeen = Time(node.LastUpdate)
                    local lastUpdate = lastSeen.secondsAgo
                    local deviceName = node.Name
                    print (lastUpdate)
                    local threshold = 172800
                   -- for deviceName, threshold in pairs(toCheck) do
            	    	if Time(node.lastUpdate).secondsAgo < threshold then
              		        --device is alive
                            if notified[deviceName] == nil then
                                dz.log(notifyHead .." "..deviceName.." : "..writeTime(lastUpdate).. ' was last response, threshold='..writeTime(threshold),dz.LOG_FORCE)
                            else
                                dz.log(notifyHead .." ".. 'Signal back from sensor '..deviceName)
                                notified[deviceName] = nil  --remove from notified list
                                os.execute('curl -s -X POST "https://api.telegram.org/bot'..teleTok..'/sendMessage?chat_id='..chatId..'&text='..notifyHead .." ".. 'Signal back from sensor ."')
                            end
                        else 
                            --lost signal:
                            if notified[deviceName] == nil then
                            --immediate notification after signal lost:
                            dz.log (notifyHead .." ".. 'Signal lost: '..deviceName .." sent "..writeTime(lastUpdate).. ' the last signal, threshold='..writeTime(threshold)..'. Battery empty?')
                            notified[deviceName] = 1
                            os.execute('curl -s -X POST "https://api.telegram.org/bot'..teleTok..'/sendMessage?chat_id='..chatId..'&text='..notifyHead..' Signal lost: '..deviceName ..' sent '..writeTime(lastUpdate).. ' the last signal, threshold='..writeTime(threshold)..'. Battery empty?"')
                        elseif
                            --sent reminders on daily basis:
                            dz.time.matchesRule(notifyTime) and  --time slot to notify
                            dz.devices('opVakantie').state == 'Off' -- not on holiday
                        then
                            dz.log(notifyHead .." ".. 'Reminder, '..deviceName .." sent "..writeTime(lastUpdate).. ' the last signal. Battery empty?')
                            local telesignalremind = (notifyHead .." ".. 'Reminder, '..deviceName .." sent "..Time(lastUpdate).. ' the last signal. Battery empty?')
                            os.execute('curl -s -X POST "https://api.telegram.org/bot'..teleTok..'/sendMessage?chat_id='..chatId..'&text='..notifyHead .." ".. 'Reminder, '..deviceName .." sent "..writeTime(lastUpdate).. ' the last signal. Battery empty?"')
                        end
                    end
                end
            end
        end
    end

}
Thin-client --> Docker Domoticz main environment
Pi3A+ --> Google home (GAssistPi)
Pi3B+ --> Docker (P1monitor, Domoticz test environment, Ubiquity controller)
User avatar
waaren
Posts: 6028
Joined: Tuesday 03 January 2017 14:18
Target OS: Linux
Domoticz version: Beta
Location: Netherlands
Contact:

Re: Check Sensors script (dzVents)

Post by waaren »

hoeby wrote: Tuesday 04 June 2019 21:13 it works, but i can't get it to work for 100%
The script does for _, node in pairs(item.json.result) do
After that i do for deviceName, threshold in pairs(toCheck) do, to get the threshold which is paired with the device.
But when doing this, the script is run Multi-times to many.
In fact you do not need a nested loop. You will get the treshold value in the devicesToBeChecked table directly by using the key (which is the device.idx or device.name)

Code: Select all

local scriptVar = 'lastSeen'

return {
    on = { timer =  {'every minute'}, httpResponses = { scriptVar }},
    logging = { level   = domoticz.LOG_ERROR, marker  = scriptVar },
    
    execute = function(dz, item) 
        local aMinute = 60                   -- Old habits ... ;-)
        local anHour = 60 * aMinute
        local aDay = 24 * anHour
        local twoDays = 2 * aDay
        local aWeek = 7 * aDay
        local twoWeeks = 14 * aDay

        local holiday = dz.devices('opVakantie').active
        
        local function getTimeString(seconds)
            if not seconds then return 'NIL' end

            local width = 4
            if seconds > aWeek then return string.sub(tostring(seconds/aWeek),1,width)..' weeks' end
            if seconds > aDay  then return string.sub(tostring(seconds/aDay),1,width)..' days' end
            if seconds > anHour then return string.sub(tostring(seconds/anHour),1,width)..' hours' end
            if seconds > aMinute then return string.sub(tostring(seconds/aMinute),1,width)..' minutes' end
            
            return seconds .. ' seconds'
        end
        
        if not (item.isHTTPResponse) then
            dz.openURL({ 
                url = dz.settings['Domoticz url'] .. '/json.htm?type=devices&used=true',
                callback = scriptVar })
        else
            local devicesToBeChecked =  { ["982"] = twoDays, ["35"] = anHour, ["1003"]= twoDays, ["1011"]= twoDays, ["Watermeter"]= aDay } -- change to idx / name of the devices you want to check
            if holiday then
                devicesToBeChecked = { ["982"] = aWeek, ["1003"]= twoWeeks, ["1011"]= twoDays } -- change to idx / name of the devices you want to check during holidays
            end
            
            local Time = require('Time')
            for _, node in pairs(item.json.result) do
                local toCheck = ( devicesToBeChecked[node.idx] or devicesToBeChecked[node.Name]) -- now toCheck contains the treshold in seconds
                if toCheck then -- note that any other value than false or nil is true in Lua
                    dz.log('id '..  node.idx .. '(' ..node.Name ..
                                    ') lastUpdate was ' .. 
                                    getTimeString(Time(node.LastUpdate).secondsAgo) ..
                                    ' ago. Treshold is ' .. getTimeString(toCheck)
                                    ,dz.LOG_FORCE)
                end
            end
        end
    end
}
Debian buster, bullseye on RPI-4, Intel NUC.
dz Beta, Z-Wave, RFLink, RFXtrx433e, P1, Youless, Hue, Yeelight, Xiaomi, MQTT
==>> dzVents wiki
hoeby
Posts: 531
Joined: Saturday 02 June 2018 11:05
Target OS: Raspberry Pi / ODroid
Domoticz version: V2022.1
Location: Echt, Netherlands
Contact:

Re: Check Sensors script (dzVents)  [Solved]

Post by hoeby »

Thanks Waaren,

Got it working like i would.
Got me a couples of hours, to get to the result i was looking for.
Again needed to build it in sections and everytime check if the data was there. Sorry, i am not a good programmer, so need to go for trail and error ways.

The final code for me

Code: Select all

local scriptVar = 'lastSeen'

return {
    on = { timer =  {'every 10 minutes'}, httpResponses = { scriptVar }},
    --on = { timer =  {'every minute'}, httpResponses = { scriptVar }},
    --on = { timer =  {'at 08:00', 'at 10:00'}, httpResponses = { scriptVar }},
    logging = { level   = domoticz.LOG_ERROR, marker  = scriptVar },
    
    data = { notified = { initial = {} } },
    
    execute = function(dz, item)
            
            local notifyTime = 'at 10:00' --you can add multiple notification times, i.e. 'at 12:00, at 20:00'
            local notifyHead = 'dzCheckSensors'
	    local notified   = dz.data.notified -- short reference
	    local teleTok    = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
            local chatId     = 'xxxxxxxxxxxxxxxxx'
            local domoURL    = 'xxx.xxx.xxx.xxx'
            local domoPORT   = 'xxxx'
        
        function writeTime(secs)
            local t
            secs=tonumber(secs)
                if secs == nil then t='NIL'
                    else t=secs
                end
                return t 
            end
            
        function Timers(sec)
            local ti
            sec=tonumber(sec)
                if sec == nil then ti='NIL'
                    elseif sec >= 86400   then ti=string.sub(tostring(sec/24/3600),1,4)..' days'  
                    elseif sec >= 3600    then ti=string.sub(tostring(sec/3600),1,4)..' hours' 
                    elseif sec >= 60      then ti=string.sub(tostring(sec/60),1,4)..' minutes'
                    else ti=sec..' seconds'
                end
                return ti 
            end    
         
        if not (item.isHTTPResponse) then
            dz.openURL({ 
                url = (domoURL..':'..domoPORT..'/json.htm?type=devices&used=true'),
                callback = scriptVar })
        else
            if dz.devices('opVakantie').state== 'On' then
	            DevicesToCheck = {    -- timeout for each device, in seconds (with holiday)
                    ['Smoke-801414201509-zigbee']       = 1209600,    -- 2 weken
                    ['Test-Deur-Contact-Zigbee']        = 1209600,    -- 2 weken
                }
            else
                DevicesToCheck = {    -- timeout for each device, in seconds (no holiday)
                    ['Smoke-801414201509-zigbee']       = 172800,     -- 2 dagen
                    ['Test-Deur-Contact-Zigbee']        = 172800,     -- 2 dagen
                    ['Dashboard-webpage-check']         = 172800,     -- 2 dagen
                }
            end
	
            local Time = require('Time')
            for _, node in pairs(item.json.result) do
                local toCheck = ( DevicesToCheck[node.idx] or DevicesToCheck[node.Name])
                if toCheck then
                    local lastUpdate = writeTime(Time(node.LastUpdate).secondsAgo)
                    local deviceName = node.Name
                    local threshold = writeTime(toCheck)
                    	if writeTime(lastUpdate) < threshold then
              		        --device is alive
                            if notified[deviceName] == nil then
                                dz.log(notifyHead .." "..deviceName.." : "..Timers(lastUpdate).. ' was last response, threshold='..Timers(threshold),dz.LOG_FORCE)
                            else
                                dz.log(notifyHead .." ".. 'Signal back from sensor '..deviceName,dz.LOG_FORCE)
                                notified[deviceName] = nil  --remove from notified list
                                os.execute('curl -s -X POST "https://api.telegram.org/bot'..teleTok..'/sendMessage?chat_id='..chatId..'&text='..notifyHead .." ".. 'Signal back from sensor ."')
                            end
                        else 
                            --lost signal:
                            if notified[deviceName] == nil then
                            --immediate notification after signal lost:
                            dz.log (notifyHead .." ".. 'Signal lost: '..deviceName .." sent "..Timers(lastUpdate).. ' the last signal, threshold='..Timers(threshold)..'. Battery empty?',dz.LOG_FORCE)
                            notified[deviceName] = 1
                            os.execute('curl -s -X POST "https://api.telegram.org/bot'..teleTok..'/sendMessage?chat_id='..chatId..'&text='..notifyHead..' Signal lost: '..deviceName ..' sent '..Timers(lastUpdate).. ' the last signal, threshold='..Timers(threshold)..'. Battery empty?"')
                        elseif
                            --sent reminders on daily basis:
                            dz.time.matchesRule(notifyTime) and  --time slot to notify
                            dz.devices('opVakantie').state == 'Off' -- not on holiday
                        then
                            dz.log(notifyHead .." ".. 'Reminder, '..deviceName .." sent "..Timers(lastUpdate).. ' the last signal. Battery empty?',dz.LOG_FORCE)
                            os.execute('curl -s -X POST "https://api.telegram.org/bot'..teleTok..'/sendMessage?chat_id='..chatId..'&text='..notifyHead .." ".. 'Reminder, '..deviceName .." sent "..Timers(lastUpdate).. ' the last signal. Battery empty?"')
                        end
                    end
                end
            end
        end
    end

}
Thin-client --> Docker Domoticz main environment
Pi3A+ --> Google home (GAssistPi)
Pi3B+ --> Docker (P1monitor, Domoticz test environment, Ubiquity controller)
User avatar
waaren
Posts: 6028
Joined: Tuesday 03 January 2017 14:18
Target OS: Linux
Domoticz version: Beta
Location: Netherlands
Contact:

Re: Check Sensors script (dzVents)

Post by waaren »

hoeby wrote: Thursday 06 June 2019 22:36 Got it working like i would. I am not a programmer, so need to go for trial and error
Luckily that's not important here. Important is that you have fun while making steps !
Debian buster, bullseye on RPI-4, Intel NUC.
dz Beta, Z-Wave, RFLink, RFXtrx433e, P1, Youless, Hue, Yeelight, Xiaomi, MQTT
==>> dzVents wiki
hoeby
Posts: 531
Joined: Saturday 02 June 2018 11:05
Target OS: Raspberry Pi / ODroid
Domoticz version: V2022.1
Location: Echt, Netherlands
Contact:

Re: Check Sensors script (dzVents)

Post by hoeby »

waaren wrote: Thursday 06 June 2019 23:33Luckily that's not important here. Important is that you have fun while making steps !
My wife thinks different about that.
I am having great fun, that i forget the time.
My wife has to ask to come to sleep, because it is already late.
Thin-client --> Docker Domoticz main environment
Pi3A+ --> Google home (GAssistPi)
Pi3B+ --> Docker (P1monitor, Domoticz test environment, Ubiquity controller)
hoeby
Posts: 531
Joined: Saturday 02 June 2018 11:05
Target OS: Raspberry Pi / ODroid
Domoticz version: V2022.1
Location: Echt, Netherlands
Contact:

Re: Check Sensors script (dzVents)

Post by hoeby »

Changed a few little things in the script.
Also added the option to send an e-mail or telegram or both.
Changes email or telegram to true of false to decide what you would like to have

All settings that have to be done are now in the top of the script
Also a small manual is written in de top of the script what to setup.
This prevents that you have to search in the script to put in your personal settings

Does somebody have idea's what to add or change?
Or is it a nice script how this is setup?

Code: Select all

-- Verion: 19061501

-- WHAT TO SETUP TO MAKE THIS SCRIPT WORKING 
-- Make a dummy device named: opVakantie
-- Dummy device opVakantie changes the threshold timer for the devices-check
-- The idea is: opVakantie Device ON = longer threshold numbers, so you don't get notification on your holiday
-- And opVakantie Device Off = to have shorter threshold numbers.

-- Fill in your IP address of your domoticz server
-- Fill in the port number of your domoticz server

-- Set telegram true is you want telegram notification, but therefor teleTOK and chatID has to be filled in

-- Set email true is you want to receive an e-mail, but therefor the e-mail has te be setup in domoticz-->settings
-- Fill in you e-mail address where to send to

-- There is a line which says: -- Don't change things undernead this line
-- If you have no idea how the scripts works, please lissen to this.
-- If you know how it works and have ideas, please post them on http://www.domoticz.com/forum/viewtopic.php?f=59&t=18566&start=20

local scriptVar = 'lastSeen'

return {
    on = { timer =  {'every 30 minutes'}, httpResponses = { scriptVar }},
    logging = { level   = domoticz.LOG_ERROR, marker  = scriptVar },
    
    data = { notified = { initial = {} } },
    
    execute = function(dz, item)
        
        --Domoticz settings
            local domoURL     = 'xxx.xxx.xxx.xxx'            -- IP address of Domoticz
            local domoPORT    = 'xxxx'                       -- Port number of Domoticz
        
        --Telegram settings
            local telegram    = true                        -- Set true for sending telegram, set false for NOT sending telegram.
            local teleTok     = 'xxxxxxxxx:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
            local chatId      = '-xxxxxxxxxxx'
        
        --Email settings (domoticz email settings have to be filled in)
            local email       = true                        -- Set true for sending email, set false for NOT sending email.
            local mailaddress = '[email protected]'
        
        -- Global settings
            local notifyTime  = 'at 10:00'                  -- You can add multiple notification times, i.e. 'at 12:00, at 20:00'
	        local notifyHead  = 'dzCheckSensors'            -- This is the start of everynotificatio, so you know it is this script.
	         
	    -- Devices to check NO holiday.
	    --                        Devices name column                 Time column in seconds                 
	        local devices_No =  {
	                            ['Test-Deur-Contact-Zigbee']        = 172800,  -- 2 Days
                                ['Dashboard-webpage-check']         = 172800,  -- 2 Days  
	                            }
	    
	    -- Devices to check when it is holiday.
	    --                        Devices name column                 Time column in seconds
	        local devices_Yes = {
	                            ['Test-Deur-Contact-Zigbee']        = 1209600,  --14 Days
                                ['Dashboard-webpage-check']         = 1209600,  --14 Days  
	                            }
	                          
-- Don't change things undernead this line
        local notified    = dz.data.notified -- short reference
	        
        function writeTime(secs)
            local t
            secs=tonumber(secs)
                if secs == nil then t='NIL'
                    else t=secs
                end
                return t 
            end
            
        function Timers(sec)
            local ti
            sec=tonumber(sec)
                if sec == nil then ti='NIL'
                    elseif sec >= 86400   then ti=string.sub(tostring(sec/24/3600),1,4)..' days'  
                    elseif sec >= 3600    then ti=string.sub(tostring(sec/3600),1,4)..' hours' 
                    elseif sec >= 60      then ti=string.sub(tostring(sec/60),1,4)..' minutes'
                    else ti=sec..' seconds'
                end
                return ti 
            end    
        
--        for deviceName, lastUpdate in pairs(notified) do
--     	    if toCheck[deviceName]==nil then
--     	            notified[deviceName]=nil
--     	            dz.log (notifyHead .." ".. deviceName.. ' was removed from the notified table, '..Timers(threshold),99)
--            end
--        end
        
        if not (item.isHTTPResponse) then
            dz.openURL({ 
                url = (domoURL..':'..domoPORT..'/json.htm?type=devices&used=true'),
                callback = scriptVar })
        else
            if dz.devices('opVakantie').state== 'On' then
                dz.log(notifyHead .." ".. 'Vakantie-On',dz.LOG_FORCE)
	            DevicesToCheck = devices_Yes
            else
                dz.log(notifyHead .." ".. 'Vakantie-Off',dz.LOG_FORCE)
                DevicesToCheck = devices_No
            end
	
        local Time = require('Time')
            for _, node in pairs(item.json.result) do
                local toCheck = ( DevicesToCheck[node.idx] or DevicesToCheck[node.Name])
                if toCheck then
                    local lastUpdate = writeTime(Time(node.LastUpdate).secondsAgo)
                    local deviceName = node.Name
                    local threshold = writeTime(toCheck)
                    	if writeTime(lastUpdate) < threshold then
              		        --device is alive
                            if notified[deviceName] == nil then
                                dz.log(notifyHead .." "..deviceName.." : "..Timers(lastUpdate).. ' was last response, threshold='..Timers(threshold),dz.LOG_FORCE)
                            else
                                dz.log(notifyHead .." ".. ' Signal back from sensor '..deviceName,dz.LOG_FORCE)
                                notified[deviceName] = nil  --remove from notified list
                                if telegram then
                                        os.execute('curl -s -X POST "https://api.telegram.org/bot'..teleTok..'/sendMessage?chat_id='..chatId..'&text='..notifyHead .." ".. 'Signal back from sensor '..deviceName..'."')
                                    end     
                                if email then
                                    dz.email('Domoticz device check', ''..notifyHead.. 'Signal back from sensor '..deviceName..'', ''..mailaddress..'')
                                end
                            end
                        else 
                            --lost signal:
                            if notified[deviceName] == nil then
                                dz.log (notifyHead .." ".. 'Signal lost: '..deviceName .." sent "..Timers(lastUpdate).. ' the last signal, threshold='..Timers(threshold)..'. Battery empty?',dz.LOG_FORCE)
                                notified[deviceName] = 1
                                    if telegram then
                                        os.execute('curl -s -X POST "https://api.telegram.org/bot'..teleTok..'/sendMessage?chat_id='..chatId..'&text='..notifyHead..' Signal lost: '..deviceName ..' sent '..Timers(lastUpdate).. ' the last signal, threshold='..Timers(threshold)..'. Battery empty?"')
                                    end     
                                    if email then
                                        dz.email('Domoticz device check', ''..notifyHead..' Signal lost: '..deviceName ..' sent '..Timers(lastUpdate).. ' the last signal, threshold='..Timers(threshold)..'. Battery empty?', ''..mailaddress..'')
                                    end
                        elseif
                            dz.time.matchesRule(notifyTime) and  
                            dz.devices('opVakantie').state == 'Off'
                        then
                            dz.log(notifyHead .." ".. 'Reminder, '..deviceName .." sent "..Timers(lastUpdate).. ' the last signal. Battery empty?',dz.LOG_FORCE)
                            if telegram then
                                os.execute('curl -s -X POST "https://api.telegram.org/bot'..teleTok..'/sendMessage?chat_id='..chatId..'&text='..notifyHead .." ".. 'Reminder, '..deviceName .." sent "..Timers(lastUpdate).. ' the last signal. Battery empty?"')
                            end     
                            if email then
                                dz.email('Domoticz device check', ''..notifyHead..' Signal lost: '..deviceName ..' sent '..Timers(lastUpdate).. ' the last signal, threshold='..Timers(threshold)..'. Battery empty?', ''..mailaddress..'')
                            end
                        end
                    end
                end
            end
        end
    end

}
Thin-client --> Docker Domoticz main environment
Pi3A+ --> Google home (GAssistPi)
Pi3B+ --> Docker (P1monitor, Domoticz test environment, Ubiquity controller)
User avatar
waaren
Posts: 6028
Joined: Tuesday 03 January 2017 14:18
Target OS: Linux
Domoticz version: Beta
Location: Netherlands
Contact:

Re: Check Sensors script (dzVents)

Post by waaren »

hoeby wrote: Saturday 15 June 2019 17:39 Changed a few little things in the script.
Does somebody have idea's what to add or change?
Or is it a nice script how this is setup?
Nice one !

Some questions:
Is there a specific reason why you don't use dz.settings["Domoticz url"] for the domoticz server IP ?
Same question about using curl for telegram notifications. Telegram is now one of the notification sub subsystems natively supported in domoticz and dzVents.
For both of the above the advantage is that you don't have to ask in every script using this, to enter the IP, port and keys.

I don't understand what you do with function writeTime(). It does not write anything but returns a number or the string 'NIL'
I think that you could easily do without this function if you rewrite the code calling this function. This would make the script easier to read (and maintain)
Debian buster, bullseye on RPI-4, Intel NUC.
dz Beta, Z-Wave, RFLink, RFXtrx433e, P1, Youless, Hue, Yeelight, Xiaomi, MQTT
==>> dzVents wiki
hoeby
Posts: 531
Joined: Saturday 02 June 2018 11:05
Target OS: Raspberry Pi / ODroid
Domoticz version: V2022.1
Location: Echt, Netherlands
Contact:

Re: Check Sensors script (dzVents)

Post by hoeby »

waaren wrote: Saturday 15 June 2019 21:05 Is there a specific reason why you don't use dz.settings["Domoticz url"] for the domoticz server IP ?

The reason was that i got an error when using dz.settings["Domoticz url"].
But this was my mistake, i didn't filled in the local netwerk.
Changed it and tested it, works now
waaren wrote: Saturday 15 June 2019 21:05 Same question about using curl for telegram notifications. Telegram is now one of the notification sub subsystems natively supported in domoticz and dzVents.
I am doing this, because i use Multi telegram ID's.
1 for sending technical information to me and 1 for functional things, which is a group my wife is also in.
Could be changed to the dzvents telegram way. Will have a look at it to change it, to make the script easier for other users.
waaren wrote: Saturday 15 June 2019 21:05 I don't understand what you do with function writeTime(). It does not write anything but returns a number or the string 'NIL'
This is because of the trail and error way, how i sometimes program.
I removed it and changed the script. Tested it and still running

Today i added a version table undernead the script.
To see what is is changed in relation the the previous version

Code: Select all

-- Verion: 19061601

-- WHAT TO SETUP TO MAKE THIS SCRIPT WORKING 
-- Fill in the local network setting for Domoticz.
-- Go to SETTINGS --> SETTINGS --> SYSTEM --> LOCAL NETWORK.
-- Fill in your IP adres. When it is local you could fill in 127.0.0.*

-- Make a dummy device named: opVakantie
-- Dummy device opVakantie changes the threshold timer for the devices-check
-- The idea is: opVakantie Device ON = longer threshold numbers, so you don't get notification on your holiday
-- And opVakantie Device Off = to have shorter threshold numbers.

-- Set telegram true is you want telegram notification, but therefor teleTOK and chatID has to be filled in

-- Set email true is you want to receive an e-mail, but therefor the e-mail has te be setup in domoticz-->settings
-- Fill in you e-mail address where to send to

-- There is a line which says: -- Don't change things undernead this line
-- If you have no idea how the scripts works, please lissen to this.
-- If you know how it works and have ideas, please post them on http://www.domoticz.com/forum/viewtopic.php?f=59&t=18566&start=20

local scriptVar = 'lastSeen'

return {
    on = { timer =  {'every 30 minutes'}, httpResponses = { scriptVar }},
    logging = { level   = domoticz.LOG_ERROR, marker  = scriptVar },
    
    data = { notified = { initial = {} } },
    
    execute = function(dz, item)
        
        --Telegram settings
            local telegram    = false                        -- Set true for sending telegram, set false for NOT sending telegram.
            local teleTok     = 'xxxxxxxxx:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
            local chatId      = '-xxxxxxxxxx'
        
        --Email settings (domoticz email settings have to be filled in)
            local email       = false                        -- Set true for sending email, set false for NOT sending email.
            local mailaddress = '[email protected]'
        
        -- Global settings
            local notifyTime  = 'at 10:00'                  -- You can add multiple notification times, i.e. 'at 12:00, at 20:00'
	        local notifyHead  = 'dzCheckSensors'            -- This is the start of everynotification, so you know it is this script.
	         
	    -- Devices to check NO holiday.
	    --                        Devices name column                 Time column in seconds                 
	        local devices_No =  {
	                            ['Test-Deur-Contact-Zigbee']        = 172800,  -- 2 Days
                                ['Dashboard-webpage-check']         = 172800,  -- 2 Days  
	                            }
	    
	    -- Devices to check when it is holiday.
	    --                        Devices name column                 Time column in seconds
	        local devices_Yes = {
	                            ['Test-Deur-Contact-Zigbee']        = 1209600,  --14 Days
                                ['Dashboard-webpage-check']         = 1209600,  --14 Days  
	                            }
	                          
-- Don't change things undernead this line
        local notified    = dz.data.notified -- short reference

        function Timers(sec)
            local ti
            sec=tonumber(sec)
                if sec == nil then ti='NIL'
                    elseif sec >= 86400   then ti=string.sub(tostring(sec/24/3600),1,4)..' days'  
                    elseif sec >= 3600    then ti=string.sub(tostring(sec/3600),1,4)..' hours' 
                    elseif sec >= 60      then ti=string.sub(tostring(sec/60),1,4)..' minutes'
                    else ti=sec..' seconds'
                end
                return ti 
            end    
                
        if not (item.isHTTPResponse) then
            dz.openURL({ 
                url = dz.settings['Domoticz url'] .. '/json.htm?type=devices&used=true',
                callback = scriptVar })
        else
            if dz.devices('opVakantie').state== 'On' then
                dz.log(notifyHead .." ".. 'Vakantie-On',dz.LOG_FORCE)
	            DevicesToCheck = devices_Yes
	        else
                dz.log(notifyHead .." ".. 'Vakantie-Off',dz.LOG_FORCE)
                DevicesToCheck = devices_No
            end
	
        local Time = require('Time')
            for _, node in pairs(item.json.result) do
                local toCheck = ( DevicesToCheck[node.idx] or DevicesToCheck[node.Name])
                if toCheck then
                    local lastUpdate = Time(node.LastUpdate).secondsAgo
                    local deviceName = node.Name
                    local threshold = toCheck
                    	if lastUpdate < threshold then
              		        --device is alive
                            if notified[deviceName] == nil then
                                dz.log(notifyHead .." "..deviceName.." : "..Timers(lastUpdate).. ' was last response, threshold='..Timers(threshold),dz.LOG_FORCE)
                            else
                                dz.log(notifyHead .." ".. ' Signal back from sensor '..deviceName,dz.LOG_FORCE)
                                notified[deviceName] = nil  --remove from notified list
                                if telegram then
                                        os.execute('curl -s -X POST "https://api.telegram.org/bot'..teleTok..'/sendMessage?chat_id='..chatId..'&text='..notifyHead .." ".. 'Signal back from sensor '..deviceName..'."')
                                    end     
                                if email then
                                    dz.email('Domoticz device check', ''..notifyHead.. 'Signal back from sensor '..deviceName..'', ''..mailaddress..'')
                                end
                            end
                        else 
                            --lost signal:
                            if notified[deviceName] == nil then
                                dz.log (notifyHead .." ".. 'Signal lost: '..deviceName .." sent "..Timers(lastUpdate).. ' the last signal, threshold='..Timers(threshold)..'. Battery empty?',dz.LOG_FORCE)
                                notified[deviceName] = 1
                                    if telegram then
                                        os.execute('curl -s -X POST "https://api.telegram.org/bot'..teleTok..'/sendMessage?chat_id='..chatId..'&text='..notifyHead..' Signal lost: '..deviceName ..' sent '..Timers(lastUpdate).. ' the last signal, threshold='..Timers(threshold)..'. Battery empty?"')
                                    end     
                                    if email then
                                        dz.email('Domoticz device check', ''..notifyHead..' Signal lost: '..deviceName ..' sent '..Timers(lastUpdate).. ' the last signal, threshold='..Timers(threshold)..'. Battery empty?', ''..mailaddress..'')
                                    end
                        elseif
                            dz.time.matchesRule(notifyTime) and  
                            dz.devices('opVakantie').state == 'Off'
                        then
                            dz.log(notifyHead .." ".. 'Reminder, '..deviceName .." sent "..Timers(lastUpdate).. ' the last signal. Battery empty?',dz.LOG_FORCE)
                            if telegram then
                                os.execute('curl -s -X POST "https://api.telegram.org/bot'..teleTok..'/sendMessage?chat_id='..chatId..'&text='..notifyHead .." ".. 'Reminder, '..deviceName .." sent "..Timers(lastUpdate).. ' the last signal. Battery empty?"')
                            end     
                            if email then
                                dz.email('Domoticz device check', ''..notifyHead..' Signal lost: '..deviceName ..' sent '..Timers(lastUpdate).. ' the last signal, threshold='..Timers(threshold)..'. Battery empty?', ''..mailaddress..'')
                            end
                        end
                    end
                end
            end
        end
    end

}

-- Changes version 19061601
-- -WriteTime removed, this only gives NIL and wasn't used
-- -Script now works with url = dz.settings['Domoticz url'] 

-- Changes version 19061501
-- -E-mail option added
-- -With false/true you could actived of de-actived e-mail or telegram
-- -All settings on top of the script
Thin-client --> Docker Domoticz main environment
Pi3A+ --> Google home (GAssistPi)
Pi3B+ --> Docker (P1monitor, Domoticz test environment, Ubiquity controller)
hoeby
Posts: 531
Joined: Saturday 02 June 2018 11:05
Target OS: Raspberry Pi / ODroid
Domoticz version: V2022.1
Location: Echt, Netherlands
Contact:

Re: Check Sensors script (dzVents)

Post by hoeby »

Version 19061602:
changed: Using dzVents: natively send a notification to telegram

Code: Select all

--[[
Verion: 19061602

WHAT DOES THE SCRIPTS?:
It looks to the LAST SEEN date/time of a device. When threshold runs out, you get a notification to check the device.
Be sure you are adding devices that are updated in a normal situation. 
For example, devices connected to a Xiaomi gateway are not updatet, unless activated. When you add a smoke detector tru Xiaomi gateway, than the smoke detector has to give a smoke-alarm before the threshold runs out. Otherwise you get a notification. 
Advice for Xiaomi smoke-detectors is to use Zigbee2MQTT, this gateway does update the LAST SEEN date/time of Xiaomi smoke-detectors.

WHAT TO SETUP TO MAKE THIS SCRIPT WORKING
Fill in the local network setting for Domoticz.
Go to SETTINGS --> SETTINGS --> SYSTEM --> LOCAL NETWORK.
Fill in your IP adres. When it is local you could fill in 127.0.0.*
Make a dummy device named: opVakantie
Dummy device opVakantie changes the threshold timer for the devices-check
The idea is: opVakantie Device ON = longer threshold numbers, so you don't get notification on your holiday
And opVakantie Device Off = to have shorter threshold numbers.

Set telegram true is you want telegram notification, but therefor teleTOK and chatID has to be filled in SETTINGS --> SETTINGS --> NOTIFICATIONS --> TELEGRAM

Set email true is you want to receive an e-mail, but therefor the e-mail has te be setup in SETTINGS --> SETTINGS --> E-MAIL
Fill in you e-mail address where to send to

There is a line which says: -- Don't change things undernead this line
If you have no idea how the scripts works, please lissen to this.
If you know how it works and have ideas, please post them on http://www.domoticz.com/forum/viewtopic.php?f=59&t=18566&start=20
]]--

local scriptVar = 'lastSeen'

return {
    on = { timer =  {'every 30 minutes'}, httpResponses = { scriptVar }},
    logging = { level   = domoticz.LOG_ERROR, marker  = scriptVar },
    
    data = { notified = { initial = {} } },
    
    execute = function(dz, item)
        
        --Telegram settings
            local telegram    = true                        -- Set true for sending telegram, set false for NOT sending telegram.
        
        --Email settings (domoticz email settings have to be filled in)
            local email       = false                        -- Set true for sending email, set false for NOT sending email.
            local mailaddress = '[email protected]'
        
        -- Global settings
            local notifyTime  = 'at 10:00'                  -- You can add multiple notification times, i.e. 'at 12:00, at 20:00'
	        local notifyHead  = 'dzCheckSensors'            -- This is the start of everynotification, so you know it is this script.
	         
	    -- Devices to check NO holiday.
	    --                        Devices name column                 Time column in seconds                 
	        local devices_No =  {
	                            ['Test-Deur-Contact-Zigbee']        = 172800,  -- 2 Days
                                ['Dashboard-webpage-check']         = 172800,  -- 2 Days  
	                            }
	    
	    -- Devices to check when it is holiday.
	    --                        Devices name column                 Time column in seconds
	        local devices_Yes = {
	                            ['Test-Deur-Contact-Zigbee']        = 1209600,  --14 Days
                                ['Dashboard-webpage-check']         = 1209600,  --14 Days  
	                            }
	                          
-- Don't change things undernead this line
        local notified    = dz.data.notified -- short reference

        function Timers(sec)
            local ti
            sec=tonumber(sec)
                if sec == nil then ti='NIL'
                    elseif sec >= 86400   then ti=string.sub(tostring(sec/24/3600),1,4)..' days'  
                    elseif sec >= 3600    then ti=string.sub(tostring(sec/3600),1,4)..' hours' 
                    elseif sec >= 60      then ti=string.sub(tostring(sec/60),1,4)..' minutes'
                    else ti=sec..' seconds'
                end
                return ti 
            end    
       
        if not (item.isHTTPResponse) then
            dz.openURL({ 
                url = dz.settings['Domoticz url'] .. '/json.htm?type=devices&used=true',
                callback = scriptVar })
        else
            if dz.devices('opVakantie').state== 'On' then
                dz.log(notifyHead .." ".. 'Vakantie-On',dz.LOG_FORCE)
	            DevicesToCheck = devices_Yes
	        else
                dz.log(notifyHead .." ".. 'Vakantie-Off',dz.LOG_FORCE)
                DevicesToCheck = devices_No
            end
	
        local Time = require('Time')
            for _, node in pairs(item.json.result) do
                local toCheck = ( DevicesToCheck[node.idx] or DevicesToCheck[node.Name])
                if toCheck then
                    local lastUpdate = Time(node.LastUpdate).secondsAgo
                    local deviceName = node.Name
                    local threshold = toCheck
                    	if lastUpdate < threshold then
              		        --device is alive
                            if notified[deviceName] == nil then
                                dz.log(notifyHead .." "..deviceName.." : "..Timers(lastUpdate).. ' was last response, threshold='..Timers(threshold),dz.LOG_FORCE)
                            else
                                dz.log(notifyHead .." ".. ' Signal back from sensor '..deviceName,dz.LOG_FORCE)
                                notified[deviceName] = nil  --remove from notified list
                                if telegram then
                                        dz.notify(notifyHead, notifyHead .." ".. 'Signal back from sensor '..deviceName..'.',dz.PRIORITY_NORMAL,nil,nil,dz.NSS_TELEGRAM)
                                    end     
                                if email then
                                    dz.email('Domoticz device check', ''..notifyHead.. 'Signal back from sensor '..deviceName..'', ''..mailaddress..'')
                                end
                            end
                        else 
                            --lost signal:
                            if notified[deviceName] == nil then
                                dz.log (notifyHead .." ".. 'Signal lost: '..deviceName .." sent "..Timers(lastUpdate).. ' the last signal, threshold='..Timers(threshold)..'. Battery empty?',dz.LOG_FORCE)
                                notified[deviceName] = 1
                                    if telegram then
                                        dz.notify(notifyHead,  notifyHead ..' Signal lost: '..deviceName ..' sent '..Timers(lastUpdate).. ' the last signal, threshold='..Timers(threshold)..'. Battery empty?',dz.PRIORITY_NORMAL,nil,nil,dz.NSS_TELEGRAM)
                                    end     
                                    if email then
                                        dz.email('Domoticz device check', ''..notifyHead..' Signal lost: '..deviceName ..' sent '..Timers(lastUpdate).. ' the last signal, threshold='..Timers(threshold)..'. Battery empty?', ''..mailaddress..'')
                                    end
                        elseif
                            dz.time.matchesRule(notifyTime) and  
                            dz.devices('opVakantie').state == 'Off'
                        then
                            dz.log(notifyHead .." ".. 'Reminder, '..deviceName .." sent "..Timers(lastUpdate).. ' the last signal. Battery empty?',dz.LOG_FORCE)
                            if telegram then
                                dz.notify(notifyHead, notifyHead .." ".. 'Reminder, '..deviceName .." sent "..Timers(lastUpdate).. ' the last signal. Battery empty?',dz.PRIORITY_NORMAL,nil,nil,dz.NSS_TELEGRAM)
                            end     
                            if email then
                                dz.email('Domoticz device check', ''..notifyHead..' Signal lost: '..deviceName ..' sent '..Timers(lastUpdate).. ' the last signal, threshold='..Timers(threshold)..'. Battery empty?', ''..mailaddress..'')
                            end
                        end
                    end
                end
            end
        end
    end

}

--[[ 
Changes version 19061602
-Using dzVents: natively send a notification to telegram

Changes version 19061601
-WriteTime removed, this only gives NIL and wasn't used
-Script now works with url = dz.settings['Domoticz url'] 

Changes version 19061501
-E-mail option added
-With false/true you could actived of de-actived e-mail or telegram
-All settings on top of the script
]]--
Thin-client --> Docker Domoticz main environment
Pi3A+ --> Google home (GAssistPi)
Pi3B+ --> Docker (P1monitor, Domoticz test environment, Ubiquity controller)
hoeby
Posts: 531
Joined: Saturday 02 June 2018 11:05
Target OS: Raspberry Pi / ODroid
Domoticz version: V2022.1
Location: Echt, Netherlands
Contact:

Re: Check Sensors script (dzVents)

Post by hoeby »

modified one row, because IDX number to check didn't work.
Now it works.

Changes version 19061603
-Possible to fill in IDX number or device name to be checked.

Code: Select all

--[[
Verion: 19061603

WHAT DOES THE SCRIPTS?:
It looks to the LAST SEEN date/time of a device. When threshold runs out, you get a notification to check the device.
Be sure you are adding devices that are updated in a normal situation. 
For example, devices connected to a Xiaomi gateway are not updatet, unless activated. When you add a smoke detector tru Xiaomi gateway, than the smoke detector has to give a smoke-alarm before the threshold runs out. Otherwise you get a notification. 
Advice for Xiaomi smoke-detectors is to use Zigbee2MQTT, this gateway does update the LAST SEEN date/time of Xiaomi smoke-detectors.

WHAT TO SETUP TO MAKE THIS SCRIPT WORKING
Fill in the local network setting for Domoticz.
Go to SETTINGS --> SETTINGS --> SYSTEM --> LOCAL NETWORK.
Fill in your IP adres. When it is local you could fill in 127.0.0.*

Make a dummy device named: opVakantie
Dummy device opVakantie changes the threshold timer for the devices-check
The idea is: opVakantie Device ON = longer threshold numbers, so you don't get notification on your holiday
And opVakantie Device Off = to have shorter threshold numbers.

Set telegram true is you want telegram notification, 
but therefor apiKEY and chatID has to be filled in SETTINGS --> SETTINGS --> NOTIFICATIONS --> TELEGAM

Set email true is you want to receive an e-mail, but therefor the e-mail has te be setup in SETTINGS --> SETTINGS --> E-MAIL
Fill in you e-mail address where to send to

Of course fill in the devices you would like to check.
You could choose to fill in with name or IDX number of the device.

There is a line which says: -- Don't change things undernead this line
If you have no idea how the scripts works, please lissen to this.
If you know how it works and have ideas, please post them on http://www.domoticz.com/forum/viewtopic.php?f=59&t=18566&start=20
]]--

local scriptVar = 'lastSeen'

return {
    --on = { timer =  {'every 30 minutes'}, httpResponses = { scriptVar }},
    on = { timer =  {'every minute'}, httpResponses = { scriptVar }},		-- Only use this one to test. When working disable it and activate "every 30 minutes"
    --on = { timer =  {'at 08:00', 'at 10:00'}, httpResponses = { scriptVar }},
    logging = { level   = domoticz.LOG_ERROR, marker  = scriptVar },
    
    data = { notified = { initial = {} } },
    
    execute = function(dz, item)
    
        --Telegram settings
            local telegram    = true                        -- Set true for sending telegram, set false for NOT sending telegram.
        
        --Email settings (domoticz email settings have to be filled in)
            local email       = true                        -- Set true for sending email, set false for NOT sending email.
            local mailaddress = '[email protected]' -- Fill in your e-mail address, which the notification needs to be send to.
        
        -- Global settings
            local notifyTime  = 'at 10:00'                  -- You can add multiple notification times, i.e. 'at 12:00, at 20:00'
	    local notifyHead  = 'dzCheckSensors'            -- This is the start of everynotification, so you know it is this script.
	         
	    -- Devices to check NO holiday.
	    --                      Devices name or IDX number column   = Time column in seconds                 
	        local devices_No =  {
	                            ['Test-Deur-Contact-Zigbee']        = 172800,  -- 2 Days
                                    ['Dashboard-webpage-check']         = 172800,  -- 2 Days  
	                            }
	    
	    -- Devices to check when it is holiday.
	    --                      Devices name or IDX number column   = Time column in seconds
	        local devices_Yes = {
	                            ['Test-Deur-Contact-Zigbee']        = 1209600,  -- 14 Days
                                    ['335']                             = 1209600,  -- 14 Days  IDX335=Dashboard-webpage-check
	                            }
	                          
-- Don't change things undernead this line
        local notified    = dz.data.notified -- short reference

        function Timers(sec)
            local ti
            sec=tonumber(sec)
                if sec == nil then ti='NIL'
                    elseif sec >= 86400   then ti=string.sub(tostring(sec/24/3600),1,4)..' days'  
                    elseif sec >= 3600    then ti=string.sub(tostring(sec/3600),1,4)..' hours' 
                    elseif sec >= 60      then ti=string.sub(tostring(sec/60),1,4)..' minutes'
                    else ti=sec..' seconds'
                end
                return ti 
            end    
                
        if not (item.isHTTPResponse) then
            dz.openURL({ 
                url = dz.settings['Domoticz url'] .. '/json.htm?type=devices&used=true',
                callback = scriptVar })
        else
            if dz.devices('opVakantie').state== 'On' then
                dz.log(notifyHead .." ".. 'Vakantie-On',dz.LOG_FORCE)
	            DevicesToCheck = devices_Yes
	        else
                dz.log(notifyHead .." ".. 'Vakantie-Off',dz.LOG_FORCE)
                DevicesToCheck = devices_No
            end
	
        local Time = require('Time')
            for _, node in pairs(item.json.result) do
                local toCheck = ( DevicesToCheck[node.idx] or DevicesToCheck[node.Name])
                if toCheck then
                    local lastUpdate = Time(node.LastUpdate).secondsAgo
                    local deviceName = (node.Name or node.idx)
                    local threshold = toCheck
                    	if lastUpdate < threshold then
              		        --device is alive
                            if notified[deviceName] == nil then
                                dz.log(notifyHead .." "..deviceName.." : "..Timers(lastUpdate).. ' was last response, threshold='..Timers(threshold),dz.LOG_FORCE)
                            else
                                dz.log(notifyHead .." ".. ' Signal back from sensor '..deviceName,dz.LOG_FORCE)
                                notified[deviceName] = nil  --remove from notified list
                                if telegram then
                                    dz.notify(notifyHead, notifyHead .." ".. 'Signal back from sensor '..deviceName..'.',dz.PRIORITY_NORMAL,nil,nil,dz.NSS_TELEGRAM)
                                end     
                                if email then
                                    dz.email('Domoticz device check', ''..notifyHead.. ' Signal back from sensor '..deviceName..'', ''..mailaddress..'')
                                end
                            end
                        else 
                            --lost signal:
                            if notified[deviceName] == nil then
                                dz.log (notifyHead .." ".. 'Signal lost: '..deviceName .." sent "..Timers(lastUpdate).. ' the last signal, threshold='..Timers(threshold)..'. Battery empty?',dz.LOG_FORCE)
                                notified[deviceName] = 1
                                    if telegram then
                                        dz.notify(notifyHead,  notifyHead ..' Signal lost: '..deviceName ..' sent '..Timers(lastUpdate).. ' the last signal, threshold='..Timers(threshold)..'. Battery empty?',dz.PRIORITY_NORMAL,nil,nil,dz.NSS_TELEGRAM)
                                    end     
                                    if email then
                                        dz.email('Domoticz device check', ''..notifyHead..' Signal lost: '..deviceName ..' sent '..Timers(lastUpdate).. ' the last signal, threshold='..Timers(threshold)..'. Battery empty?', ''..mailaddress..'')
                                    end
                        elseif
                            dz.time.matchesRule(notifyTime) and  
                            dz.devices('opVakantie').state == 'Off'
                        then
                            dz.log(notifyHead .." ".. 'Reminder, '..deviceName .." sent "..Timers(lastUpdate).. ' the last signal. Battery empty?',dz.LOG_FORCE)
                            if telegram then
                                dz.notify(notifyHead, notifyHead .." ".. 'Reminder, '..deviceName .." sent "..Timers(lastUpdate).. ' the last signal. Battery empty?',dz.PRIORITY_NORMAL,nil,nil,dz.NSS_TELEGRAM)
                            end     
                            if email then
                                dz.email('Domoticz device check', ''..notifyHead..' Signal lost: '..deviceName ..' sent '..Timers(lastUpdate).. ' the last signal, threshold='..Timers(threshold)..'. Battery empty?', ''..mailaddress..'')
                            end
                        end
                    end
                end
            end
        end
    end

}

--[[ 
Changes version 19061603
-Possible to fill in IDX number or device name to be checked.

Changes version 19061602
-Using dzVents: natively send a notification to telegram

Changes version 19061601
-WriteTime removed, this only gives NIL and wasn't used
-Script now works with url = dz.settings['Domoticz url'] 

Changes version 19061501
-E-mail option added
-With false/true you could actived of de-actived e-mail or telegram
-All settings on top of the script
]]--
Thin-client --> Docker Domoticz main environment
Pi3A+ --> Google home (GAssistPi)
Pi3B+ --> Docker (P1monitor, Domoticz test environment, Ubiquity controller)
bassie127
Posts: 15
Joined: Tuesday 22 March 2016 10:37
Target OS: Raspberry Pi / ODroid
Domoticz version:
Contact:

Re: Check Sensors script (dzVents)

Post by bassie127 »

Great script! Works out of the box; just place script in dzEvents script directory.
Maciek
Posts: 2
Joined: Thursday 27 February 2020 13:33
Target OS: Raspberry Pi / ODroid
Domoticz version:
Contact:

Re: Check Sensors script (dzVents)

Post by Maciek »

What do I do wrong? I have error:

2020-02-27 13:36:00.597 Status: EventSystem: Script event triggered: /home/pi/domoticz/dzVents/runtime/dzVents.lua
2020-02-27 13:36:00.689 Status: dzVents: Info: Handling httpResponse-events for: "lastSeen
2020-02-27 13:36:00.710 Status: dzVents: !Info: lastSeen: dzCheckSensors Vakantie-Off
2020-02-27 13:36:00.710 Status: dzVents: Error (2.4.19): lastSeen: An error occured when calling event handler System_check
2020-02-27 13:36:00.710 Status: dzVents: Error (2.4.19): lastSeen: ...oticz/scripts/dzVents/generated_scripts/System_check.lua:102: attempt to index field 'json' (a nil value)
2020-02-27 13:36:00.628 Error: Error opening url: http://127.0.0.1:8080/json.htm?type=devices&used=true
User avatar
waaren
Posts: 6028
Joined: Tuesday 03 January 2017 14:18
Target OS: Linux
Domoticz version: Beta
Location: Netherlands
Contact:

Re: Check Sensors script (dzVents)

Post by waaren »

Maciek wrote: Thursday 27 February 2020 13:36 What do I do wrong? I have error:
2020-02-27 13:36:00.628 Error: Error opening url: http://127.0.0.1:8080/json.htm?type=devices&used=true
When not yet familiar with dzVents please start with reading Get started Before implementing (~ 5 minutes). Special attention please for "In Domoticz go to Setup > Settings > Other and in the section EventSystem make sure the checkbox 'dzVents enabled' is checked. Also make sure that in the Security section in the settings you allow 127.0.0.1 to not need a password. dzVents uses that port to send certain commands to Domoticz. Finally make sure you have set your current location in Setup > Settings > System > Location, otherwise there is no way to determine nighttime/daytime state."
Debian buster, bullseye on RPI-4, Intel NUC.
dz Beta, Z-Wave, RFLink, RFXtrx433e, P1, Youless, Hue, Yeelight, Xiaomi, MQTT
==>> dzVents wiki
Maciek
Posts: 2
Joined: Thursday 27 February 2020 13:33
Target OS: Raspberry Pi / ODroid
Domoticz version:
Contact:

Re: Check Sensors script (dzVents)

Post by Maciek »

I use few dzVents scrips so I have dzVents enabled, the rest scripts also.
Location settings was nessesery to use weather forecast script so I have already had it.
I have added 127.0.0.1 to local network settings and this error still has been there.
System restart after adding 127.0.0.1 helped. Now it works fine.
Thanks Waaren
pimseb
Posts: 42
Joined: Wednesday 13 September 2017 13:51
Target OS: Raspberry Pi / ODroid
Domoticz version: 2020.1
Location: France
Contact:

Re: Check Sensors script (dzVents)

Post by pimseb »

Hi,
I've added the script in domoticz (from the web interface) and changed all the values to fit my configuration.
Is it normal that I don't see anything happening in the logs ? Dvents scripts are enabled in the settings and I've put log level of the script to DEBUG
Running domoticz 2020.01 (last stable)
Thank you
User avatar
waaren
Posts: 6028
Joined: Tuesday 03 January 2017 14:18
Target OS: Linux
Domoticz version: Beta
Location: Netherlands
Contact:

Re: Check Sensors script (dzVents)

Post by waaren »

pimseb wrote: Thursday 23 April 2020 10:58 Is it normal that I don't see anything happening in the logs ?
No,you should see something. Are you looking at ALL messages in the log?
log.png
log.png (13.02 KiB) Viewed 2689 times

Did you also enable the EventSystem ?

[setup] [settings] [other]
settings.png
settings.png (29.58 KiB) Viewed 2689 times
and applied the settings?(red button in the top right corner)
Debian buster, bullseye on RPI-4, Intel NUC.
dz Beta, Z-Wave, RFLink, RFXtrx433e, P1, Youless, Hue, Yeelight, Xiaomi, MQTT
==>> dzVents wiki
pimseb
Posts: 42
Joined: Wednesday 13 September 2017 13:51
Target OS: Raspberry Pi / ODroid
Domoticz version: 2020.1
Location: France
Contact:

Re: Check Sensors script (dzVents)

Post by pimseb »

Hello waaren,
Thank you for your answer. You're always here to help us
Indeed I found the answer in another thread from you.
I had to change something in /etc/init.d/domoticz.sh
I replaced :

Code: Select all

DAEMON_ARGS="$DAEMON_ARGS -log /tmp/log/domoticz.log -loglevel normal"
to :

Code: Select all

DAEMON_ARGS="$DAEMON_ARGS -log /tmp/log/domoticz.log"
DAEMON_ARGS="$DAEMON_ARGS -loglevel  normal,status,error"

:) Thanks again
THBR
Posts: 43
Joined: Saturday 02 November 2019 21:05
Target OS: -
Domoticz version:
Contact:

Re: Check Sensors script (dzVents)

Post by THBR »

Hello,

I am using for at least one year the latest version of this script (19061603) without any error.

However, since the recent update of Domoticz I get the following log error in Domoticz every half hour (my timer is set on every 30 minutes).
Error: Error opening url: http://127.0.0.1:8080/json.htm?type=devices&used=true
Error: dzVents: lastSeen: HTTP/1.1 response: 404 ==>> Not Found
Error: dzVents: lastSeen: An error occurred when calling event handler Controle data van sensors
Error: dzVents: lastSeen: .../dzVents/generated_scripts/Controle data van sensors.lua:149: attempt to index a nil value (field 'json')
(IP adress 127.0.0.1 was and is listed in trusted networks in secu. setting Domoticz, nothing changed there)
(line 149 in the script is "for _, node in pairs(item.json.result) do")

My script:

local scriptVar = 'lastSeen'

return {
on = { timer = {'every 30 minutes'}, httpResponses = { scriptVar }},
--on = { timer = {'every minute'}, httpResponses = { scriptVar }}, -- Only use this one to test. When working disable it and activate "every 30 minutes"
--on = { timer = {'at 08:00', 'at 10:00'}, httpResponses = { scriptVar }},
logging = { level = domoticz.LOG_ERROR, marker = scriptVar },

data = { notified = { initial = {} } },

execute = function(dz, item)

--Telegram settings
local telegram = true -- Set true for sending telegram, set false for NOT sending telegram.

--Email settings (domoticz email settings have to be filled in)
local email = false -- Set true for sending email, set false for NOT sending email.
local mailaddress = '[email protected]' -- Fill in your e-mail address, which the notification needs to be send to.

-- Global settings
local notifyTime = 'at 01:00, at 03:00, at 05:00, at 07:00, at 09:00, at 11:00, at 13:00, at 15:00, at 17:00, at 19:00, at 21:00, at 23:00' -- You can add multiple notification times, i.e. 'at 12:00, at 20:00'
local notifyHead = 'dzCheckSensors' -- This is the start of everynotification, so you know it is this script.

-- Devices to check NO holiday.
-- Devices name or IDX number column = Time column in seconds
local devices_No = {
['Temp-1 (buiten)'] = 43200, -- 12 Hours
['Temp-2 (zolder)'] = 43200, -- 12 Hours
['Temp-3 (douche)'] = 43200, -- 12 Hours
['Temp-4 (meterkast)'] = 43200, -- 12 Hours
['Temp-5 (TVkast L)'] = 43200, -- 12 Hours
['Temp-6 (TVkast R)'] = 43200, -- 12 Hours
['Temp-7 (schuur)'] = 43200, -- 12 Hours
['Temp-8 (keuken)'] = 43200, -- 12 Hours
['Temp-9 (huiskamer)'] = 43200, -- 12 Hours
['Temp-10 (kelder)'] = 43200, -- 12 Hours
['Temp 11 (kruipruimte)'] = 86400, -- 24 Hours
['Temp-12 (CV switch)'] = 43200, -- 12 Hours
['Temp-13 (WC)'] = 43200, -- 12 Hours
['Temp-14 (display)'] = 43200, -- 12 Hours
['Temp-16 koelkast kk)'] = 43200, -- 12 Hours
['Temp-15 (diepvries bkk)'] = 43200, -- 12 Hours
['Temp-17 (veranda)'] = 43200, -- 12 Hours
['Brandmelder (schuur)'] = 43200, -- 12 Hours
['Brandmelder (bijkeuken)'] = 43200, -- 12 Hours
['Brandmelder (keuken)'] = 43200, -- 12 Hours
['Brandmelder (overloop)'] = 43200, -- 12 Hours
['Brandmelder (meterkast)'] = 43200, -- 12 Hours
['Brandmelder (zolder)'] = 43200, -- 12 Hours
['Brandmelder (huiskamer)'] = 43200, -- 12 Hours
['Brandmelder (reserve)'] = 43200, -- 12 Hours
['Waterteller'] = 43200, -- 12 Hours
['Smart plug (WC)'] = 43200, -- 12 Hours
['Smart plug (airco)'] = 3600, -- 1 Hours
['Smart plug (bkk groep)'] = 300, -- 5 Minutes
['Smart plug (huiskamerverlichting rechts)']= 3600, -- 1 Hours
['Buitenverlichting (schutting)'] = 43200, -- 12 Hours
['Veranda verlichting)'] = 43200, -- 12 Hours
['Smart plug (boiler)'] = 43200, -- 12 Hours
['Smart switch (verwarming veranda)'] = 86400, -- 24 Hours
['DWS (schuur)'] = 43200, -- 12 Hours
['DWS (Sonoff)'] = 43200, -- 12 Hours
['DWS (poort voor)'] = 43200, -- 12 Hours
['DWS (poort achter)'] = 43200, -- 12 Hours
['DWS (huiskamer raam)'] = 43200, -- 12 Hours
['Bewegingssensor (zolder)'] = 86400, -- 24 Hours
['Bewegingssensor (schuur)'] = 43200, -- 12 Hours
['Deurbel'] = 43200, -- 12 Hours
['Veranda verwarming aan/uit'] = 43200, -- 12 Hours
['Dakgootsensor (schuur)'] = 604800, -- 1 Week
['Thermostaat CV switch (AAN = boven)'] = 43200, -- 12 Hours
['Radiator (SLK1)'] = 3600, -- 1 Hours
['Radiator (SLK2)'] = 3600, -- 1 Hours
['Radiator (SLK3)'] = 3600, -- 1 Hours
['Radiator (BKK)'] = 3600, -- 1 Hours
['Radiator (gang)'] = 3600, -- 1 Hours
['Gas)'] = 3600, -- 1 Hours
}

-- Devices to check when it is holiday.
-- Devices name or IDX number column = Time column in seconds
local devices_Yes = {
['Temp-1 (buiten)'] = 1209600, -- 14 Days
['Bewegingssensor (schuur'] = 1209600, -- 14 Days IDX335=Dashboard-webpage-check
}

-- Don't change things undernead this line
local notified = dz.data.notified -- short reference

function Timers(sec)
local ti
sec=tonumber(sec)
if sec == nil then ti='NIL'
elseif sec >= 86400 then ti=string.sub(tostring(sec/24/3600),1,4)..' days'
elseif sec >= 3600 then ti=string.sub(tostring(sec/3600),1,4)..' hours'
elseif sec >= 60 then ti=string.sub(tostring(sec/60),1,4)..' minutes'
else ti=sec..' seconds'
end
return ti
end

if not (item.isHTTPResponse) then
dz.openURL({
url = dz.settings['Domoticz url'] .. '/json.htm?type=devices&used=true',
callback = scriptVar })
else
if dz.devices('opVakantie').state== 'On' then
dz.log(notifyHead .." ".. 'Vakantie-On',dz.LOG_FORCE)
DevicesToCheck = devices_Yes
else
dz.log(notifyHead .." ".. 'Vakantie-Off',dz.LOG_FORCE)
DevicesToCheck = devices_No
end

local Time = require('Time')
for _, node in pairs(item.json.result) do
local toCheck = ( DevicesToCheck[node.idx] or DevicesToCheck[node.Name])
if toCheck then
local lastUpdate = Time(node.LastUpdate).secondsAgo
local deviceName = (node.Name or node.idx)
local threshold = toCheck
if lastUpdate < threshold then
--device is alive
if notified[deviceName] == nil then
dz.log(notifyHead .." "..deviceName.." : "..Timers(lastUpdate).. ' was last response, threshold='..Timers(threshold),dz.LOG_FORCE)
else
dz.log(notifyHead .." ".. ' Signal back from sensor '..deviceName,dz.LOG_FORCE)
notified[deviceName] = nil --remove from notified list
if telegram then
dz.notify(notifyHead, notifyHead .." ".. 'Signal back from sensor '..deviceName..'.',dz.PRIORITY_NORMAL,nil,nil,dz.NSS_TELEGRAM)
end
if email then
dz.email('Domoticz device check', ''..notifyHead.. ' Signal back from sensor '..deviceName..'', ''..mailaddress..'')
end
end
else
--lost signal:
if notified[deviceName] == nil then
dz.log (notifyHead .." ".. 'Signal lost: '..deviceName .." sent "..Timers(lastUpdate).. ' the last signal, threshold='..Timers(threshold)..'. Battery empty?',dz.LOG_FORCE)
notified[deviceName] = 1
if telegram then
dz.notify(notifyHead, notifyHead ..' Signal lost: '..deviceName ..' sent '..Timers(lastUpdate).. ' the last signal, threshold='..Timers(threshold)..'. Battery empty?',dz.PRIORITY_NORMAL,nil,nil,dz.NSS_TELEGRAM)
end
if email then
dz.email('Domoticz device check', ''..notifyHead..' Signal lost: '..deviceName ..' sent '..Timers(lastUpdate).. ' the last signal, threshold='..Timers(threshold)..'. Battery empty?', ''..mailaddress..'')
end
elseif
dz.time.matchesRule(notifyTime) and
dz.devices('opVakantie').state == 'Off'
then
dz.log(notifyHead .." ".. 'Reminder, '..deviceName .." sent "..Timers(lastUpdate).. ' the last signal. Battery empty?',dz.LOG_FORCE)
if telegram then
dz.notify(notifyHead, notifyHead .." ".. 'Reminder, '..deviceName .." sent "..Timers(lastUpdate).. ' the last signal. Battery empty?',dz.PRIORITY_NORMAL,nil,nil,dz.NSS_TELEGRAM)
end
if email then
dz.email('Domoticz device check', ''..notifyHead..' Signal lost: '..deviceName ..' sent '..Timers(lastUpdate).. ' the last signal, threshold='..Timers(threshold)..'. Battery empty?', ''..mailaddress..'')
end
end
end
end
end
end
end

}

My configuration:
RaspberryPi 3b
Booting/operating from 64 GB USB-flashdevice, no SD card
Raspbian GNU/Linux 10 (buster)
Domoticz version: Upgraded on 7-5-2-25 from v2024.4 to 2025.1
Python Version: 3.7.3
Zigbee2mqtt plugin (by stas-demydiuk): v.3.2.0-beta
Zigbee2mqtt: v1.42.0 (zStack3x0 20211114)
Zigbee Slaesh's CC2652RB coördinator USB-dongle
TinyTUYA Plugin version 2.1.8
RTC DS1307
I am a beginner when it comes to such scripts, so hopefully someone can help me. Apparently something changed in the latest version of Domoticz?

Thanks!
User avatar
waltervl
Posts: 5770
Joined: Monday 28 January 2019 18:48
Target OS: Linux
Domoticz version: 2024.7
Location: NL
Contact:

Re: Check Sensors script (dzVents)

Post by waltervl »

Yes, the API has changed. See Wiki https://wiki.domoticz.com/Domoticz_API/ ... and_newer)

It should already gave warnings in the logs from 2023 about the change....
Domoticz running on Udoo X86 (on Ubuntu)
Devices/plugins: ZigbeeforDomoticz (with Xiaomi, Ikea, Tuya devices), Nefit Easy, Midea Airco, Omnik Solar, Goodwe Solar
Post Reply

Who is online

Users browsing this forum: No registered users and 1 guest