Page 1 of 1

Calculation of the Lowest and the Highest Sensor values

Posted: Tuesday 18 December 2018 12:42
by AYAMY
Hi,
I use blocky to send me a notification through pushover each morning with the actual temperature and humidity outside....
But I would send me also a notification with the lowest and highest temperature and humidity of the last 24 hours...
Could you help me?
Thanks

Re: Calculation of the Lowest and the Highest Sensor values

Posted: Wednesday 19 December 2018 1:11
by waaren
I don't think you can use Blockly to do this. It will require a call to the domoticz API like
http://<domoticzIP>:<domoticzPort/json.htm?idx=<IDX of your device>&range=day&sensor=temp&type=graph
And process the results. It can be done in Lua, dzVents or Python.

Re: Calculation of the Lowest and the Highest Sensor values

Posted: Thursday 17 January 2019 16:52
by AYAMY
thanks...
some example in lua , dzevent or python ?

Re: Calculation of the Lowest and the Highest Sensor values

Posted: Thursday 17 January 2019 19:37
by waaren
AYAMY wrote: Thursday 17 January 2019 16:52 thanks...
some example in lua , dzevent or python ?
in dzVents it would look like

Code: Select all

-- getMaxTempHum

local httpResponses = "getMaxTempHum"

return {
    on      =   {
                    timer           =   { "at 19:35"    },                       -- Your preferred time
                    httpResponses   =   { httpResponses }
                },

    logging =   {
                    level           =   domoticz.LOG_ERROR,
                    marker          =   httpResponse
                },

    execute = function(dz, item)
        -- ****************************** Your settings below this line ***************************************************
        temphumDevice = dz.devices(766)          -- Replace with ID of Device you want to be notified on
        -- ****************************** No changes required below this line *********************************************

        local extremes = {}

        local function logWrite(str,level)
            dz.log(tostring(str),level or dz.LOG_DEBUG)
        end

        local function triggerJSON()
            local  URLString   = dz.settings['Domoticz url'] .. "/json.htm?type=graph&sensor=temp&range=day&idx=" .. temphumDevice.id
            dz.openURL({    url = URLString,
                            method = "GET",
                            callback = httpResponses })
        end

        local function convertTime(timeString)               -- based on incoming format yyyy-mm-dd hh:mm
            local year, month, day, hour, minute
            _,_, year, month, day, hour, minute = string.find(timeString, "(%d+)-(%d+)-(%d+) (%d+):(%d+)")
            fmtString = os.date("%A, %d %B %Y (%H:%M)",os.time({year=year, month=month, day=day, hour=hour, minute=minute })):gsub(" 0"," ")
            logWrite(fmtString)
            return fmtString                                 -- outgoing format: ddd d mmmm yyyy (hh:mm)
        end

        local function showResult(str)
            textDevice.updateText(str)
            logWrite(str,dz.LOG_FORCE)
        end

        local function getTimeWindow(hours)
            local to   = os.time(os.date("*t"))
            local from = os.date("%A, %d %B %Y (%H:%M)",to - hours * 3600)
            local to   = os.date("%A, %d %B %Y (%H:%M)",to)
            return to, from
        end

        local function notify(from,now)
            local notificationString =  "\nhigh Temperature: " .. extremes.high.temperature .. " Celsius at " .. convertTime(extremes.high.tTime) .. "\n"
            notificationString = notificationString .. "low temperature: " .. extremes.low.temperature .. " Celsius at " .. convertTime(extremes.low.tTime) .. "\n"
            notificationString = notificationString .. "high humidity: " .. extremes.high.humidity .. "% at " .. convertTime(extremes.high.hTime) .. "\n"
            notificationString = notificationString .. "low humidity:  " .. extremes.low.humidity .. "% at " .. convertTime(extremes.low.hTime)

            logWrite("\nExtremes between " .. from .. " and " .. now .. "\n" .. notificationString,dz.LOG_FORCE)
             dz.notify("Extremes between " .. from .. " and " .. now, notificationString, dz.PRIORITY_NORMAL, nil,nil, dz.NSS_PUSHOVER )
        end

        local function getExtremes(rt)
            extremes.low                = {}
            extremes.high               = {}
            extremes.low.temperature    = 10000
            extremes.low.humidity       = 100
            extremes.high.humidity      = 0
            extremes.high.temperature   = -256

            for key in ipairs(rt) do
                if tonumber(rt[key].hu) > extremes.high.humidity then
                    logWrite("New max humidity found on " .. convertTime(rt[key].d) .. " ==>> " .. rt[key].hu )
                    extremes.high.humidity = tonumber(rt[key].hu)
                    extremes.high.hTime = rt[key].d
                end
                if tonumber(rt[key].hu) < extremes.low.humidity then
                    logWrite("New min humidity found on " .. convertTime(rt[key].d) .. " ==>> " .. rt[key].hu )
                    extremes.low.humidity = tonumber(rt[key].hu)
                    extremes.low.hTime = rt[key].d
                end
                if tonumber(rt[key].te) > extremes.high.temperature then
                    logWrite("New max temperature found on " .. convertTime(rt[key].d) .. " ==>> " .. rt[key].te )
                    extremes.high.temperature = tonumber(rt[key].te)
                    extremes.high.tTime = rt[key].d
                end
                if tonumber(rt[key].te) < extremes.low.temperature then
                    logWrite("New min temperature found on " .. convertTime(rt[key].d) .. " ==>> " .. rt[key].te )
                    extremes.low.temperature = tonumber(rt[key].te)
                    extremes.low.tTime = rt[key].d
                end
            end
            return extremes
        end


        -- Main
        if not item.isHTTPResponse then
            triggerJSON()
        elseif item.ok then                                      -- statusCode == 2xx
            extremes = getExtremes(item.json.result)
            notify(getTimeWindow(24))
        else
            logWrite("Could not get (good) data from domoticz. Error (" .. (item.statusCode or 999) .. ")"  ,dz.LOG_ERROR)
            logWrite(item.data)
        end
    end
}

