[DIY] Garden irrigation and learning project

In this subforum you can show projects you have made, or you are busy with. Please create your own topic.

Moderator: leecollings

User avatar
Siewert308SW
Posts: 288
Joined: Monday 29 December 2014 15:47
Target OS: Raspberry Pi / ODroid
Domoticz version: Stable
Location: The Netherlands
Contact:

Re: [DIY] Garden irrigation and learning project

Post by Siewert308SW »

I think i should put this in the wiki.
It is going out of hand... :D

Latest additions and changes:
Version 0.5
- MaxRainFall changed, it is now a average of your desired "Buienradar" max rain fall input to prevent the switch to flip flop
- Optimized Moist sensor script as it now triggers irrigation on a minimum value and shutsdown on a maximum value
- Added extra loggin option
- Added option to use Buienradar or not
- Added option to use Dutch or English translation

This script is still in BETA as i just wrote it and haven't fully tested it.
Be aware that i'm not a coder and it's maybe the cleanest script ever, but who cares as it works ;-)

I hope it can be of use to you and feel free to adapt it.
Bug fixes, patches, and improvements are hapiliy accepted of course.
Same counts for LUA optimizations as this is the first time i wrote,copy/past a LUA script.
When i started this i didn't had a clue what i was doing ;-)

Code: Select all

--[[

	script_time_irrigation.lua
	@author: Siewert Lameijer
	@since: 2015-06-30
	@version: 0.5 (BETA)
	@Garden Irrigation lua script 

Credits:
- Nicky Bulthuis -/- for the dusk sensor script
- Hans van der Heijden -/- for the IsItGonnaRain script
- anonymous user -/- for the "Reading weather station data" script
- dannybloe -/- for Humidity Control script
- And to all those who i forgot to mention

-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-

This script has the intention to control and maintain your garden soil humidity.
And is it is a hodgepodge of different scripts found on the Domoticz forum.

I wrote this script for my own little garden project and to beable to automate irrigation while i'm gone.
The topic can be found here: https://www.domoticz.com/forum/viewtopic.php?f=38&t=6904
Somehow it got out of hand and got big.
So i thought that maybe some of you could have a benefith of this.
Although the script is intended for irrigation.
You could adapt it for other projects.

I do assume that when you want to use this script you already have the knowhow of Lua and Domoticz.
As i won't explain the entire installation ;-)

The script does the following:
- It scraps WeatherUnderground data and processing it usable data
- It monitors buienradar (optional) to see if there are any showers upcoming 24hr
- It scraps temperature and humidity from your moist sensor and processing it usable data
- It lets you choose when (Day of the week, month and time of the day) to irrigate
- By an extensive Settings Menu you can set various settings to control when to irrigate
settings ranges from: Min/Max Temp, Min/Max Humidity pct, Amount of rain, wind, UV, day, month to stop or start irrigating.

The Hardware i use:
- DIY Garden irrigation piping as seen in the topic
- Washer 220v Watervalve 2-way
- KaKu ACM-3500-3 3-in-1 unit (controlling the 2 valves) 1 reserve for pond protector to scare the cats ;-)

This script is still in BETA as i just wrote it and haven't fully tested it.
Be aware that i'm not a coder and it's maybe the cleanest script ever, but who cares as it works ;-)  

I hope it can be of use to you and feel free to adapt it. 
Bug fixes, patches, and improvements are hapiliy accepted of course.
Same counts for LUA optimizations as this is the first time i wrote,copy/past a LUA script.
When i started this i didn't had a clue what i was doing ;-)

Siewert Lameijer

-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-

Necessities:

1x Virtual switch to be able to manual override the irrigation program (Manual Override)
1x Soil Moist & Humidity sensor
1x Active WeatherUnderground account
1x Switch to be able to control your waterpump/valve which is somehow wireless connected to domoticz
1x Garden with irrigation hardware xD

The following UserVariable have to be create:
- VarManOverride (type=integer, value=0)
- VarTimeCon (type=integer, value=0)
- VarWeatherCon (type=integer, value=0)
- VarTimeOfDayCurrent (type=integer, value=0)
- VarMayFollowProgram (type=integer, value=0)
- VarFollowsProgram (type=integer, value=0)
- VarMaxRunTime (type=integer, value=0)
- VarMoistOnline (type=integer, value=0)
- VarMoistOnlineHum (type=integer, value=0)
- VarMoistConTemp (type=integer, value=0)
- VarMoistConHum (type=integer, value=0)
- VarProgramOverride (type=integer, value=0)
- VarProgramRun (type=integer, value=0)
- VarTimeFrame (type=integer, value=0)
- VarManOverrideCon (type=integer, value=0)
- VarBuienRadarCon (type=integer, value=0)
- VarTimeFrameMon (type=integer, value=0)

-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-

Changelog:

Version 0.5
- Buienradar MaxRainFall changed, it is now a average of your desired max rain fall input to prevent the switch to flip flop
- Optimized Moist sensor script as it now triggers irrigation on a minimum value and shutsdown on a maximum value
- Added extra loggin option
- Added option to use Buienradar or not
- Added option to use Dutch or English translation

Version 0.4
- Changed Days, Months to text instead of numbers as input
- Optimized irrigation program ending and keeping it that until the next time schedule

Version 0.3
- Added Buienradar (IsItGonnaRain) script
- Optimized Max irrigation time script
- Clean some code
- Reorderd printed text

Version 0.2
- Added counter for Max irrigation time
- Added manual override
- Optimized WeatherUnderground scraping data
- Optimized Moist sensor scraping data
- Optimized user input Time Of The Day, Days and Months

Version 0.1
- Added WeatherUnderground and scraping data
- Added Moist sensor scraping Temp & Humidity data
- Added Moist sensor online check
- Added user input for Time Of The Day where irrigation may start
- Added user input for days and months where the irrigation may start
	
-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-
	



-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-
--]]

time = os.date("*t")
	commandArray = {}
--
-- **********************************************************
-- Settings Begin
-- **********************************************************
--

-- Set your desired language (English, Dutch) 
local lang = 'Dutch'

-- Lua script interval check, change the number 1 to every desired number in minutes

-- Logging: 
-- 0 = None 
-- 1 = Only critical
-- 2 = All
local logging = 2

--
-- **********************************************************
-- Location and minimum Rain Fall Variables For BuienRadar
-- **********************************************************
-- 

-- Do you want to use BuienRadar? Yes or No
local Buienradar = 'No' --(Dutch weather, rain prediction)

-- Set your location by adding Lat/Lon
local lat = '53.338023'
local lon = '6.303114'

-- Set your minimum rain fall for in a periode of 24hr 
local  VarMaxRainFall = '20'

--
-- **********************************************************
-- WeatherUnderGround Variables
-- **********************************************************
-- 
-- Name of your Weatherstation widget which contains humidity,uv,temp and pressure
local weatherstation = 'Barometer'

-- Name of your Weatherstation Wind widget
local wind = 'Wind'

-- Name of your Weatherstation Rain widget
local rain = 'Regenmeter'

-- Name of your Weatherstation UV widget
local uv = 'UV'

--
-- **********************************************************
-- Switches and Virtual Switches Variables
-- **********************************************************
--
-- Name of your manual override virtual switch
local VitManOverride = 'Irrigatie Manual Override'

-- Name of your irrigation switch for water valve/pump
local VarPump = 'Irrigatie 1 Check'

--
-- **********************************************************
-- Moist Sensor Variables
-- **********************************************************
-- 
-- Name of your Moist Sensor device
local MoistSensor = 'Vocht Sensor (border 1)'

-- Your target soil humidity percentage
local VarTarHum = '80'

-- Your minumim soil humidity percentage from which the irrigation will start
local VarMinHum = '55'

-- Your Minumum soil temperature, Lower won't trigger irrigation
local VarTarTempMin = '12'

-- Your Maximum soil temperature, Higher won't trigger irrigation
local VarTarTempMax = '25'

-- Amount of minuten/times we want to switch OFF irrigation after the program has started.		
local VarMaxRunTime_off = 60

--
-- **********************************************************
-- Day, Month and Time Variables
-- **********************************************************
--

-- Set your desired TimeOfDay for irrigation (Morning=0, Afternoon=1, Evening=2 or Night=3)
local VarTimeOfDay = '2'

-- Set your desired irrigation day, leave blank for no irrigation
-- Set Mon, Tue, Wed, Thu, Fri, Sat or Sun
local VarDay1 = 'Mon'

local VarDay2 = ''

local VarDay3 = 'Wed'

local VarDay4 = ''

local VarDay5 = 'Fri'

local VarDay6 = ''

local VarDay7 = 'Sun'

-- Set your desired irrigation month, leave blank for no irrigation, 
-- Set months like: Jan, Feb, Apr, May, Jun, Jul, Aug, Sep, ect ect
local VarMonth1 = ''

local VarMonth2 = ''

local VarMonth3 = ''

local VarMonth4 = 'Apr'

local VarMonth5 = 'May'

local VarMonth6 = 'Jun'

local VarMonth7 = 'Jul'

local VarMonth8 = 'Aug'

local VarMonth9 = 'Sep'

local VarMonth10 = ''

local VarMonth11 = ''

local VarMonth12 = ''

--
-- **********************************************************
-- Weather Variables
-- **********************************************************
-- 
-- Set your prefered max rain fall, higher won't trigger irrigation
local RainCurrent = '0'

-- Set your prefered minimum outside temperature for irrigation, Lower won't trigger irrigation
local WeatherTempMin = '13'

-- Set your prefered maximum outside temperature for irrigation, Higher won't trigger irrigation
local WeatherTempMax = '24'

-- Set your prefered maximum UV for irrigation, Higher won't trigger irrigation
local UVMax = '4'

-- Set your prefered max windspeed km/h, higher won't trigger irrigation
local WindSpeed = '50'

-- Set your prefered max windgust km/h, higher won't trigger irrigation
local WindGust = '150'


--
-- **********************************************************
-- Settings END
-- **********************************************************
--

--[[
--> Don't edit anything below this line or you could break the script!
-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-
--]]


    week       = tonumber(os.date("%V"));
	month       = tostring(os.date("%b"));
    dayno       = tonumber(os.date("%d"));
    dayofweekno = tonumber(os.date("%w"));
    day       = tostring(os.date("%a"));
    hour       = tonumber(os.date("%H"));
    min       = tonumber(os.date("%M"));

--
-- **********************************************************
-- Scrapping Weather Data from WeatherUnderground
-- **********************************************************
--
 
--
-- Weatherstation data:
-- 

sWeatherTemp, sWeatherHumidity, sWeatherUV, sWeatherPressure, sWeatherUV2 = otherdevices_svalues[weatherstation]:match("([^;]+);([^;]+);([^;]+);([^;]+);([^;]+)")
sWeatherTemp = tonumber(sWeatherTemp);
sWeatherHumidity = tonumber(sWeatherHumidity);
sWeatherUV = tonumber(sWeatherUV);
sWeatherPressure = tonumber(sWeatherPressure);
sWeatherUV2 = tonumber(sWeatherUV2);


	if logging == 1 then
		print("--------------------------------------------------------------------------------------")
		if lang == 'Dutch' then
		print("Irrigatie [HET WEER]");
		print("-- Irrigatie ==> [WeerStation] - Temperatuur: " .. sWeatherTemp .. " ");
		else
		print("Irrigation [WEATHER]");
		print("-- Irrigation ==> [WeatherStation] - Temperature: " .. sWeatherTemp .. " ");

		end
	end
	
	if logging >= 2 then
		print("--------------------------------------------------------------------------------------")
		if lang == 'Dutch' then
		print("Irrigatie [HET WEER]");
		print("-- Irrigatie ==> [WeerStation] - Temperatuur: " .. sWeatherTemp .. " ");
		print("-- Irrigatie ==> [WeerStation] - Luchtvochtigheid: " .. sWeatherHumidity .. " ");
		print("-- Irrigatie ==> [WeerStation] - Barometer: " .. sWeatherPressure .. " ");
		else
		print("Irrigation [WEATHER]");
		print("-- Irrigation ==> [WeatherStation] - Temperature: " .. sWeatherTemp .. " ");
		print("-- Irrigation ==> [WeatherStation] - Humidity: " .. sWeatherHumidity .. " ");
		print("-- Irrigation ==> [WeatherStation] - Pressure: " .. sWeatherPressure .. " ");		

		end
	end	
	
--
-- 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);

	if logging == 1 then
		if lang == 'Dutch' then
		print("-- Irrigatie ==> [Windmeter] - Windsnelheid: " .. sWindSpeed .. " ");
		print("-- Irrigatie ==> [Windmeter] - Windvlaag: " .. sWindGust .. " ");
		else
		print("-- Irrigation ==> [Windmeter] - Windspeed is: " .. sWindSpeed .. " ");
		print("-- Irrigation ==> [Windmeter] - Windgust is: " .. sWindGust .. " ");

		end
	end
	
	if logging >= 2 then
		if lang == 'Dutch' then
		print("-- Irrigatie ==> [Windmeter] - Windrichting (in graden): " .. sWindDirectionDegrees .. " ");
		print("-- Irrigatie ==> [Windmeter] - Windrichting: " .. sWindDirection .. " ");
		print("-- Irrigatie ==> [Windmeter] - Windsnelheid: " .. sWindSpeed .. " ");
		print("-- Irrigatie ==> [Windmeter] - Windvlaag: " .. sWindGust .. " ");
		print("-- Irrigatie ==> [Windmeter] - Windtemperatuur: " .. sWindTemperature .. " ");
		print("-- Irrigatie ==> [Windmeter] - Gevoelstemperatuur: " .. sWindFeel .. " ");
		else
		print("-- Irrigation ==> [Windmeter] - Winddirection (in degrees) is: " .. sWindDirectionDegrees .. " ");
		print("-- Irrigation ==> [Windmeter] - Winddirection is: " .. sWindDirection .. " ");
		print("-- Irrigation ==> [Windmeter] - Windspeed is: " .. sWindSpeed .. " ");
		print("-- Irrigation ==> [Windmeter] - Windgust is: " .. sWindGust .. " ");
		print("-- Irrigation ==> [Windmeter] - Windtemperature is: " .. sWindTemperature .. " ");
		print("-- Irrigation ==> [Windmeter] - Windfeel is: " .. sWindFeel .. " ");

		end
	end
		
	
--
-- Rainmeter data:
-- 

sRainmeterCurrent, sRainmeterTotal = otherdevices_svalues[rain]:match("([^;]+);([^;]+)")
 
sRainmeterCurrent = tonumber(sRainmeterCurrent);
sRainmeterTotal = tonumber(sRainmeterTotal);

	if logging == 1 then
		if lang == 'Dutch' then
		print("-- Irrigatie ==> [Regenmeter] - Regenval nu: " .. sRainmeterCurrent .. " ");
		print("-- Irrigatie ==> [Regenmeter] - Totale Regenval: " .. sRainmeterTotal .. " ");
		else
		print("-- Irrigation ==> [Rainmeter] - Actual rain is: " .. sRainmeterCurrent .. " ");
		print("-- Irrigation ==> [Rainmeter] - Total rain is: " .. sRainmeterTotal .. " ");

		end
	end
	
	
--
-- UV data:
-- 

sUV, sSolar = otherdevices_svalues[uv]:match("([^;]+);([^;]+)")
 
sUV = tonumber(sUV);
sSolar = tonumber(sSolar);

	if logging >= 1 then
	if lang == 'Dutch' then
		print("-- Irrigatie ==> [UV] - UV Sterkte: " .. sUV .." ");
	else
		print("-- Irrigation ==> [UV] - UV Strength is: " .. sUV .." ");

	end
	end

if  sRainmeterCurrent >= tonumber (RainCurrent)
	and sWeatherTemp >= tonumber (WeatherTempMin)
	and sWeatherTemp <= tonumber (WeatherTempMax)
	and sUV <= tonumber (UVMax)
	and sWindSpeed <= tonumber (WindSpeed)
	and sWindGust <= tonumber (WindGust)
then

	if logging >= 1 then
	if lang == 'Dutch' then
		print("-- Irrigatie ==> [HET WEER] - Weer conditie lijkt goed om te irrigeren");
	else
		print("-- Irrigation ==> [WEATHER] - Weather conditions are looking good and ready for irrigation");

	end
	end
	
	if(uservariables['VarWeatherCon'] == 0) then
	commandArray['Variable:VarWeatherCon']= '1'
    end
	
else

	if logging >= 1 then
	if lang == 'Dutch' then
		print("-- Irrigatie [INFO] ==> Weer conditie lijkt niet goed voor irrigatie");
	else
		print("-- Irrigation [INFO] ==> Weather conditions aren't good for irrigation");

	end
	end
	if(uservariables['VarWeatherCon'] == 1) then
	commandArray['Variable:VarWeatherCon']= '0'
	end	
end

if logging >= 1 then
	print("--------------------------------------------------------------------------------------")
end
	
--
-- **********************************************************
-- Scrapping Temparature and moist humidity from moist sensor
-- **********************************************************
--

--
-- Moist Sensor data:
-- 

    smoistsensorTemp, smoistsensorHumidity = otherdevices_svalues[MoistSensor]:match("([^;]+);([^;]+);([^;]+)")
    smoistsensorTemp = tonumber(smoistsensorTemp);
    smoistsensorHumidity = tonumber(smoistsensorHumidity);

	if logging >= 1 then
	if lang == 'Dutch' then
		print("Irrigatie [GROND CONDITIE]");
		print("-- Irrigatie ==> [VochtSensor] - Grond Temperatuur: " .. smoistsensorTemp .. " ");
		print("-- Irrigatie ==> [VochtSensor] - Grond Vochtigheid: " .. smoistsensorHumidity .. " ");
	else
		print("Irrigation [SOIL CONDITION]");
		print("-- Irrigation ==> [MoistSensor] - Soil Temperature: " .. smoistsensorTemp .. " ");
		print("-- Irrigation ==> [MoistSensor] - Soil Humidity: " .. smoistsensorHumidity .. " ");

	end	
	end
	
--
-- **********************************************************
-- Moist Sensor online check
-- **********************************************************
--	

if (smoistsensorTemp == 0 or smoistsensorTemp == nil) then
	if logging >= 1 then
	if lang == 'Dutch' then
    print('-- Irrigatie ==> [VochtSensor] - [ERROR] Vocht sensor geeft een temperatuur aan van 0 of nil, irrigatie word gestaakt')
	else
    print('-- Irrigation ==> [MoistSensor] - [ERROR] Moist Sensor reports Temp is 0 or nil. Skipping Irrigation')

	end
	end
	if(uservariables['VarMoistOnline'] == 1) then	
	commandArray['Variable:VarMoistOnline']= '0'
	end
		else
	if(uservariables['VarMoistOnline'] == 0) then		
	commandArray['Variable:VarMoistOnline']= '1'
	end
end

if (smoistsensorHumidity <= 6 or smoistsensorHumidity >= 99 or smoistsensorHumidity == nil) then
	if logging >= 1 then
	if lang == 'Dutch' then
    print('-- Irrigatie ==> [VochtSensor] - [Error] ==> Vocht sensor geeft een verkeerde vochtigheids waarde aan,, irrigatie word gestaakt')
	else
    print('-- Irrigation ==> [MoistSensor] - [Error] ==> Moist Sensor reports wrong Humidity values. Skipping Irrigation')

	end
	end
	if(uservariables['VarMoistOnlineHum'] == 1) then	
	commandArray['Variable:VarMoistOnlineHum']= '0'
	end
		else
	if(uservariables['VarMoistOnlineHum'] == 0) then		
	commandArray['Variable:VarMoistOnlineHum']= '1'
	end
end

--
-- **********************************************************
-- Checking Grond Temperature Conditions
-- **********************************************************
--

if 	smoistsensorTemp >= tonumber (VarTarTempMin)
	and smoistsensorTemp <= tonumber (VarTarTempMax)
then

	if logging >= 1 then
	if lang == 'Dutch' then
		print("-- Irrigatie ==> [VochtSensor] - Grond temperatuur is goed voor irrigatie");
	else
		print("-- Irrigation ==> [MoistSensor] - Soil Temp conditions are fine for irrigation");

	end	
	end
	if(uservariables['VarMoistConTemp'] == 0) then
	commandArray['Variable:VarMoistConTemp']= '1'
	end
	
else
	if logging >= 1 then
	if lang == 'Dutch' then
	print("-- Irrigatie ==> [VochtSensor] - Grond temperatuur is niet goed voor irrigatie");
	else
	print("-- Irrigation ==> [MoistSensor] - Soil Temp conditions aren't good for irrigation");

	end
	end
	if(uservariables['VarMoistConTemp'] == 1) then
	commandArray['Variable:VarMoistConTemp']= '0'
	end
end

if 	smoistsensorTemp <= tonumber (VarTarTempMin)

then

	if logging >= 2 then
	if lang == 'Dutch' then
		print("-- Irrigatie ==> [VochtSensor] - Grond temperatuur is te laag...");
	else
		print("-- Irrigation ==> [MoistSensor] - Soil Temp is to low...");

	end
	end
end

if 	smoistsensorTemp >= tonumber (VarTarTempMax)

then

	if logging >= 2 then
	if lang == 'Dutch' then
		print("-- Irrigatie ==> [VochtSensor] - Grond temperatuur is te hoog...");
	else
		print("-- Irrigation ==> [MoistSensor] - Soil Temp is to high...");

	end	
	end
end

--
-- **********************************************************
-- Checking Grond Humidity Conditions
-- **********************************************************
--

if smoistsensorHumidity >= tonumber (VarMinHum) or smoistsensorHumidity <= tonumber (VarTarHum) or smoistsensorHumidity >= tonumber (VarTarHum)
then

	if logging >= 1 then
	if lang == 'Dutch' then
		print("-- Irrigatie ==> [VochtSensor] - Grond vochtigheid is goed, geen irrigatie nodig");
	else
		print("-- Irrigation ==> [MoistSensor] - Soil humidity is fine and doesn't need irrigation");

    end	
	end
	if(uservariables['VarMoistConHum'] == 1) then
	commandArray['Variable:VarMoistConHum']= '0'
	end
end


if smoistsensorHumidity <= tonumber (VarMinHum)
then

	if logging >= 2 then
	if lang == 'Dutch' then
		print("-- Irrigatie ==> [VochtSensor] - Grond is droog...");
	else
		print("-- Irrigation ==> [MoistSensor] - Soil is dry...");

	end	
	end
	if(uservariables['VarMoistConHum'] == 0) then
	commandArray['Variable:VarMoistConHum']= '1'
	end	
end

if smoistsensorHumidity >= tonumber (VarTarHum)
then

	if logging >= 2 then
	if lang == 'Dutch' then
		print("-- Irrigatie ==> [VochtSensor] - Grond is nat...");
	else
		print("-- Irrigation ==> [MoistSensor] - Soil is wet...");

	end
	end
end
		
--
-- **********************************************************
-- Checking Buienradar 
-- **********************************************************
--
if Buienradar == 'Yes' then

	if logging >= 1 then
		print("--------------------------------------------------------------------------------------")
		print("Irrigatie [BUIENRADAR]");	
	end	
	

    tempfilename = '/var/tmp/rain.tmp'
    totalrain = 0
    rainlines = 0	
	
	
   function IsItGonnaRain( minutesinfuture )
       url='http://gps.buienradar.nl/getrr.php?lat='..lat..'&lon='..lon
       read = os.execute('curl -s -o '..tempfilename..' "'..url..'"')
       file = io.open(tempfilename, "r")

       while true do
          line = file:read("*line")
          if not line then break end
          linetime=string.sub(tostring(line), 5, 9)
          linetime2 = os.time{year=os.date('%Y'), month=os.date('%m'), day=os.date('%d'), hour=string.sub(linetime,1,2), min=string.sub(linetime,4,5), sec=os.date('%S')}
          difference = os.difftime (linetime2,os.time())

          if ((difference > 0) and (difference<=minutesinfuture*60)) then
             rain=tonumber(string.sub(tostring(line), 0, 3))
             totalrain = totalrain+rain
             rainlines=rainlines+1
          end

       end
       file:close()
       
       averagerain=totalrain/rainlines
       return(averagerain)
    end

    function round(num, idp)
       local mult = 10^(idp or 0)
       return math.floor(num * mult + 0.5) / mult
    end

--
-- **********************************************************
-- Is it gonna rain for the upcoming 24hr YES/NO
-- **********************************************************
--
local VarMaxRainFallPlus = VarMaxRainFall * 0.5 + VarMaxRainFall

       minutes=1440
       RainPrediction = IsItGonnaRain(minutes)
       RainmmHour=10^((RainPrediction-109)/32)

       if RainPrediction >= tonumber (VarMaxRainFallPlus) then
          verw = 3
		  if (uservariables['VarBuienRadarCon']) == 1  then
		  commandArray['Variable:VarBuienRadarCon']= '0'
		  end
		  if logging >= 1 then  
			print('-- Irrigatie ==> [REGEN] - Verwacht '..RainPrediction..' binnen 24 uur.')
		  end
       else
          verw = 2

		  if (uservariables['VarBuienRadarCon']) == 0  then
		  commandArray['Variable:VarBuienRadarCon']= '1'
		  end
		  if logging >= 1 then 
			print('-- Irrigatie ==> [REGEN] - Geen of weinig regen verwacht binnen 24 uur.')
		  end		  
       end
end	
	if logging >= 1 then
		print("--------------------------------------------------------------------------------------")
	end	
	
--
-- **********************************************************
-- Checking Time Frame 
-- **********************************************************
--

	if logging >= 1 then
	if lang == 'Dutch' then
		print("Irrigatie [TIMEFRAME]");	
	else
		print("Irrigation [TIMEFRAME]");	

	end
	end	

