Weather blind\sunscreen script 0.27

Moderator: leecollings

Post Reply
User avatar
remb0
Posts: 499
Joined: Thursday 11 July 2013 22:21
Target OS: Raspberry Pi / ODroid
Domoticz version: Beta
Location: The Netherlands
Contact:

Weather blind\sunscreen script 0.27

Post by remb0 »

together with MrFranky we build this script to control sunscreen of blinds.
the script is good enough but can always better :)

So if you have an idea, you see a bug of something else. let me know.

Code: Select all

--todo:
-- beter explanation
-- pushover integration
-- buienradar als crosscheck   (apart script wat de virtuele sensors op 0 tot 255 zet.
-- alert/debug   when nill values.
-- making loggin better readable
-- When in debug modus control the same only for a virtual sunscreen/blind
-- use the sombody @ home virtual switch
-- make coding more readable and maybe easier (with functions or something)
-- Questions or ideas?   contact : remco84  @   Gmail.com

--------------------------------------------------------------------------------
--      Variable
----------------------------------------------------------------------------------------------------------------
Version       = 0.027
Version_Type  = 'Beta'
   -- config ---------------------------------------------------------
TH_Wind       = uservariables["TH_Wind"] + 0		-- Treshold wind
TH_Gust       = uservariables["TH_Gust"] + 0   		-- Treshold windstoten
TH_Rain       = uservariables["TH_Rain"] + 0		-- Treshold regen/neerslag
TH_Uv_Close   = uservariables["TH_Uv_Close"] + 0 	-- 2.5 	-- treshold voor Uv close
TH_Uv_Open    = uservariables["TH_Uv_Open"] + 0		-- 1.5 	-- treshold voor Uv open   
TH_Tp_Close   = uservariables["TH_Tp_Close"] + 0	-- 20  	-- treshold voor Temperature close
TH_Tp_Open    = uservariables["TH_Tp_Open"] + 0		-- 19  	-- treshold voor Temperature close

ActionClose   = 'On'
ActionOpen    = 'Off'
UseVoice      = 'N'
ManualTime    = uservariables["Zonnescherm_ManualTime"]			-- 'D'  D=Daytime / A=All
Debugging     = uservariables["Zonnescherm_Debugging"]			-- 'Y'
Man_to_Auto   = uservariables["Man_to_Auto"] + 0				-- 240  Minutes manual override
SwitchTime    = uservariables["Zonnescherm_SwitchTime"] + 0		-- 10
LogAction     = uservariables["Zonnescherm_LogAction"]			-- 'Y' 	A=All, Y=Only on change
Notifications = uservariables["Zonnescherm_Notifications"]  	-- N-no Y= enabled

LogFile       = '/var/log/Sunscreen.log'
DeviceName    = 'Zonnescherm'
DeviceNameDebug    = 'ZonneschermDebug'
DeviceManual  = 'Zonnescherm - Manual'
IemandThuis = 'IemandThuis'
--TelegramName  = uservariables["TelegramName"]

-- Retrieve values from devices
Wu_Dev_Temp = otherdevices_svalues['WU Temperature']
Wu_Dev_Rain = otherdevices_svalues['WU Rain']
Wu_Dev_UvMe = otherdevices_svalues['WU UV']
Wu_Dev_UvMe = otherdevices_svalues['WU UV']
   -- config ------------------------
commandArray = {}
print ("______________________________________________________________________")
print (">> Sunscreen LUA Conditions.....v" .. Version .. "....." .. Version_Type)
if Debugging=='Y' then print("Zonnescherm_Debugging =   true") DeviceName = DeviceNameDebug else print("Debugging = false") end
if (otherdevices[DeviceName]) == 'Open' then print("Zonnescherm device: " .. DeviceName .. " is open") else print("Zonnescherm device: " .. DeviceName .. " is gesloten") end

-- Split values from devices
Part=1
for match in (Wu_Dev_Temp..';'):gmatch("(.-)"..';') do
   if Part==3 then Wu_Wind = tonumber(match) end
   if Part==4 then Wu_Gust = tonumber(match) end
   if Part==5 then Wu_Temp = tonumber(match) end
   Part=Part+1
end

Part=1
for match in (Wu_Dev_Rain..';'):gmatch("(.-)"..';') do
   if Part==2 then Wu_Rain = tonumber(match) end
   Part=Part+1
end

Part=1
for match in (Wu_Dev_UvMe ..';'):gmatch("(.-)"..';') do
   if Part==1 then Wu_Uv = tonumber(match) end
   Part=Part+1
end

if LogAction=='Y' or LogAction=='A' then
   f=io.open(LogFile,"a")
end
--
-- Calculate pre results
--
if (timeofday['Daytime'])   then Res_Dayl=1 else Res_Dayl=0 end
if Wu_Wind <= TH_Wind       then Res_Wind=1 else Res_Wind=0 end
if Wu_Gust <= TH_Gust       then Res_Gust=1 else Res_Gust=0 end
if Wu_Rain <= TH_Rain       then Res_Rain=1 else Res_Rain=0 end
if Wu_Uv   >= TH_Uv_Close   then Res_UvCl=1 else Res_UvCl=0 end
if Wu_Temp >= TH_Tp_Close   then Res_TpCl=1 else Res_TpCl=0 end
if Wu_Uv   <= TH_Uv_Open    then Res_UvOp=1 else Res_UvOp=0 end
if Wu_Temp <= TH_Tp_Open    then Res_TpOp=1 else Res_TpOp=0 end
--
-- Print decision info in the log
--
print ( "These conditions are valid when sunscreen is up: " )
if (timeofday['Daytime']) then 
   print (  Res_Dayl .. " - Daytime   : True" )
else
   print (  Res_Dayl .. " - Daytime   : False" )
end
print ( Res_Wind .. " - Wind        : " .. Wu_Wind .. " <= Th : " .. TH_Wind )
print ( Res_Gust .. " - Gust        : " .. Wu_Gust .. " <= Th : " .. TH_Gust )
print ( Res_Rain .. " - Rain        : " .. Wu_Rain .. " <= Th : " .. TH_Rain )
print ( Res_UvCl .. " - UV Close    : " .. Wu_Uv   .. " >= Th : " .. TH_Uv_Close )
print ( Res_TpCl .. " - Temp Close  : " .. Wu_Temp .. " >= Th : " .. TH_Tp_Close )
print ( "These conditions are valid when sunscreen is down: " )
print ( Res_UvOp .. " - UV Open     : " .. Wu_Uv   .. " <= Th : " .. TH_Uv_Open )
print ( Res_TpOp .. " - Temp Open   : " .. Wu_Temp .. " <= Th : " .. TH_Tp_Open )


-- Manual override for x minutes

if (otherdevices[DeviceManual]) == 'On' then
   now = os.date("*t") 
        T1  = os.time(now)

   Man_to_Auto = Man_to_Auto * 60
   s = otherdevices_lastupdate[DeviceManual]
        year = string.sub(s, 1, 4)
        month = string.sub(s, 6, 7)
        day = string.sub(s, 9, 10)
        hour = string.sub(s, 12, 13)
        minutes = string.sub(s, 15, 16)
        seconds = string.sub(s, 18, 19)
   
        T2 = os.time{year=year, month=month, day=day, hour=hour, min=minutes, sec=seconds}

   if os.difftime (T1,T2) > Man_to_Auto then
   commandArray[DeviceManual] = 'Off'   
        end

        if ManualTime~="D" and Res_Dayl==0 then
        --
        -- Outside daytime period, turn manual override off
        --
   commandArray[DeviceManual] = 'Off'   
        end
end

if (otherdevices[DeviceName]) == 'Open' then
   print ("Current state: Up / Open")
   if Res_Dayl + Res_Wind + Res_Gust + Res_Rain + Res_UvCl + Res_TpCl == 6 then
     if (otherdevices[DeviceManual]) == 'On' then
         print ("Sunscreen Manual Control")
     else
         t1 = os.time()
         s = otherdevices_lastupdate[DeviceName]
         year = string.sub(s, 1, 4)
         month = string.sub(s, 6, 7)
         day = string.sub(s, 9, 10)
         hour = string.sub(s, 12, 13)
         minutes = string.sub(s, 15, 16)
         seconds = string.sub(s, 18, 19)
         t2 = os.time{year=year, month=month, day=day, hour=hour, min=minutes, sec=seconds}
         difference = (os.difftime (t1, t2))
         if difference <= SwitchTime then
             print ("Recent open, wait for switchtime")
         else
             -- Close
             print ("Action: Naar beneden")
             commandArray[DeviceName] = ActionClose
 			 if UseVoice=='Y' then
				 os.execute('su pi ./home/pi/domoticz/scripts/sh/dspeak.sh "SunDown" ')
			 end
			 if LogAction=='Y' or LogAction=='A' then
				 f:write(os.date("%Y-%m-%d;%H:%M:%S") .. ";DOWN;" .. Version .. ";" .. Res_Dayl .. ";" .. Res_Wind .. ";" .. Res_Gust .. ";" .. Res_Rain .. ";" .. Res_UvCl .. ";" .. Res_TpCl .. ";" .. Res_UvOp .. ";" .. Res_TpOp .. ";" .. Wu_Wind .. ";" .. Wu_Gust .. ";" .. Wu_Rain .. ";" .. Wu_Uv .. ";" .. Wu_Temp)
                 f:write("\n")
             end
             if Notifications == 'N' then else
				commandArray['SendNotification']='Zonnescherm#Zonnescherm gaat uit (naar beneden)!#0#pushover'
             end
         end
     end
   else
      print ("Action: None")
   end
end

if (otherdevices[DeviceName]) == 'Closed' then
   print ("Current state: naar beneden")
   if Res_Dayl + Res_Wind + Res_Gust + Res_Rain < 4 or Res_UvOp==1 or Res_TpOp==1 then
		 if (otherdevices[DeviceManual]) == 'On' then
			 print ("Sunscreen Manual")
		 else
			 -- Open
			 print ("Action: Up / Open")
			 commandArray[DeviceName] = ActionOpen
			 if UseVoice=='Y' then
				 os.execute('su pi ./home/pi/domoticz/scripts/sh/dspeak.sh "SunUp" ')
			 end
			 if LogAction=='Y' or LogAction=='A' then
				 f:write(os.date("%Y-%m-%d;%H:%M:%S") .. ";OPEN;" .. Version .. ";" .. Res_Dayl .. ";" .. Res_Wind .. ";" .. Res_Gust .. ";" .. Res_Rain .. ";" .. Res_UvCl .. ";" .. Res_TpCl .. ";" .. Res_UvOp .. ";" .. Res_TpOp .. ";" .. Wu_Wind .. ";" .. Wu_Gust .. ";" .. Wu_Rain .. ";" .. Wu_Uv .. ";" .. Wu_Temp)
				 f:write("\n")
			 end
			 if Notifications == 'N' then else
				commandArray['SendNotification']='Zonnescherm#Zonnescherm gaat in (omhoog)!#0#pushover'
			 end
		 end
   else
      print ("  Action: None")
   end
end
if LogAction=='A' then
--	 DateTime ; State ; Version ; Res_Dayl ; Res_Wind ; Res_Gust ; Res_Rain ; Res_UvCl ; Res_TpCl ; Res_UvOp ; Res_TpOp ; Wu_Wind ; Wu_Gust ; Wu_Rain ; Wu_Uv ; Wu_Temp
     f:write(os.date("%Y-%m-%d;%H:%M:%S") .. ";IDLE;" .. Version .. ";" .. Res_Dayl .. ";" .. Res_Wind .. ";" .. Res_Gust .. ";" .. Res_Rain .. ";" .. Res_UvCl .. ";" .. Res_TpCl .. ";" .. Res_UvOp .. ";" .. Res_TpOp .. ";" .. Wu_Wind .. ";" .. Wu_Gust .. ";" .. Wu_Rain .. ";" .. Wu_Uv .. ";" .. Wu_Temp)
     f:write("\n")
	 f:close()
end
print ("______________________________________________________________________")
return commandArray
tlpeter
Posts: 191
Joined: Wednesday 26 November 2014 18:43
Target OS: Raspberry Pi / ODroid
Domoticz version: Beta
Location: Netherlands
Contact:

Re: Weather blind\sunscreen script 0.27

Post by tlpeter »

I will have a look tomorrow as i use a script myself controlling my sunscreen.
I use this script so you might get some idea's from that one.

Code: Select all


commandArray = {}

--Weatherstation data:
sWeatherTemp, sWeatherHumidity, sWeatherUV, sWeatherPressure, sWeatherUV2 = otherdevices_svalues['Barometer']:match("([^;]+);([^;]+);([^;]+);([^;]+);([^;]+)")
sWeatherTemp = tonumber(sWeatherTemp);
sWeatherHumidity = tonumber(sWeatherHumidity);
sWeatherPressure = tonumber(sWeatherPressure);
sWeatherUV = tonumber(sWeatherUV);
sWeatherUV2 = tonumber(sWeatherUV2);

print("______________________________________________________________________________________")
print("Weather station: Temperature is " .. sWeatherTemp .. " ");
print("Weather station: Humidity is " .. sWeatherHumidity .. " ");
print("Weather station: Pressure is " .. sWeatherPressure .. " ");
print("Weather station: UV is " .. sWeatherUV .. " ");
print("Weather station: UV2 is " .. sWeatherUV2 .. " ");
print("______________________________________________________________________________________")

------------------------------------------------------------------------

--Windmeter data:
sWindDirectionDegrees, sWindDirection, sWindSpeed, sWindGust, sWindTemperature, sWindFeel = otherdevices_svalues['Wind']:match("([^;]+);([^;]+);([^;]+);([^;]+);([^;]+);([^;]+)")

sWindDirectionDegrees = tonumber(sWindDirectionDegrees);
sWindDirection = (sWindDirection);
sWindSpeed = tonumber(sWindSpeed);
sWindGust = tonumber(sWindGust);
sWindTemperature = tonumber(sWindTemperature);
sWindFeel = tonumber(sWindFeel);

print("______________________________________________________________________________________")
print("Windmeter: Winddirection (in degrees) is: " .. sWindDirectionDegrees .. " ");
print("Windmeter: Winddirection is: " .. sWindDirection .. " ");
print("Windmeter: Windspeed is: " .. sWindSpeed .. " ");
print("Windmeter: Windgust is: " .. sWindGust .. " ");
print("Windmeter: Windtemperature is: " .. sWindTemperature .. " ");
print("Windmeter: Windfeel is: " .. sWindFeel .. " ");
print("______________________________________________________________________________________")

------------------------------------------------------------------------

--Rainmeter data:
sRainmeterCurrent, sRainmeterTotal = otherdevices_svalues['Regen']:match("([^;]+);([^;]+)")

sRainmeterCurrent = tonumber(sRainmeterCurrent);
sRainmeterTotal = tonumber(sRainmeterTotal);

print("______________________________________________________________________________________")
print("Rainmeter: Actual rain is: " .. sRainmeterCurrent .. " ");
print("Rainmeter: Total rain is: " .. sRainmeterTotal .. " ");
print("______________________________________________________________________________________")
------------------------------------------------------------------------

--UV data:
sSolar = otherdevices_svalues['Solar']:match("([^;]+)")

--sUV = tonumber(sUV);
sSolar = tonumber(sSolar);

--print("UV: UV Strength is: " .. sUV .." ");
print("UV: Solar radiation is: " .. sSolar .." ");

------------------------------------------------------------------------

--Sunscreen thresholds:
        -- Windspeed            = 100.0 (value is multiplied by 100)
        -- Rain                 =  0.0
        -- UV                   =  2.0
        -- Temperature          = 12.0
        -- Closed       = Down  = On
        -- Open         = Up    = Off

------------------------------------------------------------------------

if (timeofday['Daytime'])
        then
                print('It is past sunrise, monitoring variables for sunscreen')
        if (otherdevices['Zonnescherm'] == 'Open' )
        then
                print ('Sunscreen is up')
        else
                print ('Sunscreen is down')

end

if (otherdevices['Zonnescherm manual override']  == 'Off')
		then
				print('Manual override is turned off, follow the rest of the script')
		else
				print('Manual override is turned on, goto the end of the script and do nothing')
				goto done
end

if (otherdevices['Zonnescherm']   == 'Open'
		and sRainmeterCurrent   == 0
        and sWeatherTemp        > 12.0
		and sSolar				> 100
        and sWindSpeed          < 50
        and sWindGust           < 150)

then

        print ('Sun is shining, all thresholds OK, lowering sunscreen')
		print('______________________________________________________________________________________')
        commandArray['SendNotification']='Sunscreen#Sunscreen down --> Sun is shining'
        commandArray['Zonnescherm']='On'

				elseif (otherdevices['Zonnescherm'] == 'Closed' and sRainmeterCurrent > 0)
                then
                print ('It is raining, raising sunscreen')
				print('______________________________________________________________________________________')
                commandArray['SendNotification']='Sunscreen#Sunscreen up --> It is raining'
                commandArray['Zonnescherm']='Off'

        elseif (otherdevices['Zonnescherm'] == 'Closed' and sWeatherTemp <11.0 and otherdevices['Zonnescherm manual override'] == 'Off')
                then
                print ('Temperature too low, raising sunscreen')
				print('______________________________________________________________________________________')
                commandArray['SendNotification']='Sunscreen#Sunscreen up --> It is too cold'
                commandArray['Zonnescherm']='Off'

       elseif (otherdevices['Zonnescherm'] == 'Closed' and sSolar < 80 and otherdevices['Zonnescherm manual override'] == 'Off')
                then
                print ('Sun not shining too bright, raising sunscreen')
				print('______________________________________________________________________________________')
                commandArray['SendNotification']='Sunscreen#Sunscreen up --> Sunshine not too bright'
                commandArray['Zonnescherm']='Off'

        elseif (otherdevices['Zonnescherm'] == 'Closed' and sWindSpeed > 50)
                then
                print ('Windspeed too high, raising sunscreen')
				print('______________________________________________________________________________________')
                commandArray['SendNotification']='Sunscreen#Sunscreen up --> Windspeed too high'
                commandArray['Zonnescherm']='Off'

        elseif (otherdevices['Zonnescherm'] == 'Closed' and sWindGust > 150)
                then
                print ('Windgust too high, raising sunscreen')
				print('______________________________________________________________________________________')
                commandArray['SendNotification']='Sunscreen#Sunscreen up --> Windgust too high'
                commandArray['Zonnescherm']='Off'

else
        print('Sunscreen status OK --> No action')
		print('______________________________________________________________________________________')
end

::done::
		print("At the end of the script")
		print("______________________________________________________________________________________")
		
elseif (timeofday['Nighttime']
        and otherdevices['Zonnescherm'] == 'Closed')
        then
                print('It is night, raising sunscreen')
				print('______________________________________________________________________________________')
                commandArray['SendNotification']='Sunscreen#Sunscreen up --> It is night'
                commandArray['Zonnescherm']='Off'
        else
                print('Sunscreen already up --> No action')
		print('______________________________________________________________________________________')
end

return commandArray

tlpeter
Posts: 191
Joined: Wednesday 26 November 2014 18:43
Target OS: Raspberry Pi / ODroid
Domoticz version: Beta
Location: Netherlands
Contact:

Re: Weather blind\sunscreen script 0.27

Post by tlpeter »

I have had a better look and i see you can speakup but for me that is not needed.
I also see something with a log on a pi but i do not have a pi.
I also see an override but with time. i build a switch for that as i want to turn it on or off at all times if needed but i like the idea :D
It looks nice but i do not understand why you have all these variables in the script.
Can you explain that?
User avatar
remb0
Posts: 499
Joined: Thursday 11 July 2013 22:21
Target OS: Raspberry Pi / ODroid
Domoticz version: Beta
Location: The Netherlands
Contact:

Re: Weather blind\sunscreen script 0.27

Post by remb0 »

I user the variables from user variables in domoticz because it's easy to change from tablet, instead of ssh and opening script.
the reason i use that many variables is:

variables: log / debugging and notifications you will switch easyly: from testmode (to debug with as many info as possible) to production mode.

my manualtime variable will switch the manual overide so I can never forget to switch it of. Yo can go away, manual overide goes off and screen opens/close automatically.

other reason to put al that logica is that other users can use the script easyly and configure it to there needs. not everyone use voice or want notifications.
edwinth
Posts: 4
Joined: Monday 09 September 2013 15:47
Target OS: Raspberry Pi / ODroid
Domoticz version:
Location: Nijmegen
Contact:

Weather blind\sunscreen script 0.27

Post by edwinth »

Hello Remb0,

I like your script, testing it right now :-)

