Jump to content
  • 0

[SOLVED]Turning off light not as simple


Question

I have a simple Lua script that after no motion (between 2 motion sensors) has been detected for 20 minutes then lights turn off. my script is not working properly the lights keep turning off after a few seconds of the last motion sensor becoming safe. Can someone see what I have done wrong in the script. Thanks!

 

--[[
%% autostart
%% properties
51 value
86 value
%% weather
%% events
%% globals
Day_night
--]]

local startSource = fibaro:getSourceTrigger();
if (
 ( fibaro:getGlobalValue("Day_night") == "Day")
    and  ( tonumber(fibaro:getValue(51, "value")) == 0  and  tonumber(fibaro:getValue(86, "value")) == 0 )
or
startSource["type"] == "other"
  )
then
  
  setTimeout(function()
        fibaro:call(76, "turnOff");
    fibaro:call(78, "turnOff");
    end, 1200)
 
end

Link to post
Share on other sites

Recommended Posts

  • 1
--[[
%% autostart
%% properties
%% events
%% globals
--]]

------------------------------------
------------ Settings --------------
------------------------------------

local sensors = {
    547,
    571
}

local powers = {
  	558
}

local luxs = {
  	549,
  	572 
}
local minLevel = 100;

local timeOut = 60 * 5

-- Only allow one instance of the current scene to run at a time
if (fibaro:countScenes() > 1) then
  fibaro:abort()
end

local function inArray(needle, haystack)
    for i,n in ipairs(haystack) do
        if (tonumber(needle)==tonumber(n)) then
            return true;
        end
    end
    return false;
end

local function getSensorStatus()
    for i,n in ipairs(sensors) do
        if (tonumber(fibaro:getValue(n, "value")) > 0) then
            return 1;
        end
    end
    return 0;
end

local function getLastBreach()
    local breach = 0;
    for i,n in ipairs(sensors) do
        local nBreach = tonumber(fibaro:getValue(n, "lastBreached"));
        if(nBreach > breach) then
            breach = nBreach;
        end
    end
    return breach;
end

local function getLightStatus()
    for i,n in ipairs(powers) do
        if (tonumber(fibaro:getValue(n, "value")) > 0) then
            return 1;
        end
    end
    return 0;
end

local function getLightLastStatus()
    local breach = 0;
    for i,n in ipairs(powers) do
        local state, nBreach = fibaro:get(n, "value")
        if(nBreach > breach) then
            breach = nBreach;
        end
    end
    return breach;
end

local function setLightStatus(command)
    for i,n in ipairs(powers) do
        if (tonumber(fibaro:getValue(n, "value"))~=tonumber(command)) then
            --if (debug) then fibaro:debug("Setting device "..n.." to "..command); end
            local type = fibaro:getType(n);
            if (type == "com.fibaro.multilevelSwitch") then
                fibaro:call(n, "setValue", command);
            elseif (command > 1) then
                fibaro:call(n, "turnOn");
            else
                fibaro:call(n, "turnOff");
            end
 
        end
    end
end

