[LUA] Irrigation script - (extensive) v1.0

Post Reply
User avatar
Siewert308SW
Posts: 607
Joined: Monday 29 December 2014 16:47
Target OS: Raspberry Pi
Domoticz version: Beta
Location: The Netherlands - Zoutkamp (gn)
Contact:

[LUA] Irrigation script - (extensive) v1.0

Post by Siewert308SW » Tuesday 14 July 2015 14:32

Introduction:
This script has the intention to control and maintain your garden soil humidity.
Its a hodgepodge of different scripts found on the Domoticz forum.
Took me a couple of weeks to write/test (copy/past) the script.
But i'm happy i can share this script with you all.
It's my first LUA script so it may not be cleanest but it does the job ;-)
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: [LINK]
Somehow it got out of hand and got big.
So i thought that maybe some of you could have a benefit 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, Domoticz and other features needed to use this script.
As i won't explain the entire installation ;-)

The script does the following:
- Checks if all Virtual switches and uservariables are available, if not then it won't trigger the program and alert you which variable is missing
- It scraps WeatherUnderground data and processing it to usable data
- It monitors buienradar (optional) to see if there are any showers upcoming 2hr
- It scraps temperature and humidity from your moist sensor and processing it to usable data
- It lets you choose when to irrigate via (Day of the week, month and time of the day)
- By an extensive Settings Menu you can set various settings to control when to irrigate
settings ranges from: Min/Max WeaterTemp, Min/Max SoilTemp, Min/Max SoilHumidity pct, Amount of rain, wind, UV, day, month to stop or start irrigating.
- Also it detects if you are irrigating manual or stopped the program manually
- When a irrigation has taken place then the next irrigation will take place at the next scheduled Time Of The Day
- The irrigation has a optional MaxRunTime, when exceeded then it will stop at you desired MaxRunTime
- Irrigation will stop when the Soil Humidity has reached your desired Humidity Target

Dependencies:
- Virtual switch to be able to manual override the irrigation program (Manual Override)
- Soil Moist & Humidity sensor
- Active WeatherUnderground account
- Switch to be able to control your waterpump/valve which is somehow wireless connected to domoticz

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)

Finalize:
Be aware that i'm not a coder and it's maybe not 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 ;-)

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

Dutch Log Translation:
Irrigatie1.png
Irrigatie1.png (50.51 KiB) Viewed 2357 times
English Log Translation:
irrigation2.png
irrigation2.png (50.87 KiB) Viewed 2357 times

Code: Select all