Last year I also made a script for controling our sunscreens. Not so sophisticated like this one but I made some scripts for predicting the weather conditions.

I made chance of rain(in %) with a python script(pop.py) and a script(pop.sh) to get the value and add it to domoticz using a temp virtual temp/hum sensor:

[pop.py]

Code: Select all

import requests0 as requests
r=requests.get('http://api.wunderground.com/api/<your_api_key>/hourly/lang:NL/pws:IGELDERL103/q/NL/Nijmegen.json')
chance_of_rain=r.json
print chance_of_rain['hourly_forecast'][0]['pop']
[pop.sh]

Code: Select all

#!/bin/bash

# Domoticz server
SERVER="<username>:<passwd>@<ip>:8080"

# Get Chance of rain
POP=`python /home/pi/scripts/pop.py`

# Sensor parameters
SVALUE=$POP

# Send data
curl -s -i -H "Accept: application/json" "http://$SERVER/json.htm?type=command&param=udevice&idx=242&nvalue=$SVALUE&svalue=$SVALUE"
with cron I run the script every 30 minutes and the humidity value of the virtual sensor can be used as trigger to open/close your blinds.
I'm not a good scripter so I'm sure this can be done easier!

I also did some testing with openweathermap data to get the weather ID
So if someone is interested I can post this script.

