Begin- and endTime of some astro events  [SOLVED]

Moderator: leecollings

Nefsolive
Posts: 69
Joined: Monday 04 September 2017 17:13
Target OS: Raspberry Pi / ODroid
Domoticz version:
Contact:

Re: Begin- and endTime of some astro events

Post by Nefsolive »

waaren wrote: Thursday 10 December 2020 19:41
Nefsolive wrote: Thursday 10 December 2020 18:19 But i still have this error:
Error: dzVents: Error: (3.0.2) astro dzVents: ...icz/scripts/dzVents/generated_scripts/Eventos do Dia.lua:36: attempt to index a number value (local 'str')
I assume you changed the script because in the version I posted there is no variable "str" in line 36.
If so there is no way I can help without you sharing the script as it is now.
Hello waaren
The only change was to add new "devKeys".
The variable "str" comes from your script "makeTime (str)"
It only gives me the error when I put "['D of the Day'] = 'day_length'," I assume it will be because it is text!
I Send the script
ty

Code: Select all

-- collect begin- and endtimes of some astro events. dzVents >= 2.4.19 (domoticz V4.10717)
local scriptVar = 'astro dzVents'


return {
        on =    {
                    timer = { 'at 17:24', 'at 06:03' }, -- twice a day to be sure and 3 min past the hour because at the hour already quite busy 
                    httpResponses = { scriptVar }
                },

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

    execute = function(dz, item)
        -- domoticz text devices. Comment lines for devices you don't have / want
        local devKeys = {   -- Device names                  -- Key  in data
                            ['D do Dia']   = 'day_length',
			    ['Sol do Meio-Dia']   = 'solar_noon',
			    ['Início do Crepúsculo Civil']        = 'civil_twilight_begin',
                            ['Fim do Crepúsculo Civil']          = 'civil_twilight_end',
                            ['Início do Crepúsculo Náutico']     = 'nautical_twilight_begin',
                            ['Fim do Crepúsculo Náutico']       = 'nautical_twilight_end',
                            ['Início do Crepúsculo Astronômico'] = 'astronomical_twilight_begin',
                            ['Fim do Crepúsculo Astronômico']   = 'astronomical_twilight_end',
                        }
                     

        local function TZOffset()  -- in seconds
            return os.difftime(os.time(), os.time(os.date('!*t'))) + (dz.time.isdst and 3600 or 0)
        end

        local function makeTime(str)
            local pattern = '(%d+)-(%d+)-(%d+)T(%d+):(%d+):(%d+)'
            local runyear, runmonth, runday, runhour, runminute, runseconds = str:match(pattern)
            local timestamp = os.time({year = runyear, month = runmonth, day = runday, hour = runhour, min = runminute, sec = runseconds})
            return (os.date('%X',timestamp + TZOffset())):sub(1,5)
        end    

        local function getAstroData()
            url = 'https://api.sunrise-sunset.org/json' ..
                            '?lat=***' .. dz.settings.location.latitude ..
                            '&lng=***' .. dz.settings.location.longitude ..
                            '&formatted=0'
                dz.openURL({ url = url, callback = scriptVar })
        end

        local function procesResults(t)
            for dv, field in pairs(devKeys) do
                if dz.devices(dv) and t[field] then
                    dz.devices(dv).updateText(makeTime(t[field]))
                end
            end
        end

        if item.isHTTPResponse then
            if item.ok then 
                procesResults(item.json.results)
            else
                dz.log('problem retrieving information from sunrise-sunset.org \n' .. item.data, dz.LOG_ERROR)
            end
        else
            getAstroData()
        end
    end
}
User avatar
waaren
Posts: 6028
Joined: Tuesday 03 January 2017 14:18
Target OS: Linux
Domoticz version: Beta
Location: Netherlands
Contact:

Re: Begin- and endTime of some astro events

Post by waaren »

Nefsolive wrote: Friday 11 December 2020 11:13 The only change was to add new "devKeys".
Can you try this?

Code: Select all

-- collect begin- and endtimes of some astro events. dzVents >= 2.4.19 (domoticz V4.10717)
local scriptVar = 'astro dzVents'