Re: Calculation of the Lowest and the Highest Sensor values

Posted: Friday 18 January 2019 11:40
by AYAMY
hi
thanks for your help...

Under Domoticz --> event --> DZvent i have pasted (and modified with my idx and timer)


Code: Select all

-- getMaxTempHum

local httpResponses = "getMaxTempHum"

return {
    on      =   {
                    timer           =   { "at 11:20"    },                       -- Your preferred time
                    httpResponses   =   { httpResponses }
                },

    logging =   {
                    level           =   domoticz.LOG_ERROR,
                    marker          =   httpResponse
                },

    execute = function(dz, item)
        -- ****************************** Your settings below this line ***************************************************
        temphumDevice = dz.devices(315)          -- Replace with ID of Device you want to be notified on
        -- ****************************** No changes required below this line *********************************************

        local extremes = {}

        local function logWrite(str,level)
            dz.log(tostring(str),level or dz.LOG_DEBUG)
        end

        local function triggerJSON()
            local  URLString   = dz.settings['Domoticz url'] .. "/json.htm?type=graph&sensor=temp&range=day&idx=" .. temphumDevice.id
            dz.openURL({    url = URLString,
                            method = "GET",
                            callback = httpResponses })
        end

        local function convertTime(timeString)               -- based on incoming format yyyy-mm-dd hh:mm
            local year, month, day, hour, minute
            _,_, year, month, day, hour, minute = string.find(timeString, "(%d+)-(%d+)-(%d+) (%d+):(%d+)")
            fmtString = os.date("%A, %d %B %Y (%H:%M)",os.time({year=year, month=month, day=day, hour=hour, minute=minute })):gsub(" 0"," ")
            logWrite(fmtString)
            return fmtString                                 -- outgoing format: ddd d mmmm yyyy (hh:mm)
        end

        local function showResult(str)
            textDevice.updateText(str)
            logWrite(str,dz.LOG_FORCE)
        end

        local function getTimeWindow(hours)
            local to   = os.time(os.date("*t"))
            local from = os.date("%A, %d %B %Y (%H:%M)",to - hours * 3600)
            local to   = os.date("%A, %d %B %Y (%H:%M)",to)
            return to, from
        end

        local function notify(from,now)
            local notificationString =  "\nhigh Temperature: " .. extremes.high.temperature .. " Celsius at " .. convertTime(extremes.high.tTime) .. "\n"
            notificationString = notificationString .. "low temperature: " .. extremes.low.temperature .. " Celsius at " .. convertTime(extremes.low.tTime) .. "\n"
            notificationString = notificationString .. "high humidity: " .. extremes.high.humidity .. "% at " .. convertTime(extremes.high.hTime) .. "\n"
            notificationString = notificationString .. "low humidity:  " .. extremes.low.humidity .. "% at " .. convertTime(extremes.low.hTime)

            logWrite("\nExtremes between " .. from .. " and " .. now .. "\n" .. notificationString,dz.LOG_FORCE)
             dz.notify("Extremes between " .. from .. " and " .. now, notificationString, dz.PRIORITY_NORMAL, nil,nil, dz.NSS_PUSHOVER )
        end

        local function getExtremes(rt)
            extremes.low                = {}
            extremes.high               = {}
            extremes.low.temperature    = 10000
            extremes.low.humidity       = 100
            extremes.high.humidity      = 0
            extremes.high.temperature   = -256

            for key in ipairs(rt) do
                if tonumber(rt[key].hu) > extremes.high.humidity then
                    logWrite("New max humidity found on " .. convertTime(rt[key].d) .. " ==>> " .. rt[key].hu )
                    extremes.high.humidity = tonumber(rt[key].hu)
                    extremes.high.hTime = rt[key].d
                end
                if tonumber(rt[key].hu) < extremes.low.humidity then
                    logWrite("New min humidity found on " .. convertTime(rt[key].d) .. " ==>> " .. rt[key].hu )
                    extremes.low.humidity = tonumber(rt[key].hu)
                    extremes.low.hTime = rt[key].d
                end
                if tonumber(rt[key].te) > extremes.high.temperature then
                    logWrite("New max temperature found on " .. convertTime(rt[key].d) .. " ==>> " .. rt[key].te )
                    extremes.high.temperature = tonumber(rt[key].te)
                    extremes.high.tTime = rt[key].d
                end
                if tonumber(rt[key].te) < extremes.low.temperature then
                    logWrite("New min temperature found on " .. convertTime(rt[key].d) .. " ==>> " .. rt[key].te )
                    extremes.low.temperature = tonumber(rt[key].te)
                    extremes.low.tTime = rt[key].d
                end
            end
            return extremes
        end


        -- Main
        if not item.isHTTPResponse then
            triggerJSON()
        elseif item.ok then                                      -- statusCode == 2xx
            extremes = getExtremes(item.json.result)
            notify(getTimeWindow(24))
        else
            logWrite("Could not get (good) data from domoticz. Error (" .. (item.statusCode or 999) .. ")"  ,dz.LOG_ERROR)
            logWrite(item.data)
        end
    end
}
I have saved and Enabled the script but at 11:20 I haven't seen any info about MAxtemp... the log only show
EventSystem: reset all events...
EventSystem: Write file: /home/ubuntu/domoticz/scripts/dzVents/generated_scripts/GETMAXTEMP.lua