Code: Select all

weather: [
{
id: 800,
main: "Clear",
description: "onbewolkt",
icon: "02d"
}
],
Thanks,

Edwin
Last edited by edwinth on Tuesday 14 April 2015 8:40, edited 1 time in total.
User avatar
remb0
Posts: 499
Joined: Thursday 11 July 2013 22:21
Target OS: Raspberry Pi / ODroid
Domoticz version: Beta
Location: The Netherlands
Contact:

Re: Weather blind\sunscreen script 0.27

Post by remb0 »

in this forum there is also a script for rain prediction.
I use it right now and works very good. and a +; its lua so that's very easy.

I only use the UV sensor of weather undergroud. but that on is red very often. So I'm looking for an alternative.
can you post your openweather scripts In a little how to?
tlpeter
Posts: 191
Joined: Wednesday 26 November 2014 18:43
Target OS: Raspberry Pi / ODroid
Domoticz version: Beta
Location: Netherlands
Contact:

Re: Weather blind\sunscreen script 0.27

Post by tlpeter »

I use the solar part too which works fine.
edwinth
Posts: 4
Joined: Monday 09 September 2013 15:47
Target OS: Raspberry Pi / ODroid
Domoticz version:
Location: Nijmegen
Contact:

Re: Weather blind\sunscreen script 0.27

Post by edwinth »

Getting weather code from openweathermap (http://openweathermap.org/weather-conditions)

Change <value> with your own data

0) Get your free API key (http://openweathermap.org/register)

1) create virtual sensor
Hardware settings > Add Dummy
click on 'make virtual sensors'
create virtual sensor percentage

2) create script weercode.sh in /home/pi/scripts/

Code: Select all

#!/bin/bash

# Domoticz server
SERVER="<username>:<password>@<domoticz-ip>:8080"

# Get temperature
WC=`python /home/pi/scripts/weercode.py`

# Sensor parameters
SVALUE=$WC

# Send data
curl -s -i -H "Accept: application/json" "http://$SERVER/json.htm?type=command&param=udevice&idx=<virtual sensor ID>&nvalue=$SVALUE&svalue=$SVALUE"

3) create script weercode.py in /home/pi/scripts/

Code: Select all

import requests0 as requests
r=requests.get('http://api.openweathermap.org/data/2.5/weather?q=<city>,nl&lang=nl&units=metric&mode=json&API=<your_api_key>')
weatherid=r.json
print weatherid['weather'][0]['id']
4) make a cron job to run every x minutes (I did every 30 minutes, when you query to often your key will be disabled for the rest of the day)

5) in lua you can use the readings in percentage to trigger your script

Code: Select all