if day == VarDay1 or day == VarDay2 or day == VarDay3 or day == VarDay4 or day == VarDay5 or day == VarDay6 or day == VarDay7 
	then
	if logging >= 1 then
		if lang == 'Dutch' then
		print(os.date("-- Irrigatie ==> [TimeFrame] - Vandaag is het %A en aangemerkt als irrigatie dag"))
	else
	print(os.date("-- Irrigation ==> [TimeFrame] - Today is %A and it is a irrigation day"))

	end
	end
		if logging >= 2 then
		if lang == 'Dutch' then	
		print('-- Irrigatie ==> [TimeFrame] - Ingeroosterde dagen: '..VarDay1..'  '..VarDay2..'  '..VarDay3..'  '..VarDay4..'  '..VarDay5..'  '..VarDay6..'  '..VarDay7..'')
		else
		print('-- Irrigation ==> [TimeFrame] - Scheduled days are: '..VarDay1..'  '..VarDay2..'  '..VarDay3..'  '..VarDay4..'  '..VarDay5..'  '..VarDay6..'  '..VarDay7..'')

		end
	end
	
	if(uservariables['VarTimeFrame'] == 0) then
	commandArray['Variable:VarTimeFrame']= '1'
	end

else

	if logging >= 1 then
	if lang == 'Dutch' then
		print(os.date("-- Irrigatie ==> [TimeFrame] - Vandaag is het %A en niet aangemerkt als irrigatie dag"))
	else
		print(os.date("-- Irrigation ==> [TimeFrame] - Today is %A and isn't a scheduled irrigation day"))

	end
	end
	if logging >= 2 then
		if lang == 'Dutch' then
		print('-- Irrigatie ==> [TimeFrame] - Ingeroosterde dagen: '..VarDay1..'  '..VarDay2..'  '..VarDay3..'  '..VarDay4..'  '..VarDay5..'  '..VarDay6..'  '..VarDay7..'')
	else
		print('-- Irrigation ==> [TimeFrame] - Scheduled days are: '..VarDay1..'  '..VarDay2..'  '..VarDay3..'  '..VarDay4..'  '..VarDay5..'  '..VarDay6..'  '..VarDay7..'')

	end
	end
	
	if(uservariables['VarTimeFrame'] == 1) then
	commandArray['Variable:VarTimeFrame']= '0'
	end	
end

if month == VarMonth1 or month == VarMonth2	or month == VarMonth3 or month == VarMonth4 or month == VarMonth5 or month == VarMonth6 or month == VarMonth7 or month == VarMonth8 or month == VarMonth9 or month == VarMonth10 or month == VarMonth11 or month == VarMonth12
then
	if logging >= 1 then
	if lang == 'Dutch' then
		print(os.date("-- Irrigatie ==> [TimeFrame] - Vandaag is het een dag in %B, en deze maand is aangemerkt als irrigatie maand"))
	else
		print(os.date("-- Irrigation ==> [TimeFrame] - Today is a day in %B, and is scheduled for irrigation"))

	end
	end
	if logging >= 2 then
		if lang == 'Dutch' then
		print('-- Irrigatie ==> [TimeFrame] - Ingeroosterde maanden: '..VarMonth1..'  '..VarMonth2..'  '..VarMonth3..'  '..VarMonth4..'  '..VarMonth5..'  '..VarMonth6..'  '..VarMonth7..' '..VarMonth8..' '..VarMonth9..' '..VarMonth10..' '..VarMonth11..' '..VarMonth12..'')
	else
		print('-- Irrigation ==> [TimeFrame] - Scheduled months are: '..VarMonth1..'  '..VarMonth2..'  '..VarMonth3..'  '..VarMonth4..'  '..VarMonth5..'  '..VarMonth6..'  '..VarMonth7..' '..VarMonth8..' '..VarMonth9..' '..VarMonth10..' '..VarMonth11..' '..VarMonth12..'')

	end
	end
	
	if(uservariables['VarTimeFrameMon'] == 0) then
	commandArray['Variable:VarTimeFrameMon']= '1'
	end

else

	if logging >= 1 then
	if lang == 'Dutch' then
			print(os.date("-- Irrigatie ==> [TimeFrame] - Vandaag is het een dag in %B, en deze maand is niet aangemerkt als irrigatie maand"))
	else
			print(os.date("-- Irrigation ==> [TimeFrame] - Today is a day in %B, and isn't scheduled for irrigation"))

	end
	end
	if logging >= 2 then
		if lang == 'Dutch' then	
		print('-- Irrigatie ==> [TimeFrame] - Ingeroosterde maanden: '..VarMonth1..'  '..VarMonth2..'  '..VarMonth3..'  '..VarMonth4..'  '..VarMonth5..'  '..VarMonth6..'  '..VarMonth7..' '..VarMonth8..' '..VarMonth9..' '..VarMonth10..' '..VarMonth11..' '..VarMonth12..'')
	else
			print('-- Irrigation ==> [TimeFrame] - Scheduled months are: '..VarMonth1..'  '..VarMonth2..'  '..VarMonth3..'  '..VarMonth4..'  '..VarMonth5..'  '..VarMonth6..'  '..VarMonth7..' '..VarMonth8..' '..VarMonth9..' '..VarMonth10..' '..VarMonth11..' '..VarMonth12..'')

	end
	end
	
	if(uservariables['VarTimeFrameMon'] == 1) then
	commandArray['Variable:VarTimeFrameMon']= '0'
	end	
end		

--
-- **********************************************************
-- checking time of the day so irrigation may proceed 
-- **********************************************************
--

	if (time.hour >= 6) and (time.hour <= 11) then
		if  (uservariables['VarTimeOfDayCurrent'] ~= 0) then
				commandArray['Variable:VarTimeOfDayCurrent']= '0'
			end
	end

	if (time.hour >= 12) and (time.hour <= 19)then
		if (uservariables['VarTimeOfDayCurrent'] ~= 1) then
			commandArray['Variable:VarTimeOfDayCurrent']= '1'
		end	
	end

	if (time.hour >= 20) and (time.hour <= 23)then
		if (uservariables['VarTimeOfDayCurrent'] ~= 2) then
			commandArray['Variable:VarTimeOfDayCurrent']= '2'
		end
	end

	if (time.hour >= 0) and (time.hour <= 5)then
		if (uservariables['VarTimeOfDayCurrent'] ~= 3) then
			commandArray['Variable:VarTimeOfDayCurrent']= '3'
		end	
	end
	

	if (uservariables['VarTimeOfDayCurrent']) == tonumber (VarTimeOfDay) then
		if logging >= 1 then
		if lang == 'Dutch' then
		print("-- Irrigatie ==> [TimeFrame] - Dit dagdeel komt overeen met jouw voorkeurs dagdeel voor irrigatie")
		else
		print("-- Irrigation ==> [TimeFrame] - Time of the Day matches your desired irrigation value")

		end
		end
	if (uservariables['VarTimeCon']) == 0 then
	commandArray['Variable:VarTimeCon']= '1'
	end
end



if (uservariables['VarTimeOfDayCurrent']) ~= tonumber (VarTimeOfDay) then
		if logging >= 1 then
		if lang == 'Dutch' then
		print("-- Irrigatie ==> [TimeFrame] - Dit dagdeel komt niet overeen met jouw voorkeurs dagdeel")
		else
		print("-- Irrigation ==> [TimeFrame] - Time of the Day doesnt match your criteria.")

		end
		end
		if logging >= 2 then 	
		if lang == 'Dutch' then
		print('-- Irrigatie ==> [TimeFrame] - Programma wacht op het geschikte dagdeel')
		else
		print('-- Irrigation ==> [TimeFrame] - Waiting for the right Time of the Day')

		end
		end
	if (uservariables['VarTimeCon']) == 1 then
	commandArray['Variable:VarTimeCon']= '0'
	end
end

if logging >= 1 then
	print("--------------------------------------------------------------------------------------")
end
	if logging >= 1 then
		if lang == 'Dutch' then
		print("Irrigatie [PROGRAMMA]");	
	else
		print("Irrigation [Program]");	

	end
	end
	
--
-- **********************************************************
-- Giving the irrigation program a Go or NoGo
-- **********************************************************
--

if Buienradar == Yes then
	if (uservariables['VarTimeCon']) == 1
		and (uservariables['VarTimeFrame']) == 1
		and (uservariables['VarTimeFrameMon']) == 1 
		and (uservariables['VarWeatherCon']) == 1
		and (uservariables['VarMoistOnline']) == 1
		and (uservariables['VarMoistOnlineHum']) == 1		
		and (uservariables['VarMoistConTemp']) == 1
		and (uservariables['VarMoistOnlineHum']) == 1
		and (uservariables['VarBuienRadarCon']) == 1
		
	then
		if logging >= 1 then
		if lang == 'Dutch' then
		print("-- Irrigatie [Condities] ==> Alle condities lijken goed, en het irrigatie programma mag vervolgt worden")
		else
		print("-- Irrigation [Conditions] ==> All conditions seems to be okay, Irrigation may if needed continue program")

		end
		end
	if (uservariables['VarMayFollowProgram']) == 0 
    then
		commandArray['Variable:VarMayFollowProgram']= '1'
	end
	
	else
		if logging >= 1 then
		if lang == 'Dutch' then
		print("-- Irrigatie [Condities] ==> Niet alle condities lijken goed, en het irrigatie programma mag niet vervolgt worden")
		else
		print("-- Irrigation [Conditions] ==> Not all conditions seems to be okay, Irrigation may NOT continue program")

		end
		end
	if (uservariables['VarMayFollowProgram']) == 1 
    then
		commandArray['Variable:VarMayFollowProgram']= '0'
	end	
	end
else
	if (uservariables['VarTimeCon']) == 1
		and (uservariables['VarTimeFrame']) == 1
		and (uservariables['VarTimeFrameMon']) == 1 
		and (uservariables['VarWeatherCon']) == 1
		and (uservariables['VarMoistOnline']) == 1
		and (uservariables['VarMoistOnlineHum']) == 1		
		and (uservariables['VarMoistConTemp']) == 1
		and (uservariables['VarMoistOnlineHum']) == 1
		
	then
		if logging >= 1 then
		if lang == 'Dutch' then
		print("-- Irrigatie [Condities] ==> Alle condities lijken goed, en het irrigatie programma mag vervolgt worden")
		else
		print("-- Irrigation [Conditions] ==> All conditions seems to be okay, Irrigation may if needed continue program")

		end
		end
	if (uservariables['VarMayFollowProgram']) == 0 
    then
		commandArray['Variable:VarMayFollowProgram']= '1'
	end
	
	else
		if logging >= 1 then
		if lang == 'Dutch' then
		print("-- Irrigatie [Condities] ==> Niet alle condities lijken goed, en het irrigatie programma mag niet vervolgt worden")
		else
		print("-- Irrigation [Conditions] ==> Not all conditions seems to be okay, Irrigation may NOT continue program")

		end
		end
	if (uservariables['VarMayFollowProgram']) == 1 
    then
		commandArray['Variable:VarMayFollowProgram']= '0'
	end	
	end
end
	
--
-- **********************************************************
-- Irrigatie Program Active
-- **********************************************************
--

if (uservariables['VarMayFollowProgram']) == 1
	and (uservariables['VarProgramRun']) == 0
	and (uservariables['VarProgramOverride']) == 0
	and (uservariables['VarManOverrideCon']) == 0
	then 
if (uservariables['VarFollowsProgram']) == 0 then	
	commandArray['Variable:VarFollowsProgram']= '1'
		
end
		if logging >= 1 then
		if lang == 'Dutch' then
		print("-- Irrigatie [Programma] ==> Irrigatie Programma Geactiveerd...")
		print("-- Irrigatie [Programma] ==> Irrigatie pomp zal spoedig starten...")
		print("--------------------------------------------------------------------------------------")
		else
		print("-- Irrigation [Program] ==> Irrigation Program Activated.")
		print("-- Irrigation [Program] ==> Irrigation pump will start in a minute...")

		end
		end	
end
	
	

--
-- **********************************************************
-- Irrigatie stopped after a full runtime cycle
-- **********************************************************
--
if (uservariables['VarProgramRun']) == 1
	and (uservariables['VarProgramOverride']) == 1
then
	if logging >= 1 then
	if lang == 'Dutch' then
		print("-- Irrigatie [Programma] ==> Irrigatie Gestopt, Pomp heeft de maximale looptijd overschreden...")
		print("-- Irrigatie [Programma] ==> Wachten op een nieuwe TimeFrame...")
		print("--------------------------------------------------------------------------------------")
	else
		print("-- Irrigation [Program] ==> Irrigation Stopped, Maximum RunTime Exceeded...")
		print("-- Irrigation [Program] ==> Awaiting new TimeFrame...")

	end
	end
end

--
-- **********************************************************
-- New timeframe so irrigation reactivated
-- **********************************************************
--

if (uservariables['VarTimeCon']) == 0
	and (uservariables['VarMayFollowProgram']) == 0
	and (uservariables['VarProgramOverride']) == 1
	then 
if (uservariables['VarProgramOverride']) == 1 then	
	commandArray['Variable:VarProgramOverride']= '0'
		commandArray['Variable:VarProgramRun']= '0'
		
end
		if logging >= 1 then
		print("-- Irrigatie [Programma] ==> Irrigatie Programma Gereactiveerd...")
		print("--------------------------------------------------------------------------------------")
		end	
end


--
-- **********************************************************
-- Irrigatie stoppen, Regen Verwacht
-- **********************************************************
if Buienradar == 'Yes' then
local VarMaxRainFallAv = VarMaxRainFallPlus * 0.5 + VarMaxRainFall
if (uservariables['VarBuienRadarCon']) == 1 and (uservariables['VarProgramRun']) == 1 and RainPrediction >= tonumber (VarMaxRainFallAv)
	then 
if (uservariables['VarProgramOverride']) == 0 then	
	commandArray['Variable:VarProgramOverride']= '1'
	commandArray['Variable:VarMaxRunTime']= '-1000'
	commandArray['Variable:VarProgramRun']= '0'
	commandArray[VarPump]='Off'
	
		if logging == 1 then
		print("-- Irrigatie [Programma] ==> Irrigatie Programma gestopt, Regen Verwacht...")
		print("--------------------------------------------------------------------------------------")
		
end	
end
end
end
--]]
-- **********************************************************
-- Irrigatie stopped as the moist humidity exceed your desired value
-- **********************************************************
--

if smoistsensorHumidity >= tonumber (VarTarHum)
	and (uservariables['VarProgramRun']) == 1
	then 
if (uservariables['VarProgramOverride']) == 0 then	
	commandArray['Variable:VarProgramOverride']= '1'
	commandArray['Variable:VarMaxRunTime']= '-1000'
	commandArray['Variable:VarProgramRun']= '0'
	commandArray[VarPump]='Off'
end
		if logging >= 1 then
		if lang == 'Dutch' then
		print("-- Irrigatie [Programma] ==> Irrigatie Programma Gestopt, Grond vochtigheid heeft zijn maximale waarde behaald...")
		print("--------------------------------------------------------------------------------------")
		else
		print("-- Irrigation [Program] ==> Irrigation Program Stopped, Moist Humidity exceeded your desired value...")

		end
		end	
end 

--
-- **********************************************************
-- Irrigatie stoppen, Manual Override
-- **********************************************************
--

if otherdevices[VitManOverride] == 'On'
	and (uservariables['VarManOverrideCon']) == 0
	and (uservariables['VarProgramRun']) == 1
	then 
if (uservariables['VarProgramOverride']) == 0 then	
	commandArray['Variable:VarProgramOverride']= '1'
	commandArray['Variable:VarMaxRunTime']= '-1000'
	commandArray['Variable:VarProgramRun']= '0'
	commandArray[VarPump]='Off'
	commandArray['Variable:VarManOverrideCon']= '1'
end	
end

--
-- **********************************************************
-- Irrigatie stoppen, Manual Override
-- **********************************************************
--

if otherdevices[VitManOverride] == 'On'
	and (uservariables['VarManOverrideCon']) == 1
	then 
		if logging >= 1 then
		if lang == 'Dutch' then
		print("-- Irrigatie [Programma] ==> Irrigatie Programma Manueel gestopt!")
		print("--------------------------------------------------------------------------------------")	
		else
		print("-- Irrigation [Program] ==> Irrigation Program Stopped, Manual Override")

		end
		end 
end

if otherdevices[VitManOverride] == 'Off'
	and (uservariables['VarManOverrideCon']) == 1
	then 
if (uservariables['VarProgramOverride']) == 1 then	
	commandArray['Variable:VarProgramOverride']= '0'
	commandArray['Variable:VarMaxRunTime']= '-1000'
	commandArray['Variable:VarProgramRun']= '0'
	commandArray['Variable:VarFollowsProgram']= '0'
	commandArray['Variable:VarManOverrideCon']= '0'
	commandArray[VarPump]='Off'
	if logging >= 1 then 	
		if lang == 'Dutch' then
		print("-- Irrigatie [Programma] ==> Irrigatie Programma Gereactivated!")
		else
		print("-- Irrigation [Program] ==> Irrigation Program Reactivated, Manual Override OFF")

		end
		print("--------------------------------------------------------------------------------------")	
	end	
end	
end 

--
-- **********************************************************
-- Irrigatie Counter MaxRunTime and validate check
-- **********************************************************
--

--
-- Debug logging.
--
function debug(msg)

	if logging >= 1 then
		if lang == 'Dutch' then
		print('-- Irrigatie [DEBUG] ==> ' .. msg)
	else
		print('-- Irrigation [DEBUG] ==> ' .. msg)

	end
	end

end

--
-- Info logging.
--
function info(msg)

	if logging >= 1 then
	if lang == 'Dutch' then
		print('-- Irrigatie [Programma] ==> ' .. msg)
	else
		print('-- Irrigation [Program] ==> ' .. msg)

	end
	end

end

--
-- Error logging.
--
function error(msg)
	if logging >= 2 then
	if lang == 'Dutch' then
	print('-- Irrigatie [ERROR] ==> ' .. msg)
	else
	print('-- Irrigation [ERROR] ==> ' .. msg)

	end
	end
end

--
-- Validates the configuration
--
function validate() 

	result = true

	if not (uservariables['VarMaxRunTime']) then
		if lang == 'Dutch' then
		error('Gebruikers Variable [' .. VarMaxRunTime .. '] bestaat niet.')
		else
		error('User Variable [' .. VarMaxRunTime .. '] doesnt exist.')

		end
		result = false
	end
	
	if not otherdevices[VarPump] then
		if lang == 'Dutch' then
		error('Apparaat [' .. VarPump .. '] bestaat niet.')
		else
		error('Device [' .. VarPump .. '] doesnt exist.')

		end
		result = false
	end
	 
	if not (uservariables['VarFollowsProgram']) then
	if lang == 'Dutch' then
		error('Gebruikers Variable [' .. VarFollowsProgram .. '] bestaat niet.')
	else
		error('User Variable [' .. VarFollowsProgram .. '] doesnt exist.')

	end
	result = false
	end 


	return result

end

--
-- Tests if irrigation may start.
--
function may_update(VarIsPump)

	counter = (uservariables['VarMaxRunTime'])
	current_counter = counter
	
	-- set the counter.
	if VarIsPump and counter >= 0 then
		counter = math.min(1, counter + 1)
	elseif not VarIsPump and counter <= 0 then
		counter = math.max(VarMaxRunTime_off * -1, counter - 1)
	else
		counter = 0
	end

	if counter ~= current_counter then
		commandArray['Variable:VarMaxRunTime']= tostring(counter)
	end

	result = false
		
	if VarIsPump and counter >= 1 then
		result = true
	elseif not VarIsPump and math.abs(counter) >= VarMaxRunTime_off then
		result = true
	end
	
	return result

end

--
-- Start irrigation
--

function on_off(VarIsPump)

	update_allowed = may_update(VarIsPump)
if lang == 'Dutch' then
	info('Irrigatie Pomp = [' .. otherdevices[VarPump] .. ']')
else
	info('Irrigation Pump = [' .. otherdevices[VarPump] .. ']')

end
	if update_allowed then
		if otherdevices[VarPump] == 'Off' and VarIsPump then
 			commandArray[VarPump]='On'
			commandArray['Variable:VarFollowsProgram']= '0'
			commandArray['Variable:VarProgramRun']= '1'
		elseif (otherdevices[VarPump] == 'On' and not VarIsPump) then
 			commandArray[VarPump]='Off'
			commandArray['Variable:VarProgramOverride']= '1'
			
	end

end
end
--
-- Is Irrigatie  On.
--

function is_VarFollowsProgram_aan()

	result = false
	result = (uservariables['VarFollowsProgram'] == 1)
    return result
end
--
-- **********************************************************
-- Starting Irrigatie
-- **********************************************************
--
if validate() then
	on_off(is_VarFollowsProgram_aan())
end

	if logging >= 1 and (uservariables['VarMayFollowProgram']) == 0 
		and (uservariables['VarFollowsProgram']) == 0
		and (uservariables['VarProgramOverride']) == 0  
	then
	if lang == 'Dutch' then
		print("-- Irrigatie [Standby] ==> Irrigatie Programma op Standby.")
	else
		print("-- Irrigation [Standby] ==> Irrigation Program on Standby")

	end
	end
	
	if logging >= 1 and (uservariables['VarMayFollowProgram']) == 1 
		and (uservariables['VarFollowsProgram']) == 0
		and (uservariables['VarProgramOverride']) == 1  
	then
	if lang == 'Dutch' then
		print("-- Irrigatie [Standby] ==> Er is al geirrigeerd vandaag, Irrigatie Programma op Standby.")
	else
		print("-- Irrigation [Standby] ==> Already Irrigated today, Irrigation Program on Standby and awaiting new cycle")

	end
	end	

		if logging >= 1 then
		print("--------------------------------------------------------------------------------------")
	end
	
return commandArray
--[[
THE END!
-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-
--]]
Setup:
- RPi4 - Domo Stable / Aeotec Z-stick7 / PiHole Unbound Gemini
- RPi4 - PiHole / PiVPN Unbound Gemini
- Synology DS923+ / DS218j
- P1 Gas/Power, SmartGateway watermeter
- Fibaro switches, contacts, plugs, smoke/Co2 ect
- rootfs @ USB HDD
User avatar
Siewert308SW
Posts: 288
Joined: Monday 29 December 2014 15:47
Target OS: Raspberry Pi / ODroid
Domoticz version: Stable
Location: The Netherlands
Contact:

Re: [DIY] Garden irrigation and learning project

Post by Siewert308SW »

Version 0.6
- Optimized reset switches
- Added new UserVariable for be sure a irrigation cycle has complete ( VarProgramHasRun (type=integer, value=0) )
- Fixed some issues with Manual Override
- Added extra lines to show in log if you enabled manual override

Code: Select all

--[[

	script_time_irrigation.lua
	@author: Siewert Lameijer
	@since: 2015-06-30
	@version: 0.6 (BETA)
	@Garden Irrigation lua script 

Credits:
- Nicky Bulthuis -/- for the dusk sensor script
- Hans van der Heijden -/- for the IsItGonnaRain script
- anonymous user -/- for the "Reading weather station data" script
- dannybloe -/- for Humidity Control script
- And to all those who i forgot to mention

-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-

This script has the intention to control and maintain your garden soil humidity.
And is it is a hodgepodge of different scripts found on the Domoticz forum.

I wrote this script for my own little garden project and to beable to automate irrigation while i'm gone.
The topic can be found here: https://www.domoticz.com/forum/viewtopic.php?f=38&t=6904
Somehow it got out of hand and got big.
So i thought that maybe some of you could have a benefith of this.
Although the script is intended for irrigation.
You could adapt it for other projects.

I do assume that when you want to use this script you already have the knowhow of Lua and Domoticz.
As i won't explain the entire installation ;-)

The script does the following:
- It scraps WeatherUnderground data and processing it usable data
- It monitors buienradar (optional) to see if there are any showers upcoming 24hr
- It scraps temperature and humidity from your moist sensor and processing it usable data
- It lets you choose when (Day of the week, month and time of the day) to irrigate
- By an extensive Settings Menu you can set various settings to control when to irrigate
settings ranges from: Min/Max Temp, Min/Max Humidity pct, Amount of rain, wind, UV, day, month to stop or start irrigating.

The Hardware i use:
- DIY Garden irrigation piping as seen in the topic
- Washer 220v Watervalve 2-way
- KaKu ACM-3500-3 3-in-1 unit (controlling the 2 valves) 1 reserve for pond protector to scare the cats ;-)

This script is still in BETA as i just wrote it and haven't fully tested it.
Be aware that i'm not a coder and it's maybe the cleanest script ever, but who cares as it works ;-)  

I hope it can be of use to you and feel free to adapt it. 
Bug fixes, patches, and improvements are hapiliy accepted of course.
Same counts for LUA optimizations as this is the first time i wrote,copy/past a LUA script.
When i started this i didn't had a clue what i was doing ;-)

Siewert Lameijer

-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-

Necessities:

1x Virtual switch to be able to manual override the irrigation program (Manual Override)
1x Soil Moist & Humidity sensor
1x Active WeatherUnderground account
1x Switch to be able to control your waterpump/valve which is somehow wireless connected to domoticz
1x Garden with irrigation hardware xD

The following UserVariable have to be create:
- VarManOverride (type=integer, value=0)
- VarTimeCon (type=integer, value=0)
- VarWeatherCon (type=integer, value=0)
- VarTimeOfDayCurrent (type=integer, value=0)
- VarMayFollowProgram (type=integer, value=0)
- VarFollowsProgram (type=integer, value=0)
- VarMaxRunTime (type=integer, value=0)
- VarMoistOnline (type=integer, value=0)
- VarMoistOnlineHum (type=integer, value=0)
- VarMoistConTemp (type=integer, value=0)
- VarMoistConHum (type=integer, value=0)
- VarProgramOverride (type=integer, value=0)
- VarProgramRun (type=integer, value=0)
- VarTimeFrame (type=integer, value=0)
- VarManOverrideCon (type=integer, value=0)
- VarBuienRadarCon (type=integer, value=0)
- VarTimeFrameMon (type=integer, value=0)
- VarProgramHasRun (type=integer, value=0)

-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-

Changelog:

Version 0.6
- Optimized reset switches
- Added new UserVariable for be sure a irrigation cycle has complete ( VarProgramHasRun (type=integer, value=0) )
- Fixed some issues with Manual Override
- Added extra lines to show in log if you enabled manual override

Version 0.5
- Buienradar MaxRainFall changed, it is now a average of your desired max rain fall input to prevent the switch to flip flop
- Optimized Moist sensor script as it now triggers irrigation on a minimum value and shutsdown on a maximum value
- Added extra loggin option
- Added option to use Buienradar or not
- Added option to use Dutch or English translation

Version 0.4
- Changed Days, Months to text instead of numbers as input
- Optimized irrigation program ending and keeping it that until the next time schedule

Version 0.3
- Added Buienradar (IsItGonnaRain) script
- Optimized Max irrigation time script
- Clean some code
- Reorderd printed text

Version 0.2
- Added counter for Max irrigation time
- Added manual override
- Optimized WeatherUnderground scraping data
- Optimized Moist sensor scraping data
- Optimized user input Time Of The Day, Days and Months

Version 0.1
- Added WeatherUnderground and scraping data
- Added Moist sensor scraping Temp & Humidity data
- Added Moist sensor online check
- Added user input for Time Of The Day where irrigation may start
- Added user input for days and months where the irrigation may start
	
-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-
	



-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-
--]]

time = os.date("*t")
	commandArray = {}
--
-- **********************************************************
-- Settings Begin
-- **********************************************************
--

-- Set your desired language (English, Dutch) 
local lang = 'Dutch'

-- Lua script interval check, change the number 1 to every desired number in minutes

-- Logging: 
-- 0 = None 
-- 1 = Only critical
-- 2 = All
local logging = 2

--
-- **********************************************************
-- Location and minimum Rain Fall Variables For BuienRadar
-- **********************************************************
-- 

-- Do you want to use BuienRadar? Yes or No
local Buienradar = 'No' --(Dutch weather, rain prediction)

-- Set your location by adding Lat/Lon
local lat = '53.338023'
local lon = '6.303114'

-- Set your minimum rain fall for in a periode of 24hr 
local  VarMaxRainFall = '20'

--
-- **********************************************************
-- WeatherUnderGround Variables
-- **********************************************************
-- 
-- Name of your Weatherstation widget which contains humidity,uv,temp and pressure
local weatherstation = 'Barometer'

-- Name of your Weatherstation Wind widget
local wind = 'Wind'

-- Name of your Weatherstation Rain widget
local rain = 'Regenmeter'

-- Name of your Weatherstation UV widget
local uv = 'UV'

--
-- **********************************************************
-- Switches and Virtual Switches Variables
-- **********************************************************
--
-- Name of your manual override virtual switch
local VitManOverride = 'Irrigatie Manual Override'

-- Name of your irrigation switch for water valve/pump
local VarPump = 'Irrigatie 1 Check'

--
-- **********************************************************
-- Moist Sensor Variables
-- **********************************************************
-- 
-- Name of your Moist Sensor device
local MoistSensor = 'Vocht Sensor (border 1)'

-- Your target soil humidity percentage
local VarTarHum = '80'

-- Your minumim soil humidity percentage from which the irrigation will start
local VarMinHum = '55'

-- Your Minumum soil temperature, Lower won't trigger irrigation
local VarTarTempMin = '12'

-- Your Maximum soil temperature, Higher won't trigger irrigation
local VarTarTempMax = '25'

-- Amount of minuten/times we want to switch OFF irrigation after the program has started.		
local VarMaxRunTime_off = 60

--
-- **********************************************************
-- Day, Month and Time Variables
-- **********************************************************
--

-- Set your desired TimeOfDay for irrigation (Morning=0, Afternoon=1, Evening=2 or Night=3)
local VarTimeOfDay = '2'

-- Set your desired irrigation day, leave blank for no irrigation
-- Set Mon, Tue, Wed, Thu, Fri, Sat or Sun
local VarDay1 = 'Mon'

local VarDay2 = ''

local VarDay3 = 'Wed'

local VarDay4 = ''

local VarDay5 = 'Fri'

local VarDay6 = ''

local VarDay7 = 'Sun'

-- Set your desired irrigation month, leave blank for no irrigation, 
-- Set months like: Jan, Feb, Apr, May, Jun, Jul, Aug, Sep, ect ect
local VarMonth1 = ''

local VarMonth2 = ''

local VarMonth3 = ''

local VarMonth4 = 'Apr'

local VarMonth5 = 'May'

local VarMonth6 = 'Jun'

local VarMonth7 = 'Jul'

local VarMonth8 = 'Aug'

local VarMonth9 = 'Sep'

local VarMonth10 = ''

local VarMonth11 = ''

local VarMonth12 = ''

--
-- **********************************************************
-- Weather Variables
-- **********************************************************
-- 
-- Set your prefered max rain fall, higher won't trigger irrigation
local RainCurrent = '0'

-- Set your prefered minimum outside temperature for irrigation, Lower won't trigger irrigation
local WeatherTempMin = '13'

-- Set your prefered maximum outside temperature for irrigation, Higher won't trigger irrigation
local WeatherTempMax = '24'

-- Set your prefered maximum UV for irrigation, Higher won't trigger irrigation
local UVMax = '4'

-- Set your prefered max windspeed km/h, higher won't trigger irrigation
local WindSpeed = '50'

-- Set your prefered max windgust km/h, higher won't trigger irrigation
local WindGust = '150'


--
-- **********************************************************
-- Settings END
-- **********************************************************
--

--[[
-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-
                        Don't edit anything below this line or you could break the script!
-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-
--]]

--
-- **********************************************************
-- Irrigation Script Begin
-- **********************************************************
--

    week       = tonumber(os.date("%V"));
	month       = tostring(os.date("%b"));
    dayno       = tonumber(os.date("%d"));
    dayofweekno = tonumber(os.date("%w"));
    day       = tostring(os.date("%a"));
    hour       = tonumber(os.date("%H"));
    min       = tonumber(os.date("%M"));

	
local VarMaxRainFallPlus = VarMaxRainFall * 0.5 + VarMaxRainFall
local VarMaxRainFallAv = VarMaxRainFallPlus * 0.5 + VarMaxRainFall
local VarMaxRunTimeReset = VarMaxRunTime
--
-- **********************************************************
-- Scrapping Weather Data from WeatherUnderground
-- **********************************************************
--
 
--
-- Weatherstation data:
-- 

sWeatherTemp, sWeatherHumidity, sWeatherUV, sWeatherPressure, sWeatherUV2 = otherdevices_svalues[weatherstation]:match("([^;]+);([^;]+);([^;]+);([^;]+);([^;]+)")
sWeatherTemp = tonumber(sWeatherTemp);
sWeatherHumidity = tonumber(sWeatherHumidity);
sWeatherUV = tonumber(sWeatherUV);
sWeatherPressure = tonumber(sWeatherPressure);
sWeatherUV2 = tonumber(sWeatherUV2);


	if logging == 1 then
		print("--------------------------------------------------------------------------------------")
		if lang == 'Dutch' then
		print("-- Irrigatie [HET WEER]");
		print("-- Irrigatie ==> [WeerStation] - Temperatuur: " .. sWeatherTemp .. " ");
		else
		print("-- Irrigation [WEATHER]");
		print("-- Irrigation ==> [WeatherStation] - Temperature: " .. sWeatherTemp .. " ");

		end
	end
	
	if logging >= 2 then
		print("--------------------------------------------------------------------------------------")
		if lang == 'Dutch' then
		print("-- Irrigatie [HET WEER]");
		print("-- Irrigatie ==> [WeerStation] - Temperatuur: " .. sWeatherTemp .. " ");
		print("-- Irrigatie ==> [WeerStation] - Luchtvochtigheid: " .. sWeatherHumidity .. " ");
		print("-- Irrigatie ==> [WeerStation] - Barometer: " .. sWeatherPressure .. " ");
		else
		print("-- Irrigation [WEATHER]");
		print("-- Irrigation ==> [WeatherStation] - Temperature: " .. sWeatherTemp .. " ");
		print("-- Irrigation ==> [WeatherStation] - Humidity: " .. sWeatherHumidity .. " ");
		print("-- Irrigation ==> [WeatherStation] - Pressure: " .. sWeatherPressure .. " ");		

		end
	end	
	
--
-- 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);

	if logging == 1 then
		if lang == 'Dutch' then
		print("-- Irrigatie ==> [Windmeter] - Windsnelheid: " .. sWindSpeed .. " ");
		print("-- Irrigatie ==> [Windmeter] - Windvlaag: " .. sWindGust .. " ");
		else
		print("-- Irrigation ==> [Windmeter] - Windspeed is: " .. sWindSpeed .. " ");
		print("-- Irrigation ==> [Windmeter] - Windgust is: " .. sWindGust .. " ");

		end
	end
	
	if logging >= 2 then
		if lang == 'Dutch' then
		print("-- Irrigatie ==> [Windmeter] - Windrichting (in graden): " .. sWindDirectionDegrees .. " ");
		print("-- Irrigatie ==> [Windmeter] - Windrichting: " .. sWindDirection .. " ");
		print("-- Irrigatie ==> [Windmeter] - Windsnelheid: " .. sWindSpeed .. " ");
		print("-- Irrigatie ==> [Windmeter] - Windvlaag: " .. sWindGust .. " ");
		print("-- Irrigatie ==> [Windmeter] - Windtemperatuur: " .. sWindTemperature .. " ");
		print("-- Irrigatie ==> [Windmeter] - Gevoelstemperatuur: " .. sWindFeel .. " ");
		else
		print("-- Irrigation ==> [Windmeter] - Winddirection (in degrees) is: " .. sWindDirectionDegrees .. " ");
		print("-- Irrigation ==> [Windmeter] - Winddirection is: " .. sWindDirection .. " ");
		print("-- Irrigation ==> [Windmeter] - Windspeed is: " .. sWindSpeed .. " ");
		print("-- Irrigation ==> [Windmeter] - Windgust is: " .. sWindGust .. " ");
		print("-- Irrigation ==> [Windmeter] - Windtemperature is: " .. sWindTemperature .. " ");
		print("-- Irrigation ==> [Windmeter] - Windfeel is: " .. sWindFeel .. " ");

		end
	end
		
	
--
-- Rainmeter data:
-- 

sRainmeterCurrent, sRainmeterTotal = otherdevices_svalues[rain]:match("([^;]+);([^;]+)")
 
sRainmeterCurrent = tonumber(sRainmeterCurrent);
sRainmeterTotal = tonumber(sRainmeterTotal);

	if logging == 1 then
		if lang == 'Dutch' then
		print("-- Irrigatie ==> [Regenmeter] - Regenval nu: " .. sRainmeterCurrent .. " ");
		print("-- Irrigatie ==> [Regenmeter] - Totale Regenval: " .. sRainmeterTotal .. " ");
		else
		print("-- Irrigation ==> [Rainmeter] - Actual rain is: " .. sRainmeterCurrent .. " ");
		print("-- Irrigation ==> [Rainmeter] - Total rain is: " .. sRainmeterTotal .. " ");

		end
	end
	
	
--
-- UV data:
-- 

sUV, sSolar = otherdevices_svalues[uv]:match("([^;]+);([^;]+)")
 
sUV = tonumber(sUV);
sSolar = tonumber(sSolar);

	if logging >= 1 then
	if lang == 'Dutch' then
		print("-- Irrigatie ==> [UV] - UV Sterkte: " .. sUV .." ");
	else
		print("-- Irrigation ==> [UV] - UV Strength is: " .. sUV .." ");

	end
	end

if  sRainmeterCurrent >= tonumber (RainCurrent)
	and sWeatherTemp >= tonumber (WeatherTempMin)
	and sWeatherTemp <= tonumber (WeatherTempMax)
	and sUV <= tonumber (UVMax)
	and sWindSpeed <= tonumber (WindSpeed)
	and sWindGust <= tonumber (WindGust)
then

	if logging >= 1 then
	if lang == 'Dutch' then
		print("-- Irrigatie ==> [HET WEER] - Weer conditie lijkt goed om te irrigeren");
	else
		print("-- Irrigation ==> [WEATHER] - Weather conditions are looking good and ready for irrigation");

	end
	end
	
	if(uservariables['VarWeatherCon'] == 0) then
	commandArray['Variable:VarWeatherCon']= '1'
    end
	
else

	if logging >= 1 then
	if lang == 'Dutch' then
		print("-- Irrigatie [INFO] ==> Weer conditie lijkt niet goed voor irrigatie");
	else
		print("-- Irrigation [INFO] ==> Weather conditions aren't good for irrigation");

	end
	end
	if(uservariables['VarWeatherCon'] == 1) then
	commandArray['Variable:VarWeatherCon']= '0'
	end	
end

if logging >= 1 then
	print("--------------------------------------------------------------------------------------")
end
	
--
-- **********************************************************
-- Scrapping Temparature and moist humidity from moist sensor
-- **********************************************************
--

--
-- Moist Sensor data:
-- 

    smoistsensorTemp, smoistsensorHumidity = otherdevices_svalues[MoistSensor]:match("([^;]+);([^;]+);([^;]+)")
    smoistsensorTemp = tonumber(smoistsensorTemp);
    smoistsensorHumidity = tonumber(smoistsensorHumidity);

	if logging >= 1 then
	if lang == 'Dutch' then
		print("-- Irrigatie [GROND CONDITIE]");
		print("-- Irrigatie ==> [VochtSensor] - Grond Temperatuur: " .. smoistsensorTemp .. " ");
		print("-- Irrigatie ==> [VochtSensor] - Grond Vochtigheid: " .. smoistsensorHumidity .. " ");
	else
		print("-- Irrigation [SOIL CONDITION]");
		print("-- Irrigation ==> [MoistSensor] - Soil Temperature: " .. smoistsensorTemp .. " ");
		print("-- Irrigation ==> [MoistSensor] - Soil Humidity: " .. smoistsensorHumidity .. " ");

	end	
	end
	
--
-- **********************************************************
-- Moist Sensor online check
-- **********************************************************
--	

if (smoistsensorTemp == 0 or smoistsensorTemp == nil) then
	if logging >= 1 then
	if lang == 'Dutch' then
    print('-- Irrigatie ==> [VochtSensor] - [ERROR] Vocht sensor geeft een temperatuur aan van 0 of nil, irrigatie word gestaakt')
	else
    print('-- Irrigation ==> [MoistSensor] - [ERROR] Moist Sensor reports Temp is 0 or nil. Skipping Irrigation')

	end
	end
	if(uservariables['VarMoistOnline'] == 1) then	
	commandArray['Variable:VarMoistOnline']= '0'
	end
		else
	if(uservariables['VarMoistOnline'] == 0) then		
	commandArray['Variable:VarMoistOnline']= '1'
	end
end

if (smoistsensorHumidity <= 6 or smoistsensorHumidity >= 99 or smoistsensorHumidity == nil) then
	if logging >= 1 then
	if lang == 'Dutch' then
    print('-- Irrigatie ==> [VochtSensor] - [Error] ==> Vocht sensor geeft een verkeerde vochtigheids waarde aan,, irrigatie word gestaakt')
	else
    print('-- Irrigation ==> [MoistSensor] - [Error] ==> Moist Sensor reports wrong Humidity values. Skipping Irrigation')

	end
	end
	if(uservariables['VarMoistOnlineHum'] == 1) then	
	commandArray['Variable:VarMoistOnlineHum']= '0'
	end
		else
	if(uservariables['VarMoistOnlineHum'] == 0) then		
	commandArray['Variable:VarMoistOnlineHum']= '1'
	end
end

--
-- **********************************************************
-- Checking Grond Temperature Conditions
-- **********************************************************
--

if 	smoistsensorTemp >= tonumber (VarTarTempMin)
	and smoistsensorTemp <= tonumber (VarTarTempMax)
then

	if logging >= 1 then
	if lang == 'Dutch' then
		print("-- Irrigatie ==> [VochtSensor] - Grond temperatuur is goed voor irrigatie");
	else
		print("-- Irrigation ==> [MoistSensor] - Soil Temp conditions are fine for irrigation");

	end	
	end
	if(uservariables['VarMoistConTemp'] == 0) then
	commandArray['Variable:VarMoistConTemp']= '1'
	end
	
else
	if logging >= 1 then
	if lang == 'Dutch' then
	print("-- Irrigatie ==> [VochtSensor] - Grond temperatuur is niet goed voor irrigatie");
	else
	print("-- Irrigation ==> [MoistSensor] - Soil Temp conditions aren't good for irrigation");

	end
	end
	if(uservariables['VarMoistConTemp'] == 1) then
	commandArray['Variable:VarMoistConTemp']= '0'
	end
end

if 	smoistsensorTemp <= tonumber (VarTarTempMin)

then

	if logging >= 2 then
	if lang == 'Dutch' then
		print("-- Irrigatie ==> [VochtSensor] - Grond temperatuur is te laag...");
	else
		print("-- Irrigation ==> [MoistSensor] - Soil Temp is to low...");

	end
	end
end

if 	smoistsensorTemp >= tonumber (VarTarTempMax)

then

	if logging >= 2 then
	if lang == 'Dutch' then
		print("-- Irrigatie ==> [VochtSensor] - Grond temperatuur is te hoog...");
	else
		print("-- Irrigation ==> [MoistSensor] - Soil Temp is to high...");

	end	
	end
end

--
-- **********************************************************
-- Checking Grond Humidity Conditions
-- **********************************************************
--

if smoistsensorHumidity >= tonumber (VarMinHum) or smoistsensorHumidity <= tonumber (VarTarHum) or smoistsensorHumidity >= tonumber (VarTarHum)
then

	if logging >= 1 then
	if lang == 'Dutch' then
		print("-- Irrigatie ==> [VochtSensor] - Grond vochtigheid is goed, geen irrigatie nodig");
	else
		print("-- Irrigation ==> [MoistSensor] - Soil humidity is fine and doesn't need irrigation");

    end	
	end
	if(uservariables['VarMoistConHum'] == 1) then
	commandArray['Variable:VarMoistConHum']= '0'
	end
end


if smoistsensorHumidity <= tonumber (VarMinHum)
then

	if logging >= 2 then
	if lang == 'Dutch' then
		print("-- Irrigatie ==> [VochtSensor] - Grond is droog...");
	else
		print("-- Irrigation ==> [MoistSensor] - Soil is dry...");

	end	
	end
	if(uservariables['VarMoistConHum'] == 0) then
	commandArray['Variable:VarMoistConHum']= '1'
	end	
end

if smoistsensorHumidity >= tonumber (VarTarHum)
then

	if logging >= 2 then
	if lang == 'Dutch' then
		print("-- Irrigatie ==> [VochtSensor] - Grond is nat...");
	else
		print("-- Irrigation ==> [MoistSensor] - Soil is wet...");

	end
	end
end

		
--
-- **********************************************************
-- Checking Buienradar 
-- **********************************************************
--
if Buienradar == 'Yes' then

	if logging >= 1 then
		print("--------------------------------------------------------------------------------------")
		print("-- Irrigatie [BUIENRADAR]");	
	end	
	

    tempfilename = '/var/tmp/rain.tmp'
    totalrain = 0
    rainlines = 0	
	
	
   function IsItGonnaRain( minutesinfuture )
       url='http://gps.buienradar.nl/getrr.php?lat='..lat..'&lon='..lon
       read = os.execute('curl -s -o '..tempfilename..' "'..url..'"')
       file = io.open(tempfilename, "r")

       while true do
          line = file:read("*line")
          if not line then break end
          linetime=string.sub(tostring(line), 5, 9)
          linetime2 = os.time{year=os.date('%Y'), month=os.date('%m'), day=os.date('%d'), hour=string.sub(linetime,1,2), min=string.sub(linetime,4,5), sec=os.date('%S')}
          difference = os.difftime (linetime2,os.time())

          if ((difference > 0) and (difference<=minutesinfuture*60)) then
             rain=tonumber(string.sub(tostring(line), 0, 3))
             totalrain = totalrain+rain
             rainlines=rainlines+1
          end

       end
       file:close()
       
       averagerain=totalrain/rainlines
       return(averagerain)
    end

    function round(num, idp)
       local mult = 10^(idp or 0)
       return math.floor(num * mult + 0.5) / mult
    end

--
-- **********************************************************
-- Is it gonna rain for the upcoming 24hr YES/NO
-- **********************************************************
--

       minutes=1440
       RainPrediction = IsItGonnaRain(minutes)
       RainmmHour=10^((RainPrediction-109)/32)

       if RainPrediction >= tonumber (VarMaxRainFallPlus) then
          verw = 3
		  if (uservariables['VarBuienRadarCon']) == 1  then
		  commandArray['Variable:VarBuienRadarCon']= '0'
		  end
		  if logging >= 1 then  
			print('-- Irrigatie ==> [REGEN] - Verwacht '..RainPrediction..' binnen 24 uur.')
		  end
       else
          verw = 2

		  if (uservariables['VarBuienRadarCon']) == 0  then
		  commandArray['Variable:VarBuienRadarCon']= '1'
		  end
		  if logging >= 1 then 
			print('-- Irrigatie ==> [REGEN] - Geen of weinig regen verwacht binnen 24 uur.')
		  end		  
       end
end	
	if logging >= 1 then
		print("--------------------------------------------------------------------------------------")
	end	
	
--
-- **********************************************************
-- Checking Time Frame 
-- **********************************************************
--

	if logging >= 1 then
	if lang == 'Dutch' then
		print("-- Irrigatie [TIMEFRAME]");	
	else
		print("-- Irrigation [TIMEFRAME]");	

	end
	end	

if day == VarDay1 or day == VarDay2 or day == VarDay3 or day == VarDay4 or day == VarDay5 or day == VarDay6 or day == VarDay7 
	then
	if logging >= 1 then
		if lang == 'Dutch' then
		print(os.date("-- Irrigatie ==> [TimeFrame] - Vandaag is het %A en aangemerkt als irrigatie dag"))
	else
	print(os.date("-- Irrigation ==> [TimeFrame] - Today is %A and it is a irrigation day"))

	end
	end
		if logging >= 2 then
		if lang == 'Dutch' then	
		print('-- Irrigatie ==> [TimeFrame] - Ingeroosterde dagen: '..VarDay1..'  '..VarDay2..'  '..VarDay3..'  '..VarDay4..'  '..VarDay5..'  '..VarDay6..'  '..VarDay7..'')
		else
		print('-- Irrigation ==> [TimeFrame] - Scheduled days are: '..VarDay1..'  '..VarDay2..'  '..VarDay3..'  '..VarDay4..'  '..VarDay5..'  '..VarDay6..'  '..VarDay7..'')

		end
	end
	
	if(uservariables['VarTimeFrame'] == 0) then
	commandArray['Variable:VarTimeFrame']= '1'
	end

else

	if logging >= 1 then
	if lang == 'Dutch' then
		print(os.date("-- Irrigatie ==> [TimeFrame] - Vandaag is het %A en niet aangemerkt als irrigatie dag"))
	else
		print(os.date("-- Irrigation ==> [TimeFrame] - Today is %A and isn't a scheduled irrigation day"))

	end
	end
	if logging >= 2 then
		if lang == 'Dutch' then
		print('-- Irrigatie ==> [TimeFrame] - Ingeroosterde dagen: '..VarDay1..'  '..VarDay2..'  '..VarDay3..'  '..VarDay4..'  '..VarDay5..'  '..VarDay6..'  '..VarDay7..'')
	else
		print('-- Irrigation ==> [TimeFrame] - Scheduled days are: '..VarDay1..'  '..VarDay2..'  '..VarDay3..'  '..VarDay4..'  '..VarDay5..'  '..VarDay6..'  '..VarDay7..'')

	end
	end
	
	if(uservariables['VarTimeFrame'] == 1) then
	commandArray['Variable:VarTimeFrame']= '0'
	end	
end

if month == VarMonth1 or month == VarMonth2	or month == VarMonth3 or month == VarMonth4 or month == VarMonth5 or month == VarMonth6 or month == VarMonth7 or month == VarMonth8 or month == VarMonth9 or month == VarMonth10 or month == VarMonth11 or month == VarMonth12
then
	if logging >= 1 then
	if lang == 'Dutch' then
		print(os.date("-- Irrigatie ==> [TimeFrame] - Vandaag is het een dag in %B, en deze maand is aangemerkt als irrigatie maand"))
	else
		print(os.date("-- Irrigation ==> [TimeFrame] - Today is a day in %B, and is scheduled for irrigation"))

	end
	end
	if logging >= 2 then
		if lang == 'Dutch' then
		print('-- Irrigatie ==> [TimeFrame] - Ingeroosterde maanden: '..VarMonth1..'  '..VarMonth2..'  '..VarMonth3..'  '..VarMonth4..'  '..VarMonth5..'  '..VarMonth6..'  '..VarMonth7..' '..VarMonth8..' '..VarMonth9..' '..VarMonth10..' '..VarMonth11..' '..VarMonth12..'')
	else
		print('-- Irrigation ==> [TimeFrame] - Scheduled months are: '..VarMonth1..'  '..VarMonth2..'  '..VarMonth3..'  '..VarMonth4..'  '..VarMonth5..'  '..VarMonth6..'  '..VarMonth7..' '..VarMonth8..' '..VarMonth9..' '..VarMonth10..' '..VarMonth11..' '..VarMonth12..'')

	end
	end
	
	if(uservariables['VarTimeFrameMon'] == 0) then
	commandArray['Variable:VarTimeFrameMon']= '1'
	end