function checkLux()
	local totalLux   = 0;
  	local averigeLux = 0;
  	if #luxs > 0 then
		for i = 1, #luxs do
      		totalLux = totalLux + tonumber(fibaro:getValue(luxs[i], 'value'));
    	end
    	averigeLux = math.floor(totalLux / #luxs);
  	else
    	averigeLux = 50;
  	end
  	return averigeLux;
end

local function keepLightOn()
    local lastBreached = getLastBreach();
    local time = os.time();
    --fibaro:debug("Last breach:"..(time-lastBreached).."sec ago");
   
    if (getSensorStatus() == 1) then
        return true;
    end

    if ((time-getLightLastStatus()) >= timeOut) then
    else
    	return true;
    end
  
    if ((time-lastBreached)>= timeOut) then
        return false;
    end
   
    return true;
end

local status = 0;

fibaro:debug("Started...")

while true do
	-- if no light
  	if (getLightStatus() == 0) then
    
    	-- script mean = ON, but really = OFF
    	if (status == 1) then
      		fibaro:debug("LAMP WAS OFF MANUALLY: WAIT");
      		status = 0;
      		while (getSensorStatus() == 1) do
        		fibaro:sleep(1000);
        	end
      		fibaro:debug("LAMP WAS OFF MANUALLY: OK");
      	end
    
    	-- check exernal conditions here
    	-- can check lux or Day / Night mode / etc
    	if (1 == 1) then
          -- if check on motion      	
          if (getSensorStatus() == 1) then
                fibaro:debug("LAMP ON (BY MOTION)");
                setLightStatus(100);
                status = 1;
          end
      	else
      		-- ignore
      	end
    
	else
    	if (status == 0) then
      		fibaro:debug("LAMP WAS ON MANUALLY");
      		status = 1;
      	end
    
    	-- if light
    	if keepLightOn() then
        	-- nothing todo
      	else
        	-- turn off
        	fibaro:debug("LAMP OFF (NO MOTION)");
        	setLightStatus(0);
        	status = 0;
      	end
    end
  	
	fibaro:sleep(1000)
end

 

Link to post
Share on other sites
  • 0
Quote

setTimeout(function()
        fibaro:call(76, "turnOff");
    fibaro:call(78, "turnOff");
    end, 1200)

 

1200 is 1.2 seconds (=1200 milliseconds)

20 minutes = (20*60*1000)

Edited by RH_Dreambox
Link to post
Share on other sites
  • 0

Thanks thats seems to work better. 

 

The only issue I seem to be having is when the lights are on and I am moving around in the room (motion sensors in room to trigger lights) the lights will go off then will come back on after about 10 seconds. it only does it sometimes not every time. I think it is something to do with the motion sensors.

 

thoughts?

Link to post
Share on other sites
  • 0

Here is an example of how to do.
A timer is required to be reset on every new movement.
The light is lit, IF the global variable is = Night, AND if any of the two sensors feel motion.
For each new motion, the timer is restarted.

Also, note that the motion sensor may have a time lag affecting the total time.
In my case (Aeon multisensor) parameter 3, I have set to 1 minute which will be added to the total time.
Timer = 20 min + sensor 1 min = 21 min.
Hope this helps you.

--[[
%% autostart
%% properties
51 value
86 value
%% weather
%% events
%% globals
--]]

if (fibaro:countScenes()>1) then fibaro:abort() end -- Run only one scene

local light_1 = 76 -- ID Lamp 1
local light_2 = 78 -- ID lamp 2
local sensor_1 = 51 -- Mov. sensor 1
local sensor_2 = 86 -- Mov. sensor 2
local timer = 20 -- Timer in minutes

local counter = timer

if (
  (fibaro:getGlobalValue("Day_night") == "Night")
  and
  (tonumber(fibaro:getValue(sensor_1, "value")) > 0) or (tonumber(fibaro:getValue(sensor_2, "value")) > 0)
)
then
  fibaro:debug("Turn on lights")
  fibaro:call(light_1, "turnOn")
  fibaro:call(light_2, "turnOn")
  
  while counter > 0
  do
    counter = counter -1
    fibaro:sleep(60*1000)
    fibaro:debug("Counter = ".. counter)
    if
    tonumber(fibaro:getValue(sensor_1, "value")) > 0 or tonumber(fibaro:getValue(sensor_2, "value")) > 0
    then
      counter = timer
    end
  end
  
  fibaro:debug("Turn off lights")
  fibaro:call(light_1, "turnOff")
  fibaro:call(light_2, "turnOff")
end

 

Link to post
Share on other sites
  • 0

All,

 

I did simplify RH_Dreambox' code to use with 1 motion sensor and 1 switch:

 

--[[
%% autostart
%% properties
%% weather
%% events
%% globals
38 value
--]]

 

if (fibaro:countScenes()>1)
  then fibaro:abort()
end

 

local light = 166      -- ID Light switch
local sensor = 38      -- ID Motion sensor
local timer = 15       -- Time in minutes
local counter = timer

 

if tonumber(fibaro:getValue(sensor, "value")) > 0
  then
  fibaro:call(light, "turnOn")
  while counter > 0
  do
    counter = counter -1
    fibaro:sleep(60*1000)
    if tonumber(fibaro:getValue(sensor, "value")) > 0
      then
      counter = timer
    end
  end
  fibaro:call(light, "turnOff")
end

 

But every time when the counter will be lowered by 1 minute counter = counter -1, there is also a 1 minute sleep fibaro:sleep(60*1000).

During that sleep, no movements of the motion sensor are detected.

 

So the timer never will reset except when there is a move exactly after the 1 minute sleep while checking the condition of the motion sensor.

if tonumber(fibaro:getValue(sensor, "value")) > 0

 

Is there a smart way to solve this issue?

 

Thanks before hand.

 

 

Edited by Fitchie
Link to post
Share on other sites
  • 0

What make and model is your motion sensor? In the manual you should be able to find a parameter to increase the blind (or safe timeout) value to > 1 minute.

Link to post
Share on other sites
  • 0

Fibaro Motion Sensor FGMS-001.

 

Blind time: 2 seconds (parameter 2)

Motion cancellation time : 5 seconds (parameter 6)

 

I'm using the motion sensors also as alarm actors, so I'm not sure it's a good idea to increase the blind time.

Link to post
Share on other sites
  • 0

Please increase p6 to 70 or higher. Sensor still reports motion immediately and it will stay breached, until 70 sec without motion have passed. If it detects motion within 70 seconds, it stays breached and resets that internal timer. The scene checks every 60 seconds so it won't turn off the lights if you keep triggering the sensor, because the sensor reports motion for at least 70 seconds.

 

Does this help?

Link to post
Share on other sites
  • 0

Hi Peter,

 

That's a great idea, but when leaving the house and enabling the built in Fibaro alarm, I've to wait for 70 seconds before all breached motion detectors are safe to arm the system.

For that reason I did lower parameter 6 to a few seconds.

 

Another idea is to lower the timer in the script every second (in stead of every minute):

 

--[[
%% autostart
%% properties
199 value
%% weather
%% events
%% globals
--]]

 

if (fibaro:countScenes()>1)
  then fibaro:abort()
end

 

local light = 166        -- ID Light switch
local sensor = 199       -- ID Motion sensor
local timer = 600        -- Time in seconds
local counter = timer

 

if tonumber(fibaro:getValue(sensor, "value")) > 0
  then
  fibaro:call(light, "turnOn")
  while counter > 0
  do
    counter = counter -1
    fibaro:sleep(1000)
    if tonumber(fibaro:getValue(sensor, "value")) > 0
      then
      counter = timer
    end
  end
  fibaro:call(light, "turnOff")
end

 

This works as well, but will use some extra resources from the HC2.

 

Link to post
Share on other sites
  • 0

Absolutely. You will have to find a compromise then. Maybe 15-30 seconds. It will save some battery. I recommend to increase sleep to 5 seconds to lower resources...

Link to post
Share on other sites
  • 0

The code was originally written for fibaro: sleep in seconds.
But "amat" would have a very long delay (20 min) so I chose to have minutes instead of seconds.
Otherwise, there would have been a lot of debug rows as output :-)

 