weercode = tonumber(otherdevices_svalues['Weercode'])
wolken = tonumber(otherdevices_svalues['Clouds_percentage'])
if ((weercode ==800 or weercode ==801 or weercode ==904) or (weercode ==802 and wolken <= 0.40)) then
6) In the above example I also used the cloudcover(wolken) from forecast.io, you can use this one also. Procedure is the same (https://developer.forecast.io/docs/v2)
cloudCover: A numerical value between 0 and 1 (inclusive) representing the percentage of sky occluded by clouds. A value of 0 corresponds to clear sky, 0.4 to scattered clouds, 0.75 to broken cloud cover, and 1 to completely overcast skies.

Code: Select all

import requests0 as requests
r=requests.get('https://api.forecast.io/forecast/<your_api_key>/<LATITUDE,LONGITUDE>')
clouds=r.json
print clouds['currently']['cloudCover']
edwinth
Posts: 4
Joined: Monday 09 September 2013 15:47
Target OS: Raspberry Pi / ODroid
Domoticz version:
Location: Nijmegen
Contact:

Re: Weather blind\sunscreen script 0.27

Post by edwinth »

Hello,

I need some help adding a trigger StartTime because the sun is only shining past 13:00 at the front of our house so closing before that time is not needed.

Made a uservariable 'Zonnescherm_StartTime' type 'Times'
In the script I have to add an extra line to check if the current time is past the time set in the variable.
I think something like "if current time > zonnescherm_StartTime then Res_Start=1 else Res_Start=0 end"
But I don't know how to do that so maybe someone can explain howto implement the time evaluation ?

Then in all the calculations add Res_Start and +1 for the total result to trigger the Switch.

Thanks in advance.

Edwin
Justintime
Posts: 228
Joined: Thursday 21 May 2015 9:08
Target OS: Raspberry Pi / ODroid
Domoticz version: Beta
Contact:

Re: Weather blind\sunscreen script 0.27

Post by Justintime »

Is this script ready? Because i am looking for a good Sunscreen script..... i am a noob in lua scripting.

Can someone provide a noob tutorial to get this script working? Like what do i have to change. And how to get this working with buienradar.
User avatar
Brutus
Posts: 249
Joined: Friday 26 September 2014 9:33
Target OS: Windows
Domoticz version:
Location: Netherlands
Contact:

Re: Weather blind\sunscreen script 0.27

Post by Brutus »

I also like to know that... LUA isn't the language I speak ;)

I have ordered screens but the Domotica for it is already installed hahaha.

So I am also looking for a good solution to automate my screens by weather and sunlight.

Not constantly up and down when there is one cloud.
1x Intel NUC8i5BEK (Windows 10 x64) Domoticz on Virtualbox with DietPi.
1x Aeon Labs USB Z-Stick S2
1x P1 Smart Meter USB
28x Fibaro Modules
SMA Solar System
Daikin Airco / Heating
Denon DHT-S716H & DSW-1H
franzelare
Posts: 141
Joined: Thursday 19 February 2015 21:48
Target OS: Raspberry Pi / ODroid
Domoticz version:
Contact:

Re: Weather blind\sunscreen script 0.27

Post by franzelare »

some ideas I added to my script:
- close the screen on a fixed time, in case you are not home (my case midnight)
- add a rain sensor, in addition to only a rain meter, the rain meter only starts with a fixed amount of rain, the sensor much earlier
- use the indoor temperature, to let the living heat up in spring
- check if the central heating is on, in case the requested temperature is higher than the actual, closing the screen will waste energy, since you block the heat from the sun but burn fosile fuel to heat the house.
User avatar
remb0
Posts: 499
Joined: Thursday 11 July 2013 22:21
Target OS: Raspberry Pi / ODroid
Domoticz version: Beta
Location: The Netherlands
Contact:

Re: Weather blind\sunscreen script 0.27

Post by remb0 »

I have a new version @ home.
with:
- indoor temp
- dropbox loggin upload
-loggin to excel
- much more...

but I use buienradar instead of a own meter because I don;t own rain meters..
donations are welcome :)

But if you have improvements because of new lua functionalities, of efficenter coding please let me know!

Code: Select all

-- Time Sunscreen
-- Check the (weather)conditions for controlling the Suncreen.
--
-- Release notes:
--  *104 12-07-2015 Using user variables instead of the normal variables
--  *105 15-07-2015 Open/Closed commando variabel, Start bash shell after change
--  *106 23-07-2015 Buienradar, Layout logfile, logfile name with ~d / ~m 
--------------------------------------------------------------------------------
-- Variable
--
Script		  = 'Time Sunscreen'						--
Version       = 106										--
VersionLog	  = 106										--
Version_Type  = 'Beta 01'								--
Man_or_Auto   = 'Auto'									-- Default

package.path = package.path .. ';' .. '/home/pi/domoticz/scripts/lua/?.lua'
My = require('MyFunc')
--------------------------------------------------------------------------------
-- Functions
--
function SendANotification()
	commandArray['SendNotification']='Sunscreen ' .. NewState .. '#Sunscreen ' .. DeviceName .. ' was in state ' .. CurState .. ' new state is ' .. NewState .. ', reason for change is ' .. My.EnumClear(Reason) .. ' / '.. os.date("%Y-%m-%d;%H:%M:%S").. '#0#pushover'
end

function LogActions()
	LogFile=string.gsub(LogFile,"~d",os.date("%Y-%m-%d"))
	LogFile=string.gsub(LogFile,"~m",os.date("%Y-%m"))
	
	if not My.File_exists(LogFile) then
	 f=io.open(LogFile,"a")
	 f:write("Datum ; Tijd ; DeviceName ; Man_or_Auto ; Current State ; New state ;  Reason up ; Version #".. VersionLog .."# ; Version Type ; " ..
	         "Result_Daytime ; Result_Hour ; Result_Wind ; Result_Gust ; Result_Wu_Rain ; Result_Br_Rain ; Result_UvClose ; Result_Temperature_Close ; Result_UvOp ; Result_TemperatureOp ; Result ; "..
			 "Nu_Hour <".. TH_Hour .." ; Wu_Wind <=".. TH_Wind .. "; Wu_Gust <=".. TH_Gust .. "; Wu_Rain <=".. TH_Wu_Rain .. "; Br_Rain <=".. TH_Br_Rain .. " ; Wu_Uv <=".. TH_Uv_Close .. "/" .. TH_Uv_Open .. "; Wu_Temperature <=".. TH_Tp_Close .. "/".. TH_Tp_Open .. "; "..
			 "Uv Sim ; SwManStart ; SwManEnd ; Switch manual ; SwManDif ; Notifications ; LogAction ; SwitchTime ; SwitchDiff ; " .. 
			 LogCap01 .. ";" .. LogCap02 .. ";" .. LogCap03)
     f:write("\r\n")
	 else
	 f=io.open(LogFile,"r")
	 c=f:read("*line")
	 if string.match(c, "#" ..VersionLog .. "#") then
	 else
		print(".  Version of logfile ".. LogFile .." is not correct.")
	 end
	 f:close()
	 f=io.open(LogFile,"a")
   end
    f:write(os.date("%Y-%m-%d;%H:%M:%S") .. ";" .. DeviceName .. ";" .. Man_or_Auto .. ";" .. CurState .. ";" .. NewState .. ";" .. My.EnumClear(Reason) ..  ";" .. Version .. ";" .. Version_Type .. ";" .. 
	          Res_Dayl .. ";" .. Res_Hour .. ";" .. Res_Wind .. ";" .. Res_Gust .. ";" .. Res_WuRain .. ";" .. Res_BrRain .. ";" .. Res_UvCl .. ";" .. Res_TpCl .. ";" .. Res_UvOp .. ";" .. Res_TpOp .. ";".. Result .. ";" .. 
			  Nu_Hour .. ";" .. Wu_Wind .. ";" .. Wu_Gust .. ";" .. Wu_Rain .. ";" .. Br_Rain .. ";".. Wu_Uv .. ";" .. Wu_Temp .. ";" .. 
			  Uv_Sim .. ";"  .. SwManStart .. ";" .. SwManEnd .. ";" .. Man_to_Auto .. ";" .. SwManDif .. ";" .. Notifications .. ";" .. LogAction .. ";" .. SwitchTime .. ";" .. SwitchDiff .. ";" .. 
			  LogAdd01 .. ";" .. LogAdd02 .. ";" .. LogAdd03)
    f:write("\r\n")
    f:close()
end
--------------------------------------------------------------------------------

commandArray = {}
print ("______________________________________________________________________")
print (">> ".. Script .. ".......v" .. Version .. "....." .. Version_Type)

-- User variables
--
UserVarErr     = 0
RunFast        = My.GetUserVar("SUN_RunFast") 		  	-- 5
RunSlow        = My.GetUserVar("SUN_RunSlow") 		  	-- 5
RunLast        = My.GetUserVar("SUN_RunLast")        	-- 2015-07-29 18:30:00

if (timeofday['Daytime']) then RunEveryxMin=RunFast else RunEveryxMin=RunSlow end
TDiff = My.Round(My.TimeDiff(os.time(),RunLast)/60,0)
if TDiff < RunEveryxMin then 
	print (".  Wait : ".. TDiff .. " / " .. RunEveryxMin)
	goto done