else

	if logging >= 1 then
	if lang == 'Dutch' then
			print(os.date("-- Irrigatie ==> [TimeFrame] - Vandaag is het een dag in %B, en deze maand is niet aangemerkt als irrigatie maand"))
	else
			print(os.date("-- Irrigation ==> [TimeFrame] - Today is a day in %B, and isn't scheduled for irrigation"))

	end
	end
	if logging >= 2 then
		if lang == 'Dutch' then	
		print('-- Irrigatie ==> [TimeFrame] - Ingeroosterde maanden: '..VarMonth1..'  '..VarMonth2..'  '..VarMonth3..'  '..VarMonth4..'  '..VarMonth5..'  '..VarMonth6..'  '..VarMonth7..' '..VarMonth8..' '..VarMonth9..' '..VarMonth10..' '..VarMonth11..' '..VarMonth12..'')
	else
			print('-- Irrigation ==> [TimeFrame] - Scheduled months are: '..VarMonth1..'  '..VarMonth2..'  '..VarMonth3..'  '..VarMonth4..'  '..VarMonth5..'  '..VarMonth6..'  '..VarMonth7..' '..VarMonth8..' '..VarMonth9..' '..VarMonth10..' '..VarMonth11..' '..VarMonth12..'')

	end
	end
	
	if(uservariables['VarTimeFrameMon'] == 1) then
	commandArray['Variable:VarTimeFrameMon']= '0'
	end	
end		

--
-- **********************************************************
-- checking time of the day so irrigation may proceed 
-- **********************************************************
--

	if (time.hour >= 6) and (time.hour <= 11) then
		if  (uservariables['VarTimeOfDayCurrent'] ~= 0) then
				commandArray['Variable:VarTimeOfDayCurrent']= '0'
			end
	end

	if (time.hour >= 12) and (time.hour <= 19)then
		if (uservariables['VarTimeOfDayCurrent'] ~= 1) then
			commandArray['Variable:VarTimeOfDayCurrent']= '1'
		end	
	end

	if (time.hour >= 20) and (time.hour <= 23)then
		if (uservariables['VarTimeOfDayCurrent'] ~= 2) then
			commandArray['Variable:VarTimeOfDayCurrent']= '2'
		end
	end

	if (time.hour >= 0) and (time.hour <= 5)then
		if (uservariables['VarTimeOfDayCurrent'] ~= 3) then
			commandArray['Variable:VarTimeOfDayCurrent']= '3'
		end	
	end
	

	if (uservariables['VarTimeOfDayCurrent']) == tonumber (VarTimeOfDay) then
		if logging >= 1 then
		if lang == 'Dutch' then
		print("-- Irrigatie ==> [TimeFrame] - Dit dagdeel komt overeen met jouw voorkeurs dagdeel voor irrigatie")
		else
		print("-- Irrigation ==> [TimeFrame] - Time of the Day matches your desired irrigation value")

		end
		end
	if (uservariables['VarTimeCon']) == 0 then
	commandArray['Variable:VarTimeCon']= '1'
	end
end



if (uservariables['VarTimeOfDayCurrent']) ~= tonumber (VarTimeOfDay) then
		if logging >= 1 then
		if lang == 'Dutch' then
		print("-- Irrigatie ==> [TimeFrame] - Dit dagdeel komt niet overeen met jouw voorkeurs dagdeel")
		else
		print("-- Irrigation ==> [TimeFrame] - Time of the Day doesnt match your criteria")

		end
		end
		if logging >= 2 then 	
		if lang == 'Dutch' then
		print('-- Irrigatie ==> [TimeFrame] - Programma wacht op het geschikte dagdeel')
		else
		print('-- Irrigation ==> [TimeFrame] - Waiting for the right Time of the Day')

		end
		end
	if (uservariables['VarTimeCon']) == 1 then
	commandArray['Variable:VarTimeCon']= '0'
	end
end

if logging >= 1 then
	print("--------------------------------------------------------------------------------------")
end
	if logging >= 1 then
		if lang == 'Dutch' then
		print("-- Irrigatie [Programma]");	
	else
		print("-- Irrigation [Program]");	

	end
	end
	
--
-- **********************************************************
-- Giving the irrigation program a Go or NoGo
-- **********************************************************
--
if Buienradar == 'Yes' then

	if (uservariables['VarTimeCon']) == 1
		and (uservariables['VarTimeFrame']) == 1
		and (uservariables['VarTimeFrameMon']) == 1 
		and (uservariables['VarWeatherCon']) == 1
		and (uservariables['VarMoistOnline']) == 1
		and (uservariables['VarMoistOnlineHum']) == 1		
		and (uservariables['VarMoistConTemp']) == 1
		and (uservariables['VarMoistOnlineHum']) == 1
		and (uservariables['VarBuienRadarCon']) == 1
		and (uservariables['VarManOverrideCon']) == 0		
	then
		if logging >= 1 then
		if lang == 'Dutch' then
		print("-- Irrigatie [Condities] ==> Alle condities lijken goed, en het irrigatie programma mag vervolgt worden")
		else
		print("-- Irrigation [Conditions] ==> All conditions seems to be okay, Irrigation may if needed continue program")
		end
		end

	if (uservariables['VarMayFollowProgram']) == 0 
    then
		commandArray['Variable:VarMayFollowProgram']= '1'
	end
	
	else
		if logging >= 1 then
		if lang == 'Dutch' then
		print("-- Irrigatie [Condities] ==> Niet alle condities lijken goed, en het irrigatie programma mag niet vervolgt worden")
		else
		print("-- Irrigation [Conditions] ==> Not all conditions seems to be okay, Irrigation may NOT continue program")
		end
		end
	if (uservariables['VarMayFollowProgram']) == 1 
    then
		commandArray['Variable:VarMayFollowProgram']= '0'
	end	
	end
	
else

	if (uservariables['VarTimeCon']) == 1
		and (uservariables['VarTimeFrame']) == 1
		and (uservariables['VarTimeFrameMon']) == 1 
		and (uservariables['VarWeatherCon']) == 1
		and (uservariables['VarMoistOnline']) == 1
		and (uservariables['VarMoistOnlineHum']) == 1		
		and (uservariables['VarMoistConTemp']) == 1
		and (uservariables['VarMoistOnlineHum']) == 1
		and (uservariables['VarManOverrideCon']) == 0		
	then
		if logging >= 1 then
		if lang == 'Dutch' then
		print("-- Irrigatie [Condities] ==> Alle condities lijken goed, en het irrigatie programma mag vervolgt worden")
		else
		print("-- Irrigation [Conditions] ==> All conditions seems to be okay, Irrigation may if needed continue program")
		end
		end

	if (uservariables['VarMayFollowProgram']) == 0 
    then
		commandArray['Variable:VarMayFollowProgram']= '1'
	end
	
	else
		if logging >= 1 then
		if lang == 'Dutch' then
		print("-- Irrigatie [Condities] ==> Niet alle condities lijken goed, en het irrigatie programma mag niet vervolgt worden")
		else
		print("-- Irrigation [Conditions] ==> Not all conditions seems to be okay, Irrigation may NOT continue program")
		end
		end
	if (uservariables['VarMayFollowProgram']) == 1 
    then
		commandArray['Variable:VarMayFollowProgram']= '0'
	end	
	end

end

	
--
-- **********************************************************
-- Irrigatie Program Active
-- **********************************************************
--

if (uservariables['VarMayFollowProgram']) == 1
	and (uservariables['VarProgramRun']) == 0
	and (uservariables['VarProgramOverride']) == 0
	and (uservariables['VarManOverrideCon']) == 0
	then 

	commandArray['Variable:VarFollowsProgram']= '1'

		if logging >= 1 then
		if lang == 'Dutch' then
		print("-- Irrigatie [Programma] ==> Irrigatie Programma Geactiveerd...")
		print("-- Irrigatie [Programma] ==> Irrigatie pomp zal spoedig starten...")
		print("--------------------------------------------------------------------------------------")
		else
		print("-- Irrigation [Program] ==> Irrigation Program Activated")
		print("-- Irrigation [Program] ==> Irrigation pump will start in a minute...")

		end
		end	
end
	
	

--
-- **********************************************************
-- Irrigatie stopped after a full runtime cycle
-- **********************************************************
--
if (uservariables['VarProgramRun']) == 1
	and (uservariables['VarProgramOverride']) == 1
	and (uservariables['VarManOverrideCon']) == 0
then
	if logging >= 1 then
	if lang == 'Dutch' then
		print("-- Irrigatie [Programma] ==> Irrigatie Gestopt, Pomp heeft de maximale looptijd overschreden...")
		print("-- Irrigatie [Programma] ==> Wachten op een nieuwe TimeFrame...")
		print("--------------------------------------------------------------------------------------")
	else
		print("-- Irrigation [Program] ==> Irrigation Stopped, Maximum RunTime Exceeded...")
		print("-- Irrigation [Program] ==> Awaiting new TimeFrame...")

	end
	end
end

--
-- **********************************************************
-- New timeframe so irrigation reactivated
-- **********************************************************
--

if (uservariables['VarTimeCon']) == 0
	and (uservariables['VarProgramOverride']) == 1
	and (uservariables['VarProgramHasRun']) == 1
	and (uservariables['VarManOverrideCon']) == 0
	then 	
	commandArray['Variable:VarProgramOverride']= '0'
	commandArray['Variable:VarProgramRun']= '0'
	commandArray['Variable:VarProgramHasRun']= '0'
		

		if logging >= 1 then
		if lang == 'Dutch' then
		print("-- Irrigatie [Programma] ==> Irrigatie Programma Gereactiveerd...")
		else
		print("-- Irrigatie [Program] ==> Irrigation Program Reactivated...")
		end
		print("--------------------------------------------------------------------------------------")
		end	
end

if (uservariables['VarTimeCon']) == 0
	and (uservariables['VarProgramOverride']) == 1
	and (uservariables['VarProgramHasRun']) == 0
	and (uservariables['VarManOverrideCon']) == 0
	then 	
	commandArray['Variable:VarProgramOverride']= '0'
	commandArray['Variable:VarProgramRun']= '0'
	commandArray['Variable:VarProgramHasRun']= '0'
		
		if logging >= 1 then
		if lang == 'Dutch' then
		print("-- Irrigatie [Programma] ==> Irrigatie Programma Gereactiveerd...")
		else
		print("-- Irrigatie [Program] ==> Irrigation Program Reactivated...")
		end
		print("--------------------------------------------------------------------------------------")
		end	
end


--
-- **********************************************************
-- Irrigatie stoppen, Regen Verwacht
-- **********************************************************
if Buienradar == 'Yes' then
if (uservariables['VarBuienRadarCon']) == 1 and (uservariables['VarProgramRun']) == 1 and RainPrediction >= tonumber (VarMaxRainFallAv) and (uservariables['VarManOverrideCon']) == 0
	then 
if (uservariables['VarProgramOverride']) == 0 then	
	commandArray['Variable:VarProgramOverride']= '1'
	commandArray['Variable:VarMaxRunTime']= VarMaxRunTimeReset
	commandArray['Variable:VarProgramRun']= '0'
	commandArray[VarPump]='Off'
	
		if logging == 1 then
		print("-- Irrigatie [Programma] ==> Irrigatie Programma gestopt, Regen Verwacht...")
		print("--------------------------------------------------------------------------------------")
		
end	
end
end
end
--]]
-- **********************************************************
-- Irrigatie stopped as the moist humidity exceed your desired value
-- **********************************************************
--

if smoistsensorHumidity >= tonumber (VarTarHum)
	and (uservariables['VarProgramRun']) == 1 and (uservariables['VarManOverrideCon']) == 0
	then 
	commandArray['Variable:VarProgramOverride']= '1'
	commandArray['Variable:VarMaxRunTime']= VarMaxRunTimeReset
	commandArray['Variable:VarProgramRun']= '0'
	commandArray['Variable:VarProgramHasRun']= '1'
	commandArray[VarPump]='Off'

		if logging >= 1 then
		if lang == 'Dutch' then
		print("-- Irrigatie [Programma] ==> Irrigatie Programma Gestopt, Grond vochtigheid heeft zijn maximale waarde behaald...")
		print("--------------------------------------------------------------------------------------")
		else
		print("-- Irrigation [Program] ==> Irrigation Program Stopped, Moist Humidity exceeded your desired value...")

		end
		end	
end 

--
-- **********************************************************
-- Irrigatie stoppen, Manual Override
-- **********************************************************
--

if otherdevices[VitManOverride] == 'On'
	and (uservariables['VarManOverrideCon']) == 0
	then 
	commandArray['Variable:VarProgramOverride']= '1'
	commandArray['Variable:VarMaxRunTime']= VarMaxRunTimeReset
	commandArray['Variable:VarProgramRun']= '0'
	commandArray[VarPump]='Off'
	commandArray['Variable:VarManOverrideCon']= '1'	
end

--
-- **********************************************************
-- Irrigatie stoppen, Manual Override
-- **********************************************************
--

if otherdevices[VitManOverride] == 'On'
	and (uservariables['VarManOverrideCon']) == 1
	then 
		if logging >= 1 then
		if lang == 'Dutch' then
		print("-- Irrigatie [Programma] ==> Irrigatie Programma Manueel gestopt!")
		print("--------------------------------------------------------------------------------------")	
		else
		print("-- Irrigation [Program] ==> Irrigation Program Stopped, Manual Override")

		end
		end 
end

if otherdevices[VitManOverride] == 'Off'
	and (uservariables['VarManOverrideCon']) == 1
	then 	
	commandArray['Variable:VarProgramOverride']= '0'
	commandArray['Variable:VarMaxRunTime']= VarMaxRunTimeReset
	commandArray['Variable:VarProgramRun']= '0'
	commandArray['Variable:VarFollowsProgram']= '0'
	commandArray['Variable:VarManOverrideCon']= '0'
	commandArray[VarPump]='Off'
	if logging >= 1 then 	
		if lang == 'Dutch' then
		print("-- Irrigatie [Programma] ==> Irrigatie Programma Gereactivated!")
		else
		print("-- Irrigation [Program] ==> Irrigation Program Reactivated, Manual Override OFF")

		end
		print("--------------------------------------------------------------------------------------")	
	end	
end 

--
-- **********************************************************
-- Irrigatie Counter MaxRunTime and validate check
-- **********************************************************
--

--
-- Debug logging.
--
function debug(msg)

	if logging >= 1 then
		if lang == 'Dutch' then
		print('-- Irrigatie [DEBUG] ==> ' .. msg)
	else
		print('-- Irrigation [DEBUG] ==> ' .. msg)

	end
	end

end

--
-- Info logging.
--
function info(msg)

	if logging >= 1 then
	if lang == 'Dutch' then
		print('-- Irrigatie [Programma] ==> ' .. msg)
	else
		print('-- Irrigation [Program] ==> ' .. msg)

	end
	end

end

--
-- Error logging.
--
function error(msg)
	if logging >= 2 then
	if lang == 'Dutch' then
	print('-- Irrigatie [ERROR] ==> ' .. msg)
	else
	print('-- Irrigation [ERROR] ==> ' .. msg)

	end
	end
end

--
-- Validates the configuration
--
function validate() 

	result = true

	if not (uservariables['VarMaxRunTime']) then
		if lang == 'Dutch' then
		error('Gebruikers Variable [' .. VarMaxRunTime .. '] bestaat niet.')
		else
		error('User Variable [' .. VarMaxRunTime .. '] doesnt exist.')

		end
		result = false
	end
	
	if not otherdevices[VarPump] then
		if lang == 'Dutch' then
		error('Apparaat [' .. VarPump .. '] bestaat niet.')
		else
		error('Device [' .. VarPump .. '] doesnt exist.')

		end
		result = false
	end
	 
	if not (uservariables['VarFollowsProgram']) then
	if lang == 'Dutch' then
		error('Gebruikers Variable [' .. VarFollowsProgram .. '] bestaat niet.')
	else
		error('User Variable [' .. VarFollowsProgram .. '] doesnt exist.')

	end
	result = false
	end 


	return result

end

--
-- Tests if irrigation may start.
--
function may_update(VarIsPump)

	counter = (uservariables['VarMaxRunTime'])
	current_counter = counter
	
	-- set the counter.
	if VarIsPump and counter >= 0 then
		counter = math.min(1, counter + 1)
	elseif not VarIsPump and counter <= 0 then
		counter = math.max(VarMaxRunTime_off * -1, counter - 1)
	else
		counter = 0
	end

	if counter ~= current_counter then
		commandArray['Variable:VarMaxRunTime']= tostring(counter)
	end

	result = false
		
	if VarIsPump and counter >= 1 then
		result = true
	elseif not VarIsPump and math.abs(counter) >= VarMaxRunTime_off then
		result = true
	end
	
	return result

end

--
-- Start irrigation
--

function on_off(VarIsPump)

	update_allowed = may_update(VarIsPump)
if lang == 'Dutch' then
	info('Irrigatie Pomp = [' .. otherdevices[VarPump] .. ']')
else
	info('Irrigation Pump = [' .. otherdevices[VarPump] .. ']')

end
	if update_allowed then
		if otherdevices[VarPump] == 'Off' and VarIsPump then
 			commandArray[VarPump]='On'
			commandArray['Variable:VarFollowsProgram']= '0'
			commandArray['Variable:VarProgramRun']= '1'
		elseif (otherdevices[VarPump] == 'On' and not VarIsPump) then
 			commandArray[VarPump]='Off'
			commandArray['Variable:VarProgramOverride']= '1'
			commandArray['Variable:VarProgramHasRun']= '1'
			
	end

end
end
--
-- Is Irrigatie  On.
--

function is_VarFollowsProgram_aan()

	result = false
	result = (uservariables['VarFollowsProgram'] == 1)
    return result
end
--
-- **********************************************************
-- Starting Irrigatie
-- **********************************************************
--
if validate() then
	on_off(is_VarFollowsProgram_aan())
end

	if(uservariables['VarProgramHasRun']) == 1
		and (uservariables['VarProgramOverride']) == 0  
	then
	if logging >= 1 then
	if lang == 'Dutch' then
		print("-- Irrigatie [Standby] ==> Irrigatie Programma op Standby")
	else
		print("-- Irrigation [Standby] ==> Irrigation Program on Standby")

	end
	end
	end
	
	if (uservariables['VarProgramOverride']) == 1 
		and (uservariables['VarProgramHasRun']) == 1 
	then
	if logging >= 1 then
	if lang == 'Dutch' then
		print("-- Irrigatie [Standby] ==> Er is al geirrigeerd vandaag, Irrigatie Programma op Standby")
	else
		print("-- Irrigation [Standby] ==> Already Irrigated today, Irrigation Program on Standby and awaiting new cycle")

	end
	end
	end	
	
		if (uservariables['VarProgramOverride']) == 0 
		and (uservariables['VarProgramHasRun']) == 0
		and (uservariables['VarMayFollowProgram']) == 0 
	then
if logging >= 1 then
	if lang == 'Dutch' then
		print("-- Irrigatie [Standby] ==> Irrigatie Programma op Standby")
	else
		print("-- Irrigation [Standby] ==> Irrigation Program on Standby")

	end
	end
	end	

		if logging >= 1 then
		print("--------------------------------------------------------------------------------------")
	end
	
return commandArray
--[[
THE END!
-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-
--]]
Setup:
- RPi4 - Domo Stable / Aeotec Z-stick7 / PiHole Unbound Gemini
- RPi4 - PiHole / PiVPN Unbound Gemini
- Synology DS923+ / DS218j
- P1 Gas/Power, SmartGateway watermeter
- Fibaro switches, contacts, plugs, smoke/Co2 ect
- rootfs @ USB HDD
User avatar
blackdog65
Posts: 311
Joined: Tuesday 17 June 2014 18:25
Target OS: Raspberry Pi / ODroid
Domoticz version:
Location: Norfolk, UK
Contact:

Re: [DIY] Garden irrigation and learning project

Post by blackdog65 »

Nice work!
I showed my wife your project and compared it to ours... she now wants to know if a PiCam can spot Greenfly and activate an insecticide sprayer :shock: I think she was joking :?

I've had pressure problems and thought it was all because I'm pumping water from a 2000L water butt and not from mains. So maybe it's really the valve to blame. I did think about using central heating motorised valves... but it then gets expensive
http://www.screwfix.com/p/flomasta-2790 ... alve/8982g
£45 each... and I need 4 eeeek!!! :o I'm glad I tried that green hose I showed you, it really works well.
CubieTruck Master
RasPi slaves
Aeon Labs Z-Stick, multi sensor
Fibaro Dimmers, relays, Universal sensors
EQ3 MAX!
TKB Sockets
RFXCOM
LightwaveRF sockets, switches, relays, doorbell
MySensors
ESPEasy ESP8266-12E
User avatar
Siewert308SW
Posts: 288
Joined: Monday 29 December 2014 15:47
Target OS: Raspberry Pi / ODroid
Domoticz version: Stable
Location: The Netherlands
Contact:

Re: [DIY] Garden irrigation and learning project

Post by Siewert308SW »

blackdog65 wrote:Nice work!
I showed my wife your project and compared it to ours... she now wants to know if a PiCam can spot Greenfly and activate an insecticide sprayer :shock: I think she was joking :?

I've had pressure problems and thought it was all because I'm pumping water from a 2000L water butt and not from mains. So maybe it's really the valve to blame. I did think about using central heating motorised valves... but it then gets expensive
http://www.screwfix.com/p/flomasta-2790 ... alve/8982g
£45 each... and I need 4 eeeek!!! :o I'm glad I tried that green hose I showed you, it really works well.
Thx...

Ha Ha... It could but needs a perfect and flawless recognition software :mrgreen:

What about a submersible pump and big enough to feed 4 hoses at the same time, or do you want to be able switch them separately?
Such a submersible pump cost less and has enough power.

8000l/h
https://www.conrad.nl/nl/renkforce-vuil ... 34026.html
Setup:
- RPi4 - Domo Stable / Aeotec Z-stick7 / PiHole Unbound Gemini
- RPi4 - PiHole / PiVPN Unbound Gemini
- Synology DS923+ / DS218j
- P1 Gas/Power, SmartGateway watermeter
- Fibaro switches, contacts, plugs, smoke/Co2 ect
- rootfs @ USB HDD
User avatar
blackdog65
Posts: 311
Joined: Tuesday 17 June 2014 18:25
Target OS: Raspberry Pi / ODroid
Domoticz version:
Location: Norfolk, UK
Contact:

Re: [DIY] Garden irrigation and learning project

Post by blackdog65 »

Hmmmm.... that's exactly the pump I have. It must have a valve of some type or it will syphon all the water over night when it's switched off. And it looks like the valve is the pressure limiter. Maybe the 2-port valve is the answer.

If I spend any more money on this... it would be cheaper to employ a Polish guy with a watering can :lol:
CubieTruck Master
RasPi slaves
Aeon Labs Z-Stick, multi sensor
Fibaro Dimmers, relays, Universal sensors
EQ3 MAX!
TKB Sockets
RFXCOM
LightwaveRF sockets, switches, relays, doorbell
MySensors
ESPEasy ESP8266-12E
User avatar
Siewert308SW
Posts: 288
Joined: Monday 29 December 2014 15:47
Target OS: Raspberry Pi / ODroid
Domoticz version: Stable
Location: The Netherlands
Contact:

Re: [DIY] Garden irrigation and learning project

Post by Siewert308SW »

blackdog65 wrote:Hmmmm.... that's exactly the pump I have. It must have a valve of some type or it will syphon all the water over night when it's switched off. And it looks like the valve is the pressure limiter. Maybe the 2-port valve is the answer.

If I spend any more money on this... it would be cheaper to employ a Polish guy with a watering can :lol:

LoL... Maybe i should call the Labor Office :lol:

I came home earlier due to the outside heat.
No way i'm going to be at a camping with 39 degrees, But i rebuild the irrigation this morning.
As the Valve was a 2way and i wanted to use one port for a different purpose when i started this project.

I now divide the 2 border sections.
Instead of 1 12mtr section with different tabs to each plant.
I now have 2 sections with different tabs to each plant.
1 section is 5mtr and the other 6mtr.
This solved my problem and now i do have enough pressure on both hoses.
Save me some more money to spent on a trail and error adventure ;)
Setup:
- RPi4 - Domo Stable / Aeotec Z-stick7 / PiHole Unbound Gemini
- RPi4 - PiHole / PiVPN Unbound Gemini
- Synology DS923+ / DS218j
- P1 Gas/Power, SmartGateway watermeter
- Fibaro switches, contacts, plugs, smoke/Co2 ect
- rootfs @ USB HDD
JacquesMulders
Posts: 33
Joined: Saturday 03 January 2015 22:05
Target OS: Raspberry Pi / ODroid
Domoticz version:
Location: The Netherlands
Contact:

Re: [DIY] Garden irrigation and learning project

Post by JacquesMulders »

Hi,

nice work!

I'm also making irrigation in my garden.

i've bin looking at your script, what a monster :oops: :D .

but how do you look if there is rain coming in the next 24 hours? buienradar only supplies coming 2 hours... when i use the link in your script...

keep up the good work!
User avatar
Siewert308SW
Posts: 288
Joined: Monday 29 December 2014 15:47
Target OS: Raspberry Pi / ODroid
Domoticz version: Stable
Location: The Netherlands
Contact:

Re: [DIY] Garden irrigation and learning project

Post by Siewert308SW »

JacquesMulders wrote:Hi,

nice work!

I'm also making irrigation in my garden.

i've bin looking at your script, what a monster :oops: :D .

but how do you look if there is rain coming in the next 24 hours? buienradar only supplies coming 2 hours... when i use the link in your script...

keep up the good work!
Thx...

As for buienradar, good question.
Never looked at how far Buienradar was sending data about upcoming rain.
Just had a look at what the script produced in the form of data.
And indeed, it only produces 2hr of info.
So 24hr is useless...
Have to think what i'm going to do with this script.

As for the irrigation script it self.
I'm completly rebuilding it.
There where/found some issues regarding overrides and the runmaxtime.
Couldn't find the culprit so rebuilding and testing every step to make sure it does work this time.
The issue is that in some cases the irrigation goes in a continues loop or after one cycle it will never turn on again.
Setup:
- RPi4 - Domo Stable / Aeotec Z-stick7 / PiHole Unbound Gemini
- RPi4 - PiHole / PiVPN Unbound Gemini
- Synology DS923+ / DS218j
- P1 Gas/Power, SmartGateway watermeter
- Fibaro switches, contacts, plugs, smoke/Co2 ect
- rootfs @ USB HDD
User avatar
Siewert308SW
Posts: 288
Joined: Monday 29 December 2014 15:47
Target OS: Raspberry Pi / ODroid
Domoticz version: Stable
Location: The Netherlands
Contact:

Re: [DIY] Garden irrigation and learning project

Post by Siewert308SW »

Rebuild and added some new features to the script...

Version 0.7
- Rewrote script due to a issue for which i couldn't find the culprit
- Reduced the amount of uservariables
- Some UserVariables have been renamed
- Fixed Soil Humidity scrap script
- Fixed MaxRunTime Counter
- Changed Buienradar prediction to 2hr as this is the max by Buienradar it self
- Optimized Manual pump start
- Optimized displayed text in log regarding the running program and it's doings
- Fixed program stop when target humidity has been reached
- Fixed TimeOfTheDay schedule
- Added counter to log to see how long the irrigation program is still active until shutdown
- Added code to check when the moist sensor was last seen, if longer then 10minuten then no irrigation

Code: Select all

--[[

   script_time_irrigation.lua
   @author: Siewert Lameijer
   @since: 2015-07-12
   @version: 0.7 (BETA)
   @Garden Irrigation lua script

Credits:
- Nicky Bulthuis -/- for the dusk sensor script
- Hans van der Heijden -/- for the IsItGonnaRain script
- anonymous user -/- for the "Reading weather station data" script
- dannybloe -/- for Humidity Control script
- And to all those who i forgot to mention

-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-

This script has the intention to control and maintain your garden soil humidity.
And is it is a hodgepodge of different scripts found on the Domoticz forum.
Be aware that using this script for the first time it may take awhile before irrigation script has collected all the data.

I wrote this script for my own little garden project and to beable to automate irrigation while i'm gone.
The topic can be found here: https://www.domoticz.com/forum/viewtopic.php?f=38&t=6904
Somehow it got out of hand and got big.
So i thought that maybe some of you could have a benefith of this.
Although the script is intended for irrigation.
You could adapt it for other projects.

I do assume that when you want to use this script you already have the knowhow of Lua and Domoticz.
As i won't explain the entire installation ;-)

The script does the following:
- It scraps WeatherUnderground data and processing it usable data
- It monitors buienradar (optional) to see if there are any showers upcoming 24hr
- It scraps temperature and humidity from your moist sensor and processing it usable data
- It lets you choose when (Day of the week, month and time of the day) to irrigate
- By an extensive Settings Menu you can set various settings to control when to irrigate
settings ranges from: Min/Max Temp, Min/Max Humidity pct, Amount of rain, wind, UV, day, month to stop or start irrigating.

The Hardware i use:
- DIY Garden irrigation piping as seen in the topic
- Washer 220v Watervalve 2-way
- KaKu ACM-3500-3 3-in-1 unit (controlling the 2 valves) 1 reserve for pond protector to scare the cats ;-)

This script is still in BETA as i just wrote it and haven't fully tested it.
Be aware that i'm not a coder and it's maybe the cleanest script ever, but who cares as it works ;-) 

I hope it can be of use to you and feel free to adapt it.
Bug fixes, patches, and improvements are hapiliy accepted of course.
Same counts for LUA optimizations as this is the first time i wrote,copy/past a LUA script.
When i started this i didn't had a clue what i was doing ;-)

Siewert Lameijer

-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-

Necessities:

1x Virtual switch to be able to manual override the irrigation program (Manual Override)
1x Soil Moist & Humidity sensor
1x Active WeatherUnderground account
1x Switch to be able to control your waterpump/valve which is somehow wireless connected to domoticz
1x Garden with irrigation hardware xD

The following UserVariable have to be create:
- VarBuienRadarCon (type=integer, value=0)
- VarFollowsProgram (type=integer, value=0)
- VarManOverride (type=integer, value=0)
- VarMaxRunTime (type=integer, value=0)
- VarMoistHumCon (type=integer, value=0)
- VarMoistLastSeen (type=integer, value=0)
- VarMoistOnline (type=integer, value=0)
- VarMoistOnlineHum (type=integer, value=0)
- VarMoistTempCon (type=integer, value=0)
- VarProgram (type=integer, value=0)
- VarProgramHasRun (type=integer, value=0)
- VarProgramStopHum (type=integer, value=0)
- VarScheduledDays (type=integer, value=0)
- VarScheduledMonths (type=integer, value=0)
- VarScheduledTOD (type=integer, value=0)
- VarScheduledTODcurrent (type=integer, value=0)
- VarWeatherCon (type=integer, value=0)

-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-

Changelog:

Version 0.7
- Rewrote script due to a issue for which i couldn't find the culprit
- Reduced the amount of uservariables
- Some UserVariables have been renamed
- Fixed Soil Humidity scrap script
- Added MoistSensor Last Seen Check (max last seen is set to 10min)
- Fixed MaxRunTime Counter
- Changed Buienradar prediction to 2hr as this is the max by Buienradar it self
- Optimized Manual pump start
- Optimized displayed text in log regarding the running program and it's doings 
- Fixed program stop when target humidity has been reached
- Fixed TimeOfTheDay schedule
- Added counter to log to see how long the irrigation program is still active until shutdown
- Added code to check when the moist sensor was last seen, if longer then 10minuten then no irrigation
 
Version 0.6
- Optimized reset switches
- Added new UserVariable for be sure a irrigation cycle has complete ( VarProgramHasRun (type=integer, value=0) )
- Fixed some issues with Manual Override
- Added extra lines to show in log if you enabled manual override

Version 0.5
- Buienradar MaxRainFall changed, it is now a average of your desired max rain fall input to prevent the switch to flip flop
- Optimized Moist sensor script as it now triggers irrigation on a minimum value and shutsdown on a maximum value
- Added extra loggin option
- Added option to use Buienradar or not
- Added option to use Dutch or English translation

Version 0.4
- Changed Days, Months to text instead of numbers as input
- Optimized irrigation program ending and keeping it that until the next time schedule

Version 0.3
- Added Buienradar (IsItGonnaRain) script
- Optimized Max irrigation time script
- Clean some code
- Reorderd printed text

Version 0.2
- Added counter for Max irrigation time
- Added manual override
- Optimized WeatherUnderground scraping data
- Optimized Moist sensor scraping data
- Optimized user input Time Of The Day, Days and Months

Version 0.1
- Added WeatherUnderground and scraping data
- Added Moist sensor scraping Temp & Humidity data
- Added Moist sensor online check
- Added user input for Time Of The Day where irrigation may start
- Added user input for days and months where the irrigation may start
	
-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-]]

--
-- **********************************************************
-- Settings Begin
-- **********************************************************
--

-- Set your desired language (English, Dutch) 
local lang = 'English'

-- Logging: 0 = None, 1 = Little Bit, 2 = All
local logging = 2

--
-- **********************************************************
-- Water Valve/Pump Variables
-- **********************************************************
--

-- Name of your irrigation switch for water valve/pump
local VarIsPump = 'Irrigatie 1 Check'

-- Max minuten/times we want to switch OFF irrigation after the program has started.			
local VarMaxRunTime = 15

--
-- **********************************************************
-- Virtual Switches Variables
-- **********************************************************
--

-- Name of your manual override virtual switch
local VitManOverride = 'Irrigatie Manual Override'

--
-- **********************************************************
-- WeatherUnderGround Settings
-- **********************************************************
-- 
-- Name of your Weatherstation widget which contains humidity,uv,temp and pressure
local weatherstation = 'Barometer'

-- Name of your Weatherstation Wind widget
local wind = 'Wind'

-- Name of your Weatherstation Rain widget
local rain = 'Regenmeter'

-- Name of your Weatherstation UV widget
local uv = 'UV'

--
-- **********************************************************
-- WeatherUnderground Variables
-- **********************************************************
-- 
-- Set your prefered max rain fall, higher won't trigger irrigation
local RainMax = '0'

-- Set your prefered minimum outside temperature for irrigation, Lower won't trigger irrigation
local WeatherTempMin = '13'

-- Set your prefered maximum outside temperature for irrigation, Higher won't trigger irrigation
local WeatherTempMax = '25'

-- Set your prefered maximum UV for irrigation, Higher won't trigger irrigation
local UVMax = '6'

-- Set your prefered max windspeed km/h, higher won't trigger irrigation
local WindSpeed = '50'

-- Set your prefered max windgust km/h, higher won't trigger irrigation
local WindGust = '150'

--
-- **********************************************************
-- BuienRadar Location and minimum Rain Fall Variables
-- **********************************************************
-- 

-- Do you want to use BuienRadar? Yes or No
local Buienradar = 'Yes' --(Dutch weather, rain prediction)

-- Set your location by adding Lat/Lon
local lat = '53.338023'
local lon = '6.303114'

-- Set your minimum rain fall for in a periode of 24hr 
local  VarMaxRainFall = '100'

--
-- **********************************************************
-- Moist Sensor Variables
-- **********************************************************
-- 

-- Name of your Moist Sensor device
local MoistSensor = 'Vocht Sensor (border Zijkant)'

-- Your target soil humidity percentage
local VarTarHum = '50'

-- Your minumim soil humidity percentage from which the irrigation will start
local VarMinHum = '40'

-- Your Minumum soil temperature, Lower won't trigger irrigation
local VarTarTempMin = '12'

-- Your Maximum soil temperature, Higher won't trigger irrigation
local VarTarTempMax = '30'

--
-- **********************************************************
-- Scheduled Days
-- **********************************************************
--

-- Set your desired TimeOfDay for irrigation (Morning=0, Afternoon=1, Evening=2 or Night=3)
local VarTimeOfDay = '1'

-- Set your desired irrigation day, leave blank for no irrigation
-- Set Mon, Tue, Wed, Thu, Fri, Sat or Sun
local VarDay1 = 'Mon'

local VarDay2 = 'Tue'

local VarDay3 = 'Wed'

local VarDay4 = 'Thu'

local VarDay5 = 'Fri'

local VarDay6 = 'Sat'

local VarDay7 = 'Sun'

--
-- **********************************************************
-- Scheduled Months
-- **********************************************************
--

-- Set your desired irrigation month, leave blank for no irrigation, 
-- Set months like: Jan, Feb, Apr, May, Jun, Jul, Aug, Sep, ect ect
local VarMonth1 = ''

local VarMonth2 = ''

local VarMonth3 = ''

local VarMonth4 = 'Apr'

local VarMonth5 = 'May'

local VarMonth6 = 'Jun'

local VarMonth7 = 'Jul'

local VarMonth8 = 'Aug'

local VarMonth9 = 'Sep'

local VarMonth10 = ''

local VarMonth11 = ''

local VarMonth12 = ''


--
-- **********************************************************
-- Settings End
-- **********************************************************
--

--[[
-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-
                        Don't edit anything below this line or you could break the script!
-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-
--]]

time = os.date("*t")
commandArray = {}

--
-- **********************************************************
-- Scrapping Weather Data from WeatherUnderground
-- **********************************************************
if logging >= 1 then
	print("--------------------------------------------------------------------------------------")
	if lang == 'Dutch' then	
	print('-- Irrigatie [HET WEER]');
	else
	print('-- Irrigation [WEATHER]');
	end
end	
	
--
--
-- WeatherStation data:
-- 

sWeatherTemp, sWeatherHumidity, sWeatherUV, sWeatherPressure, sWeatherUV2 = otherdevices_svalues[weatherstation]:match("([^;]+);([^;]+);([^;]+);([^;]+);([^;]+)")
sWeatherTemp = tonumber(sWeatherTemp);
sWeatherHumidity = tonumber(sWeatherHumidity);
sWeatherUV = tonumber(sWeatherUV);
sWeatherPressure = tonumber(sWeatherPressure);
sWeatherUV2 = tonumber(sWeatherUV2);

if logging == 1 then
	if lang == 'Dutch' then
		print("-- Irrigatie ==> [WeerStation] - Temperatuur: " .. sWeatherTemp .. " ");
	else	
		print("-- Irrigation ==> [WeatherStation] - Temperature: " .. sWeatherTemp .. " ");
	end
end
	
if logging >= 2 then
	if lang == 'Dutch' then
		print("-- Irrigatie ==> [WeerStation] - Temperatuur: " .. sWeatherTemp .. " ");
		print("-- Irrigatie ==> [WeerStation] - Vochtigheid: " .. sWeatherHumidity .. " ");
		print("-- Irrigatie ==> [WeerStation] - Barometer: " .. sWeatherPressure .. " ");	
	else
		print("-- Irrigation ==> [WeatherStation] - Temperature: " .. sWeatherTemp .. " ");
		print("-- Irrigation ==> [WeatherStation] - Humidity: " .. sWeatherHumidity .. " ");
		print("-- Irrigation ==> [WeatherStation] - Pressure: " .. sWeatherPressure .. " ");		
	end	
end

--
-- 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);

if logging == 1 then
		if lang == 'Dutch' then
		print("-- Irrigatie ==> [Windmeter] - Windsnelheid: " .. sWindSpeed .. " ");
		print("-- Irrigatie ==> [Windmeter] - Windvlaag: " .. sWindGust .. " ");		
		else
		print("-- Irrigation ==> [Windmeter] - Windspeed: " .. sWindSpeed .. " ");
		print("-- Irrigation ==> [Windmeter] - Windgust: " .. sWindGust .. " ");
		end
end
	
if logging >= 2 then
		if lang == 'Dutch' then
		print("-- Irrigatie ==> [Windmeter] - Windrichting (in graden): " .. sWindDirectionDegrees .. " ");
		print("-- Irrigatie ==> [Windmeter] - Windrichting: " .. sWindDirection .. " ");
		print("-- Irrigatie ==> [Windmeter] - Windsnelheid: " .. sWindSpeed .. " ");
		print("-- Irrigatie ==> [Windmeter] - Windvlaag: " .. sWindGust .. " ");
		print("-- Irrigatie ==> [Windmeter] - Windtemperatuur: " .. sWindTemperature .. " ");
		print("-- Irrigatie ==> [Windmeter] - Gevoelstemperatuur: " .. sWindFeel .. " ");		
		else
		print("-- Irrigation ==> [Windmeter] - Winddirection (in degrees): " .. sWindDirectionDegrees .. " ");
		print("-- Irrigation ==> [Windmeter] - Winddirection: " .. sWindDirection .. " ");
		print("-- Irrigation ==> [Windmeter] - Windspeed: " .. sWindSpeed .. " ");
		print("-- Irrigation ==> [Windmeter] - Windgust: " .. sWindGust .. " ");
		print("-- Irrigation ==> [Windmeter] - Windtemperature: " .. sWindTemperature .. " ");
		print("-- Irrigation ==> [Windmeter] - Windfeel: " .. sWindFeel .. " ");
		end
end
	
--
-- Rainmeter data:
-- 

sRainmeterCurrent, sRainmeterTotal = otherdevices_svalues[rain]:match("([^;]+);([^;]+)")
 
sRainmeterCurrent = tonumber(sRainmeterCurrent);
sRainmeterTotal = tonumber(sRainmeterTotal);

if logging >= 1 then
		if lang == 'Dutch' then
		print("-- Irrigatie ==> [Regenmeter] - Actuele regenval: " .. sRainmeterCurrent .. " ");
		print("-- Irrigatie ==> [Regenmeter] - Totale regenval: " .. sRainmeterTotal .. " ");		
		else
		print("-- Irrigation ==> [Rainmeter] - Actual rain is: " .. sRainmeterCurrent .. " ");
		print("-- Irrigation ==> [Rainmeter] - Total rain is: " .. sRainmeterTotal .. " ");
		end
end		
	
--
-- UV data:
-- 

sUV, sSolar = otherdevices_svalues[uv]:match("([^;]+);([^;]+)")
 
sUV = tonumber(sUV);
sSolar = tonumber(sSolar);

if logging >= 1 then
	if lang == 'Dutch' then
	print("-- Irrigatie ==> [UV] - UV Sterkte: " .. sUV .." ");	
	else
	print("-- Irrigation ==> [UV] - UV Strength: " .. sUV .." ");
	end
end

if  sRainmeterTotal >= tonumber (RainMax)
	and sWeatherTemp >= tonumber (WeatherTempMin)
	and sWeatherTemp <= tonumber (WeatherTempMax)
	and sUV <= tonumber (UVMax)
	and sWindSpeed <= tonumber (WindSpeed)
	and sWindGust <= tonumber (WindGust)
then

if logging >= 1 then
	if lang == 'Dutch' then
	print("-- Irrigatie ==> [WEER INFO] - Weer conditie lijkt goed voor irrigatie");
	else
	print("-- Irrigation ==> [WEATHER INFO] - Weather conditions are looking good and ready for irrigation");
	end
end
	
	if(uservariables['VarWeatherCon'] == 0) then
	commandArray['Variable:VarWeatherCon']= '1'
    end
	
else

if logging >= 1 then
	if lang == 'Dutch' then
	print("-- Irrigatie ==> [WEER INFO] - Weer conditie lijkt NIET goed voor irrigatie");
	else
	print("-- Irrigation [WEATHER INFO] ==> Weather conditions aren't good for irrigation");
	end
end
	
	if(uservariables['VarWeatherCon'] == 1) then
	commandArray['Variable:VarWeatherCon']= '0'
	end	
end

--
-- **********************************************************
-- Checking Buienradar
-- **********************************************************
--
if Buienradar == 'Yes' then

	if logging >= 1 then
		print("--------------------------------------------------------------------------------------")
		print("-- Irrigation [BUIENRADAR]");	
	end	
	

    tempfilename = '/var/tmp/rain.tmp'
    totalrain = 0
    rainlines = 0	
	
	
   function IsItGonnaRain( minutesinfuture )
       url='http://gps.buienradar.nl/getrr.php?lat='..lat..'&lon='..lon
       read = os.execute('curl -s -o '..tempfilename..' "'..url..'"')
       file = io.open(tempfilename, "r")

       while true do
          line = file:read("*line")
          if not line then break end
          linetime=string.sub(tostring(line), 5, 9)
          linetime2 = os.time{year=os.date('%Y'), month=os.date('%m'), day=os.date('%d'), hour=string.sub(linetime,1,2), min=string.sub(linetime,4,5), sec=os.date('%S')}
          difference = os.difftime (linetime2,os.time())

          if ((difference > 0) and (difference<=minutesinfuture*60)) then
             rain=tonumber(string.sub(tostring(line), 0, 3))
             totalrain = totalrain+rain
             rainlines=rainlines+1
          end

       end
       file:close()
       
       averagerain=totalrain/rainlines
       return(averagerain)
    end

    function round(num, idp)
       local mult = 10^(idp or 0)
       return math.floor(num * mult + 0.5) / mult
    end

--
-- **********************************************************
-- Is it gonna rain for the upcoming 2hr YES/NO
-- **********************************************************
--

       minutes=120
       RainPrediction = IsItGonnaRain(minutes)
       RainmmHour=10^((RainPrediction-109)/32)

       if RainPrediction >= tonumber (VarMaxRainFall) then
          verw = 3
		  if (uservariables['VarBuienRadarCon']) == 1  then
		  commandArray['Variable:VarBuienRadarCon']= '0'
		  end
		  if logging >= 1 then  
			print('-- Irrigation ==> [REGEN] - ['..RainPrediction..'] regen verwacht binnen 2uur')
		  end
       else
          verw = 2

		  if (uservariables['VarBuienRadarCon']) == 0  then
		  commandArray['Variable:VarBuienRadarCon']= '1'
		  end
		  if logging >= 1 then 
			print('-- Irrigatie ==> [REGEN] - Geen of weinig regen verwacht binnen 2uur')
		  end		  
       end
end	

--
-- **********************************************************
-- MoistSensor Scrapping Temparature and humidity
-- **********************************************************
--

    smoistsensorTemp, smoistsensorHumidity = otherdevices_svalues[MoistSensor]:match("([^;]+);([^;]+);([^;]+)")
    smoistsensorTemp = tonumber(smoistsensorTemp);
    smoistsensorHumidity = tonumber(smoistsensorHumidity);

	if logging >= 1 then
		print("--------------------------------------------------------------------------------------")
	if lang == 'Dutch' then
		print("-- Irrigatie [GROND CONDITIES]");	
	else	
		print("-- Irrigation [SOIL CONDITION]");
	end
	end
	
if logging >= 1 then
	if lang == 'Dutch' then
		print("-- Irrigatie ==> [VochtSensor] - Grond Temperatuur: " .. smoistsensorTemp .. " ");
		print("-- Irrigatie ==> [VochtSensor] - Grond Vochtigheid: " .. smoistsensorHumidity .. " ");	
	else	
		print("-- Irrigation ==> [MoistSensor] - Soil Temperature: " .. smoistsensorTemp .. " ");
		print("-- Irrigation ==> [MoistSensor] - Soil Humidity: " .. smoistsensorHumidity .. " ");
	end
end	

--
-- **********************************************************
-- Checking Soil Temperature Conditions
-- **********************************************************
--

if 	smoistsensorTemp >= tonumber (VarTarTempMin)
	and smoistsensorTemp <= tonumber (VarTarTempMax)
then

if logging >= 2 then
	if lang == 'Dutch' then
		print("-- Irrigatie ==> [VochtSensor] - Grond temperatuur is goed voor irrigatie");
	else
		print("-- Irrigation ==> [MoistSensor] - Soil temperatuur is fine for irrigation");
	end
end

	if(uservariables['VarMoistTempCon'] == 0) then
	commandArray['Variable:VarMoistTempCon']= '1'
	end
	
elseif 	smoistsensorTemp <= tonumber (VarTarTempMin) then

if logging >= 2 then
	if lang == 'Dutch' then
		print("-- Irrigatie ==> [VochtSensor] - Grond temperatuur is te laag");
	else
		print("-- Irrigation ==> [MoistSensor] - Soil Temperature is to low");
	end
end

		if(uservariables['VarMoistTempCon'] == 1) then
		commandArray['Variable:VarMoistTempCon']= '0'
		end
		
elseif	smoistsensorTemp >= tonumber (VarTarTempMax) then
if logging >= 2 then
	if lang == 'Dutch' then
		print("-- Irrigatie ==> [VochtSensor] - Grond temperatuur is te hoog");
	else
		print("-- Irrigation ==> [MoistSensor] - Soil Temperature is to high");
	end
end

		if(uservariables['VarMoistTempCon'] == 1) then
		commandArray['Variable:VarMoistTempCon']= '0'
		end
end

--
-- **********************************************************
-- Checking Soil Humidity Conditions
-- **********************************************************
--

if 	smoistsensorHumidity >= tonumber (VarMinHum)
	and smoistsensorHumidity <= tonumber (VarTarHum)
then
if logging >= 2 then	
	if lang == 'Dutch' then
		print("-- Irrigatie ==> [VochtSensor] - Grond vochtigheid is goed, geen irrigatie nodig");
	else
		print("-- Irrigation ==> [MoistSensor] - Soil Humidity conditions are fine, no irrigation required");
	end	
end

	if(uservariables['VarMoistHumCon'] == 1) then
	commandArray['Variable:VarMoistHumCon']= '0'
	end
	
elseif 	smoistsensorHumidity <= tonumber (VarMinHum) then

if logging >= 2 then
	if lang == 'Dutch' then
		print("-- Irrigatie ==> [VochtSensor] - Grond vochtigheid is te laag");
	else
		print("-- Irrigation ==> [MoistSensor] - Soil humidity is to low");
	end	
end

		if(uservariables['VarMoistHumCon'] == 0) then
		commandArray['Variable:VarMoistHumCon']= '1'
		end

elseif	smoistsensorHumidity >= tonumber (VarTarHum) then

if logging >= 2 then
	if lang == 'Dutch' then
		print("-- Irrigatie ==> [VochtSensor] - Grond vochtigheid is te hoog");
	else
		print("-- Irrigation ==> [MoistSensor] - Soil humidity is to high");
	end	
end

		if(uservariables['VarMoistHumCon'] == 1) then
		commandArray['Variable:VarMoistHumCon']= '0'
		end		

end

--
-- **********************************************************
-- Moist Sensor online check
-- **********************************************************
--

if (smoistsensorTemp == 0 or smoistsensorTemp == nil) then
if logging >= 1 then
	if lang == 'Dutch' then
	print("-- Irrigatie ==> [VochtSensor] - [ERROR] Vochtsensor geeft een temperatuur aan van 0 of nil");
	else
    print('-- Irrigation ==> [MoistSensor] - [ERROR] Moist Sensor reports Temp is 0 or nil')
	end
end

	if(uservariables['VarMoistOnline'] == 1) then	
	commandArray['Variable:VarMoistOnline']= '0'
	end
		else
	if(uservariables['VarMoistOnline'] == 0) then		
	commandArray['Variable:VarMoistOnline']= '1'
	end
end

if (smoistsensorHumidity <= 6 or smoistsensorHumidity == nil) then
if logging >= 1 then
	if lang == 'Dutch' then
	print("-- Irrigatie ==> [VochtSensor] - [ERROR] Vochtsensor geeft een vochtigheid aan van 0 of nil");
	else
    print('-- Irrigation ==> [MoistSensor] - [ERROR] ==> Moist Sensor reports wrong Humidity values')
end
end

	if(uservariables['VarMoistOnlineHum'] == 1) then	
	commandArray['Variable:VarMoistOnlineHum']= '0'
	end
		else
	if(uservariables['VarMoistOnlineHum'] == 0) then		
	commandArray['Variable:VarMoistOnlineHum']= '1'
	end
end

--
-- **********************************************************
-- Moist Sensor Last Seen Check
-- **********************************************************
--
t1 = os.time()
s = otherdevices_lastupdate[MoistSensor]
	
	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}

Moist = (os.difftime (t1, t2))

if (Moist > 600) then

if logging >= 1 then
print('--')

if lang == 'Dutch' then
	print('--')
	print('-- Irrigatie ==> [VochtSensor] - [ERROR] Vochtsensor '..Moist..' Seconden geleden voor het laatste gezien')
	print('-- Irrigatie ==> [VochtSensor] - Dat is te lang geleden om een betrouwbaar beeld te vormen')	
	else
	print('--')	
	print('-- Irrigation ==> [MoistSensor] - [ERROR] MoistSensor last seen '..Moist..' seconds ago')
	print('-- Irrigation ==> [MoistSensor] - Thats too long ago to be reliable')	
	end