return
{
    on =
    {
        timer =
        {
            'at 17:24',
            'at 06:03',
        }, 
        httpResponses =
        {
            scriptVar
        }
    },

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

    execute = function(dz, item)
        -- domoticz text devices. Comment lines for devices you don't have / want
        local devKeys =
        {   -- Device names                  -- Key  in data
            ['D do Dia'] = 'day_length',
            ['Sol do Meio-Dia'] = 'solar_noon',
            ['Início do Crepúsculo Civil'] = 'civil_twilight_begin',
            ['Fim do Crepúsculo Civil'] = 'civil_twilight_end',
            ['Início do Crepúsculo Náutico'] = 'nautical_twilight_begin',
            ['Fim do Crepúsculo Náutico'] = 'nautical_twilight_end',
            ['Início do Crepúsculo Astronômico'] = 'astronomical_twilight_begin',
            ['Fim do Crepúsculo Astronômico'] = 'astronomical_twilight_end',
        }

        local function TZOffset()  -- in seconds
            return os.difftime(os.time(), os.time(os.date('!*t'))) + (dz.time.isdst and 3600 or 0)
        end

        local function makeTime(str)
            local pattern = '(%d+)-(%d+)-(%d+)T(%d+):(%d+):(%d+)'
            local runyear, runmonth, runday, runhour, runminute, runseconds = str:match(pattern)
            local timestamp = os.time({year = runyear, month = runmonth, day = runday, hour = runhour, min = runminute, sec = runseconds})
            return (os.date('%X',timestamp + TZOffset())):sub(1,5)
        end

        local function seconds2Text(seconds)
            local hours = math.floor(seconds / 3600)
            local minutes = math.floor(( seconds - hours * 3600 ) /60 )
            local seconds = seconds % 60

            return hours .. ' hours, ' .. minutes .. ' minutes and ' .. seconds .. ' seconds.'
        end

        local function getAstroData()
            url = 'https://api.sunrise-sunset.org/json' ..
                            '?lat=' .. dz.settings.location.latitude ..
                            '&lng=' .. dz.settings.location.longitude ..
                            '&formatted=0'
                dz.openURL(
                {
                    url = url,
                    callback = scriptVar,
                })
        end

        local function procesResults(t)
            for dv, field in pairs(devKeys) do
                if dz.devices(dv) and field == 'day_length' then
                    dz.devices(dv).updateText(seconds2Text(t[field]))
                elseif dz.devices(dv) and t[field] then
                    dz.devices(dv).updateText(makeTime(t[field]))
                end
            end
        end

        if item.isHTTPResponse and item.isJSON then
            procesResults(item.json.results)
        elseif isHTTPResponse then
            dz.log('problem retrieving information from sunrise-sunset.org \n' .. item.data, dz.LOG_ERROR)
        else
            getAstroData()
        end
    end
}
Debian buster, bullseye on RPI-4, Intel NUC.
dz Beta, Z-Wave, RFLink, RFXtrx433e, P1, Youless, Hue, Yeelight, Xiaomi, MQTT
==>> dzVents wiki
Nefsolive
Posts: 69
Joined: Monday 04 September 2017 17:13
Target OS: Raspberry Pi / ODroid
Domoticz version:
Contact:

Re: Begin- and endTime of some astro events

Post by Nefsolive »

waaren wrote: Friday 11 December 2020 15:20
Nefsolive wrote: Friday 11 December 2020 11:13 The only change was to add new "devKeys".
Can you try this?
Hello Waaren,

Works brilliant!
Thank u again, for the script, work and your amazing help!
if we don’t talk in the meantime, I wish you a Merry Christmas.

Best regards
leby
Posts: 98
Joined: Monday 28 July 2014 9:58
Target OS: Raspberry Pi / ODroid
Domoticz version: 2020.2
Location: Stockholm
Contact:

Re: Begin- and endTime of some astro events

Post by leby »

Hallo Warren, first many thanks for all code you have given us!! dzvents is a reel blessing for an amateur like me!!

The script you given us in this tread I would like to use in a slightly different scenario!
I want to control the lights in two different places, they obviously then have different sunset / sunrise. This means that Domoticz location is not enough.

I therefore tried to manipulate your script but cant solve all :-( so if you have time to guide me I would be great full.

The script as is works but I would like if possible to do one out of two modifications:
1: best (fantastic) would be if the created new Sunset_Spain and Sunrise_Spain could be used in the same way as dzvents sunset / sunrise. I realise that it is to ask to much but have to ask ;-)
2: second best would be if it could be changed so that instead of (or both) updating a text object it would turn ON a switch at the time fetched for sunrise / sunset. I'm thinking that I create two dummy switches for sunset/sunrise and then the script do something like "sunrise.switchOn().afterMin("fetchedtime-now")" well the result would be that a switch turns on at sunrise and another at sunset. This two could then be used to trigger scripts for my second location.

Code: Select all

-- collect begin- and endtimes of some astro events. dzVents >= 2.4.19 (domoticz V4.10717) 
local scriptVar = 'astro dzVents'