end
nu=tostring(os.date ("%Y-%m-%d %H:%M:%S"))
commandArray['Variable:SUN_RunLast'] = nu
print (".  ")
DeviceLuaMstr  = My.GetUserVar("LUA_MasterSW")		    -- LUA_MasterSW
lat			   = My.GetUserVar("Gen_Latitude") + 0 		-- 
lon			   = My.GetUserVar("Gen_Longitude") + 0		--
LogFile        = My.GetUserVar("SUN_LogFile")			-- /home/pi/log/Sunscreen.csv
DeviceName     = My.GetUserVar("SUN_DeviceName")		-- Sunscreen
DeviceManual   = My.GetUserVar("SUN_DeviceManual")		-- Sunscreen - Manual
DeviceAtHome   = My.GetUserVar("SUN_DeviceAtHome")		-- Not in use
DeviceTemp	   = My.GetUserVar("SUN_DeviceTemp")		-- 45.00;NE;0;0;23.1;23.1	In most cases this is the wind device. Temperature is on position 5
DeviceRain     = My.GetUserVar("SUN_DeviceRain")		-- 0;0.0					Weather undergMy.Round Rain device
DeviceUvme     = My.GetUserVar("SUN_DeviceUvme")		-- 0.0;0.0					Weather undergMy.Round Uv device
DeviceBuien    = My.GetUserVar("SUN_DeviceBuien")		-- 2						Buienradar (under construction) 
DeviceAddVal01 = My.GetUserVar("SUN_AddValue01")		-- Temp_Livingroom
DeviceAddVal02 = My.GetUserVar("SUN_AddValue02")		-- Temp_Bedroom
DeviceAddVal03 = My.GetUserVar("SUN_AddValue03")		-- x
InstVersion    = My.GetUserVar("SUN_InstVersion")   	-- 104
ActionClose    = My.GetUserVar("SUN_ActionClose")		-- On
ActionOpen     = My.GetUserVar("SUN_ActionOpen")		-- Off
ShAfterAction  = My.GetUserVar("SUN_ShAfterAction")		-- sudo /home/pi/domoticz/scripts/bash/log-dropbox.sh
TH_Wind        = My.GetUserVar("SUN_TH_Wind") + 0		-- Treshold wind
TH_Gust        = My.GetUserVar("SUN_TH_Gust") + 0   	-- Treshold windstoten
TH_Wu_Rain        = My.GetUserVar("SUN_TH_Wu_Rain") + 0	-- Treshold regen/neerslag
TH_Br_Rain     = My.GetUserVar("SUN_TH_Br_Rain") + 0	-- Treshold regen/neerslag
TH_Uv_Close    = My.GetUserVar("SUN_TH_Uv_Close") + 0 	-- 2.5 	-- treshold voor Uv close
TH_Uv_Open     = My.GetUserVar("SUN_TH_Uv_Open") + 0	-- 1.5 	-- treshold voor Uv open   
TH_Tp_Close    = My.GetUserVar("SUN_TH_Tp_Close") + 0	-- 20  	-- treshold voor Temperature close
TH_Tp_Open     = My.GetUserVar("SUN_TH_Tp_Open") + 0	-- 19  	-- treshold voor Temperature close
TH_Hour        = My.GetUserVar("SUN_TH_Hour") + 0		-- Treshold hour
ManualTime     = My.GetUserVar("SUN_ManualTime")		-- 'D'  D=Daytime / A=All
Debugging      = My.GetUserVar("SUN_Debugging")			-- 'Y'
Man_to_Auto    = My.GetUserVar("SUN_Man_to_Auto") + 0	-- 240  Minutes manual override
SwitchTime     = My.GetUserVar("SUN_SwitchTime") + 0	-- 10
LogAction      = My.GetUserVar("SUN_LogAction")			-- 'Y' 	A=All, Y=Only on change
Notifications  = My.GetUserVar("SUN_Notifications")		-- 'Y'  Y=Yes, N=No

if UserVarErr> 0 then
	print (".  Please check user variables.")
	print (".  ")
end
InstV=tonumber(InstVersion)
if InstV==nil then InstV=100 end
if InstV < Version then
	print (".  ")
	print (".  Registered version : " .. InstV .. " , running version : " .. Version )
	print (".  Not able to update automatically.")
	print (".  ")
	-- commandArray['Variable:SUN_InstVersion']= tostring(Version)
	goto done
end
if UserVarErr> 0 then goto done end

if (otherdevices[DeviceLuaMstr]) == 'Off' then
	print (".  LUA Master switch is off")
	goto done
end

-- Variable
-- 
if (string.len(DeviceAddVal01)) > 1 then
	LogCap01	  = DeviceAddVal01					--
	LogAdd01      = My.GetValue(otherdevices_svalues[DeviceAddVal01],1)
else
	LogCap01	  = "nvt"					--
	LogAdd01      = 0
end
if (string.len(DeviceAddVal02)) > 1 then
	LogCap02	  = DeviceAddVal02						--
	LogAdd02      = My.GetValue(otherdevices_svalues[DeviceAddVal02],1)
else
	LogCap02	  = "nvt"					--
	LogAdd02      = 0
end
if (string.len(DeviceAddVal03)) > 1 then
	LogCap03	  = DeviceAddVal03								--
	LogAdd03      = My.GetValue(otherdevices_svalues[DeviceAddVal03],1)				
else
	LogCap03	  = "nvt"					--
	LogAdd03      = 0
end


--
-- Retrieve values from weather devices
--
Wu_Dev_Temp = otherdevices_svalues[DeviceTemp]
Wu_Dev_Rain = otherdevices_svalues[DeviceRain]
Wu_Dev_UvMe = otherdevices_svalues[DeviceUvme]
Br_Dev_Rain = otherdevices_svalues[DeviceBuien]
--
-- Split values from devices
--
Wu_Wind = My.GetValue(Wu_Dev_Temp,3)
Wu_Gust = My.GetValue(Wu_Dev_Temp,4)
Wu_Temp = My.GetValue(Wu_Dev_Temp,5)
Wu_Rain = My.GetValue(Wu_Dev_Rain,2)
Wu_Uv = My.GetValue(Wu_Dev_UvMe,1) 

Nu_Hour=tonumber(os.date('%H',time))
Reason="" 
Reascl="" 
Reasop="" 
Uv_Wim=""
--
-- Special correction for hot days
--
Uv_Sim=""
if Wu_Uv < TH_Uv_Close and Wu_Temp >= 20 and Nu_Hour >= 7 and Nu_Hour <= 9 then 
	Wu_Uv = TH_Uv_Close 
	Uv_Sim = "01 Hot day rule" 
end
if Wu_Uv < TH_Uv_Close and Wu_Uv >= 0.1 and  Wu_Temp >= 20 and Nu_Hour >= 9 and Nu_Hour <= 11 then 
	Wu_Uv = TH_Uv_Close 
	Uv_Sim = "02 Hot day rule"
end
--
-- Calculate pre results
-- Redenen om niet naar beneden te gaan
RainPrediction = My.Round(My.IsItGonnaRain(15, lat, lon),1)
-- Br_Rain=My.Round(10^((RainPrediction-109)/32),1)
Br_Rain = RainPrediction

if (timeofday['Daytime'])   then Res_Dayl=1   else Res_Dayl=0 Reason=Reason .. "Sunrise ," end
if Nu_Hour < TH_Hour        then Res_Hour=1   else Res_Hour=0 Reason=Reason .. "Hour " .. Nu_Hour .. " ," end
if Wu_Wind <= TH_Wind       then Res_Wind=1   else Res_Wind=0 Reason=Reason .. "Wu Wind " .. Wu_Wind .. " ," end
if Wu_Gust <= TH_Gust       then Res_Gust=1   else Res_Gust=0 Reason=Reason .. "Wu Gust " .. Wu_Gust .. " ," end
if Wu_Rain <= TH_Wu_Rain    then Res_WuRain=1 else Res_WuRain=0 Reason=Reason .. "Wu Rain " .. Wu_Rain .. " ," end
if Br_Rain <= TH_Br_Rain    then Res_BrRain=1 else Res_BrRain=0 Reason=Reason .. "Br Rain " .. Br_Rain .. " ," end
-- Redenen om niet naar beneden te gaan
if Wu_Uv   >= TH_Uv_Close   then Res_UvCl=1   else Res_UvCl=0 Reascl=Reascl .. "Wu Uv Closed " .. Wu_Uv .. " ," end
if Wu_Temp >= TH_Tp_Close   then Res_TpCl=1   else Res_TpCl=0 Reascl=Reascl .. "Wu Temp Closed " .. Wu_Temp .. " ," end
-- Redenen om niet naar beneden te blijven (dus scherm omhoog)
if Wu_Uv   >= TH_Uv_Open    then Res_UvOp=1   else Res_UvOp=0 Reasop=Reasop .. "Wu Uv Open " .. Wu_Uv .. " ," end
if Wu_Temp >= TH_Tp_Open    then Res_TpOp=1   else Res_TpOp=0 Reasop=Reasop .. "Wu Temp Open " .. Wu_Temp .. " ," end
--
-- Print decision info in the log
--
if (otherdevices[DeviceName]) == 'Open' then
	print ( ".  These conditions are valid when sunscreen is Up / Open: " )
else
	print ( ".  These conditions are valid when sunscreen is Down / Closed: " )
end
if (timeofday['Daytime']) then 
	print ( ".  " .. Res_Dayl .. " - Daytime   : True" )
else
	print ( ".  " .. Res_Dayl .. " - Daytime   : False" )