Link to post
Share on other sites
  • 0
4 minutes ago, RH_Dreambox said:

The code was originally written for fibaro: sleep in seconds.
But "amat" would have a very long delay (20 min) so I chose to have minutes instead of seconds.
Otherwise, there would have been a lot of debug rows as output :-)

 

:D

 

Good point. It brings up an interesting issue: what are the optimal values for the sleep and the parameters of the sensors? I think no two HA solutions are equal, so I give only a recommendation.

Link to post
Share on other sites
  • 0
2 hours ago, Fitchie said:

Hi Peter,

 

That's a great idea, but when leaving the house and enabling the built in Fibaro alarm, I've to wait for 70 seconds before all breached motion detectors are safe to arm the system.

For that reason I did lower parameter 6 to a few seconds.

 

Another idea is to lower the timer in the script every second (in stead of every minute):

 

--[[
%% autostart
%% properties
199 value
%% weather
%% events
%% globals
--]]

 

if (fibaro:countScenes()>1)
  then fibaro:abort()
end

 

local light = 166        -- ID Light switch
local sensor = 199       -- ID Motion sensor
local timer = 600        -- Time in seconds
local counter = timer

 

if tonumber(fibaro:getValue(sensor, "value")) > 0
  then
  fibaro:call(light, "turnOn")
  while counter > 0
  do
    counter = counter -1
    fibaro:sleep(1000)
    if tonumber(fibaro:getValue(sensor, "value")) > 0
      then
      counter = timer
    end
  end
  fibaro:call(light, "turnOff")
end

 

This works as well, but will use some extra resources from the HC2.

 

Hi Fitchie,

 

How did you calculate the time in minutes or seconds in this program ? local timer = 600(seconds) or local timer = 20(minutes)? How the Timer variable will know the time in seconds or in minutes ? 

 

Thankyou  

Link to post
Share on other sites
  • 0

Hi Jibran,

 

You have 2 options:

 