return {
        on =    {
                    devices = {311},
                    timer = { 'at 00:03'}, -- once a day to be sure and 3 min past the hour because at the hour already quite busy 
                    httpResponses = { scriptVar }
                },

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

    execute = function(dz, item)
        -- domoticz text devices. Comment lines for devices you don't have / want changed namne to Sunset_Spain and Sunrise_Spain
        local devKeys = {   -- Device names                  -- Key  in data
                            ['Sunset_Spain']                      = 'sunset',
                            ['Sunrise_Spain']                     = 'sunrise',
                        } 

        local function TZOffset()  -- in seconds
            return os.difftime(os.time(), os.time(os.date('!*t'))) + (dz.time.isdst and 3600 or 0)
        end

        local function makeTime(str)
            local pattern = '(%d+)-(%d+)-(%d+)T(%d+):(%d+):(%d+)'
            local runyear, runmonth, runday, runhour, runminute, runseconds = str:match(pattern)
            local timestamp = os.time({year = runyear, month = runmonth, day = runday, hour = runhour, min = runminute, sec = runseconds})
            return (os.date('%X',timestamp + TZOffset())):sub(1,5)
        end    

        local function getAstroData() --- replaced the fetch from domoticz to another location, my second location!
                dz.openURL({ url = 'https://api.sunrise-sunset.org/json?lat=38.129097&lng=-0.692064&formatted=0', callback = scriptVar })
        end

        local function procesResults(t)
            for dv, field in pairs(devKeys) do
                if dz.devices(dv) and t[field] then
                    dz.devices(dv).updateText(makeTime(t[field]))
                end
            end
        end

        if item.isHTTPResponse then
            if item.ok then 
                procesResults(item.json.results)
            else
                dz.log('problem retrieving information from sunrise-sunset.org \n' .. item.data, dz.LOG_ERROR)
            end
        else
            getAstroData()
        end
    end
}
Well worth a try anyhow, now I'm running two instances of Domoticz and hoped to reduce that to one :-)
/lennart
User avatar
waaren
Posts: 6028
Joined: Tuesday 03 January 2017 14:18
Target OS: Linux
Domoticz version: Beta
Location: Netherlands
Contact:

Re: Begin- and endTime of some astro events

Post by waaren »

leby wrote: Friday 08 January 2021 14:29 best (fantastic) would be if the created new Sunset_Spain and Sunrise_Spain could be used in the same way as dzvents sunset / sunrise.
Can you try this one ?

Code: Select all

-- collect begin- and endtimes of some astro events. dzVents >= 2.4.19 (domoticz V4.10717)

local scriptVar = 'astro dzVents'

return
{
    on =
    {
        timer =  -- twice a day to be sure and 3 min past the hour because at the hour already quite busy
        {
            'at 00:03',
            'at 06:03'
        },

        devices =
        {
            'astroTrigger', -- Just for test / development. Can be ignored.
        },

        httpResponses =
        {
            scriptVar .. '*',
        },
    },

    logging =
    {
        level = domoticz.LOG_DEBUG, -- set to domoticz.LOG_DEBUG
        marker = scriptVar,
    },

    execute = function(dz, item)

        local latSpain = 38.129097 -- optional
        local lonSpain = -0.692064 -- optional

        -- domoticz text devices. Comment lines for devices or remove them if you don't have / want
        local devKeys =
        {   -- Device names                  -- Key  in data             defaults
            ['Civil Twilight End']          = 'civil_twilight_end',
            ['Civil Twilight Start']        = 'civil_twilight_begin',
            ['Nautical Twilight End']       = 'nautical_twilight_begin',
            ['Nautical Twilight Start']     = 'nautical_twilight_end',
            ['Astronomical Twilight End']   = 'astronomical_twilight_begin',
            ['Astronomical Twilight Start'] = 'astronomical_twilight_end',
            ['Sunset']                      = 'sunset',
            ['Sunrise']                     = 'sunrise',
            ['Other'] =
                {
                    ['Spain'] =
                    {
                        ['Sunset_Spain'] = 'sunset',
                        ['Sunrise_Spain'] = 'sunrise',
                    },
                },
        }

        local function TZOffset()  -- in seconds
            return os.difftime(os.time(), os.time(os.date('!*t'))) + (dz.time.isdst and 3600 or 0)
        end

        local function makeTime(str)
            local pattern = '(%d+)-(%d+)-(%d+)T(%d+):(%d+):(%d+)'
            local runyear, runmonth, runday, runhour, runminute, runseconds = str:match(pattern)
            local timestamp = os.time({year = runyear, month = runmonth, day = runday, hour = runhour, min = runminute, sec = runseconds})
            return (os.date('%X',timestamp + TZOffset())):sub(1,5)
        end

        local function getAstroData(lat, lon, other, delay)
            local other = other or ''
            url = 'https://api.sunrise-sunset.org/json' ..
                            '?lat=' .. (lat or dz.settings.location.latitude) ..
                            '&lng=' .. (lon or dz.settings.location.longitude) ..
                            '&formatted=0'
                dz.openURL(
                {
                    url = url,
                    callback = scriptVar  .. other
                }).afterSec(delay or 0)
        end

        local function procesResults(t, location)
            dz.utils.dumpTable(t)
            location, _ = location:gsub(scriptVar,'')
            if location ~= '' then devKeys = devKeys.Other[location] end

            for dv, field in pairs(devKeys) do
                if dv ~= 'Other' and dz.devices(dv) and t[field] then
                    dz.devices(dv).updateText(makeTime(t[field]))
                end
            end
        end

        if item.isHTTPResponse and item.json then
            procesResults(item.json.results, item.trigger)
        elseif item.isTimer or item.isDevice then
            getAstroData()
            getAstroData(latSpain,lonSpain, 'Spain', 5) -- optional other location
        else
            dz.log('problem retrieving information from sunrise-sunset.org for ' .. item.trigger:gsub(scriptVar,''), dz.LOG_ERROR)
            dz.log(item,dz.LOG_DEBUG)
        end
    end
}
Debian buster, bullseye on RPI-4, Intel NUC.
dz Beta, Z-Wave, RFLink, RFXtrx433e, P1, Youless, Hue, Yeelight, Xiaomi, MQTT
==>> dzVents wiki
leby
Posts: 98
Joined: Monday 28 July 2014 9:58
Target OS: Raspberry Pi / ODroid
Domoticz version: 2020.2
Location: Stockholm
Contact:

Re: Begin- and endTime of some astro events

Post by leby »

:) Absolutely what can I expect? Should I try to use "Sunset_Spain" as a global variable the same way I use sunset??

Just for info:
I run the script and get this in the logg:

Code: Select all

2021-01-08 18:11:40.629 Status: EventSystem: Script event triggered: /home/pi/domoticz/dzVents/runtime/dzVents.lua
2021-01-08 18:11:41.526 Status: dzVents: Info: Handling httpResponse-events for: "astro dzVentsSpain"
2021-01-08 18:11:41.527 Status: dzVents: Info: astro dzVents: ------ Start internal script: Test sunset sunrise: HTTPResponse: "astro dzVentsSpain"
2021-01-08 18:11:41.529 Status: dzVents: > nautical_twilight_end: 2021-01-08T18:02:07+00:00
2021-01-08 18:11:41.529 Status: dzVents: > civil_twilight_end: 2021-01-08T17:29:24+00:00
2021-01-08 18:11:41.529 Status: dzVents: > astronomical_twilight_end: 2021-01-08T18:33:57+00:00
2021-01-08 18:11:41.529 Status: dzVents: > sunset: 2021-01-08T17:00:22+00:00
2021-01-08 18:11:41.529 Status: dzVents: > civil_twilight_begin: 2021-01-08T06:50:09+00:00
2021-01-08 18:11:41.529 Status: dzVents: > nautical_twilight_begin: 2021-01-08T06:17:26+00:00
2021-01-08 18:11:41.529 Status: dzVents: > solar_noon: 2021-01-08T12:09:46+00:00
2021-01-08 18:11:41.529 Status: dzVents: > astronomical_twilight_begin: 2021-01-08T05:45:36+00:00
2021-01-08 18:11:41.529 Status: dzVents: > day_length: 34872
2021-01-08 18:11:41.529 Status: dzVents: > sunrise: 2021-01-08T07:19:10+00:00
2021-01-08 18:11:41.559 Status: dzVents: Debug: astro dzVents: Processing device-adapter for Sunset_Spain: Text device
2021-01-08 18:11:41.562 Status: dzVents: Debug: astro dzVents: Processing device-adapter for Sunrise_Spain: Text device
2021-01-08 18:11:41.562 Status: dzVents: Info: astro dzVents: ------ Finished Test sunset sunrise
Don't know if it is correct or not..
/lennart
User avatar
waaren
Posts: 6028
Joined: Tuesday 03 January 2017 14:18
Target OS: Linux
Domoticz version: Beta
Location: Netherlands
Contact:

Re: Begin- and endTime of some astro events

Post by waaren »

leby wrote: Friday 08 January 2021 17:54 :) Absolutely what can I expect? Should I try to use "Sunset_Spain" as a global variable the same way I use sunset??

Don't know if it is correct or not..
Looks OK to me. You should see the sunset and sunrise times in the text devices you created for it.
Debian buster, bullseye on RPI-4, Intel NUC.
dz Beta, Z-Wave, RFLink, RFXtrx433e, P1, Youless, Hue, Yeelight, Xiaomi, MQTT
==>> dzVents wiki
leby
Posts: 98
Joined: Monday 28 July 2014 9:58
Target OS: Raspberry Pi / ODroid
Domoticz version: 2020.2
Location: Stockholm
Contact:

Re: Begin- and endTime of some astro events

Post by leby »

waaren wrote: Friday 08 January 2021 18:23 Looks OK to me. You should see the sunset and sunrise times in the text devices you created for it.
Ok, sorry I'm not native English speaking so perhaps it was unclear.
The script worked before and updated the text objects. What I tried to ask about was this below:
Perhaps you last script will update a device, now I did se this code:

Code: Select all

elseif item.isTimer or item.isDevice then
I will let it run a day and that should give me the answer I guess

If possible to do one out of two modifications:
1: best (fantastic) would be if the created new Sunset_Spain and Sunrise_Spain could be used in the same way as dzvents sunset / sunrise. I realise that it is to ask to much but have to ask ;-)
2: second best would be if it could be changed so that instead of (or both) updating a text object it would turn ON a switch at the time fetched for sunrise / sunset. I'm thinking that I create two dummy switches for sunset/sunrise and then the script do something like "sunrise.switchOn().afterMin("fetchedtime-now")" well the result would be that a switch turns on at sunrise and another at sunset. This two could then be used to trigger scripts for my second location.