end
	if(uservariables['VarMoistLastSeen'] == 1) then	
	commandArray['Variable:VarMoistLastSeen']= '0'
	end
else

if logging >= 2 then
if lang == 'Dutch' then
	print('-- Irrigatie ==> [VochtSensor] - Vochtsensor '..Moist..' Seconden geleden voor het laatste gezien')
	else
	print('-- Irrigation ==> [MoistSensor] - MoistSensor last seen '..Moist..' seconds ago')
	end
end
	if(uservariables['VarMoistLastSeen'] == 0) then	
	commandArray['Variable:VarMoistLastSeen']= '1'
	end
	
end	

--
-- **********************************************************
-- Retrieve Date & Time 
-- **********************************************************
--

    week       = tonumber(os.date("%V"));
	month       = tostring(os.date("%b"));
    dayno       = tonumber(os.date("%d"));
    dayofweekno = tonumber(os.date("%w"));
    day       = tostring(os.date("%a"));
    hour       = tonumber(os.date("%H"));
    min       = tonumber(os.date("%M"));
	
--
-- **********************************************************
-- Checking Scheduled Days 
-- **********************************************************
--

if logging >= 1 then
   print("--------------------------------------------------------------------------------------")
if lang == 'Dutch' then
   print('-- Irrigatie [ROOSTER]')
else   
   print('-- Irrigation [TIMEFRAME]')
end
end

if day == VarDay1 or day == VarDay2 or day == VarDay3 or day == VarDay4 or day == VarDay5 or day == VarDay6 or day == VarDay7 
	then
	if logging >= 1 then
if lang == 'Dutch' then
	print(os.date("-- Irrigatie ==> [Rooster] - Vandaag is het %A en jouw ingeroosterde voorkeurs irrigatie dag"))
else	
	print(os.date("-- Irrigation ==> [Scheduled Days] - Today is %A and it is your desired scheduled day"))
end
end

	if logging >= 2 then
if lang == 'Dutch' then
	print('-- Irrigatie ==> [Rooster] - Ingeroosterde dagen: '..VarDay1..'  '..VarDay2..'  '..VarDay3..'  '..VarDay4..'  '..VarDay5..'  '..VarDay6..'  '..VarDay7..'')
else	
	print('-- Irrigation ==> [Scheduled Days] - Scheduled days: '..VarDay1..'  '..VarDay2..'  '..VarDay3..'  '..VarDay4..'  '..VarDay5..'  '..VarDay6..'  '..VarDay7..'')
end
end	
	if(uservariables['VarScheduledDays'] == 0) then
	commandArray['Variable:VarScheduledDays']= '1'
	end

else

	if logging >= 1 then
if lang == 'Dutch' then
	print(os.date("-- Irrigatie ==> [Rooster] - Vandaag is het %A en is NIET jouw ingeroosterde voorkeurs irrigatie dag"))
	else	
		print(os.date("-- Irrigation ==> [Scheduled Days] - Today is %A and it is NOT your desired scheduled day"))
	end
	end
	
	if logging >= 2 then
if lang == 'Dutch' then
	print('-- Irrigatie ==> [Rooster] - Ingeroosterde dagen: '..VarDay1..'  '..VarDay2..'  '..VarDay3..'  '..VarDay4..'  '..VarDay5..'  '..VarDay6..'  '..VarDay7..'')
	else		
		print('-- Irrigation ==> [Scheduled Days] - Scheduled days are: '..VarDay1..'  '..VarDay2..'  '..VarDay3..'  '..VarDay4..'  '..VarDay5..'  '..VarDay6..'  '..VarDay7..'')
	end
	end
	
	if(uservariables['VarScheduledDays'] == 1) then
	commandArray['Variable:VarScheduledDays']= '0'
	end	
end

--
-- **********************************************************
-- Scheduled Months
-- **********************************************************
--

if month == VarMonth1 or month == VarMonth2	or month == VarMonth3 or month == VarMonth4 or month == VarMonth5 or month == VarMonth6 or month == VarMonth7 or month == VarMonth8 or month == VarMonth9 or month == VarMonth10 or month == VarMonth11 or month == VarMonth12
then
	if logging >= 1 then
		if lang == 'Dutch' then
		print(os.date("-- Irrigatie ==> [Rooster] - Vandaag is het en dag in %B, en jouw ingeroosterde voorkeurs irrigatie maand"))
	else	
		print(os.date("-- Irrigation ==> [Scheduled Months] - Today is a day in %B, and is scheduled for irrigation"))
		end
	end

	
	if logging >= 2 then
		if lang == 'Dutch' then
		print('-- Irrigatie ==> [Rooster] - Ingeroosterde maanden: '..VarMonth1..'  '..VarMonth2..'  '..VarMonth3..'  '..VarMonth4..'  '..VarMonth5..'  '..VarMonth6..'  '..VarMonth7..' '..VarMonth8..' '..VarMonth9..' '..VarMonth10..' '..VarMonth11..' '..VarMonth12..'')
	else	
		print('-- Irrigation ==> [Scheduled Months] - Scheduled months: '..VarMonth1..'  '..VarMonth2..'  '..VarMonth3..'  '..VarMonth4..'  '..VarMonth5..'  '..VarMonth6..'  '..VarMonth7..' '..VarMonth8..' '..VarMonth9..' '..VarMonth10..' '..VarMonth11..' '..VarMonth12..'')
		end
	end
	
	if(uservariables['VarScheduledMonths'] == 0) then
	commandArray['Variable:VarScheduledMonths']= '1'
	end

else

	if logging >= 1 then
		if lang == 'Dutch' then
			print(os.date("-- Irrigatie ==> [Maand Rooster] - Vandaag is het een dag in %B, en is NIET jouw ingeroosterde voorkeurs irrigatie maand"))
	else
			print(os.date("-- Irrigation ==> [Scheduled Months] - Today is a day in %B, and isn't scheduled for irrigation"))
		end
	end
	
	if logging >= 2 then
		if lang == 'Dutch' then	
		print('-- Irrigatie ==> [Rooster] - Ingeroosterde maanden: '..VarMonth1..'  '..VarMonth2..'  '..VarMonth3..'  '..VarMonth4..'  '..VarMonth5..'  '..VarMonth6..'  '..VarMonth7..' '..VarMonth8..' '..VarMonth9..' '..VarMonth10..' '..VarMonth11..' '..VarMonth12..'')
	else
		print('-- Irrigation ==> [Scheduled Months] - Scheduled months are: '..VarMonth1..'  '..VarMonth2..'  '..VarMonth3..'  '..VarMonth4..'  '..VarMonth5..'  '..VarMonth6..'  '..VarMonth7..' '..VarMonth8..' '..VarMonth9..' '..VarMonth10..' '..VarMonth11..' '..VarMonth12..'')
		end
	end
	
	if(uservariables['VarScheduledMonths'] == 1) then
	commandArray['Variable:VarScheduledMonths']= '0'
	end	
end	

--
-- **********************************************************
-- Scheduled Day Time
-- **********************************************************
--

if (timeofday['Daytime']) and (time.hour < 12)
then
		if  (uservariables['VarScheduledTODcurrent'] ~= 0) then
				commandArray['Variable:VarScheduledTODcurrent']= '0'
		end

elseif (timeofday['Daytime']) and (time.hour >= 12)
then
		if (uservariables['VarScheduledTODcurrent'] ~= 1) then
			commandArray['Variable:VarScheduledTODcurrent']= '1'
		end	

elseif (timeofday['Nighttime']) and (time.hour < 22)
then
		if (uservariables['VarScheduledTODcurrent'] ~= 2) then
			commandArray['Variable:VarScheduledTODcurrent']= '2'
		end

elseif (timeofday['Nighttime']) and (time.hour >= 22)
then
		if (uservariables['VarScheduledTODcurrent'] ~= 3) then
			commandArray['Variable:VarScheduledTODcurrent']= '3'
		end	

elseif (timeofday['Nighttime'])
then
		if (uservariables['VarScheduledTODcurrent'] ~= 3) then
			commandArray['Variable:VarScheduledTODcurrent']= '3'
		end	
end



if (uservariables['VarScheduledTODcurrent']) == tonumber (VarTimeOfDay) then
	if logging >= 1 then
		if lang == 'Dutch' then	
		print("-- Irrigatie ==> [Rooster] - Huidige dagdeel komt overeen met jouw voorkeurs dagdeel")
		else
		print("-- Irrigation ==> [Scheduled Time] - Time of the Day matches your desired scheduled TimeOfTheDay")
		end
	end
	if (uservariables['VarScheduledTOD']) == 0 then
	commandArray['Variable:VarScheduledTOD']= '1'
	end

else

	if logging >= 1 then
	if lang == 'Dutch' then	
		print("-- Irrigatie ==> [Rooster] - Huidige dagdeel komt NIET overeen met jouw voorkeurs dagdeel")
	else
		print("-- Irrigation ==> [Scheduled Time] - Time of the Day doesn't match your desired scheduled TimeOfTheDay")
	end
	end

	if (uservariables['VarScheduledTOD']) == 1 then
	commandArray['Variable:VarScheduledTOD']= '0'
	end
	
	end	

--
-- **********************************************************
-- Irrigation Program
-- **********************************************************
--
if Buienradar == 'Yes' then
if (uservariables['VarScheduledTOD'] == 1
	and uservariables['VarScheduledMonths'] == 1
	and uservariables['VarScheduledDays'] == 1
	and uservariables['VarMoistHumCon'] == 1
	and uservariables['VarMoistTempCon'] == 1
	and uservariables['VarBuienRadarCon'] == 1
	and uservariables['VarWeatherCon'] == 1
	and uservariables['VarMoistOnline'] == 1
	and uservariables['VarMoistOnlineHum'] == 1
	and uservariables['VarMoistLastSeen'] == 1
	and uservariables['VarProgramStopHum'] == 0
	and uservariables['VarManOverride'] == 0
	and uservariables['VarProgramHasRun'] == 0
	and uservariables['VarFollowsProgram'] == 0
	and uservariables['VarProgram'] == 0
	and otherdevices[VarIsPump] == 'Off')
then
commandArray['Variable:VarProgram']= '1'
end

else

if (uservariables['VarScheduledTOD'] == 1
	and uservariables['VarScheduledMonths'] == 1
	and uservariables['VarScheduledDays'] == 1
	and uservariables['VarMoistHumCon'] == 1
	and uservariables['VarMoistTempCon'] == 1
	and uservariables['VarWeatherCon'] == 1
	and uservariables['VarMoistOnline'] == 1
	and uservariables['VarMoistOnlineHum'] == 1
	and uservariables['VarMoistLastSeen'] == 1
	and uservariables['VarProgramStopHum'] == 0
	and uservariables['VarManOverride'] == 0
	and uservariables['VarProgramHasRun'] == 0
	and uservariables['VarFollowsProgram'] == 0
	and uservariables['VarProgram'] == 0
	and otherdevices[VarIsPump] == 'Off')
then
commandArray['Variable:VarProgram']= '1'
end

end


local VarIsCounter = 'VarMaxRunTime'
local VarMax = VarMaxRunTime * -1
if logging >= 1 then
   print("--------------------------------------------------------------------------------------")
   	if lang == 'Dutch' then	
	print('-- Irrigatie [PROGRAMMA]')
	else
    print('-- Irrigation [PROGRAM]')
end
end

if otherdevices[VitManOverride]  == 'On' and uservariables['VarManOverride'] == 0
	then
	commandArray['Variable:VarManOverride']= '1'
elseif otherdevices[VitManOverride]  == 'On' and uservariables['VarManOverride'] == 1 and uservariables['VarMaxRunTime'] ~= VarMax
	then
	commandArray['Variable:VarMaxRunTime']=tostring(VarMax)
	commandArray['Variable:VarProgram']= '0'
	commandArray['Variable:VarProgramRun']= '0'
	commandArray['Variable:VarProgramHasRun']= '0'	
	commandArray[VarIsPump]='Off'	
elseif otherdevices[VitManOverride]  == 'Off' and uservariables['VarManOverride'] == 1
	then 	
	commandArray['Variable:VarManOverride']= '0'	
end
	
function info(msg)

	if logging >= 1 then
	   	if lang == 'Dutch' then	
		print('-- Irrigatie ==> [Programma] - ' .. msg)
		else
		print('-- Irrigation ==> [Program] - ' .. msg)
	end
	end

end

function may_update(is_irrigate)

	counter = tonumber(uservariables[VarIsCounter])
	current_counter = counter
	
	if is_irrigate and uservariables['VarManOverride'] == 0 and counter >= 0 then
		counter = math.min(1, counter + 1)
	elseif not is_irrigate and uservariables['VarManOverride'] == 0 and counter <= 0 then
		counter = math.max(VarMaxRunTime * -1, counter - 1)
	else
	if uservariables['VarManOverride'] == 0 then
		counter = 0
	end	
	end

	if counter ~= current_counter then
		commandArray['Variable:' .. VarIsCounter]=tostring(counter)
	end

	result = false
		
	if is_irrigate and counter >= 1 then
		result = true
	elseif not is_irrigate and math.abs(counter) >= VarMaxRunTime then
		result = true
	end

	
	return result

end

function on_off(is_irrigate)

	update_allowed = may_update(is_irrigate)
	
	if logging >= 1 then
	   	if lang == 'Dutch' then	
		info('Pomp Status [' .. otherdevices[VarIsPump] .. ']')
		else
		info('Pump State [' .. otherdevices[VarIsPump] .. ']')
	end
	end	

	if update_allowed then
		if otherdevices[VarIsPump] == 'Off' 
			and uservariables['VarProgram'] == 1 
			and uservariables['VarProgramHasRun'] == 0 
			and uservariables['VarManOverride'] == 0
			and is_irrigate then
 			commandArray[VarIsPump]='On'
			commandArray['Variable:VarProgram']= '0'
		elseif (otherdevices[VarIsPump] == 'On' 
				and uservariables['VarProgram'] == 0 
				and uservariables['VarProgramHasRun'] == 0 
				and uservariables['VarManOverride'] == 0
				and not is_irrigate) then
 			commandArray[VarIsPump]='Off'
			commandArray['Variable:VarProgramHasRun']= '1'
			commandArray['Variable:VarFollowsProgram']= '0'			
		end
	end

end

function is_VarProgram_aan()

	result = false
	result = (uservariables['VarProgram'] == 1)
    return result
end


	on_off(is_VarProgram_aan())
	
--
-- **********************************************************
-- New timeframe so irrigation reactivated
-- **********************************************************
--

if (uservariables['VarScheduledTOD']) == 0 and (uservariables['VarProgramHasRun']) == 1
	then 
	commandArray['Variable:VarProgramHasRun']= '0'
	commandArray['Variable:VarProgramStopHum']= '0'	
end	

--
-- **********************************************************
-- Irrigation Program manual or automatic check
-- **********************************************************
--	
if uservariables['VarMaxRunTime'] >= 0 and otherdevices[VarIsPump] == 'Off'	
then
commandArray['Variable:VarFollowsProgram']= '1'
end

if otherdevices[VarIsPump] == 'On' and uservariables['VarFollowsProgram'] == 0	
then
	   	if lang == 'Dutch' then	
		print('-- Irrigatie ==> [Programma] - Irrigatie programma manueel gestart')
		else
		print('-- Irrigation ==> [Program] - Irrigation program started manually')
	end
end
--
-- **********************************************************
-- Irrigation Program Max Run Time Remaining
-- **********************************************************
--	

if uservariables['VarMaxRunTime'] <= 0 and otherdevices[VarIsPump] == 'On' and uservariables['VarFollowsProgram'] == 1
then
VarRemaining_counter = uservariables['VarMaxRunTime']
VarRemaining = VarRemaining_counter + VarMaxRunTime -1
	if logging >= 2 then
	   	if lang == 'Dutch' then	
		print('-- Irrigatie ==> [Programma] - [' .. VarRemaining .. '] minuten resterend totdat programma word beeindigd')
		else
		print('-- Irrigation ==> [Program] - [' .. VarRemaining .. '] minutes remaining until irrigation will stop')	
		end
	end	
end

--
-- **********************************************************
-- Stop Irrigation when Moist Humidity has reached your desired humidity
-- **********************************************************
--

if (uservariables['VarFollowsProgram']) == 1 and (uservariables['VarProgramStopHum']) == 0
	and smoistsensorHumidity >= tonumber (VarTarHum)
then
	commandArray['Variable:VarProgramStopHum']= '1'	
end

if (uservariables['VarFollowsProgram']) == 1 and (uservariables['VarProgramStopHum']) == 1
then
	commandArray['Variable:VarMaxRunTime']=tostring(VarMax)
	commandArray[VarIsPump]='Off'
	commandArray['Variable:VarProgramHasRun']= '1'
	commandArray['Variable:VarFollowsProgram']= '0'		
end

if uservariables['VarProgramHasRun'] == 1
	and (uservariables['VarProgramStopHum']) == 1
	and uservariables['VarProgram'] == 0 
	and uservariables['VarManOverride'] == 0 
	and otherdevices[VarIsPump] == 'Off'
	then
	if logging >= 1 then
	
	   	if lang == 'Dutch' then	
		print('-- Irrigatie ==> [Programma] - Irrigatie programma heeft vandaag al geirrigeerd, Grondvochtigheid target is behaalt')
		print('-- Irrigatie ==> [Programma] - Programma word op de eerst volgende irrigatie dag herstart')
		else	
		print('-- Irrigation ==> [Program] - Irrigation program already irrigated today and soil humidity reached target')
		print('-- Irrigation ==> [Program] - Program will reactivated on the next scheduled irrigation day')		
		end
	end
end	

--
-- **********************************************************
-- Irrigation Program Stop Information
-- **********************************************************
--	

if uservariables['VarProgramHasRun'] == 1
	and (uservariables['VarProgramStopHum']) == 0
	and uservariables['VarProgram'] == 0 
	and uservariables['VarManOverride'] == 0 
	and otherdevices[VarIsPump] == 'Off'
	then
	if logging >= 1 then	
	   	if lang == 'Dutch' then	
		print('-- Irrigatie ==> [Programma] - Irrigatie programma heeft vandaag al geirrigeerd, Grondvochtigheid target is NIET behaalt')
		print('-- Irrigatie ==> [Programma] - Programma word op de eerst volgende irrigatie dag herstart')
		else	
		print('-- Irrigation ==> [Program] - Irrigation program already irrigated today but soil humidity didnt reached target')
		print('-- Irrigation ==> [Program] - Program will reactivated on the next scheduled irrigation day')	
		end
	end
end

if uservariables['VarProgramHasRun'] == 0 and uservariables['VarProgram'] == 0 and uservariables['VarManOverride'] == 0 and otherdevices[VarIsPump] == 'Off'
	then
	
	if logging >= 1 then	
	   	if lang == 'Dutch' then	
		print('-- Irrigatie ==> [Programma] - Irrigatie programma standby, en word hervat als alle condities inorde zijn')
		else
		print('-- Irrigation ==> [Program] - Irrigation program standby, awaiting for all conditions to be okay')	
		end
	end
end

if uservariables['VarManOverride'] == 1 and otherdevices[VarIsPump] == 'Off'
	then
	if logging >= 1 then	
	   	if lang == 'Dutch' then	
		print('-- Irrigatie ==> [Programma] - Irrigatie programma manueel gestopt')	
		else
		print('-- Irrigation ==> [Program] - Irrigation program Stopped, Manual Override')		
		end
	end	
end

if logging >= 1 then
   print("--------------------------------------------------------------------------------------")
end
return commandArray
Dutch Log:
Dutch Log
Dutch Log
Irrigatie1.png (50.51 KiB) Viewed 5776 times
English Log:
English Log
English Log
irrigation2.png (50.87 KiB) Viewed 5776 times
Setup:
- RPi4 - Domo Stable / Aeotec Z-stick7 / PiHole Unbound Gemini
- RPi4 - PiHole / PiVPN Unbound Gemini
- Synology DS923+ / DS218j
- P1 Gas/Power, SmartGateway watermeter
- Fibaro switches, contacts, plugs, smoke/Co2 ect
- rootfs @ USB HDD
User avatar
Siewert308SW
Posts: 288
Joined: Monday 29 December 2014 15:47
Target OS: Raspberry Pi / ODroid
Domoticz version: Stable
Location: The Netherlands
Contact:

Re: [DIY] Garden irrigation and learning project

Post by Siewert308SW »

Version 0.8
- Added validate check for switches and uservariables
- Fixed some misspelling (Do you find more misspellings, please let me know
- Added Max MoisSensor Last Seen option

Code: Select all

--[[

   script_time_irrigation.lua
   @author: Siewert Lameijer
   @since: 2015-07-12
   @version: 0.7 (BETA)
   @Garden Irrigation lua script

Credits:
- Nicky Bulthuis -/- for the dusk sensor script
- Hans van der Heijden -/- for the IsItGonnaRain script
- anonymous user -/- for the "Reading weather station data" script
- dannybloe -/- for Humidity Control script
- And to all those who i forgot to mention

-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-

This script has the intention to control and maintain your garden soil humidity.
And is it is a hodgepodge of different scripts found on the Domoticz forum.
Be aware that using this script for the first time it may take awhile before irrigation script has collected all the data.

I wrote this script for my own little garden project and to beable to automate irrigation while i'm gone.
The topic can be found here: https://www.domoticz.com/forum/viewtopic.php?f=38&t=6904
Somehow it got out of hand and got big.
So i thought that maybe some of you could have a benefith of this.
Although the script is intended for irrigation.
You could adapt it for other projects.

I do assume that when you want to use this script you already have the knowhow of Lua and Domoticz.
As i won't explain the entire installation ;-)

The script does the following:
- It scraps WeatherUnderground data and processing it usable data
- It monitors buienradar (optional) to see if there are any showers upcoming 24hr
- It scraps temperature and humidity from your moist sensor and processing it usable data
- It lets you choose when (Day of the week, month and time of the day) to irrigate
- By an extensive Settings Menu you can set various settings to control when to irrigate
settings ranges from: Min/Max Temp, Min/Max Humidity pct, Amount of rain, wind, UV, day, month to stop or start irrigating.

The Hardware i use:
- DIY Garden irrigation piping as seen in the topic
- Washer 220v Watervalve 2-way
- KaKu ACM-3500-3 3-in-1 unit (controlling the 2 valves) 1 reserve for pond protector to scare the cats ;-)

This script is still in BETA as i just wrote it and haven't fully tested it.
Be aware that i'm not a coder and it's maybe the cleanest script ever, but who cares as it works ;-) 

I hope it can be of use to you and feel free to adapt it.
Bug fixes, patches, and improvements are hapiliy accepted of course.
Same counts for LUA optimizations as this is the first time i wrote,copy/past a LUA script.
When i started this i didn't had a clue what i was doing ;-)

Siewert Lameijer

-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-

Necessities:

1x Virtual switch to be able to manual override the irrigation program (Manual Override)
1x Soil Moist & Humidity sensor
1x Active WeatherUnderground account
1x Switch to be able to control your waterpump/valve which is somehow wireless connected to domoticz
1x Garden with irrigation hardware xD

The following UserVariable have to be create:
- VarBuienRadarCon (type=integer, value=0)
- VarFollowsProgram (type=integer, value=0)
- VarManOverride (type=integer, value=0)
- VarMaxRunTime (type=integer, value=0)
- VarMoistHumCon (type=integer, value=0)
- VarMoistLastSeen (type=integer, value=0)
- VarMoistOnline (type=integer, value=0)
- VarMoistOnlineHum (type=integer, value=0)
- VarMoistTempCon (type=integer, value=0)
- VarProgram (type=integer, value=0)
- VarProgramHasRun (type=integer, value=0)
- VarProgramStopHum (type=integer, value=0)
- VarScheduledDays (type=integer, value=0)
- VarScheduledMonths (type=integer, value=0)
- VarScheduledTOD (type=integer, value=0)
- VarScheduledTODcurrent (type=integer, value=0)
- VarWeatherCon (type=integer, value=0)

-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-

Changelog:

Version 0.7
- Added validate check for switches and uservariables
- Fixed some misspelling (Do you find more misspellings, please let me know
- Added Max MoisSensor Last Seen option

Version 0.7
- Rewrote script due to a issue for which i couldn't find the culprit
- Reduced the amount of uservariables
- Some UserVariables have been renamed
- Fixed Soil Humidity scrap script
- Added MoistSensor Last Seen Check (max last seen is set to 10min)
- Fixed MaxRunTime Counter
- Changed Buienradar prediction to 2hr as this is the max by Buienradar it self
- Optimized Manual pump start
- Optimized displayed text in log regarding the running program and it's doings 
- Fixed program stop when target humidity has been reached
- Fixed TimeOfTheDay schedule
- Added counter to log to see how long the irrigation program is still active until shutdown
- Added code to check when the moist sensor was last seen, if longer then 10minuten then no irrigation
 
Version 0.6
- Optimized reset switches
- Added new UserVariable for be sure a irrigation cycle has complete ( VarProgramHasRun (type=integer, value=0) )
- Fixed some issues with Manual Override
- Added extra lines to show in log if you enabled manual override

Version 0.5
- Buienradar MaxRainFall changed, it is now a average of your desired max rain fall input to prevent the switch to flip flop
- Optimized Moist sensor script as it now triggers irrigation on a minimum value and shutsdown on a maximum value
- Added extra loggin option
- Added option to use Buienradar or not
- Added option to use Dutch or English translation

Version 0.4
- Changed Days, Months to text instead of numbers as input
- Optimized irrigation program ending and keeping it that until the next time schedule

Version 0.3
- Added Buienradar (IsItGonnaRain) script
- Optimized Max irrigation time script
- Clean some code
- Reorderd printed text

Version 0.2
- Added counter for Max irrigation time
- Added manual override
- Optimized WeatherUnderground scraping data
- Optimized Moist sensor scraping data
- Optimized user input Time Of The Day, Days and Months

Version 0.1
- Added WeatherUnderground and scraping data
- Added Moist sensor scraping Temp & Humidity data
- Added Moist sensor online check
- Added user input for Time Of The Day where irrigation may start
- Added user input for days and months where the irrigation may start
	
-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-]]