end
	print ( ".  " .. Res_Hour ..   " - Wu Hour  : " .. Nu_Hour .. " <= Th : " .. TH_Hour )
	print ( ".  " .. Res_Wind ..   " - Wu Wind  : " .. Wu_Wind .. " <= Th : " .. TH_Wind )
	print ( ".  " .. Res_Gust ..   " - Wu Gust  : " .. Wu_Gust .. " <= Th : " .. TH_Gust )
	print ( ".  " .. Res_WuRain .. " - Wu Rain  : " .. Wu_Rain .. " <= Th : " .. TH_Wu_Rain )
	print ( ".  " .. Res_BrRain .. " - Br Rain  : " .. Br_Rain .. " <= Th : " .. TH_Br_Rain )
if (otherdevices[DeviceName]) == 'Open' then
	print ( ".  " .. Res_UvCl ..   " - Wu Uv-i  : " .. Wu_Uv   .. " >= Th : " .. TH_Uv_Close .. " (Up / Open)")
	print ( ".  " .. Res_TpCl ..   " - Wu Temp  : " .. Wu_Temp .. " >= Th : " .. TH_Tp_Close .. " (Up / Open)")
	Reason=Reason .. Reascl
	Result = Res_Dayl + Res_Hour + Res_Wind + Res_Gust + Res_WuRain + Res_UvCl + Res_TpCl + Res_BrRain
else
	print ( ".  " .. Res_UvOp ..   " - Wu Uv-i  : " .. Wu_Uv   .. " >= Th : " .. TH_Uv_Open .. " (Down / Closed)")
	print ( ".  " .. Res_TpOp ..   " - Wu Temp  : " .. Wu_Temp .. " >= Th : " .. TH_Tp_Open .. " (Down / Closed)")
	Reason=Reason .. Reasop
	Result = Res_Dayl + Res_Hour + Res_Wind + Res_Gust + Res_WuRain + Res_UvOp + Res_TpOp + Res_BrRain
end
	print ( ".  " .. Result .. " / 8 score.")
if (Wu_Rain<1 and Br_Rain>1) or (Br_Rain<1 and Wu_Rain>1) then 
	print ( ".  Difference between WU and Buienradar result.  WU : " .. Res_WuRain .. " Buienradar : " .. Res_BrRain)
end
	
--
-- Manual override for x minutes
--
SwManStart = otherdevices[DeviceManual]
TDiff = My.Round(My.TimeDiff(os.time(),otherdevices_lastupdate[DeviceManual])/60,0)
if (otherdevices[DeviceManual]) == 'On' then
	print (".  Last change manual state : " .. TDiff .. " minutes ago.")
	if TDiff >= Man_to_Auto then
		-- To long in manual mode, switch to auto
		print(".  Turn Manual switch off")
		commandArray[DeviceManual] = 'Off'   
	end

	if ManualTime~="D" and Res_Dayl==0 then
		-- Outside daytime period, turn manual override off
		print(".  Turn Manual switch off, outside daytime")
		commandArray[DeviceManual] = 'Off'   
	end
end

SwitchDiff = My.Round(My.TimeDiff(os.time(),otherdevices_lastupdate[DeviceName])/60,0)
-- print (".  Last change screen state : " .. SwitchDiff .. " minutes ago.")		
SwManEnd = otherdevices[DeviceManual]
SwManDif = TDiff

--
-- Current state Up / Open			Change to  		Down / Closed	?
--
if (otherdevices[DeviceName]) == 'Open' then
	CurState="Up / Open"
	if Res_Dayl + Res_Hour + Res_Wind + Res_Gust + Res_WuRain + Res_UvCl + Res_TpCl + Res_BrRain == 8 then
		if (otherdevices[DeviceManual]) == 'On' then
			print (".  Sunscreen Manual")
			Man_or_Auto = 'Manual'
			Reason=Reason .. " (Manual) , "
		else
			if SwitchDiff <= SwitchTime then
				print (".  Recent open, wait for switchtime")
				Reason=Reason .. "Recent open , "
			else
				-- Closed
				NewState = "Down / Closed"
				print (".  Action: Change to state : " .. NewState)
				commandArray[DeviceName] = ActionClose
				if Reason == "" then Reason = "No reason ," end
				if Notifications == 'Y' then SendANotification() end
				if LogAction == 'Y' or LogAction == 'A' then LogActions() end
				if (string.len(ShAfterAction)) > 1 then os.execute(ShAfterAction) end
			end
		end
	else
		if (otherdevices[DeviceManual]) == 'On' then
			print (".  Sunscreen Manual")
			Man_or_Auto = 'Manual'
			Reason=Reason .. " (Manual) , "
		end
		print (".  Action: None, Reason to stay in state Up / Open :")
	end
end


--
-- Current state Down / Closed		Change to 		Up / Open		?
--
if (otherdevices[DeviceName]) == 'Closed' or (otherdevices[DeviceName]) == 'Stopped' then
	if (otherdevices[DeviceName]) == 'Closed' then CurState = "Down / Closed" else CurState="Stopped" end
	if Res_Dayl + Res_Hour + Res_Wind + Res_Gust + Res_WuRain + Res_UvOp + Res_TpOp + Res_BrRain < 8 then
		if (otherdevices[DeviceManual]) == 'On' then
			print (".  Sunscreen Manual")
			Man_or_Auto = 'Manual'
			Reason=Reason .. "Manual , "
		else
				-- Open
				NewState = "Up / Open"
				print (".  Action: Change to state : " .. NewState)
				commandArray[DeviceName] = ActionOpen
				if Reason == "" then Reason = "No reason ," end
				if Notifications == 'Y' then SendANotification() end
				if LogAction == 'Y' or LogAction == 'A' then LogActions() end
				if (string.len(ShAfterAction)) > 1 then os.execute(ShAfterAction) end
		end
	else
		print (".  Action: None (Down / Closed)")
		end
end

NewState = "Idle"
if Reason == "" then Reason = "No reason ," end
print ( ".  Reason: " .. My.EnumClear(Reason))
if LogAction=='A' then LogActions() end
::done::
print ("______________________________________________________________________")
return commandArray
franzelare
Posts: 141
Joined: Thursday 19 February 2015 21:48
Target OS: Raspberry Pi / ODroid
Domoticz version:
Contact:

Re: Weather blind\sunscreen script 0.27

Post by franzelare »

this is what I currently run, I log only changes to a text file to keep it readable...
need to move that to a sub routine to make the code more readable

I also added a possiblity to close the screen at sunset of at a fixed time

Code: Select all

commandArray = {}

PRINT_MODE = true                   -- when true print all used values
SCREEN_NAME = 'Zonwering'           -- name sunscreen

-- declare some constants
-- adjust to your specific situation
TH_GUST = 60               -- gust limit that will close screen
TH_WIND = 40               -- windspeed that will close the screen
TH_Rain       = 0.1           -- Treshold regen/neerslag
TH_Uv_Close   = 1.9          -- treshold voor Uv close
TH_Uv_Open    = 0.9          -- treshold voor Uv open   
TH_Tp_Close   = 24          -- treshold voor outside Temperature to close
TH_Tp_Open    = 12          -- treshold voor outside Temperature to open
TH_Tp_Binnen_Close  = 20          -- treshold voor inside Temperature to close
TH_Tp_Binnen_Open  = 17          -- treshold voor inside Temperature to open
SwitchTime    = 5          -- timer between open/close actoin
RainTime      = 10           -- timer after rainfall where the screen is not allowed to open
ManualTime    = 60           -- timer after manual operation where the screen will not be controlled automatically (also to be set in zonwering device script)

-- screen closing trigger for the evening
TH_Close = NightTime        -- "NightTime" or "CloseTime" will select if the screen closes at a set time of after sunset
-- ifscreen should be closed at a fixed time
CloseTimeHour     = 23		-- time when sunscreen should be closed (hour)
CloseTimeMinute   = 59		-- time when sunscreen should be closed (minute)

-- declare sensor names
SENSOR_WIND_NAME = 'Wind'     -- exact device name of the wind sensor
SENSOR_UV_NAME = 'UV'     -- exact device name of the UV sensor
SENSOR_RAIN_NAME = 'Regen'     -- exact device name of the rain meter
SENSOR_RAINON_NAME = 'Regent'     -- exact device name of the rain sensor
SENSOR_TEMP_NAME = 'Buiten'     -- exact device name of the outdoor temperature sensor
SENSOR_TEMPBINNEN_NAME = 'Woonkamer'  -- exact device name of the indoor temperature sensor
SETPOINT_TEMPBINNEN_NAME = 'WoonkamerSetpoint'  -- exact device name of the indoor temperature setpoint