- timer in seconds

local timer = 600        -- Time in seconds

fibaro:sleep(1000)

 

- timer in minutes

local timer = 10         -- Time in minutes

fibaro:sleep(60*1000)

 

Implementing the 'seconds timer' will take some more system resources from your HC, but then the motion sensor can also be used for alarming purposes.

Choosing the 'minutes timer' will induce less load on your HC, but as consequence you have to lower the 'blind time' of the motion sensor to >60 seconds.

 

 

Link to post
Share on other sites
  • 0

Thanks guys these suggestions have helped. I am still trying to learn Lua. In this code below I am trying to tell HC2 to only turn on the lights if I am present (Andy_Present = 1), if it is "Day", if the lux sensor is below 15 and motion is detected. The lights keep coming on everytime motion is detected no matter if it is day or night. No I do not have another scene controlling any of the lights. Can someone help? if you have any suggestions to shorten the code and put less strain on the system please let me know. Thanks in advance! 

 

--[[
%% autostart
%% properties
51 value
86 value
%% weather
%% events
%% globals
--]]


if (fibaro:countScenes()>1) then fibaro:abort() end -- Run only one scene

local light_1 = 76 -- ID Lamp 1
local light_2 = 78 -- ID lamp 2
local sensor_1 = 51 -- Mov. sensor 1
local sensor_2 = 86 -- Mov. sensor 2
local timer = 20 -- Timer in minutes

local counter = timer
  
if (
  (fibaro:getGlobalValue("TimeOfDay") == "Day") and
  (tonumber(fibaro:getValue(sensor_1, "value")) > 0) or (tonumber(fibaro:getValue(sensor_2, "value")) > 0)
    and
    tonumber(fibaro:getGlobalValue("Andy_Present")) == tonumber("1")
    )
then
  fibaro:debug("Turn on lights")
  fibaro:call(light_1, "setValue", "10")
  fibaro:call(light_2, "setValue", "10")
  
  while counter > 0
  do
    counter = counter -1
    fibaro:sleep(60*1000)
    fibaro:debug("Counter = ".. counter)
    if
    tonumber(fibaro:getValue(sensor_1, "value")) > 0 or tonumber(fibaro:getValue(sensor_2, "value")) > 0
    then
      counter = timer
    end
  end
  
  fibaro:debug("Turn off lights")
  fibaro:call(light_1, "turnOff")
  fibaro:call(light_2, "turnOff")
end

Link to post
Share on other sites
  • 0

Have some questions:

 

what does this do? Present variable?

 

local function inArray(needle, haystack)
    for i,n in ipairs(haystack) do
        if (tonumber(needle)==tonumber(n)) then
            return true;
        end
    end
    return false;
end

why are you getting the average of the Lux?

 