--
-- **********************************************************
-- Settings Begin
-- **********************************************************
--

-- Set your desired language (English, Dutch) 
local lang = 'Dutch'

-- Logging: 0 = None, 1 = Little Bit, 2 = All
local logging = 2

--
-- **********************************************************
-- Water Valve/Pump Variables
-- **********************************************************
--

-- Name of your irrigation switch for water valve/pump
local VarIsPump = 'Irrigatie 1 Check'

-- Max minuten/times we want to switch OFF irrigation after the program has started.			
local VarMaxRunTime = 15

--
-- **********************************************************
-- Virtual Switches Variables
-- **********************************************************
--

-- Name of your manual override virtual switch
local VitManOverride = 'Irrigatie Manual Override'

--
-- **********************************************************
-- WeatherUnderGround Settings
-- **********************************************************
-- 
-- Name of your Weatherstation widget which contains humidity,uv,temp and pressure
local weatherstation = 'Barometer'

-- Name of your Weatherstation Wind widget
local wind = 'Wind'

-- Name of your Weatherstation Rain widget
local rain = 'Regenmeter'

-- Name of your Weatherstation UV widget
local uv = 'UV'

--
-- **********************************************************
-- WeatherUnderground Variables
-- **********************************************************
-- 
-- Set your prefered max rain fall, higher won't trigger irrigation
local RainMax = '0'

-- Set your prefered minimum outside temperature for irrigation, Lower won't trigger irrigation
local WeatherTempMin = '13'

-- Set your prefered maximum outside temperature for irrigation, Higher won't trigger irrigation
local WeatherTempMax = '25'

-- Set your prefered maximum UV for irrigation, Higher won't trigger irrigation
local UVMax = '6'

-- Set your prefered max windspeed km/h, higher won't trigger irrigation
local WindSpeed = '50'

-- Set your prefered max windgust km/h, higher won't trigger irrigation
local WindGust = '150'

--
-- **********************************************************
-- BuienRadar Location and minimum Rain Fall Variables
-- **********************************************************
-- 

-- Do you want to use BuienRadar? Yes or No
local Buienradar = 'Yes' --(Dutch weather, rain prediction)

-- Set your location by adding Lat/Lon
local lat = '53.338023'
local lon = '6.303114'

-- Set your minimum rain fall for in a periode of 24hr 
local  VarMaxRainFall = '100'

--
-- **********************************************************
-- Moist Sensor Variables
-- **********************************************************
-- 

-- Name of your Moist Sensor device
local MoistSensor = 'Vocht Sensor (border Zijkant)'

-- Last Seen Max time in seconds for when the program will halt
local VarMoistLastSeen = 600

-- Your target soil humidity percentage
local VarTarHum = '70'

-- Your minumim soil humidity percentage from which the irrigation will start
local VarMinHum = '45'

-- Your Minumum soil temperature, Lower won't trigger irrigation
local VarTarTempMin = '12'

-- Your Maximum soil temperature, Higher won't trigger irrigation
local VarTarTempMax = '30'

--
-- **********************************************************
-- Scheduled Days
-- **********************************************************
--

-- Set your desired TimeOfDay for irrigation (Morning=0, Afternoon=1, Evening=2 or Night=3)
local VarTimeOfDay = '2'

-- Set your desired irrigation day, leave blank for no irrigation
-- Set Mon, Tue, Wed, Thu, Fri, Sat or Sun
local VarDay1 = 'Mon'

local VarDay2 = 'Tue'

local VarDay3 = 'Wed'

local VarDay4 = 'Thu'

local VarDay5 = 'Fri'

local VarDay6 = 'Sat'

local VarDay7 = 'Sun'

--
-- **********************************************************
-- Scheduled Months
-- **********************************************************
--

-- Set your desired irrigation month, leave blank for no irrigation, 
-- Set months like: Jan, Feb, Apr, May, Jun, Jul, Aug, Sep, ect ect
local VarMonth1 = ''

local VarMonth2 = ''

local VarMonth3 = ''

local VarMonth4 = 'Apr'

local VarMonth5 = 'May'

local VarMonth6 = 'Jun'

local VarMonth7 = 'Jul'

local VarMonth8 = 'Aug'

local VarMonth9 = 'Sep'

local VarMonth10 = ''

local VarMonth11 = ''

local VarMonth12 = ''


--
-- **********************************************************
-- Settings End
-- **********************************************************
--

--[[
-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-
                        Don't edit anything below this line or you could break the script!
-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-
--]]

commandArray = {}

--
-- **********************************************************
-- Irrigation Program Variables Check
-- **********************************************************
--

--
-- Error logging.
--

function error(msg)
	print("--------------------------------------------------------------------------------------")
	print('-- Irrigation [ERROR] ==>  ' .. msg)
end	


function validate()

result = true
	
--
-- Switches and Devices Error logging.
--
	if not otherdevices[VarIsPump] then
		error('Device [' .. VarIsPump .. '] doesnt exist.')
			result = false	
	end
	
	if not otherdevices[VitManOverride] then
		error('Device [' .. VitManOverride .. '] doesnt exist.')
				result = false
	end

	if not otherdevices[weatherstation] then
		error('Device [' .. weatherstation .. '] doesnt exist.')
				result = false
	end	

	if not otherdevices[wind] then
	
		error('Device [' .. wind .. '] doesnt exist.')
				result = false
	end	

	if not otherdevices[rain] then
	
		error('Device [' .. rain .. '] doesnt exist.')
				result = false
	end	

	if not otherdevices[wind] then
	
		error('Device [' .. uv .. '] doesnt exist.')
				result = false
	end	

	if not otherdevices[MoistSensor] then
	
		error('Device [' .. MoistSensor .. '] doesnt exist.')
				result = false
	end

--
-- User Variables Error logging.
--

	if not uservariables['VarBuienRadarCon'] then
		error('User Variable [ VarBuienRadarCon ] doesnt exist.')
		result = false
	end		
	
	if not uservariables['VarFollowsProgram'] then
		error('User Variable [ VarFollowsProgram  ] doesnt exist.')
		result = false
	end			
	
	if not uservariables['VarManOverride'] then
		error('User Variable [ VarManOverride  ] doesnt exist.')
		result = false
	end			
	
	if not uservariables['VarMaxRunTime'] then
		error('User Variable [ VarMaxRunTime  ] doesnt exist.')
		result = false
	end			
	
	if not uservariables['VarMoistHumCon'] then
		error('User Variable [ VarMoistHumCon  ] doesnt exist.')
		result = false
	end			
	
	if not uservariables['VarMoistLastSeen'] then
		error('User Variable [ VarMoistLastSeen  ] doesnt exist.')
    	result = false
	end			
	
	if not uservariables['VarMoistOnline'] then
		error('User Variable [ VarMoistOnline  ] doesnt exist.')
		result = false
	end			
	
	if not uservariables['VarMoistOnlineHum'] then
		error('User Variable [ VarMoistOnlineHum  ] doesnt exist.')
		result = false
	end			
	
	if not uservariables['VarMoistTempCon'] then
		error('User Variable [ VarMoistTempCon  ] doesnt exist.')
		result = false
	end			
	
	if not uservariables['VarProgram'] then
		error('User Variable [ VarProgram  ] doesnt exist.')
		result = false
	end			
	
	if not uservariables['VarProgramHasRun'] then
		error('User Variable [ VarProgramHasRun  ] doesnt exist.')
		result = false
	end			
	
	if not uservariables['VarProgramStopHum'] then
		error('User Variable [ VarProgramStopHum  ] doesnt exist.')
		result = false
	end			
	
	if not uservariables['VarScheduledDays'] then
		error('User Variable [ VarScheduledDays  ] doesnt exist.')
		result = false
	end			
	
	if not uservariables['VarScheduledMonths'] then
		error('User Variable [ VarScheduledMonths  ] doesnt exist.')
		result = false
	end			
	
	if not uservariables['VarScheduledTOD'] then
		error('User Variable [ VarScheduledTOD  ] doesnt exist.')
			result = false
	end		
	
	if not uservariables['VarScheduledTODcurrent'] then
		error('User Variable [ VarScheduledTODcurrent  ] doesnt exist.')
		result = false
	end			
	
	if not uservariables['VarWeatherCon'] then
		error('User Variable [ VarWeatherCon  ] doesnt exist.')
		result = false
	end			
		
	
return result	
end

--
-- **********************************************************
-- END Irrigation Program Variables Check
-- **********************************************************
--
	
if validate() then	

time = os.date("*t")

--
-- **********************************************************
-- Scrapping Weather Data from WeatherUnderground
-- **********************************************************
--
if logging >= 1 then
	print("--------------------------------------------------------------------------------------")
	if lang == 'Dutch' then	
	print('-- Irrigatie [HET WEER]');
	else
	print('-- Irrigation [WEATHER]');
	end
end	
	
--
--
-- WeatherStation data:
-- 

sWeatherTemp, sWeatherHumidity, sWeatherUV, sWeatherPressure, sWeatherUV2 = otherdevices_svalues[weatherstation]:match("([^;]+);([^;]+);([^;]+);([^;]+);([^;]+)")
sWeatherTemp = tonumber(sWeatherTemp);
sWeatherHumidity = tonumber(sWeatherHumidity);
sWeatherUV = tonumber(sWeatherUV);
sWeatherPressure = tonumber(sWeatherPressure);
sWeatherUV2 = tonumber(sWeatherUV2);

if logging == 1 then
	if lang == 'Dutch' then
		print("-- Irrigatie ==> [WeerStation] - Temperatuur: " .. sWeatherTemp .. " ");
	else	
		print("-- Irrigation ==> [WeatherStation] - Temperature: " .. sWeatherTemp .. " ");
	end
end
	
if logging >= 2 then
	if lang == 'Dutch' then
		print("-- Irrigatie ==> [WeerStation] - Temperatuur: " .. sWeatherTemp .. " ");
		print("-- Irrigatie ==> [WeerStation] - Vochtigheid: " .. sWeatherHumidity .. " ");
		print("-- Irrigatie ==> [WeerStation] - Barometer: " .. sWeatherPressure .. " ");	
	else
		print("-- Irrigation ==> [WeatherStation] - Temperature: " .. sWeatherTemp .. " ");
		print("-- Irrigation ==> [WeatherStation] - Humidity: " .. sWeatherHumidity .. " ");
		print("-- Irrigation ==> [WeatherStation] - Pressure: " .. sWeatherPressure .. " ");		
	end	
end

--
-- 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);

if logging == 1 then
		if lang == 'Dutch' then
		print("-- Irrigatie ==> [Windmeter] - Windsnelheid: " .. sWindSpeed .. " ");
		print("-- Irrigatie ==> [Windmeter] - Windvlaag: " .. sWindGust .. " ");		
		else
		print("-- Irrigation ==> [Windmeter] - Windspeed: " .. sWindSpeed .. " ");
		print("-- Irrigation ==> [Windmeter] - Windgust: " .. sWindGust .. " ");
		end
end
	
if logging >= 2 then
		if lang == 'Dutch' then
		print("-- Irrigatie ==> [Windmeter] - Windrichting (in graden): " .. sWindDirectionDegrees .. " ");
		print("-- Irrigatie ==> [Windmeter] - Windrichting: " .. sWindDirection .. " ");
		print("-- Irrigatie ==> [Windmeter] - Windsnelheid: " .. sWindSpeed .. " ");
		print("-- Irrigatie ==> [Windmeter] - Windvlaag: " .. sWindGust .. " ");
		print("-- Irrigatie ==> [Windmeter] - Windtemperatuur: " .. sWindTemperature .. " ");
		print("-- Irrigatie ==> [Windmeter] - Gevoelstemperatuur: " .. sWindFeel .. " ");		
		else
		print("-- Irrigation ==> [Windmeter] - Winddirection (in degrees): " .. sWindDirectionDegrees .. " ");
		print("-- Irrigation ==> [Windmeter] - Winddirection: " .. sWindDirection .. " ");
		print("-- Irrigation ==> [Windmeter] - Windspeed: " .. sWindSpeed .. " ");
		print("-- Irrigation ==> [Windmeter] - Windgust: " .. sWindGust .. " ");
		print("-- Irrigation ==> [Windmeter] - Windtemperature: " .. sWindTemperature .. " ");
		print("-- Irrigation ==> [Windmeter] - Windfeel: " .. sWindFeel .. " ");
		end
end
	
--
-- Rainmeter data:
-- 

sRainmeterCurrent, sRainmeterTotal = otherdevices_svalues[rain]:match("([^;]+);([^;]+)")
 
sRainmeterCurrent = tonumber(sRainmeterCurrent);
sRainmeterTotal = tonumber(sRainmeterTotal);

if logging >= 1 then
		if lang == 'Dutch' then
		print("-- Irrigatie ==> [Regenmeter] - Actuele regenval: " .. sRainmeterCurrent .. " ");
		print("-- Irrigatie ==> [Regenmeter] - Totale regenval: " .. sRainmeterTotal .. " ");		
		else
		print("-- Irrigation ==> [Rainmeter] - Actual rain is: " .. sRainmeterCurrent .. " ");
		print("-- Irrigation ==> [Rainmeter] - Total rain is: " .. sRainmeterTotal .. " ");
		end
end		
	
--
-- UV data:
-- 

sUV, sSolar = otherdevices_svalues[uv]:match("([^;]+);([^;]+)")
 
sUV = tonumber(sUV);
sSolar = tonumber(sSolar);

if logging >= 1 then
	if lang == 'Dutch' then
	print("-- Irrigatie ==> [UV] - UV Sterkte: " .. sUV .." ");	
	else
	print("-- Irrigation ==> [UV] - UV Strength: " .. sUV .." ");
	end
end

if  sRainmeterTotal >= tonumber (RainMax)
	and sWeatherTemp >= tonumber (WeatherTempMin)
	and sWeatherTemp <= tonumber (WeatherTempMax)
	and sUV <= tonumber (UVMax)
	and sWindSpeed <= tonumber (WindSpeed)
	and sWindGust <= tonumber (WindGust)
then

if logging >= 1 then
	if lang == 'Dutch' then
	print("-- Irrigatie ==> [WEER INFO] - Weer conditie lijkt goed voor irrigatie");
	else
	print("-- Irrigation ==> [WEATHER INFO] - Weather conditions are looking good and ready for irrigation");
	end
end
	
	if(uservariables['VarWeatherCon'] == 0) then
	commandArray['Variable:VarWeatherCon']= '1'
    end
	
else

if logging >= 1 then
	if lang == 'Dutch' then
	print("-- Irrigatie ==> [WEER INFO] - Weer conditie lijkt NIET goed voor irrigatie");
	else
	print("-- Irrigation [WEATHER INFO] ==> Weather conditions aren't good for irrigation");
	end
end
	
	if(uservariables['VarWeatherCon'] == 1) then
	commandArray['Variable:VarWeatherCon']= '0'
	end	
end

--
-- **********************************************************
-- Checking Buienradar
-- **********************************************************
--
if Buienradar == 'Yes' then

	if logging >= 1 then
		print("--------------------------------------------------------------------------------------")
		print("-- Irrigation [BUIENRADAR]");	
	end	
	

    tempfilename = '/var/tmp/rain.tmp'
    totalrain = 0
    rainlines = 0	
	
	
   function IsItGonnaRain( minutesinfuture )
       url='http://gps.buienradar.nl/getrr.php?lat='..lat..'&lon='..lon
       read = os.execute('curl -s -o '..tempfilename..' "'..url..'"')
       file = io.open(tempfilename, "r")

       while true do
          line = file:read("*line")
          if not line then break end
          linetime=string.sub(tostring(line), 5, 9)
          linetime2 = os.time{year=os.date('%Y'), month=os.date('%m'), day=os.date('%d'), hour=string.sub(linetime,1,2), min=string.sub(linetime,4,5), sec=os.date('%S')}
          difference = os.difftime (linetime2,os.time())

          if ((difference > 0) and (difference<=minutesinfuture*60)) then
             rain=tonumber(string.sub(tostring(line), 0, 3))
             totalrain = totalrain+rain
             rainlines=rainlines+1
          end

       end
       file:close()
       
       averagerain=totalrain/rainlines
       return(averagerain)
    end

    function round(num, idp)
       local mult = 10^(idp or 0)
       return math.floor(num * mult + 0.5) / mult
    end

--
-- **********************************************************
-- Is it gonna rain for the upcoming 2hr YES/NO
-- **********************************************************
--

       minutes=120
       RainPrediction = IsItGonnaRain(minutes)
       RainmmHour=10^((RainPrediction-109)/32)

       if RainPrediction >= tonumber (VarMaxRainFall) then
          verw = 3
		  if (uservariables['VarBuienRadarCon']) == 1  then
		  commandArray['Variable:VarBuienRadarCon']= '0'
		  end
		  if logging >= 1 then  
			print('-- Irrigation ==> [REGEN] - ['..RainPrediction..'] regen verwacht binnen 2uur')
		  end
       else
          verw = 2

		  if (uservariables['VarBuienRadarCon']) == 0  then
		  commandArray['Variable:VarBuienRadarCon']= '1'
		  end
		  if logging >= 1 then 
			print('-- Irrigatie ==> [REGEN] - Geen of weinig regen verwacht binnen 2uur')
		  end		  
       end
end	

--
-- **********************************************************
-- MoistSensor Scrapping Temparature and humidity
-- **********************************************************
--

    smoistsensorTemp, smoistsensorHumidity = otherdevices_svalues[MoistSensor]:match("([^;]+);([^;]+);([^;]+)")
    smoistsensorTemp = tonumber(smoistsensorTemp);
    smoistsensorHumidity = tonumber(smoistsensorHumidity);

	if logging >= 1 then
		print("--------------------------------------------------------------------------------------")
	if lang == 'Dutch' then
		print("-- Irrigatie [GROND CONDITIES]");	
	else	
		print("-- Irrigation [SOIL CONDITION]");
	end
	end
	
if logging >= 1 then
	if lang == 'Dutch' then
		print("-- Irrigatie ==> [VochtSensor] - Grond Temperatuur: " .. smoistsensorTemp .. " ");
		print("-- Irrigatie ==> [VochtSensor] - Grond Vochtigheid: " .. smoistsensorHumidity .. " ");	
	else	
		print("-- Irrigation ==> [MoistSensor] - Soil Temperature: " .. smoistsensorTemp .. " ");
		print("-- Irrigation ==> [MoistSensor] - Soil Humidity: " .. smoistsensorHumidity .. " ");
	end
end	

--
-- **********************************************************
-- Checking Soil Temperature Conditions
-- **********************************************************
--

if 	smoistsensorTemp >= tonumber (VarTarTempMin)
	and smoistsensorTemp <= tonumber (VarTarTempMax)
then

if logging >= 2 then
	if lang == 'Dutch' then
		print("-- Irrigatie ==> [VochtSensor] - Grond temperatuur is goed voor irrigatie");
	else
		print("-- Irrigation ==> [MoistSensor] - Soil temperatuur is fine for irrigation");
	end
end

	if(uservariables['VarMoistTempCon'] == 0) then
	commandArray['Variable:VarMoistTempCon']= '1'
	end
	
elseif 	smoistsensorTemp <= tonumber (VarTarTempMin) then

if logging >= 2 then
	if lang == 'Dutch' then
		print("-- Irrigatie ==> [VochtSensor] - Grond temperatuur is te laag");
	else
		print("-- Irrigation ==> [MoistSensor] - Soil Temperature is to low");
	end
end

		if(uservariables['VarMoistTempCon'] == 1) then
		commandArray['Variable:VarMoistTempCon']= '0'
		end
		
elseif	smoistsensorTemp >= tonumber (VarTarTempMax) then
if logging >= 2 then
	if lang == 'Dutch' then
		print("-- Irrigatie ==> [VochtSensor] - Grond temperatuur is te hoog");
	else
		print("-- Irrigation ==> [MoistSensor] - Soil Temperature is to high");
	end
end

		if(uservariables['VarMoistTempCon'] == 1) then
		commandArray['Variable:VarMoistTempCon']= '0'
		end
end

--
-- **********************************************************
-- Checking Soil Humidity Conditions
-- **********************************************************
--

if 	smoistsensorHumidity >= tonumber (VarMinHum)
	and smoistsensorHumidity <= tonumber (VarTarHum)
then
if logging >= 2 then	
	if lang == 'Dutch' then
		print("-- Irrigatie ==> [VochtSensor] - Grond vochtigheid is goed, geen irrigatie nodig");
	else
		print("-- Irrigation ==> [MoistSensor] - Soil Humidity conditions are fine, no irrigation required");
	end	
end

	if(uservariables['VarMoistHumCon'] == 1) then
	commandArray['Variable:VarMoistHumCon']= '0'
	end
	
elseif 	smoistsensorHumidity <= tonumber (VarMinHum) then

if logging >= 2 then
	if lang == 'Dutch' then
		print("-- Irrigatie ==> [VochtSensor] - Grond vochtigheid is te laag");
	else
		print("-- Irrigation ==> [MoistSensor] - Soil humidity is to low");
	end	
end

		if(uservariables['VarMoistHumCon'] == 0) then
		commandArray['Variable:VarMoistHumCon']= '1'
		end

elseif	smoistsensorHumidity >= tonumber (VarTarHum) then

if logging >= 2 then
	if lang == 'Dutch' then
		print("-- Irrigatie ==> [VochtSensor] - Grond vochtigheid is te hoog");
	else
		print("-- Irrigation ==> [MoistSensor] - Soil humidity is to high");
	end	
end

		if(uservariables['VarMoistHumCon'] == 1) then
		commandArray['Variable:VarMoistHumCon']= '0'
		end		

end

--
-- **********************************************************
-- Moist Sensor online check
-- **********************************************************
--

if (smoistsensorTemp == 0 or smoistsensorTemp == nil) then
if logging >= 1 then
	if lang == 'Dutch' then
	print("-- Irrigatie ==> [VochtSensor] - [ERROR] Vochtsensor geeft een temperatuur aan van 0 of nil");
	else
    print('-- Irrigation ==> [MoistSensor] - [ERROR] Moist Sensor reports Temp is 0 or nil')
	end
end

	if(uservariables['VarMoistOnline'] == 1) then	
	commandArray['Variable:VarMoistOnline']= '0'
	end
		else
	if(uservariables['VarMoistOnline'] == 0) then		
	commandArray['Variable:VarMoistOnline']= '1'
	end
end

if (smoistsensorHumidity <= 6 or smoistsensorHumidity == nil) then
if logging >= 1 then
	if lang == 'Dutch' then
	print("-- Irrigatie ==> [VochtSensor] - [ERROR] Vochtsensor geeft een vochtigheid aan van 0 of nil");
	else
    print('-- Irrigation ==> [MoistSensor] - [ERROR] ==> Moist Sensor reports wrong Humidity values')
end
end

	if(uservariables['VarMoistOnlineHum'] == 1) then	
	commandArray['Variable:VarMoistOnlineHum']= '0'
	end
		else
	if(uservariables['VarMoistOnlineHum'] == 0) then		
	commandArray['Variable:VarMoistOnlineHum']= '1'
	end
end

--
-- **********************************************************
-- Moist Sensor Last Seen Check
-- **********************************************************
--
t1 = os.time()
s = otherdevices_lastupdate[MoistSensor]
	
	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}

Moist = (os.difftime (t1, t2))

if (Moist > VarMoistLastSeen) then

if logging >= 1 then
print('--')

if lang == 'Dutch' then
	print('--')
	print('-- Irrigatie ==> [VochtSensor] - [ERROR] Vochtsensor '..Moist..' Seconden geleden voor het laatste gezien')
	print('-- Irrigatie ==> [VochtSensor] - Dat is te lang geleden om een betrouwbaar beeld te vormen')	
	else
	print('--')	
	print('-- Irrigation ==> [MoistSensor] - [ERROR] MoistSensor last seen '..Moist..' seconds ago')
	print('-- Irrigation ==> [MoistSensor] - Thats too long ago to be reliable')	
	end
end
	if(uservariables['VarMoistLastSeen'] == 1) then	
	commandArray['Variable:VarMoistLastSeen']= '0'
	end
else

if logging >= 2 then
if lang == 'Dutch' then
	print('-- Irrigatie ==> [VochtSensor] - Vochtsensor '..Moist..' Seconden geleden voor het laatste gezien')
	else
	print('-- Irrigation ==> [MoistSensor] - MoistSensor last seen '..Moist..' seconds ago')
	end
end
	if(uservariables['VarMoistLastSeen'] == 0) then	
	commandArray['Variable:VarMoistLastSeen']= '1'
	end
	
end	

--
-- **********************************************************
-- Retrieve Date & Time 
-- **********************************************************
--

    week       = tonumber(os.date("%V"));
	month       = tostring(os.date("%b"));
    dayno       = tonumber(os.date("%d"));
    dayofweekno = tonumber(os.date("%w"));
    day       = tostring(os.date("%a"));
    hour       = tonumber(os.date("%H"));
    min       = tonumber(os.date("%M"));
	
--
-- **********************************************************
-- Checking Scheduled Days 
-- **********************************************************
--

if logging >= 1 then
   print("--------------------------------------------------------------------------------------")
if lang == 'Dutch' then
   print('-- Irrigatie [ROOSTER]')
else   
   print('-- Irrigation [TIMEFRAME]')
end
end

if day == VarDay1 or day == VarDay2 or day == VarDay3 or day == VarDay4 or day == VarDay5 or day == VarDay6 or day == VarDay7 
	then
	if logging >= 1 then
if lang == 'Dutch' then
	print(os.date("-- Irrigatie ==> [Rooster] - Vandaag is het %A en jouw ingeroosterde voorkeurs irrigatie dag"))