-- get the global variables:
TempTriggerClose = tonumber(uservariables['TempTrigger']) --status if high temperature limit was exceeded before
TempTriggerBinnenClose = tonumber(uservariables['TempTriggerBinnen']) --status if high temperature limit was exceeded before
UVTriggerClose = tonumber(uservariables['UVTrigger']) --status if high UV limit was exceeded before
WindGust = tonumber(uservariables['WindGust']) --get old windgust value
WindSpeed = tonumber(uservariables['WindSpeed']) --get old windspeed value
RainTmin1 = tonumber(uservariables['RainTmin1']) --get old rain value
RainTimer = tonumber(uservariables['RainTimer']) --get rain timer
ManualTimer = tonumber(uservariables['ManualTimer']) --get manual timer

-- Retrieve values from devices
Wu_Dev_Wind = otherdevices_svalues[SENSOR_WIND_NAME]
Wu_Dev_Rain = otherdevices_svalues[SENSOR_RAIN_NAME]
Wu_Dev_UV = otherdevices_svalues[SENSOR_UV_NAME]
Wu_Dev_Temp = otherdevices_svalues[SENSOR_TEMP_NAME]
Wu_Dev_TempBinnen = otherdevices_svalues[SENSOR_TEMPBINNEN_NAME]
Wu_Dev_SetpBinnen = otherdevices_svalues[SETPOINT_TEMPBINNEN_NAME]

-- check for manual mode
if PRINT_MODE == true then
	print ('ManualTimer: ' .. ManualTimer)
end
if (ManualTimer == 1) then
	commandArray['ZonweringManual'] = 'Off'
	ManualTimer = 0
    if PRINT_MODE == true then
	    print ('Switching off Zonweringmanual switch')
    end
end
if (ManualTimer >= 1) then
	ManualTimer = ManualTimer - 1
    if PRINT_MODE == true then
	    print ('Deducting 1 from Zonwering manual timer to :' .. ManualTimer)
    end
end

-- break up wind meter in separate values
Part=1
for match in (Wu_Dev_Wind..';'):gmatch("(.-)"..';') do
   if Part==3 then Wu_WindSpeed = tonumber(match) end
   if Part==4 then Wu_WindGust = tonumber(match) end
   Part=Part+1
end

-- break up rain meter in separate values
Part=1
for match in (Wu_Dev_Rain..';'):gmatch("(.-)"..';') do
   if Part==2 then Wu_Rain = tonumber(match) end
   Part=Part+1
end

-- break up UV meter in separate values
Part=1
for match in (Wu_Dev_UV ..';'):gmatch("(.-)"..';') do
   if Part==1 then Wu_UV = tonumber(match) end
   Part=Part+1
end

-- break up temperature meter in separate values
Part=1
for match in (Wu_Dev_Temp ..';'):gmatch("(.-)"..';') do
   if Part==1 then Wu_Temp = tonumber(match) end
   Part=Part+1
end

-- convert temperature livingroom into numbers
Wu_TempBinnen = tonumber(Wu_Dev_TempBinnen)

-- convert temperaturesetpoint livingroom into numbers
Wu_SetpBinnen = tonumber(Wu_Dev_SetpBinnen)

if PRINT_MODE == true then
 print('Data collected')
 print('Wu_Dev_TempBuiten: ' .. Wu_Dev_Temp)
 print('Wu_Dev_TempBinnen: ' .. Wu_Dev_TempBinnen)
 print('Wu_Dev_SetpointBinnen: ' .. Wu_Dev_SetpBinnen)
 print('Wu_Dev_Wind: ' .. Wu_Dev_Wind)
 print('Wu_Dev_Rain: ' .. Wu_Dev_Rain)
 print('Wu_Dev_UV: ' .. Wu_Dev_UV)
 print(' ')
 print('New values >>>>>>>>>>>')
 print('TempBuiten: ' .. Wu_Temp .. '   TresholdClose = ' .. TH_Tp_Close)
 print('TempBinnen: ' .. Wu_TempBinnen .. '   TresholdClose = ' .. TH_Tp_Binnen_Close)
 print('SetpointBinnen: ' .. Wu_SetpBinnen)
 print('Gust: ' .. Wu_WindGust .. '   TresholdClose = ' .. TH_GUST)
 print('Speed: ' .. Wu_WindSpeed .. '   TresholdClose = ' .. TH_WIND)
 print('Rain: ' .. Wu_Rain .. '   TresholdClose = ' .. TH_Rain)
 print('RainTmin1: ' .. RainTmin1)
 print('UV: ' .. Wu_UV .. '   TresholdClose = ' .. TH_Uv_Close)
	if (otherdevices[SCREEN_NAME]) == 'Open' then print("scherm: In") end
	if (otherdevices[SCREEN_NAME]) == 'Closed' then print("scherm: Uit") end

end

-- check temperature outside trigger
if (Wu_Temp >= TH_Tp_Close) then TempTriggerClose = 1 end
if (Wu_Temp <= TH_Tp_Open) then TempTriggerOpen = 0 else TempTriggerOpen = 1 end

-- check temperature inside trigger
if (Wu_TempBinnen >= TH_Tp_Binnen_Close) then TempTriggerBinnenClose = 1 end
if (Wu_TempBinnen <= TH_Tp_Binnen_Open) then TempTriggerBinnenOpen = 0 else TempTriggerBinnenOpen = 1 end

-- check if heating is on (setpoint bigger than actual)
if (Wu_SetpBinnen >= Wu_TempBinnen) then HeaterOff = 0 else HeaterOff=1 end
    
-- check UV trigger
if (Wu_UV >= TH_Uv_Close) then UVTriggerClose = 1 end
if (Wu_UV <= TH_Uv_Open) then UVTriggerOpen = 0 else UVTriggerOpen = 1 end

-- check for new rainfall
Add_Rain=Wu_Rain-RainTmin1

-- Check to set rain timer
if (Add_Rain >= TH_Rain) then 
	RainTimer = RainTime
	end

-- Update rain timer	
if (RainTimer > 0) then
	Res_RainTimer = 0
	RainTimer = RainTimer - 1
else
	Res_RainTimer = 1
end

-- check tresholds 
if Wu_WindSpeed <= TH_WIND       then Res_Wind=1 else Res_Wind=0 end
if Wu_WindGust <= TH_GUST       then Res_Gust=1 else Res_Gust=0 end
if Add_Rain < TH_Rain       then Res_Rain=1 else Res_Rain=0 end
if otherdevices[SENSOR_RAINON_NAME] == 'Off' then Res_RainOn=0 else Res_RainOn=1 end
if (timeofday['Daytime'])   then Res_Dayl=1 else Res_Dayl=0 end

if PRINT_MODE == true then
 print(' ')
 print('New triggers set >>>>>>>>>>>')
 print('Close triggers')
 print('TempTriggerBuienClose: ' .. TempTriggerClose)
 print('TempTriggerBinnenClose: ' .. TempTriggerBinnenClose)
 print('UVTriggerClose: ' .. UVTriggerClose)
 print('RainTimer: ' .. RainTimer)
 print('Res_RainTimer: ' .. Res_RainTimer)
 print(' ')
 print('Open triggers')
 print('UVTriggerOpen: ' .. UVTriggerOpen .. '   (not used)')
 print('TempTriggerOpen: ' .. TempTriggerOpen)
 print('TempTriggerBinnenOpen: ' .. TempTriggerBinnenOpen)
 print('Heating inside off: ' .. HeaterOff)
 print('Res_Wind: ' .. Res_Wind)
 print('Res_Gust: ' .. Res_Gust)
 print('Res_Rain: ' .. Res_Rain)    
 print('Add_Rain: ' .. Add_Rain)
 print('Res_RainOn: ' .. Res_RainOn)
 print('Res_Dayl: ' .. Res_Dayl)
end

--decide if to close the screen
if (otherdevices[SCREEN_NAME]) ~= 'Open' then
    if PRINT_MODE == true then
        print('Screen is out, check if it needs to be closed')
    end
    if Res_Wind + Res_Gust + Res_Rain + Res_RainOn + Res_RainTimer + TempTriggerOpen + TempTriggerBinnenOpen + HeaterOff < 8 then
        commandArray['ZonweringAuto'] = 'On' 	    
        commandArray['SchermOff'] = 'On'
        if PRINT_MODE == true then
    	    print('Closing screen due to weather')
        end
	    -- write info to file
        file = io.open("/home/pi/domoticz/log/zonwering.log", "a")
        io.output(file)
        tlog = os.time()
        io.write(tlog.. ",CloseWeather," .. Wu_Temp .. "," .. Wu_TempBinnen .. "," .. Wu_SetpBinnen .. "," .. Wu_WindGust .. "," .. Wu_WindSpeed .. "," .. Wu_Rain .. "," .. RainTmin1 .. "," .. Wu_UV .. "," .. Res_RainOn .. "\n")
        io.close(file)
	    ManualTimer = 0
    	commandArray['Variable:ManualTimer'] = tostring(ManualTimer)
    else
        if PRINT_MODE == true then
            print('Screen can remain out, no change needed')
        end
    end