--[[

   script_time_irrigation.lua
   @author: Siewert Lameijer
   @since: 2015-07-14
   @version: 1.0
   @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.
Its 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 benefit 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 to usable data
- It monitors buienradar (optional) to see if there are any showers upcoming 2hr
- It scraps temperature and humidity from your moist sensor and processing it to usable data
- It lets you choose when to irrigate(Day of the week, month and time of the day)
- By an extensive Settings Menu you can set various settings to control when to irrigate
settings ranges from: Min/Max WeaterTemp, Min/Max SoilTemp, Min/Max SoilHumidity pct, Amount of rain, wind, UV, day, month to stop or start irrigating.
- Also it detects if you are irrigating manual or stopped the program manually
- When a irrigation has taken place then the next irrigation will take place at the next scheduled Time Of The Day
- The irrigation has a optional MaxRunTime, when exceeded then it will stop at you desired MaxRunTime
- Irrigation will stop when the Soil Humidity has reached your desired Humidity Target

The Hardware i use:
- DIY Garden irrigation piping as seen in the topic
- Washer Watervalve 2-way
- KaKu ACM-3500-3 3-in-1 unit 

Be aware that i'm not a coder and it's maybe not 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

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

Dependencies:

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 1.0
- Initial release

Version 0.9
- Added thirth Log Info option (only Pump info)

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

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,
-- 3 = Only Pump Info
local logging = 2

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

-- Name of your irrigation switch for water valve/pump
local VarIsPump = 'Irrigation_Valve'

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

--
-- **********************************************************
-- 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 = '5'

-- 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 (only usable for Dutch users)
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 
-- mm/per uur = 10^((waarde -109)/32)
-- Dus 77 = 0.1 mm/uur 
local  VarMaxRainFall = '100'

--
-- **********************************************************
-- MoistSensor Variables
-- **********************************************************
-- 

-- Name of your Moist Sensor device
local MoistSensor = 'MoistSensor'

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

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

-- 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 = ''

local VarDay3 = 'Wed'

local VarDay4 = ''

local VarDay5 = 'Fri'

local VarDay6 = ''

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 and logging <= 2 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 and logging <= 2 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 and logging <= 2 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 and logging <= 2 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 and logging <= 2 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 and logging <= 2 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 and logging <= 2 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 and logging <= 2 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 and logging <= 2 then
		print("--------------------------------------------------------------------------------------")
	if lang == 'Dutch' then
		print("-- Irrigatie [GROND CONDITIES]");	
	else	
		print("-- Irrigation [SOIL CONDITION]");
	end
	end
	
if logging >= 1 and logging <= 2 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	

--
-- **********************************************************
-- MoistSensor 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

--
-- **********************************************************
-- MoistSensor 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

--
-- **********************************************************
-- MoistSensor online check
-- **********************************************************
--

if (smoistsensorTemp == 0 or smoistsensorTemp == nil) then
if logging >= 1 and logging <= 2 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 and logging <= 2 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

--
-- **********************************************************
-- MoistSensor 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 and logging <= 2 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 and logging <= 2 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 and logging <= 2 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 and logging <= 2 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 and logging <= 2 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 and logging <= 2 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 and logging <= 2 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 and logging <= 2 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 or logging == 3 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 or logging == 3 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 or logging == 3 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 or logging == 3 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 or logging == 3 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 or logging == 3 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 or logging == 3 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 or logging == 3 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 or logging == 3 then
   print("--------------------------------------------------------------------------------------")
end

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

return commandArray
Setup:
- RPi3 - PIco HV3.0A / Domo Beta 3.9XXX / RFXtrx433E / Aeotec Gen5
- RPi3 - PIco HV3.0A / PiHole / PiVPN / NAS / Print Server
- Youless Elec&Gas
- FI9803P Cams
- KD101 detectors
- Zwave & KaKu

MyDomoticz scripts: @GitHub
PIco UPS Toolkit: @GitHub

User avatar
ThinkPad
Posts: 1754
Joined: Tuesday 30 September 2014 8:49
Target OS: Linux
Domoticz version: beta
Location: The Netherlands
Contact:

Re: [LUA] Irrigation script - (extensive) v1.0

Post by ThinkPad » Tuesday 14 July 2015 15:52

Moved to 'Scripts' subforum.

P.S. Have you considered making a wiki-page? Login credentials for wiki are the same as for the forum. To create a new page just request a non-existing URL (http://domoticz.com/wiki/Garden_irrigation)
ThinkTheme - theme for Domoticz
My (Dutch) blog: http://thinkpad.tweakblogs.net - My Domoticz scripts: Bitbucket
I'm not (very) active anymore on this forum as i don't use Domoticz anymore.

User avatar
Siewert308SW
Posts: 607
Joined: Monday 29 December 2014 16:47
Target OS: Raspberry Pi
Domoticz version: Beta
Location: The Netherlands - Zoutkamp (gn)
Contact:

Re: [LUA] Irrigation script - (extensive) v1.0

Post by Siewert308SW » Tuesday 14 July 2015 15:59

ThinkPad wrote:Moved to 'Scripts' subforum.

P.S. Have you considered making a wiki-page? Login credentials for wiki are the same as for the forum. To create a new page just request a non-existing URL (http://domoticz.com/wiki/Garden_irrigation)
Thx for moving the thread.
Did consider it but couldn't find a way to create one.
So just claiming a not existing url does the job, thx

[edit]
This should should do the job ;-)
https://www.domoticz.com/wiki/Garden_Irrigation
Setup:
- RPi3 - PIco HV3.0A / Domo Beta 3.9XXX / RFXtrx433E / Aeotec Gen5
- RPi3 - PIco HV3.0A / PiHole / PiVPN / NAS / Print Server
- Youless Elec&Gas
- FI9803P Cams
- KD101 detectors
- Zwave & KaKu

MyDomoticz scripts: @GitHub
PIco UPS Toolkit: @GitHub

niki_lauda
Posts: 130
Joined: Saturday 31 August 2013 14:48
Target OS: Raspberry Pi
Domoticz version: beta
Location: Eindhoven (NL)
Contact:

Re: [LUA] Irrigation script - (extensive) v1.0

Post by niki_lauda » Tuesday 14 July 2015 19:11

Siewert
This is just what I was looking for. Because of the drouhgt in the last few month my garden had a hard time.

I will implement the script and report back.

User avatar
Siewert308SW
Posts: 607
Joined: Monday 29 December 2014 16:47
Target OS: Raspberry Pi
Domoticz version: Beta
Location: The Netherlands - Zoutkamp (gn)
Contact:

Re: [LUA] Irrigation script - (extensive) v1.0

Post by Siewert308SW » Tuesday 14 July 2015 19:17

niki_lauda wrote:Siewert
This is just what I was looking for. Because of the drouhgt in the last few month my garden had a hard time.

I will implement the script and report back.
Your welcome,
Thats why i wrote it, i'm a lot from home these days and due to the drought and upcoming summer holidays i wanted to try if i could automate my garden irrigation.
I have tested it with virtual switches as the last couple of days a lot of rain fell and no irrigation is required.
Today it's the first time it is live on my PI so i hope as we can expect warm weather again at the end of the week to test the script live ;-)
Setup:
- RPi3 - PIco HV3.0A / Domo Beta 3.9XXX / RFXtrx433E / Aeotec Gen5
- RPi3 - PIco HV3.0A / PiHole / PiVPN / NAS / Print Server
- Youless Elec&Gas
- FI9803P Cams
- KD101 detectors
- Zwave & KaKu

MyDomoticz scripts: @GitHub
PIco UPS Toolkit: @GitHub

Toon
Posts: 1
Joined: Monday 20 June 2016 18:43
Target OS: NAS (Synology & others)
Domoticz version:
Contact:

Re: [LUA] Irrigation script - (extensive) v1.0

Post by Toon » Monday 20 June 2016 18:52

My problem is a lot smaller than what is written here.

I have a stand alone irrigation computer. This has a rain sensor possibility. Basically if it rained it blocks the computer by disconnecting a wire. I want to use this with a switch connected to the server.
What I want is to count the rain in the last x days . If the amount of rain from the wheather site is above a certain amount I want to have a virtual switch to go on, if it is below a certain level to be off. The addition of buiienradar is nice to have.

This virtual switch I will connect to the real switch to act as rain sensor on my irrigation computer.

I'm not a programmer so making this script is above my head.

How would a lua script to make this virtual switch look like?

Many regards if anybody could help me.

ruben86
Posts: 5
Joined: Tuesday 02 June 2015 23:42
Target OS: Raspberry Pi
Domoticz version: 2.4028
Contact:

Re: [LUA] Irrigation script - (extensive) v1.0

Post by ruben86 » Monday 11 July 2016 11:03

I love this script! But it would be helpful for me to make it possible to irrigate twice a day. Since I am using a dripping system.
Is it somehow possible to add the function to irrigate both in the morning and in the night?

Thanks!

astrapowerrr
Posts: 59
Joined: Tuesday 31 January 2017 21:34
Target OS: -
Domoticz version:
Contact:

Re: [LUA] Irrigation script - (extensive) v1.0

Post by astrapowerrr » Tuesday 10 July 2018 22:27

Hi Siewert,

What a nice script I got it running this evening. And tomorrow will be the first scheduled irrigation day if the weather is good.

It was simple to copy.
So thanks for writing this script.

When I want to use Buienradar I get a error in the log.
Googled and searched the forum.
But I don’t know if it’s specific to your script.
See my screenshot from the log files. Image

So if you or somebody can help me with this I would appreciate.


UPDATE:
Found the solution somewhere else on this forum.


Try to add the -L paramter in the curl command: read = os.execute('curl -L -s -o '..tempfilename..' "'..url..'"')
This enable follow redirects using the location header flag

That's the one !
I had already changed this, but made it -s -o -L instead of -L -s -o :lol: :lol:

so siewert if you still follow/update your script, maybe this needs to be fixed in the future for other members.

ps there are als 2 dutch translation mistakes:
1 inorde needs to be in orde
2 vandaag is het en dag needs to be vandaag is het een dag




Verzonden vanaf mijn iPhone met Tapatalk

Post Reply

Who is online

Users browsing this forum: No registered users and 1 guest