Re: Calculation of the Lowest and the Highest Sensor values

Posted: Thursday 18 April 2019 11:03
by whawhe
I found this script excellent. Thanks waaren!
@ayamy I had the trigger type as HTTP request, then it worked fine.

Re: Calculation of the Lowest and the Highest Sensor values

Posted: Thursday 18 April 2019 11:45
by Egregius
waaren wrote: Wednesday 19 December 2018 1:11 It can be done in Lua, dzVents or Python.
You forgot PHP ;)

I always find it amazing how much code is needed in lua to achive something this simple :o

In php only 1/10 of code is needed:

Code: Select all

$since=strftime("%F", time()-86400);
$sql="SELECT device, min(status) as min, max(status) as max  FROM log WHERE (device = 'buiten_temp' OR device = 'humidity') AND timestamp > '$since' GROUP BY device;";
if (!$result=$db->query($sql)) {
    die('There was an error running the query ['.$sql.' - '.$db->error.']');
}
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
    $data[$row['device']]['min']=$row['min'];
    $data[$row['device']]['max']=$row['max'];
}
telegram('Temperature last 24 hours: min='.$data['buiten_temp']['min'].', max='.$data['buiten_temp']['max'].'. Humidity: min='.$data['humidity']['min'].', max='.$data['humidity']['min'].'.');

Re: Calculation of the Lowest and the Highest Sensor values

Posted: Thursday 18 April 2019 12:35
by waaren
Egregius wrote: Thursday 18 April 2019 11:45
waaren wrote: Wednesday 19 December 2018 1:11 It can be done in Lua, dzVents or Python.
You forgot PHP ;)
I always find it amazing how much code is needed in lua to achive something this simple :o
Sorry, I am just not smart enough to understand PHP. Please forgive me my ignorance.