end

--decide if to put the screen down
if (otherdevices[SCREEN_NAME]) ~= 'Closed' then
    if (ManualTimer == 0) then
        if PRINT_MODE == true then
            print('Check if screeen needs to be operated automatically')
        end
    if (UVTriggerClose + TempTriggerClose + TempTriggerBinnenClose + Res_Dayl ==4) then
        if PRINT_MODE == true then
            print('Triggers to open screen are all valid, checking close screen triggers')
        end
	    if Res_Wind + Res_Gust + Res_Rain + Res_RainOn + Res_RainTimer  + TempTriggerOpen + TempTriggerBinnenOpen + HeaterOff == 8 then
		    t1 = os.time()
	            s = otherdevices_lastupdate[SCREEN_NAME]
            	year = string.sub(s, 1, 4)
	            month = string.sub(s, 6, 7)
            	day = string.sub(s, 9, 10)
	            hour = string.sub(s, 12, 13)
            	minutes = string.sub(s, 15, 16)
	            seconds = string.sub(s, 18, 19)
            	t2 = os.time{year=year, month=month, day=day, hour=hour, min=minutes, sec=seconds}
	            difference = (os.difftime (t1, t2))
    	if PRINT_MODE == true then
	    	print('Screen is allowed to open, close triggers are not valid')
		    print('t1: ' .. t1)
    		print('s: ' .. s)
	    	print('year: ' .. year)
		    print('month: ' .. month)
    		print('day: ' .. day)
	    	print('hour: ' .. hour)
		    print('minutes: ' .. minutes)
    		print('seconds: ' .. seconds)
	    	print('t2: ' .. t2)
		    print('difference: ' .. difference)
    		print('SwitchTime: ' .. SwitchTime)
	    end
    	if difference <= SwitchTime then
	       	print('Switch time history: ' .. difference)
    	    print('Recent closed manually, wait for switchtime')
    	else
	    	if (otherdevices[SCREEN_NAME]) == 'Open' then
                commandArray['ZonweringAuto'] = 'On' 	    
	            commandArray['SchermOn'] = 'On'
    		    print('Opening screen')
	            -- write info to file
                file = io.open("/home/pi/domoticz/log/zonwering.log", "a")
                io.output(file)
                tlog = os.time()
                io.write(tlog.. ",OpenAuto," .. Wu_Temp .. "," .. Wu_TempBinnen .. "," .. Wu_SetpBinnen .. "," .. Wu_WindGust .. "," .. Wu_WindSpeed .. "," .. Wu_Rain .. "," .. RainTmin1 .. "," .. Wu_UV .. "," .. Res_RainOn .. "\n")
                io.close(file)
		        else
	    	        print('Screen is already open')
        		end
	        end
        else
            if PRINT_MODE == true then
    	        print('screen not opened due to weather')
	        end
        end
        else 
    	    if PRINT_MODE == true then
     	        print('Triggers to open the screen are not active')
            end
        end
    else
	    if PRINT_MODE == true then
    	    print('Manual timer active, not checking screen triggers')
        end
    end
else
    if PRINT_MODE == true then
	    print('Screen already fully down, no need to check triggers')
    end
end

-- check if it is time to close the screen (option 1)
time = os.date("*t")
if (time.hour == CloseTimeHour and time.min == CloseTimeMinute) and ((otherdevices[SCREEN_NAME]) ~= 'Open') and (TH_Close == CloseTime) then
	print('Closing screen due to time trigger')
    commandArray['ZonweringAuto'] = 'On' 	    
    commandArray['SchermOff'] = 'On'
	-- write info to file
    file = io.open("/home/pi/domoticz/log/zonwering.log", "a")
    io.output(file)
    tlog = os.time()
    io.write(tlog.. ",CloseTime," .. Wu_Temp .. "," .. Wu_TempBinnen .. "," .. Wu_SetpBinnen .. "," .. Wu_WindGust .. "," .. Wu_WindSpeed .. "," .. Wu_Rain .. "," .. RainTmin1 .. "," .. Wu_UV .. "," .. Res_RainOn .. "\n")
    io.close(file)
    --reset triggers at night
	TempTriggerClose = 0
	TempTriggerBinnenClose = 0
	UVTriggerClose = 0
end

-- check if is daytime is over and to close the screen (option 2)
if (Res_Dayl==0) and ((otherdevices[SCREEN_NAME]) ~= 'Open') and (TH_Close == NightTime) then
	print('Closing screen due to sunset')
    commandArray['ZonweringAuto'] = 'On' 	    
    commandArray['SchermOff'] = 'On'
	-- write info to file
    file = io.open("/home/pi/domoticz/log/zonwering.log", "a")
    io.output(file)
    tlog = os.time()
    io.write(tlog.. ",CloseSunset," .. Wu_Temp .. "," .. Wu_TempBinnen .. "," .. Wu_SetpBinnen .. "," .. Wu_WindGust .. "," .. Wu_WindSpeed .. "," .. Wu_Rain .. "," .. RainTmin1 .. "," .. Wu_UV .. "," .. Res_RainOn .. "\n")
    io.close(file)
    --reset triggers at night
	TempTriggerClose = 0
	TempTriggerBinnenClose = 0
	UVTriggerClose = 0
end

--copy current rain to RainTmin1
RainTmin1 = Wu_Rain

-- save the globals
commandArray['Variable:WindGust'] = tostring(Wu_WindGust)
commandArray['Variable:WindSpeed'] = tostring(Wu_WindSpeed)
commandArray['Variable:TempTrigger'] = tostring(TempTriggerClose)
commandArray['Variable:TempTriggerBinnen'] = tostring(TempTriggerBinnenClose)
commandArray['Variable:UVTrigger'] = tostring(UVTriggerClose)
commandArray['Variable:RainTmin1'] = tostring(RainTmin1)
commandArray['Variable:RainTimer'] = tostring(RainTimer)
commandArray['Variable:ManualTimer'] = tostring(ManualTimer)

return commandArray
User avatar
remb0
Posts: 499
Joined: Thursday 11 July 2013 22:21
Target OS: Raspberry Pi / ODroid
Domoticz version: Beta
Location: The Netherlands
Contact:

Re: Weather blind\sunscreen script 0.27

Post by remb0 »

I had that already with: TH_Hour but not with minutes. thanks!

But I already log to screen but also to a csv file.
when the file doesn't exist create it, and you can choose what to log: all or only changes.
edwinth
Posts: 4
Joined: Monday 09 September 2013 15:47
Target OS: Raspberry Pi / ODroid
Domoticz version:
Location: Nijmegen
Contact:

Re: Weather blind\sunscreen script 0.27

Post by edwinth »

Hello Remb0, I'm trying to get this sunscreen script running but I get an error. Perhaps you know what causes the issue.

2016-09-12 14:20:01.583 Error: EventSystem: in /home/pi/domoticz/scripts/lua/script_time_Sunscreen.lua: /home/pi/domoticz/scripts/lua/MyFunc.lua:62: bad argument #1 to 'len' (string expected, got nil)

I think it has something to do with time comparisson "if string.len(Time2)>12 then Time2 = My.ConvTime(Time2) end" but i'm missing the skills to solve this.

Edit: Problem solved, SUN_DeviceManual value was incorrect.

Thanks in advance,

Edwin
ruben86
Posts: 4
Joined: Tuesday 02 June 2015 23:42
Target OS: Raspberry Pi / ODroid
Domoticz version: V2020.1
Location: Netherlands
Contact:

Re: Weather blind\sunscreen script 0.27

Post by ruben86 »

First of all, thanks a lot for your effort building this script!
Currently I am looking for a script like this to make my sunscreen smarter.
Unfortunately I don't understand how I need to implement the script.
Is there somewhere a guide, or at least some tips to get me started?
User avatar
PeterCelica
Posts: 21
Joined: Monday 13 March 2017 20:20
Target OS: NAS (Synology & others)
Domoticz version: 3.0.7602
Location: Netherlands
Contact:

Re: Weather blind\sunscreen script 0.27

Post by PeterCelica »

Hi, i found your script here while I was looking for an advanced script with weather thresholds and I found your impressive script here.

The only thing is that I'm working with Domoticz on a Synology NAS and I don't know what to do with the line:
file = io.open("/home/pi/domoticz/log/zonwering.log", "a") for a Raspberry PI I presume.

Hope somebody can help me with this issue.

Thanks and
Best regards, Peter.
Post Reply

Who is online

Users browsing this forum: Amazon [Bot] and 1 guest