function checkLux()
	local totalLux   = 0;
  	local averigeLux = 0;
  	if #luxs > 0 then
		for i = 1, #luxs do
      		totalLux = totalLux + tonumber(fibaro:getValue(luxs[i], 'value'));
    	end
    	averigeLux = math.floor(totalLux / #luxs);
  	else
    	averigeLux = 50;
  	end
  	return averigeLux;
end

 

I need to tell the system to only do this if the Variable "TimeOfDay" = "Day". I did not see this in the code.

 

 

Link to post
Share on other sites
  • 0
local function inArray(needle, haystack)

yes check the variable in the array

 

5 hours ago, amatt said:

why are you getting the average of the Lux?

 

cuz I have 2 (two) sensor in the room and avg is best for me. use min / max if you want it.

 

5 hours ago, amatt said:

I need to tell the system to only do this if the Variable "TimeOfDay" = "Day". I did not see this in the code.

 

sorry, but if I provide all code what you wanted - you will never learn to develop code in LUA, my IMHO

 

On 9/20/2017 at 1:29 PM, 10der said:

-- check exernal conditions here

-- can check lux or Day / Night mode / etc

if (1 == 1) then

 

 

here is should be like a:

 

if  ( fibaro:getGlobalValue("Day_night") == "Day")

instead of

if (1 == 1)

Edited by 10der
Link to post
Share on other sites
  • 0

Thanks for everyone's input on this. it has been working well over the past few months. I just got some hue bulbs and looking to integrate these bulbs into this scene but having some difficulty doing so. Any assistance would be much appreciated.

Link to post
Share on other sites
  • 0
On 11/8/2017 at 4:25 AM, amatt said:

Thanks for everyone's input on this. it has been working well over the past few months. I just got some hue bulbs and looking to integrate these bulbs into this scene but having some difficulty doing so. Any assistance would be much appreciated.

 

Hi @amatt,

 

Check this:

 

Link to post
Share on other sites
  • 0

Everyone,

 

I have been running with the code for while now but am getting errors and the scene stops running about once a day now and constantly have to stop it then re-run it. 

 

I am not sure what the error means. can anyone help? *also I get API errors.

 

--[[
%% autostart
%% properties
%% globals
--]]

----------------------------------------------
-- MAIN SCENE FOR TIME BASED EVENTS CONTROL --
----------------------------------------------
-- Coded by Sankotronic © 2016
-- Version 1.1

--[[
This scene will take care of all time based events mostly by changing global
variables at specified time, but can also be used to call other scenes at
prefered time or pressing buttons on VDs! Before usage need to configure 
following global variables:
"HomeTable"       - predefined global variable table with device and scene 
                    IDs. Recommended to use since z-wave devices can change
                    their ID with re-inclusion and then is neccesary to edit
                    only scene which make this table and only device ID in 
                    scene headers. Much less time and effort is needed than 
                    without that option!
"Darkness"        - global variable, possible values: 0 - Day time, 
                    1 - Night time, value is set by this scene
"AlarmClockStatus" - predefined global variable with values: "On", "Off" - 
                    It determines if alarm clock is turned On or Off and 
                    value is changed by Alarm Clock VD coded by jompa68 see:
                    http://forum.fibaro.com/index.php?/topic/20053-acwut-alarmclock-wakeuptime-version-210/?p=77376
"PresentState"    - predefined global variable with values: "Home", "Away", 
                    "Holiday" - It determines our presence at home. Variable 
                    value is changed by three different scenes that are 
                    activated manually in my case "Leaving house", "Going on
                    Holidays" and "Returning home"
"SeasonState"     - predefined global variable with values: "Spring", "Summer", 
                    "Autumn", "Winter" - value is set by this scene
"WeekDay"         - predefined global variable with values: "Sunday", "Monday",
                    "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" 
                    - value set by this scene
"TimeOfDay"       - predefined global variable with values: "Morning", "Day",
                    "Evening", "Night" - value is set by this scene
"MarginSunrise"   - global variable with possible values from -30 to +30 Min
                    set by virtual device for Sunrise/Sunset - it determines
                    when will Sunrise make changes to the system and can be
                    set from -30 or half hour before real sunrise time to +30
                    or half hour later. 
"MarginSunset"    - global variable with possible values from -30 to +30 Min 
                    set by virtual device for Sunrise/Sunset - it determines 
                    when will Sunset make changes to the system and can be 
                    set from -30 or half hour before real sunset time to +30 
                    or half hour later.
"DemoMode"        - predefined global variable with values: "Yes", "No" - 
                    value changed by VD and if set to "Yes" then scene will 
                    no more change time based variables like Darkness, 
                    TimeOfDay, SeasonState so they can be changed by VD to 
                    make test of the system or just demostration
--]]

-- PART FOR USERS TO DEFINE GLOBALS AND STUFF with explanation --------------------
-- SETUP GLOBAL VARIABLES -- enter names and value mapping of your global variables
-- or leave as it is
-- "Darkness" is global variable with two possible states 0 - for day time and 1
-- for night time and it is changed at sunrise & sunset by main scene that is 
-- responsible for all time based events. See my other posts for details
local darkness        = "Darkness";
local darknessMapping = {Light="0", Dark="1"};
local presentState        = "PresentState";
local presentStateMapping = {Home="Home", Away="Away", Holiday="Holiday"};
-- predefined global variable that keeps current day of week.
local weekDay             = "WeekDay";
local weekDayMapping      = {Sunday="Nedjelja", Monday="Ponedjeljak", Tuesday="Utorak", Wednesday="Srijeda", Thursday="Četvrtak", Friday="Petak", Saturday="Subota"};
-- enter week days in your language and mapped in previous variable
local weekDayMap          = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
-- predefined global variable that keeps current season
local seasonState         = "SeasonState";
local seasonStateMapping  = {Spring="Spring", Summer="Summer", Fall="Fall", Winter="Winter"};
-- predefined global variable that keeps current time of day
local timeOfDay           = "TimeOfDay";
local timeOfDayMapping    = {Morning="Morning", Day="Day", Evening="Evening", Night="Night", Early="Early Morning"};
--global variables for months

-- global variables that keep values set by VDs
local marginSunrise       = "MarginSunrise";
local marginSunset        = "MarginSunset";
local marginNight         = "MarginNight"; -- difference for night time
local nightTime           = "NightTime";
local marginDay           = "MarginDay"; -- difference for day time
local dayTime             = "DayTime";
local monthstate           = "MonthState";

local deBug        = true;
local sumDebug     = true;
-- END OF CODE PART FOR USERS TO EDIT AND SETUP --------------------------

-- BELLOW CODE NO NEED TO MODIFY BY USER ---------------------------------
-- function to calculate time by adding or substracting hours and minutes
function calculateTime(time, DH, DM)
  local H  = tonumber(string.sub(time, 1, 2));
  local M  = tonumber(string.sub(time, 4, 5));
  M = M + DM
  if M >= 60 then
     M = M - 60
     H = H + 1
  elseif M < 0 then
    M = 60 + M
    H = H - 1
  end
  H = H + DH
  if string.len(H) < 2  then H = string.format("%s%s", '0', H) end 
  if string.len(M) < 2  then M = string.format("%s%s", '0', M) end 
  return string.format("%s:%s", H, M)
end

-- function to calculate time by adding hours and minutes
function calculateTimeString(time, duration)
  local H  = tonumber(string.sub(time, 1, 2));
  local M  = tonumber(string.sub(time, 4, 5));
  local DH = tonumber(string.sub(time, 1, 2));
  local DM = tonumber(string.sub(time, 4, 5));
  M = M + DM
  if M >= 60 then M = M - 60; H = H + 1
  elseif M < 0 then M = 60 + M; H = H - 1; end
  H = H + DH
  if H > 24 then H = H - 24 end
  if string.len(H) < 2  then H = string.format("%s%s", '0', H) end 
  if string.len(M) < 2  then M = string.format("%s%s", '0', M) end 
  return string.format("%s:%s", H, M)
end

while true do
  -- get actual time and set up some important variables
  local currenttime  = os.date('*t');
  local currentmonth = currenttime['month']
  local currentday   = currenttime['day']
  local currentwday  = currenttime['wday'];
  local currenthour  = currenttime['hour'];
  local currentmin   = currenttime['min'];
  local TimeCurrent  = os.date("%H:%M", os.time());
  local currentDate  = os.date('*t');
  local earlymorning = "05:00"
  local morning       = "07:00"
  local day             = "10:00"
  local evening         = "17:00"
  local night         = "22:30"
  local sunset       = fibaro:getValue(1, "sunsetHour");
  local sunrise      = fibaro:getValue(1, "sunriseHour");
  local months = {'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'};

 
  -- amount of minutes before/after sunrise value
  local marginRise   = tonumber(fibaro:getGlobalValue(marginSunrise));
  -- amount of minutes before/after sunset value
  local marginSet    = tonumber(fibaro:getGlobalValue(marginSunset));
    
  -- Calculate sunrise & sunset time in loop so that change of margin is used immediately
  sunrisetime        = calculateTime(sunrise, 0, marginRise)
  sunsettime         = calculateTime(sunset,  0, marginSet)
    
  if deBug then fibaro:debug("Sunrise time: ".. sunrisetime..", Sunset time: "..sunsettime) end;
  -- Calculate when to change state of TimeOfDay for Day and Night
  dayMargin          = fibaro:getGlobalValue(marginDay);
  daytime            = calculateTimeString(sunrisetime, dayMargin);
                       fibaro:setGlobal(dayTime, daytime);
  nightMargin        = fibaro:getGlobalValue(marginNight);
  nighttime          = calculateTimeString(sunsettime, nightMargin);
                       fibaro:setGlobal(nightTime, nighttime);
 
    
    -- check time of day and setup darkness and TimeOfDay global 
    -- that affects lights and blinds
    if TimeCurrent >= sunrisetime and TimeCurrent < daytime then
      if deBug then fibaro:debug("Its light outside") end
      fibaro:setGlobal(darkness, darknessMapping.Light)
      
    elseif TimeCurrent >= daytime and TimeCurrent < sunsettime then
      if deBug then fibaro:debug("Its light outside") end
      fibaro:setGlobal(darkness, darknessMapping.Light)
     
    elseif TimeCurrent >= sunsettime and TimeCurrent < nighttime then
      if deBug then fibaro:debug("Its dark outside") end
      fibaro:setGlobal(darkness, darknessMapping.Dark)
    else
      if deBug then fibaro:debug("Its Dark outside") end
      fibaro:setGlobal(darkness, darknessMapping.Dark)
    end

if TimeCurrent>=earlymorning and TimeCurrent < morning then
    if deBug then fibaro:debug("Between night and morning set TimeOfDay to Early Morning") end
fibaro:setGlobal(timeOfDay, timeOfDayMapping.Early);
elseif TimeCurrent>=morning and TimeCurrent < day then
if deBug then fibaro:debug("Between morning and day set TimeOfDay to Morning") end
fibaro:setGlobal(timeOfDay, timeOfDayMapping.Morning);
elseif TimeCurrent>=day and TimeCurrent < evening then
  if deBug then fibaro:debug("Between daytime and evening set TimeOfDay to Day") end
fibaro:setGlobal(timeOfDay, timeOfDayMapping.Day);
      elseif TimeCurrent>=evening and TimeCurrent < night then
  if deBug then fibaro:debug("Between evening and night set TimeOfDay to Evening") end
      fibaro:setGlobal(timeOfDay, timeOfDayMapping.Evening);
        else
        if deBug then fibaro:debug("Between nighttime and morning set TimeOfDay to Night") end
      fibaro:setGlobal(timeOfDay, timeOfDayMapping.Night);
    end
      
    fibaro:setGlobal(weekDay, weekDayMap[currentwday]);
  
  
    if deBug then fibaro:debug("Day of week is "..weekDayMap[currentwday]) end;
      
    -- Check time of year and set global for season time
    if (currentmonth >= 1 and currentmonth < 3) then
      if deBug then fibaro:debug("Month is January or february") end;
      fibaro:setGlobal(seasonState, seasonStateMapping.Winter);
    elseif currentmonth == 3 then
     if deBug then fibaro:debug("Month is March") end;
      if currentday < 21 then
        fibaro:setGlobal(seasonState, seasonStateMapping.Winter);
      else  
        fibaro:setGlobal(seasonState, seasonStateMapping.Spring);
      end  
    elseif ( currentmonth >3 and currentmonth < 6) then
      if deBug then fibaro:debug("Month is April or May") end;
      fibaro:setGlobal(seasonState, seasonStateMapping.Spring);
    elseif currentmonth == 6 then
      if deBug then fibaro:debug("Month is June") end;
      if currentday < 21 then
        fibaro:setGlobal(seasonState, seasonStateMapping.Spring);
      else
        fibaro:setGlobal(seasonState, seasonStateMapping.Summer);
      end
    elseif  ( currentmonth > 6 and currentmonth < 9) then  
      if deBug then fibaro:debug("Month is July or August") end;
      fibaro:setGlobal(seasonState, seasonStateMapping.Summer);
    elseif currentmonth == 9 then
      if deBug then fibaro:debug("Month is September") end;
      if currentday < 23 then
        fibaro:setGlobal(seasonState, seasonStateMapping.Summer);
      else
        fibaro:setGlobal(seasonState, seasonStateMapping.Fall);
      end
    elseif (currentmonth > 9 and currentmonth < 12) then  
      if deBug then fibaro:debug("Month is October or November") end;
      fibaro:setGlobal(seasonState, seasonStateMapping.Fall);
    elseif currentmonth == 12 then
      if deBug then fibaro:debug("Month is December") end;
      if currentday < 21 then
        fibaro:setGlobal(seasonState, seasonStateMapping.Fall);
      else
        fibaro:setGlobal(seasonState, seasonStateMapping.Winter);
      end
    else
      if deBug then fibaro:debug("Error setting season") end;
    end
    if deBug then fibaro:debug(" Season is "..fibaro:getGlobalValue(seasonState)) end;
 
  fibaro:setGlobal(monthstate, months[currentmonth]);
  
  end
  
  if sumDebug then fibaro:debug("Darkness: " .. fibaro:getGlobalValue(darkness) .. " Sunset: " .. sunset .. " (" .. sunsettime .. ") Sunrise: " .. sunrise .. " (" .. sunrisetime .. ") TimeOfDay: " .. fibaro:getGlobalValue(timeOfDay)) end
  -- Run loop every minute
  fibaro:sleep(59750);

Screen Shot 2018-09-06 at 7.53.54 PM.png

Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Answer this question...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...