Is any of the two options above possible you think?

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

Re: Begin- and endTime of some astro events

Post by waaren »

leby wrote: Friday 08 January 2021 18:36 Is any of the two options above possible you think?
Option 1 is not feasible.

With regards to option 2
According to your profile you are on 2020.1 and therefore probably not very easy to do something like it.
If you were on a more recent version you should be able to do something like

Code: Select all

sunrise.switchOn().at(fetchedTime)
or even better

Code: Select all

emitEvent('sunriseSpain Activity").at('fetchedTime')
Debian buster, bullseye on RPI-4, Intel NUC.
dz Beta, Z-Wave, RFLink, RFXtrx433e, P1, Youless, Hue, Yeelight, Xiaomi, MQTT
==>> dzVents wiki
leby
Posts: 98
Joined: Monday 28 July 2014 9:58
Target OS: Raspberry Pi / ODroid
Domoticz version: 2020.2
Location: Stockholm
Contact:

Re: Begin- and endTime of some astro events

Post by leby »

waaren wrote: Friday 08 January 2021 19:34 With regards to option 2
According to your profile you are on 2020.1 and therefore probably not very easy to do something like it.
If you were on a more recent version you should be able to do something like

Code: Select all

sunrise.switchOn().at(fetchedTime)
or even better

Code: Select all

emitEvent('sunriseSpain Activity").at('fetchedTime')
Ok, now upgraded to 2020.2,
Focusing on alt 2. cloud you give me some more help, most of your code is to advanced for me. :?

Changed so that instead of (or both) updating a text object it would turn ON a switch at the time fetched for sunrise / sunset. I'm thinking that I create two dummy switches for sunset/sunrise and then the script do something like "sunrise.switchOn().afterMin("fetchedtime-now")" well the result would be that a switch turns on at sunrise and another at sunset. This two could then be used to trigger scripts for my second location.
/lennart
User avatar
waaren
Posts: 6028
Joined: Tuesday 03 January 2017 14:18
Target OS: Linux
Domoticz version: Beta
Location: Netherlands
Contact:

Re: Begin- and endTime of some astro events

Post by waaren »

leby wrote: Friday 08 January 2021 20:17 Ok, now upgraded to 2020.2,
Focusing on alt 2. cloud you give me some more help, most of your code is to advanced for me. :?
First script updates the set text devices and sends a customEvent trigger at Spain sunset time and another one at - sunrise Spain time

Code: Select all

-- collect begin- and endtimes of some astro events. dzVents >= 3.0

local scriptVar = 'astro dzVents'

return
{
    on =
    {
        timer =  -- twice a day to be sure and 3 min past the hour because at the hour already quite busy
        {
            'at 00:03',
            'at 06:03'
        },

        devices =
        {
            'astroTrigger', -- Just for test / development. Can be ignored.
        },

        httpResponses =
        {
            scriptVar .. '*',
        },
    },

    logging =
    {
        level = domoticz.LOG_DEBUG, -- set to domoticz.LOG_DEBUG
        marker = scriptVar,
    },

    execute = function(dz, item)

        local latSpain = 38.129097 -- optional
        local lonSpain = -0.692064 -- optional

        -- domoticz text devices. Comment lines for devices or remove them if you don't have / want
        local devKeys =
        {   -- Device names                  -- Key  in data             defaults
            ['Civil Twilight End']          = 'civil_twilight_end',
            ['Civil Twilight Start']        = 'civil_twilight_begin',
            ['Nautical Twilight End']       = 'nautical_twilight_begin',
            ['Nautical Twilight Start']     = 'nautical_twilight_end',
            ['Astronomical Twilight End']   = 'astronomical_twilight_begin',
            ['Astronomical Twilight Start'] = 'astronomical_twilight_end',
            ['Sunset']                      = 'sunset',
            ['Sunrise']                     = 'sunrise',
        }
        -- customEvent triggers
        local customEventKeys =
        {
            ['Sunset_Spain'] = 'sunset',
            ['Sunrise_Spain'] = 'sunrise',
        }

        local function TZOffset()  -- in seconds
            return os.difftime(os.time(), os.time(os.date('!*t'))) + (dz.time.isdst and 3600 or 0)
        end

        local function makeTime(str)
            local pattern = '(%d+)-(%d+)-(%d+)T(%d+):(%d+):(%d+)'
            local runyear, runmonth, runday, runhour, runminute, runseconds = str:match(pattern)
            local timestamp = os.time({year = runyear, month = runmonth, day = runday, hour = runhour, min = runminute, sec = runseconds})
            return (os.date('%X',timestamp + TZOffset())):sub(1,5)
        end

        local function getAstroData(lat, lon, other, delay)
            local other = other or ''
            url = 'https://api.sunrise-sunset.org/json' ..
                            '?lat=' .. (lat or dz.settings.location.latitude) ..
                            '&lng=' .. (lon or dz.settings.location.longitude) ..
                            '&formatted=0'
                dz.openURL(
                {
                    url = url,
                    callback = scriptVar  .. other
                }).afterSec(delay or 0)
        end

        local function procesResults(t, location)
            location, _ = location:gsub(scriptVar,'')
            if location ~= '' then
                for trigger, field in pairs(customEventKeys) do
                    if t[field] then
                        dz.log('dz.emitEvent(' .. trigger .. ').at(' .. makeTime(t[field]) .. ')',dz.LOG_DEBUG )
                        dz.emitEvent(trigger).at(makeTime(t[field]))
                    end
                end
            else
                for dv, field in pairs(devKeys) do
                    if dz.devices(dv) and t[field] then
                        dz.devices(dv).updateText(makeTime(t[field]))
                    end
                end
            end
        end

        if item.isHTTPResponse and item.json then
            procesResults(item.json.results, item.trigger)
        elseif item.isTimer or item.isDevice then
            getAstroData()
            getAstroData(latSpain,lonSpain, 'Spain', 5) -- optional other location
        else
            dz.log('problem retrieving information from sunrise-sunset.org for ' .. item.trigger:gsub(scriptVar,''), dz.LOG_ERROR)
            dz.log(item,dz.LOG_DEBUG)
        end
    end
}

Second script is an example script that is triggered by the customEvents send by the first script. So you do not need an extra dummy device or uservariable.

Code: Select all

-- waitd for the custome Events send by the astro events scripts. dzVents >= 3.0

return
{
    on =
    {
        customEvents =
        {
            'Sunset_Spain',
            'Sunrise_Spain',
        },
    },

    logging =
    {
        level = domoticz.LOG_DEBUG, -- set to domoticz.LOG_ERROR when all OK
        marker = 'astro Events',
    },

    data =
    {
        executed =
        {
            initial = 0,
        },
    },

    execute = function(dz, item)
        if dz.data.executed > ( os.time() - 300 ) then
            dz.log('Multiple customEvents triggered for the same time. No action needed ',dz.LOG_DEBUG)
        elseif item.trigger == 'Sunset_Spain' then
            dz.log('Your actions for sunset after this line ',dz.LOG_FORCE)

        elseif item.trigger == 'Sunrise_Spain' then
            dz.log('Your actions for sunrise after this line ',dz.LOG_FORCE)

        else
            dz.log('Unknown trigger. This should not be possible', dz.LOG_ERROR)
        end

        dz.data.executed = os.time()

    end
}

Debian buster, bullseye on RPI-4, Intel NUC.
dz Beta, Z-Wave, RFLink, RFXtrx433e, P1, Youless, Hue, Yeelight, Xiaomi, MQTT
==>> dzVents wiki
leby
Posts: 98
Joined: Monday 28 July 2014 9:58
Target OS: Raspberry Pi / ODroid
Domoticz version: 2020.2
Location: Stockholm
Contact:

Re: Begin- and endTime of some astro events

Post by leby »

waaren wrote: Saturday 09 January 2021 0:05
Second script is an example script that is triggered by the customEvents send by the first script. So you do not need an extra dummy device or uservariable.

Code: Select all

-- waitd for the custome Events send by the astro events scripts. dzVents >= 3.0

return
{
    on =
    {
        customEvents =
        {
            'Sunset_Spain',
            'Sunrise_Spain',
        },
    },

    logging =
    {
        level = domoticz.LOG_DEBUG, -- set to domoticz.LOG_ERROR when all OK
        marker = 'astro Events',
    },

    data =
    {
        executed =
        {
            initial = 0,
        },
    },

    execute = function(dz, item)
        if dz.data.executed > ( os.time() - 300 ) then
            dz.log('Multiple customEvents triggered for the same time. No action needed ',dz.LOG_DEBUG)
        elseif item.trigger == 'Sunset_Spain' then
            dz.log('Your actions for sunset after this line ',dz.LOG_FORCE)

        elseif item.trigger == 'Sunrise_Spain' then
            dz.log('Your actions for sunrise after this line ',dz.LOG_FORCE)

        else
            dz.log('Unknown trigger. This should not be possible', dz>LOG_ERROR)
        end

        dz.data.executed = os.time()

    end
}

Must admit that I feel a bit stupid (perhaps I am :-))

I get what the first script do (I think)
Skärmklipp.JPG
Skärmklipp.JPG (38.65 KiB) Viewed 1101 times
But what does the second script do? It seems as it is a trigger but when does it trigger? Does it trigger at the time off the text in 'Sunset_Spain', and 'Sunrise_Spain', how does it know that it is the time in the text objekt??

If I would guess I would say that I should replace

Code: Select all

 dz.log('Your actions for sunset after this line ',dz.LOG_FORCE)
With what ever I want to happen, at each step?
When is this??

Code: Select all

 if dz.data.executed > ( os.time() - 300 ) the
Sorry to bother you this much and thanks for all the help....

I will test and replace the actions after "then" with update of some variable and see what I get, perhaps I can understand then...
/lennart
User avatar
waaren
Posts: 6028
Joined: Tuesday 03 January 2017 14:18
Target OS: Linux
Domoticz version: Beta
Location: Netherlands
Contact:

Re: Begin- and endTime of some astro events

Post by waaren »

leby wrote: Saturday 09 January 2021 9:56
With what ever I want to happen, at each step?

I will test and replace the actions after "then" with update of some variable and see what I get, perhaps I can understand then...
Can you please first read the dzVents wiki sections on customEvents and emitEvent (use [ctrl]-f to search)
For now I can't explain better then what I posted earlier

"Second script is an example script that is triggered by the customEvents send by the first script. So you do not need an extra dummy device or uservariable"
When is this??

Code: Select all

 if dz.data.executed > ( os.time() - 300 ) the
This is a check to evaluate if the second script was already activate in the last 300 seconds.
Debian buster, bullseye on RPI-4, Intel NUC.
dz Beta, Z-Wave, RFLink, RFXtrx433e, P1, Youless, Hue, Yeelight, Xiaomi, MQTT
==>> dzVents wiki
leby
Posts: 98
Joined: Monday 28 July 2014 9:58
Target OS: Raspberry Pi / ODroid
Domoticz version: 2020.2
Location: Stockholm
Contact:

Re: Begin- and endTime of some astro events

Post by leby »

waaren wrote: Saturday 09 January 2021 10:04
Can you please first read the dzVents wiki sections on customEvents and emitEvent (use [ctrl]-f to search)
For now I can't explain better then what I posted earlier
:D Well not 100% sure that I understand after I have read the wiki but perhaps?! I give it a try, you can just ignore me if you don't have more time for me now...

This part say that this is a customEvents

Code: Select all

        local customEventKeys =
        {
            ['Sunset_Spain'] = 'sunset',
            ['Sunrise_Spain'] = 'sunrise',
        }
and this part creates the information that will be used to decide what happend (could be sunset in spain) and when the trigger should acrivate?!

Code: Select all

 dz.log('dz.emitEvent(' .. trigger .. ').at(' .. makeTime(t[field]) .. ')',dz.LOG_DEBUG )
I have not guessed where the customEvents is saved, perhaps in a table in dzvents area??

Well I will try them out and hope for the best, many thanks for all help!!!
/lennart
User avatar
waaren
Posts: 6028
Joined: Tuesday 03 January 2017 14:18
Target OS: Linux
Domoticz version: Beta
Location: Netherlands
Contact:

Re: Begin- and endTime of some astro events

Post by waaren »

leby wrote: Saturday 09 January 2021 12:29

Code: Select all

 dz.log('dz.emitEvent(' .. trigger .. ').at(' .. makeTime(t[field]) .. ')',dz.LOG_DEBUG )
No this line only writes something to the log.


the line

Code: Select all

                       dz.emitEvent(trigger).at(makeTime(t[field]))
triggers the customEvent (saved in memory only) at the the sunset or sunrise in Spain time that have been collected from api.sunrise-sunset.org
Debian buster, bullseye on RPI-4, Intel NUC.
dz Beta, Z-Wave, RFLink, RFXtrx433e, P1, Youless, Hue, Yeelight, Xiaomi, MQTT
==>> dzVents wiki
leby
Posts: 98
Joined: Monday 28 July 2014 9:58
Target OS: Raspberry Pi / ODroid
Domoticz version: 2020.2
Location: Stockholm
Contact:

Re: Begin- and endTime of some astro events

Post by leby »

waaren wrote: Saturday 09 January 2021 12:37

Code: Select all

                       dz.emitEvent(trigger).at(makeTime(t[field]))
triggers the customEvent (saved in memory only) at the the sunset or sunrise in Spain time that have been collected from api.sunrise-sunset.org
:D :D :D fantastic! it seems to work as far as I have tested. Think I at least understand the principle even if the code is to advanced for me.

One question, if Domoticz is restarted I assume the customEvent is lost if it is held in memory, right?

I'm not sure if I dare to ask but please just ignore this if you don't feel like it, the help I received so far is fantastic and basically solves my problem but her we go..

--- Would it be possible to add an offset in minutes to the time the "customEvent" triggers?
Thinking perhaps something like this:
['Sunset_Spain'] [-30] = 'sunset',
['Sunrise_Spain'] [+45]= 'sunrise',
This would then mean that the trigger happens 30 minutes before sunset (I'm using that today) and 45 minutes after sunrise?
/lennart
User avatar
waaren
Posts: 6028
Joined: Tuesday 03 January 2017 14:18
Target OS: Linux
Domoticz version: Beta
Location: Netherlands
Contact:

Re: Begin- and endTime of some astro events

Post by waaren »

leby wrote: Sunday 10 January 2021 12:37 One question, if Domoticz is restarted I assume the customEvent is lost if it is held in memory, right?
Yes same principle as with afterSec() for a device
Would it be possible to add an offset in minutes to the time the "customEvent" triggers?
This should do that

Code: Select all


-- collect begin- and endtimes of some astro events. dzVents >= 3.0

local scriptVar = 'astro dzVents'

return
{
    on =
    {
        timer =  -- twice a day to be sure and 3 min past the hour because at the hour already quite busy
        {
            'at 00:03',
            'at 06:03'
        },

        devices =
        {
            'astroTrigger', -- Just for test / development. Can be ignored.
        },

        httpResponses =
        {
            scriptVar .. '*',
        },
    },

    logging =
    {
        level = domoticz.LOG_DEBUG, -- set to domoticz.LOG_ERROR when all OK
        marker = scriptVar,
    },

    execute = function(dz, item)

        local latSpain = 38.129097 -- optional
        local lonSpain = -0.692064 -- optional

        -- domoticz text devices. Comment lines for devices or remove them if you don't have / want
        local devKeys =
        {   -- Device names                  -- Key  in data             defaults
            ['Civil Twilight End']          = 'civil_twilight_end',
            ['Civil Twilight Start']        = 'civil_twilight_begin',
            ['Nautical Twilight End']       = 'nautical_twilight_begin',
            ['Nautical Twilight Start']     = 'nautical_twilight_end',
            ['Astronomical Twilight End']   = 'astronomical_twilight_begin',
            ['Astronomical Twilight Start'] = 'astronomical_twilight_end',
            ['Sunset']                      = 'sunset',
            ['Sunrise']                     = 'sunrise',
        }
        -- customEvent triggers
        local customEventKeys =
        { --  device             key       offset
            ['Sunset_Spain'] = { 'sunset', -30 },
            ['Sunrise_Spain'] = { 'sunrise', 45 },
        }

        local function TZOffset()  -- in seconds
            return os.difftime(os.time(), os.time(os.date('!*t'))) + (dz.time.isdst and 3600 or 0)
        end

        local function makeTime(str, offset)
            local offset = offset or 0
            local pattern = '(%d+)-(%d+)-(%d+)T(%d+):(%d+):(%d+)'
            local runyear, runmonth, runday, runhour, runminute, runseconds = str:match(pattern)
            local timestamp = os.time({year = runyear, month = runmonth, day = runday, hour = runhour, min = runminute + offset, sec = runseconds})
            return (os.date('%X',timestamp + TZOffset())):sub(1,5)
        end

        local function getAstroData(lat, lon, other, delay)
            local other = other or ''
            url = 'https://api.sunrise-sunset.org/json' ..
                            '?lat=' .. (lat or dz.settings.location.latitude) ..
                            '&lng=' .. (lon or dz.settings.location.longitude) ..
                            '&formatted=0'
                dz.openURL(
                {
                    url = url,
                    callback = scriptVar  .. other
                }).afterSec(delay or 0)
        end

        local function procesResults(t, location)
            location, _ = location:gsub(scriptVar,'')
            if location ~= '' then
                for trigger, field in pairs(customEventKeys) do
                    if t[field[1]] then
                        dz.log('dz.emitEvent(' .. trigger .. ').at(' .. makeTime(t[field[1]],field[2]) .. ')',dz.LOG_DEBUG )
                        dz.emitEvent(trigger).at(makeTime(t[field[1]],field[2]))
                    end
                end
            else
                for dv, field in pairs(devKeys) do
                    if dz.devices(dv) and t[field] then
                        dz.devices(dv).updateText(makeTime(t[field]))
                    end
                end
            end
        end

        if item.isHTTPResponse and item.json then
            procesResults(item.json.results, item.trigger)
        elseif item.isTimer or item.isDevice then
            getAstroData()
            getAstroData(latSpain,lonSpain, 'Spain', 5) -- optional other location
        else
            dz.log('problem retrieving information from sunrise-sunset.org for ' .. item.trigger:gsub(scriptVar,''), dz.LOG_ERROR)
            dz.log(item,dz.LOG_DEBUG)
        end
    end
}
Debian buster, bullseye on RPI-4, Intel NUC.
dz Beta, Z-Wave, RFLink, RFXtrx433e, P1, Youless, Hue, Yeelight, Xiaomi, MQTT
==>> dzVents wiki
leby
Posts: 98
Joined: Monday 28 July 2014 9:58
Target OS: Raspberry Pi / ODroid
Domoticz version: 2020.2
Location: Stockholm
Contact:

Re: Begin- and endTime of some astro events

Post by leby »

waaren wrote: Saturday 09 January 2021 0:05 Second script is an example script that is triggered by the customEvents send by the first script. So you do not need an extra dummy device or uservariable.
...
I'm amazed how you can write all this code with nearly zero mistake! As far as I got now it seems to solve all my needs :P .
I have only fund one very small code error that I have no problem changing myself but if someone else will try this code they can change it before they run.
dz.log('Unknown trigger. This should not be possible', dz>LOG_ERROR)

should be (a ">" should be replaced with a ".")
dz.log('Unknown trigger. This should not be possible', dz.LOG_ERROR)
Guessing that you typed to fast!

This two scripts really allowed me to merge two Domoticz into one, many thanks!!
/lennart
Post Reply

Who is online

Users browsing this forum: No registered users and 0 guests