else	
	print(os.date("-- Irrigation ==> [Scheduled Days] - Today is %A and it is your desired scheduled day"))
end
end

	if logging >= 2 then
if lang == 'Dutch' then
	print('-- Irrigatie ==> [Rooster] - Ingeroosterde dagen: '..VarDay1..'  '..VarDay2..'  '..VarDay3..'  '..VarDay4..'  '..VarDay5..'  '..VarDay6..'  '..VarDay7..'')
else	
	print('-- Irrigation ==> [Scheduled Days] - Scheduled days: '..VarDay1..'  '..VarDay2..'  '..VarDay3..'  '..VarDay4..'  '..VarDay5..'  '..VarDay6..'  '..VarDay7..'')
end
end	
	if(uservariables['VarScheduledDays'] == 0) then
	commandArray['Variable:VarScheduledDays']= '1'
	end

else

	if logging >= 1 then
if lang == 'Dutch' then
	print(os.date("-- Irrigatie ==> [Rooster] - Vandaag is het %A en is NIET jouw ingeroosterde voorkeurs irrigatie dag"))
	else	
		print(os.date("-- Irrigation ==> [Scheduled Days] - Today is %A and it is NOT your desired scheduled day"))
	end
	end
	
	if logging >= 2 then
if lang == 'Dutch' then
	print('-- Irrigatie ==> [Rooster] - Ingeroosterde dagen: '..VarDay1..'  '..VarDay2..'  '..VarDay3..'  '..VarDay4..'  '..VarDay5..'  '..VarDay6..'  '..VarDay7..'')
	else		
		print('-- Irrigation ==> [Scheduled Days] - Scheduled days are: '..VarDay1..'  '..VarDay2..'  '..VarDay3..'  '..VarDay4..'  '..VarDay5..'  '..VarDay6..'  '..VarDay7..'')
	end
	end
	
	if(uservariables['VarScheduledDays'] == 1) then
	commandArray['Variable:VarScheduledDays']= '0'
	end	
end

--
-- **********************************************************
-- Scheduled Months
-- **********************************************************
--

if month == VarMonth1 or month == VarMonth2	or month == VarMonth3 or month == VarMonth4 or month == VarMonth5 or month == VarMonth6 or month == VarMonth7 or month == VarMonth8 or month == VarMonth9 or month == VarMonth10 or month == VarMonth11 or month == VarMonth12
then
	if logging >= 1 then
		if lang == 'Dutch' then
		print(os.date("-- Irrigatie ==> [Rooster] - Vandaag is het en dag in %B, en jouw ingeroosterde voorkeurs irrigatie maand"))
	else	
		print(os.date("-- Irrigation ==> [Scheduled Months] - Today is a day in %B, and is scheduled for irrigation"))
		end
	end

	
	if logging >= 2 then
		if lang == 'Dutch' then
		print('-- Irrigatie ==> [Rooster] - Ingeroosterde maanden: '..VarMonth1..'  '..VarMonth2..'  '..VarMonth3..'  '..VarMonth4..'  '..VarMonth5..'  '..VarMonth6..'  '..VarMonth7..' '..VarMonth8..' '..VarMonth9..' '..VarMonth10..' '..VarMonth11..' '..VarMonth12..'')
	else	
		print('-- Irrigation ==> [Scheduled Months] - Scheduled months: '..VarMonth1..'  '..VarMonth2..'  '..VarMonth3..'  '..VarMonth4..'  '..VarMonth5..'  '..VarMonth6..'  '..VarMonth7..' '..VarMonth8..' '..VarMonth9..' '..VarMonth10..' '..VarMonth11..' '..VarMonth12..'')
		end
	end
	
	if(uservariables['VarScheduledMonths'] == 0) then
	commandArray['Variable:VarScheduledMonths']= '1'
	end

else

	if logging >= 1 then
		if lang == 'Dutch' then
			print(os.date("-- Irrigatie ==> [Maand Rooster] - Vandaag is het een dag in %B, en is NIET jouw ingeroosterde voorkeurs irrigatie maand"))
	else
			print(os.date("-- Irrigation ==> [Scheduled Months] - Today is a day in %B, and isn't scheduled for irrigation"))
		end
	end
	
	if logging >= 2 then
		if lang == 'Dutch' then	
		print('-- Irrigatie ==> [Rooster] - Ingeroosterde maanden: '..VarMonth1..'  '..VarMonth2..'  '..VarMonth3..'  '..VarMonth4..'  '..VarMonth5..'  '..VarMonth6..'  '..VarMonth7..' '..VarMonth8..' '..VarMonth9..' '..VarMonth10..' '..VarMonth11..' '..VarMonth12..'')
	else
		print('-- Irrigation ==> [Scheduled Months] - Scheduled months are: '..VarMonth1..'  '..VarMonth2..'  '..VarMonth3..'  '..VarMonth4..'  '..VarMonth5..'  '..VarMonth6..'  '..VarMonth7..' '..VarMonth8..' '..VarMonth9..' '..VarMonth10..' '..VarMonth11..' '..VarMonth12..'')
		end
	end
	
	if(uservariables['VarScheduledMonths'] == 1) then
	commandArray['Variable:VarScheduledMonths']= '0'
	end	
end	

--
-- **********************************************************
-- Scheduled Day Time
-- **********************************************************
--

if (timeofday['Daytime']) and (time.hour < 12)
then
		if  (uservariables['VarScheduledTODcurrent'] ~= 0) then
				commandArray['Variable:VarScheduledTODcurrent']= '0'
		end

elseif (timeofday['Daytime']) and (time.hour >= 12)
then
		if (uservariables['VarScheduledTODcurrent'] ~= 1) then
			commandArray['Variable:VarScheduledTODcurrent']= '1'
		end	

elseif (timeofday['Nighttime']) and (time.hour < 22)
then
		if (uservariables['VarScheduledTODcurrent'] ~= 2) then
			commandArray['Variable:VarScheduledTODcurrent']= '2'
		end

elseif (timeofday['Nighttime']) and (time.hour >= 22)
then
		if (uservariables['VarScheduledTODcurrent'] ~= 3) then
			commandArray['Variable:VarScheduledTODcurrent']= '3'
		end	

elseif (timeofday['Nighttime'])
then
		if (uservariables['VarScheduledTODcurrent'] ~= 3) then
			commandArray['Variable:VarScheduledTODcurrent']= '3'
		end	
end



if (uservariables['VarScheduledTODcurrent']) == tonumber (VarTimeOfDay) then
	if logging >= 1 then
		if lang == 'Dutch' then	
		print("-- Irrigatie ==> [Rooster] - Huidige dagdeel komt overeen met jouw voorkeurs dagdeel")
		else
		print("-- Irrigation ==> [Scheduled Time] - Time of the Day matches your desired scheduled TimeOfTheDay")
		end
	end
	if (uservariables['VarScheduledTOD']) == 0 then
	commandArray['Variable:VarScheduledTOD']= '1'
	end

else

	if logging >= 1 then
	if lang == 'Dutch' then	
		print("-- Irrigatie ==> [Rooster] - Huidige dagdeel komt NIET overeen met jouw voorkeurs dagdeel")
	else
		print("-- Irrigation ==> [Scheduled Time] - Time of the Day doesn't match your desired scheduled TimeOfTheDay")
	end
	end

	if (uservariables['VarScheduledTOD']) == 1 then
	commandArray['Variable:VarScheduledTOD']= '0'
	end
	
	end

--
-- **********************************************************
-- Irrigation Program
-- **********************************************************
--
if Buienradar == 'Yes' then
if (uservariables['VarScheduledTOD'] == 1
	and uservariables['VarScheduledMonths'] == 1
	and uservariables['VarScheduledDays'] == 1
	and uservariables['VarMoistHumCon'] == 1
	and uservariables['VarMoistTempCon'] == 1
	and uservariables['VarBuienRadarCon'] == 1
	and uservariables['VarWeatherCon'] == 1
	and uservariables['VarMoistOnline'] == 1
	and uservariables['VarMoistOnlineHum'] == 1
	and uservariables['VarMoistLastSeen'] == 1
	and uservariables['VarProgramStopHum'] == 0
	and uservariables['VarManOverride'] == 0
	and uservariables['VarProgramHasRun'] == 0
	and uservariables['VarFollowsProgram'] == 0
	and uservariables['VarProgram'] == 0
	and otherdevices[VarIsPump] == 'Off')
then
commandArray['Variable:VarProgram']= '1'
end

else

if (uservariables['VarScheduledTOD'] == 1
	and uservariables['VarScheduledMonths'] == 1
	and uservariables['VarScheduledDays'] == 1
	and uservariables['VarMoistHumCon'] == 1
	and uservariables['VarMoistTempCon'] == 1
	and uservariables['VarWeatherCon'] == 1
	and uservariables['VarMoistOnline'] == 1
	and uservariables['VarMoistOnlineHum'] == 1
	and uservariables['VarMoistLastSeen'] == 1
	and uservariables['VarProgramStopHum'] == 0
	and uservariables['VarManOverride'] == 0
	and uservariables['VarProgramHasRun'] == 0
	and uservariables['VarFollowsProgram'] == 0
	and uservariables['VarProgram'] == 0
	and otherdevices[VarIsPump] == 'Off')
then
commandArray['Variable:VarProgram']= '1'
end

end


local VarIsCounter = 'VarMaxRunTime'
local VarMax = VarMaxRunTime * -1
if logging >= 1 then
   print("--------------------------------------------------------------------------------------")
   	if lang == 'Dutch' then	
	print('-- Irrigatie [PROGRAMMA]')
	else
    print('-- Irrigation [PROGRAM]')
end
end

if otherdevices[VitManOverride]  == 'On' and uservariables['VarManOverride'] == 0
	then
	commandArray['Variable:VarManOverride']= '1'
elseif otherdevices[VitManOverride]  == 'On' and uservariables['VarManOverride'] == 1 and uservariables['VarMaxRunTime'] ~= VarMax
	then
	commandArray['Variable:VarMaxRunTime']=tostring(VarMax)
	commandArray['Variable:VarProgram']= '0'
	commandArray['Variable:VarProgramRun']= '0'
	commandArray['Variable:VarProgramHasRun']= '0'	
	commandArray[VarIsPump]='Off'	
elseif otherdevices[VitManOverride]  == 'Off' and uservariables['VarManOverride'] == 1
	then 	
	commandArray['Variable:VarManOverride']= '0'	
end
	
function info(msg)

	if logging >= 1 then
	   	if lang == 'Dutch' then	
		print('-- Irrigatie ==> [Programma] - ' .. msg)
		else
		print('-- Irrigation ==> [Program] - ' .. msg)
	end
	end

end

function may_update(is_irrigate)

	counter = tonumber(uservariables[VarIsCounter])
	current_counter = counter
	
	if is_irrigate and uservariables['VarManOverride'] == 0 and counter >= 0 then
		counter = math.min(1, counter + 1)
	elseif not is_irrigate and uservariables['VarManOverride'] == 0 and counter <= 0 then
		counter = math.max(VarMaxRunTime * -1, counter - 1)
	else
	if uservariables['VarManOverride'] == 0 then
		counter = 0
	end	
	end

	if counter ~= current_counter then
		commandArray['Variable:' .. VarIsCounter]=tostring(counter)
	end

	result = false
		
	if is_irrigate and counter >= 1 then
		result = true
	elseif not is_irrigate and math.abs(counter) >= VarMaxRunTime then
		result = true
	end

	
	return result

end

function on_off(is_irrigate)

	update_allowed = may_update(is_irrigate)
	
	if logging >= 1 then
	   	if lang == 'Dutch' then	
		info('Pomp Status [' .. otherdevices[VarIsPump] .. ']')
		else
		info('Pump State [' .. otherdevices[VarIsPump] .. ']')
	end
	end	

	if update_allowed then
		if otherdevices[VarIsPump] == 'Off' 
			and uservariables['VarProgram'] == 1 
			and uservariables['VarProgramHasRun'] == 0 
			and uservariables['VarManOverride'] == 0
			and is_irrigate then
 			commandArray[VarIsPump]='On'
			commandArray['Variable:VarProgram']= '0'
		elseif (otherdevices[VarIsPump] == 'On' 
				and uservariables['VarProgram'] == 0 
				and uservariables['VarProgramHasRun'] == 0 
				and uservariables['VarManOverride'] == 0
				and not is_irrigate) then
 			commandArray[VarIsPump]='Off'
			commandArray['Variable:VarProgramHasRun']= '1'
			commandArray['Variable:VarFollowsProgram']= '0'			
		end
	end

end

function is_VarProgram_aan()

	result = false
	result = (uservariables['VarProgram'] == 1)
    return result
end


	on_off(is_VarProgram_aan())
	
--
-- **********************************************************
-- New timeframe so irrigation reactivated
-- **********************************************************
--

if (uservariables['VarScheduledTOD']) == 0 and (uservariables['VarProgramHasRun']) == 1
	then 
	commandArray['Variable:VarProgramHasRun']= '0'
	commandArray['Variable:VarProgramStopHum']= '0'	
end	

--
-- **********************************************************
-- Irrigation Program manual or automatic check
-- **********************************************************
--	
if uservariables['VarMaxRunTime'] >= 0 and otherdevices[VarIsPump] == 'Off'	
then
commandArray['Variable:VarFollowsProgram']= '1'
end

if otherdevices[VarIsPump] == 'On' and uservariables['VarFollowsProgram'] == 0	
then
	   	if lang == 'Dutch' then	
		print('-- Irrigatie ==> [Programma] - Irrigatie programma manueel gestart')
		else
		print('-- Irrigation ==> [Program] - Irrigation program started manually')
	end
end
--
-- **********************************************************
-- Irrigation Program Max Run Time Remaining
-- **********************************************************
--	

if uservariables['VarMaxRunTime'] <= 0 and otherdevices[VarIsPump] == 'On' and uservariables['VarFollowsProgram'] == 1
then
VarRemaining_counter = uservariables['VarMaxRunTime']
VarRemaining = VarRemaining_counter + VarMaxRunTime -1
	if logging >= 2 then
	   	if lang == 'Dutch' then	
		print('-- Irrigatie ==> [Programma] - [' .. VarRemaining .. '] minuten resterend totdat programma word beeindigd')
		else
		print('-- Irrigation ==> [Program] - [' .. VarRemaining .. '] minutes remaining until irrigation will stop')	
		end
	end	
end

--
-- **********************************************************
-- Stop Irrigation when Moist Humidity has reached your desired humidity
-- **********************************************************
--

if (uservariables['VarFollowsProgram']) == 1 and (uservariables['VarProgramStopHum']) == 0
	and smoistsensorHumidity >= tonumber (VarTarHum)
then
	commandArray['Variable:VarProgramStopHum']= '1'	
end

if (uservariables['VarFollowsProgram']) == 1 and (uservariables['VarProgramStopHum']) == 1
then
	commandArray['Variable:VarMaxRunTime']=tostring(VarMax)
	commandArray[VarIsPump]='Off'
	commandArray['Variable:VarProgramHasRun']= '1'
	commandArray['Variable:VarFollowsProgram']= '0'		
end

if uservariables['VarProgramHasRun'] == 1
	and (uservariables['VarProgramStopHum']) == 1
	and uservariables['VarProgram'] == 0 
	and uservariables['VarManOverride'] == 0 
	and otherdevices[VarIsPump] == 'Off'
	then
	if logging >= 1 then
	
	   	if lang == 'Dutch' then	
		print('-- Irrigatie ==> [Programma] - Irrigatie programma heeft vandaag al geirrigeerd, Grondvochtigheid target is behaalt')
		print('-- Irrigatie ==> [Programma] - Programma word op de eerst volgende irrigatie dag herstart')
		else	
		print('-- Irrigation ==> [Program] - Irrigation program already irrigated today and soil humidity reached target')
		print('-- Irrigation ==> [Program] - Program will reactivated on the next scheduled irrigation day')		
		end
	end
end	

--
-- **********************************************************
-- Irrigation Program Stop Information
-- **********************************************************
--	

if uservariables['VarProgramHasRun'] == 1
	and (uservariables['VarProgramStopHum']) == 0
	and uservariables['VarProgram'] == 0 
	and uservariables['VarManOverride'] == 0 
	and otherdevices[VarIsPump] == 'Off'
	then
	if logging >= 1 then	
	   	if lang == 'Dutch' then	
		print('-- Irrigatie ==> [Programma] - Irrigatie programma heeft vandaag al geirrigeerd, Grondvochtigheid target is NIET behaalt')
		print('-- Irrigatie ==> [Programma] - Programma word op de eerst volgende irrigatie dag herstart')
		else	
		print('-- Irrigation ==> [Program] - Irrigation program already irrigated today but soil humidity didnt reached target')
		print('-- Irrigation ==> [Program] - Program will reactivated on the next scheduled irrigation day')	
		end
	end
end

if uservariables['VarProgramHasRun'] == 0 and uservariables['VarProgram'] == 0 and uservariables['VarManOverride'] == 0 and otherdevices[VarIsPump] == 'Off'
	then
	
	if logging >= 1 then	
	   	if lang == 'Dutch' then	
		print('-- Irrigatie ==> [Programma] - Irrigatie programma standby, en word hervat als alle condities inorde zijn')
		else
		print('-- Irrigation ==> [Program] - Irrigation program standby, awaiting for all conditions to be okay')	
		end
	end
end

if uservariables['VarManOverride'] == 1 and otherdevices[VarIsPump] == 'Off'
	then
	if logging >= 1 then	
	   	if lang == 'Dutch' then	
		print('-- Irrigatie ==> [Programma] - Irrigatie programma manueel gestopt')	
		else
		print('-- Irrigation ==> [Program] - Irrigation program Stopped, Manual Override')		
		end
	end	
end

if logging >= 1 then
   print("--------------------------------------------------------------------------------------")
end

else
	print("--------------------------------------------------------------------------------------")
end

return commandArray
Setup:
- RPi4 - Domo Stable / Aeotec Z-stick7 / PiHole Unbound Gemini
- RPi4 - PiHole / PiVPN Unbound Gemini
- Synology DS923+ / DS218j
- P1 Gas/Power, SmartGateway watermeter
- Fibaro switches, contacts, plugs, smoke/Co2 ect
- rootfs @ USB HDD
User avatar
Siewert308SW
Posts: 288
Joined: Monday 29 December 2014 15:47
Target OS: Raspberry Pi / ODroid
Domoticz version: Stable
Location: The Netherlands
Contact:

Re: [DIY] Garden irrigation and learning project

Post by Siewert308SW »

V1.0 of the script has been released and opened a new topic for this script only.

viewtopic.php?f=38&t=7290
Setup:
- RPi4 - Domo Stable / Aeotec Z-stick7 / PiHole Unbound Gemini
- RPi4 - PiHole / PiVPN Unbound Gemini
- Synology DS923+ / DS218j
- P1 Gas/Power, SmartGateway watermeter
- Fibaro switches, contacts, plugs, smoke/Co2 ect
- rootfs @ USB HDD
User avatar
epierre
Posts: 522
Joined: Wednesday 05 March 2014 13:16
Target OS: Linux
Domoticz version:
Location: France
Contact:

Re: [DIY] Garden irrigation and learning project

Post by epierre »

Hello,

So bad I've not been able to follow this post...

Is there a way to make it work outside of netherland (without buienradar) ? does forecast.io would provide the same rain forecast ?
ImperiHome & MyDomoAtHome on top of:
868.42Mhz - Vera Lite - Fibaro SS-101, S-211, K-101, FWP - Fortress SSA2
433Mhz - Cubie Domoticz + RFXtrx + Oregon || Foscam 9821W
2,4Ghz - Cubie MySensors Gateway + COV + TempHumidity + Pressure + WaterMeter
zicht
Posts: 251
Joined: Sunday 11 May 2014 11:09
Target OS: Windows
Domoticz version: 2023.1+
Location: NL
Contact:

Re: [DIY] Garden irrigation and learning project

Post by zicht »

Hi

How is the heat dissipation with your systems ?
I have a 220V washing machine valve installed, but i reduced the water pressure significant by a pressure reducer to make it more workable and dose the amount of water spilled. However the valve seems to become very warm (HOT!) now....

I am just curious if you have the same effects ?
I love your work in this project !
Rpi & Win x64. Using : cam's,RFXCom, LaCrosse, RFY, HuE, google, standard Lua, Tasker, Waze traveltime, NLAlert&grip2+,curtains, vacuum, audioreceiver, smart-heating&cooling + many more (= automate all repetitive simple tasks)
ThinkPad
Posts: 890
Joined: Tuesday 30 September 2014 8:49
Target OS: Linux
Domoticz version: beta
Location: The Netherlands
Contact:

Re: [DIY] Garden irrigation and learning project

Post by ThinkPad »

Washingmachine valve is not built to operate long times. Maybe being activate for a minute or so (to fill the drum) and then off for a while.

You could have a look for some butterfly valve or magnet valve. Keyword for having it active for a while is 'duty cycle', look it up so you know what to look for :)
I am not active on this forum anymore.
User avatar
epierre
Posts: 522
Joined: Wednesday 05 March 2014 13:16
Target OS: Linux
Domoticz version:
Location: France
Contact:

Re: [DIY] Garden irrigation and learning project

Post by epierre »

Water valves are "normally off", it means the solenoïd is pushed down by a spring, and when there is a current delivered, the solenoid goes in open mode. Thus it avoid electricity linked water leaks (remember that the pressure must be compensated by the spring while it is off !).

In my garden the valves heat when they are in use which is normal for there is dissipation, nothing is wrong on this.
ImperiHome & MyDomoAtHome on top of:
868.42Mhz - Vera Lite - Fibaro SS-101, S-211, K-101, FWP - Fortress SSA2
433Mhz - Cubie Domoticz + RFXtrx + Oregon || Foscam 9821W
2,4Ghz - Cubie MySensors Gateway + COV + TempHumidity + Pressure + WaterMeter
ThinkPad
Posts: 890
Joined: Tuesday 30 September 2014 8:49
Target OS: Linux
Domoticz version: beta
Location: The Netherlands
Contact:

Re: [DIY] Garden irrigation and learning project

Post by ThinkPad »

Ok, but don't you think there is a difference between a washingmachine valve and a valve meant for irrigation purposes?
I think there is (different coil or something).
I am not active on this forum anymore.
User avatar
epierre
Posts: 522
Joined: Wednesday 05 March 2014 13:16
Target OS: Linux
Domoticz version:
Location: France
Contact:

Re: [DIY] Garden irrigation and learning project

Post by epierre »

ThinkPad wrote:Ok, but don't you think there is a difference between a washingmachine valve and a valve meant for irrigation purposes?
I think there is (different coil or something).
from the picture I see at the beginning no, there is a body and a top, the top holds the spring and the solenoïd it pushes in the bottom.

the washing machine valve has the same design issues that a water gardening one, have water only when needed and never leak in between, for domestic use pressure is between 3-6 bars max 10, in industrial irrigation it can be much more...

heat is not an issue if you water for some minutes, just do not control your inhouse water system with it always on ;-) it is not the same use ;-)

there are quater turn valves if you want to cut your domestic water in case you find a leak, but usually there is a servo motor and this is much more expensive.
ImperiHome & MyDomoAtHome on top of:
868.42Mhz - Vera Lite - Fibaro SS-101, S-211, K-101, FWP - Fortress SSA2
433Mhz - Cubie Domoticz + RFXtrx + Oregon || Foscam 9821W
2,4Ghz - Cubie MySensors Gateway + COV + TempHumidity + Pressure + WaterMeter
User avatar
blackdog65
Posts: 311
Joined: Tuesday 17 June 2014 18:25
Target OS: Raspberry Pi / ODroid
Domoticz version:
Location: Norfolk, UK
Contact:

Re: [DIY] Garden irrigation and learning project

Post by blackdog65 »

Just a quick note...
I've been having problems with pressure loss through the washing machine valves so I bought one of these
http://www.ebay.co.uk/itm/321813372024? ... EBIDX%3AIT
It fits straight onto a standard radiator TRV body. When energized it takes about 20-30 secs to open and the same to close but the flow looks good in preliminary testing.
If it's all good I'll make up a little 4 port manifold with these on and give it a try :D
CubieTruck Master
RasPi slaves
Aeon Labs Z-Stick, multi sensor
Fibaro Dimmers, relays, Universal sensors
EQ3 MAX!
TKB Sockets
RFXCOM
LightwaveRF sockets, switches, relays, doorbell
MySensors
ESPEasy ESP8266-12E
curious
Posts: 132
Joined: Saturday 02 April 2016 19:38
Target OS: -
Domoticz version:
Contact:

Re: [DIY] Garden irrigation and learning project

Post by curious »

@siewert.
I am not allowed to send you a private message because I just joined this forum for a few days.
The photos seems to be removed from your own server/site? Is there a way to publish them again ?

Allthough I am living not far from Zoutkamp I don't want to go and stare in your garden. :)
BarryT
Posts: 361
Joined: Tuesday 31 March 2015 22:06
Target OS: Linux
Domoticz version: 2024.3
Location: east netherlands
Contact:

Re: [DIY] Garden irrigation and learning project

Post by BarryT »

i'm getting these errors, any idea?

2016-04-24 12:44:00.437 Error: EventSystem: in /home/pi/domoticz/scripts/lua/script_time_irrigatie2.lua: /home/pi/domoticz/scripts/lua/script_time_irrigatie2.lua:334: attempt to index field '?' (a nil value)
2016-04-24 12:44:00.454 Error: EventSystem: in /home/pi/domoticz/scripts/lua/--script_time_irrigatie.lua: /home/pi/domoticz/scripts/lua/--script_time_irrigatie.lua:291: attempt to concatenate global 'VarIsPump' (a nil value)

*Edit, its working allready :)
Raspberry / ESP Boards / Relais / Milight / Hue / OTGW / P1 / Xiaomi / RFXCom / RFLink / ZWave / Conbee II / Z2M / MQTT / A lot of scripts and many more..
Software: Linux, Android and Windows
Post Reply

Who is online

Users browsing this forum: No registered users and 1 guest