Page 1 sur 1

[LUA] VMC et capteurs d'humidité

Publié : 23 août 2016, 11:46
par Warp
Bonjour,

j'ai adapter le script de Danny (dannybloe) http://www.domoticz.com/wiki/Humidity_control pour gérer deux capteurs d'humidité (une sale d'eau et une salle de bain :

Code : Tout sélectionner

--[[
 
This script controls the humidity in a typical bathroom setting by detecting
relative rises in humidity in a short period.
Of course it requires a humidity sensor and a binary switch controlling a VMC.
(there is no provision for variable speed ventilators here!)
 
How it works (assuming the default constants as defined below):
Every 5 minutes a reading is done. Every reading is stored together
with the previous reading and is stored in two user variables (humidityS1Tmin5 and humidityS1Tmin10).
So it has two reading over the past 10 minutes.
It then takes the lowest of the two and compares it with the latest reading and
calculates a delta.target
If the delta is 3 or higher (see constants) then the VMC will be turned
on, it calculates the target humidity and the 'humidity-decrease program' is started (VMCFollowsProgram=1).
From then on, every 5 minutes the current humidity is compared to the
stored target humidity. Basically if that target is reached, the VMC is turned off
and the 'program' is ended.
Of course, it is possible that the target is never reached (might start raining outside
or whatever). Then there is a failsafe (VMC_MAX_TIME) after which the ventilator
will be turned off.
 
Also, it will detect if the ventilator is manually switched off during a program
or when it is switched on before the program starts.
 
Along the lines it prints to the log and sends notifications
but of course you can turn that off by removing those lines.
 
--]]
 
commandArray = {}
   

-- declare some constants
-- adjust to your specific situation
local thisfilename = "/var/tmp/HumidityJsonAllDevData.tmp"
SAMPLE_INTERVAL = 5                 -- time in minutes when a the script logic will happen
VMC_DELTA_TRIGGER = 3               -- augmentation de l'humidité qui va déclencher la VMC
VMC_MAX_TIME = 24                   -- nombre maximal de cycles de la VMC en position allumé,
                                    -- dans le cas où on n'a jamais atteint le taux d'humidité cible
TARGET_OFFSET = 4                   -- La VMC s'arrète si la (target+offset) est atteinte.
                                    -- (peut-être qu'il prend trop de temps pour atteindre la vraie cible en raison de serviettes humides, etc.)

VMC_NAME = 'VMC_Rapide'              -- exact device name of the switch turning on/off the ventilator
SENSOR1_NAME = 'SDB_TH'              -- le nom exact du périphérique de capteur d'humidité 
SENSOR2_NAME = 'SDE_TH'              -- le nom exact du périphérique de capteur d'humidité
 
TEST_MODE = false                   -- lorsqu'il est vrai HUMVAR_TEST_MODE est utilisé à la place du capteur réel
TEST_MODE_HUMVARS1 = 0             -- fake humidity value, give it a test value 
TEST_MODE_HUMVARS2 = 0             -- fake humidity value, give it a test value 
PRINT_MODE = false		    -- lorsqu'il est vrai rensignera les logs et envéras des notifications
 
if PRINT_MODE == true then
   print('VMC control')
end
--
-- **** functions ****

-- Init file
--
function init_file(file)
   humCounter = 0
   humidityS1Tmin5 = 0
   humidityS1Tmin10 = 0
   targetVMCOffS1Humidity = 0
   VMCMaxS1Timer = 0
   humidityS2Tmin5 = 0
   humidityS2Tmin10 = 0
   targetVMCOffS2Humidity = 0
   VMCMaxS2Timer = 0
   VMCFollowsProgram = 0
   write_file(file)
   return 
end
-- Write file
--
function write_file(file)
  local f = io.open(file, "w")
  f:write('humCounter = ' .. humCounter .. '\n')
  f:write('humidityS1Tmin5 = ' .. humidityS1Tmin5 .. '\n')
  f:write('humidityS1Tmin10 = ' .. humidityS1Tmin10 .. '\n')
  f:write('targetVMCOffS1Humidity = ' .. targetVMCOffS1Humidity .. '\n')
  f:write('VMCMaxS1Timer = ' .. VMCMaxS1Timer .. '\n')
  f:write('humidityS2Tmin5 = ' .. humidityS2Tmin5 .. '\n')
  f:write('humidityS2Tmin10 = ' .. humidityS2Tmin10 .. '\n')
  f:write('targetVMCOffS2Humidity = ' .. targetVMCOffS2Humidity .. '\n')
  f:write('VMCMaxS2Timer = ' .. VMCMaxS2Timer .. '\n')
  f:write('VMCFollowsProgram = ' .. VMCFollowsProgram .. '\n')
  f:close()
  return 
end
-- see if the file exists
function file_exists(file)
  local f = io.open(file, "rb")
  if f then f:close() end
  return f ~= nil
end
-- get all lines from a file, returns an empty 
-- list/table if the file does not exist
function lines_from(file)
  if not file_exists(file) then 
    init_file(file)
    -- return {} 
  end
  lines = {}
  for line in io.lines(file) do 
    lines[#lines + 1] = line
  end
  return lines
end

 
-- get the global variables:
-- this script runs every minute, humCounter is used to create SAMPLE_INTERVAL periods
-- tests the functions above
local file = thisfilename
local lines = lines_from(file)


-- print all line numbers and their contents
for k,v in pairs(lines) do
    svariable, snumber = v:match("([^,]+)=([^,]+)")
    if (tostring(svariable) == 'humCounter ') then 
	humCounter = tonumber(snumber)
    elseif (tostring(svariable) == 'humidityS1Tmin5 ') then        -- youngest reading
	humidityS1Tmin5 = tonumber(snumber)
    elseif (tostring(svariable) == 'humidityS1Tmin10 ') then       -- oldest reading
	humidityS1Tmin10 = tonumber(snumber)
    elseif (tostring(svariable) == 'targetVMCOffS1Humidity ') then -- target humidity
	targetVMCOffS1Humidity = tonumber(snumber)
    elseif (tostring(svariable) == 'VMCMaxS1Timer ') then
	VMCMaxS1Timer = tonumber(snumber)
    elseif (tostring(svariable) == 'humidityS2Tmin5 ') then        -- youngest reading
	humidityS2Tmin5 = tonumber(snumber)
    elseif (tostring(svariable) == 'humidityS2Tmin10 ') then       -- oldest reading
	humidityS2Tmin10 = tonumber(snumber)
    elseif (tostring(svariable) == 'targetVMCOffS2Humidity ') then -- target humidity
	targetVMCOffS2Humidity = tonumber(snumber)
    elseif (tostring(svariable) == 'VMCMaxS2Timer ') then
	VMCMaxS2Timer = tonumber(snumber)
    elseif (tostring(svariable) == 'VMCFollowsProgram ') then    -- marker indicating that the
	VMCFollowsProgram = tonumber(snumber)                    -- decrease program is started
    end
end


targetS1 = 0 -- will hold the target humidity when the program starts
targetS2 = 0 -- will hold the target humidity when the program starts
 
-- get the current humidity value
if (TEST_MODE) then
    currentS1 = TEST_MODE_HUMVARS1
    currentS2 = TEST_MODE_HUMVARS2
else
    currentS1 = otherdevices_humidity[SENSOR1_NAME]
    currentS2 = otherdevices_humidity[SENSOR2_NAME]  
end
 
-- check if the sensor is on or has some weird reading
if (currentS1 == 0 or currentS1 == nil or currentS2 == 0 or currentS2 == nil) then
    print('currentS1 is 0 or nil. Skipping this reading')
    commandArray['SendNotification'] = 'currentS1 or currentS2 is 0 or nil. Skipping this reading'
    return commandArray
end
 
if PRINT_MODE == true then
		print('Current humidity S1:' .. currentS1)
		print('humidityS1Tmin5: ' .. humidityS1Tmin5)
		print('humidityS1Tmin10: ' .. humidityS1Tmin10)
		print('VMCMaxS1Timer: ' .. VMCMaxS1Timer)
		print('targetVMCOffS1Humidity:' .. targetVMCOffS1Humidity)
		print('Current humidity S2:' .. currentS2)		
		print('humidityS2Tmin5: ' .. humidityS2Tmin5)
		print('humidityS2Tmin10: ' .. humidityS2Tmin10)
		print('VMCMaxS2Timer: ' .. VMCMaxS2Timer)
		print('targetVMCOffS2Humidity:' .. targetVMCOffS2Humidity)
		print('humCounter:' .. humCounter)
		print('VMCFollowsProgram:' .. VMCFollowsProgram)
end
 
-- increase cycle counter
humCounter = humCounter + 1
 
if (humCounter >= SAMPLE_INTERVAL) then
 
    if (humidityS1Tmin5 == 0) then
        -- initialization, assume this is the first time
        humidityS1Tmin5 = currentS1
        humidityS1Tmin10 = currentS1
    end
    if (humidityS2Tmin5 == 0) then
        -- initialization, assume this is the first time
        humidityS2Tmin5 = currentS2
        humidityS2Tmin10 = currentS2
    end    
 
    humCounter = 0 -- reset the cycle counter
 
    -- pick the lowest history value to calculate the delta
    -- this also makes sure that two relative small deltas in the past 2*interval minutes are treated as one larger rise
    -- and therefore will still trigger the ventilator
    -- I don't want to use a longer interval instead because I want the ventilator to start as soon as possible
    -- (so rather after 5 minutes instead of after 15 minutes because the mirrors in the bathroom become kinda useless ;-)

    -- Choisir la valeur de l'histoire la plus basse pour calculer le delta 
    -- ce qui rend aussi sûr que deux relativement petits deltas dans les dernières minutes d'intervalle 2 * sont traitées comme une seule grande hausse 
    -- et ne seront donc encore déclencher le ventilateur 
    -- Je ne veux pas utiliser un intervalle plus long à la place parce que je veux que le ventilateur commence dès que possible 
    -- (donc plutôt au bout de 5 minutes au lieu de 15 minutes, parce que les miroirs dans la salle de bains devient un peu inutile ;-)

    deltaS1 = currentS1 - math.min(humidityS1Tmin10, humidityS1Tmin5)
    deltaS2 = currentS2 - math.min(humidityS2Tmin10, humidityS2Tmin5)    
if PRINT_MODE == true then
	print('DeltaS1: ' .. deltaS1)
	print('DeltaS2: ' .. deltaS2)	
end
 
    -- pick the lowest history value
    targetS1 = math.min(humidityS1Tmin10, humidityS1Tmin5) + TARGET_OFFSET
    targetS2 = math.min(humidityS2Tmin10, humidityS2Tmin5) + TARGET_OFFSET    
 
    -- shift the previous measurements
    humidityS1Tmin10 = humidityS1Tmin5
    humidityS2Tmin10 = humidityS2Tmin5    
    -- and store the currentS1 & currentS2
    humidityS1Tmin5 = currentS1
    humidityS2Tmin5 = currentS2
 
    if (otherdevices[VMC_NAME]=='Off' or (otherdevices[VMC_NAME]=='On' and VMCFollowsProgram==0)) then
        -- either the VMC is off or it is on but the decrease program has not started
        -- in that latter case we start the program anyway. This could happen if someone turns on the ventilator
        -- manually because he/she is about to take a shower and doesn't like damp mirrors.
        -- I don't do this because the ventilator removes heat from the bathroom and I want this to happen
        -- as late as possible ;-)
	    -- Soit le ventilateur est éteint, ou il est allumé mais le programme de déshumidification n'a pas commencé
        -- Dans ce dernier cas, nous commençons le programme de toute façon. Cela pourrait se produire si quelqu'un se met en marche le ventilateur
        -- Manuellement, car il / elle est sur le point de prendre une douche et ne veux pas de miroirs humides.
        -- Je ne fais pas cela parce que le ventilateur évacue la chaleur de la salle de bains et je veux que cela se produise
        -- Le plus tard possible;-)
 
        if (VMCFollowsProgram == 1 and otherdevices[VMC_NAME]=='Off') then
	    -- probable que quelqu'un a éteint le ventilateur tandis que le programme de déshumidification est exécuté.
            VMCFollowsProgram = 0
        end
 
        -- see if we have to turn it on
        if (deltaS1 >= VMC_DELTA_TRIGGER) then
            -- time to start the VMC
            commandArray[VMC_NAME] = 'On'
            targetVMCOffS1Humidity = targetS1
 
            if (VMCFollowsProgram == 1) then
                print('Ventilator was already on but we start the de-humidifying program')
            end
 
            VMCFollowsProgram = 1
 
            -- set the safety stop
            VMCMaxS1Timer = VMC_MAX_TIME
 
			if PRINT_MODE == true then
                print('Rise in humidity. Turning on the vents. DeltaS1: ' .. deltaS1)
                print('Target humidity for turning the ventilator: ' ..targetVMCOffS1Humidity)
                commandArray['SendNotification'] = 'Ventilator is on#The ventilator was activated at humidity level ' .. currentS1 .. '#0'
			end
        end
        if (deltaS2 >= VMC_DELTA_TRIGGER) then
            -- time to start the VMC
            commandArray[VMC_NAME] = 'On'
            targetVMCOffS2Humidity = targetS2
 
            if (VMCFollowsProgram == 1) then
                print('Ventilator was already on but we start the de-humidifying program')
            end
 
            VMCFollowsProgram = 1
 
            -- set the safety stop
            VMCMaxS2Timer = VMC_MAX_TIME
 
			if PRINT_MODE == true then
                print('Rise in humidity. Turning on the vents. DeltaS2: ' .. deltaS2)
                print('Target humidity for turning the ventilator: ' ..targetVMCOffS2Humidity)
                commandArray['SendNotification'] = 'Ventilator is on#The ventilator was activated at humidity level ' .. currentS2 .. '#0'
			end
        end    
 
    else
        if (VMCMaxS1Timer > 0 or VMCMaxS2Timer > 0) then
            -- possible that someone started the ventialator manually
            if VMCMaxS1Timer > 0 then VMCMaxS1Timer = VMCMaxS1Timer - 1 end
            if VMCMaxS2Timer > 0 then VMCMaxS2Timer = VMCMaxS2Timer - 1 end
        end
 
 
        if (VMCFollowsProgram == 1) then -- not manually started
 
            if (deltaS1 >= VMC_DELTA_TRIGGER) then
                -- ok, there is another VMC_DELTA_TRIGGER rise in humidity
                -- when this happen we reset the VMCMaxS1Timer to a new count down
                -- because we have to ventilate a bit longer due to the extra humidity
                if PRINT_MODE == true then
				    print('Another large increase detected, resetting max timer. DeltaS1: ' .. deltaS1)
				end
                VMCMaxS1Timer = VMC_MAX_TIME
            end
            if (deltaS2 >= VMC_DELTA_TRIGGER) then
                -- ok, there is another VMC_DELTA_TRIGGER rise in humidity
                -- when this happen we reset the VMCMaxS1Timer to a new count down
                -- because we have to ventilate a bit longer due to the extra humidity
                if PRINT_MODE == true then
				    print('Another large increase detected, resetting max timer. DeltaS2: ' .. deltaS2)
				end
                VMCMaxS2Timer = VMC_MAX_TIME
            end            
 
            -- first see if it can be turned off
            if (
                ((currentS1 <= targetVMCOffS1Humidity or targetVMCOffS1Humidity==0) and (currentS2 <= targetVMCOffS2Humidity or targetVMCOffS2Humidity==0)) 
                or (VMCMaxS1Timer==0 and VMCMaxS2Timer==0)
                ) then
                commandArray[VMC_NAME] = 'Off'
                msg = ''
 
                if ((VMCMaxS1Timer==0 and VMCMaxS2Timer==0) and (currentS1 > targetVMCOffS1Humidity or currentS2 > targetVMCOffS2Humidity)) then
                    msg = 'Target not reached but safety time-out is triggered.'
                    if PRINT_MODE == true then
					    print(msg)
					end
                else
                    msg = 'Target humidity reached'
                    if PRINT_MODE == true then
					    print(msg)
					end
                end
 
				if PRINT_MODE == true then
                    print('Arret de la VMC')
                    msg = msg .. '\nArret de la VMC'
				end
 
                targetVMCOffS1Humidity = 0
                VMCMaxS1Timer = 0
                targetVMCOffS2Humidity = 0
                VMCMaxS2Timer = 0                
                VMCFollowsProgram = 0
                -- reset history in this case.. we start all over
                -- Tmin10 is still in the 'ventilator=On'-zone
                humidityS1Tmin10 = humidityS1Tmin5
                humidityS2Tmin10 = humidityS2Tmin5                
                 if PRINT_MODE == true then
				    commandArray['SendNotification'] = 'VMC is off#' .. msg .. '#0'
				end
 
            else
                -- we haven't reached the target yet
               if PRINT_MODE == true then
			    print('Humidity deltaS1: ' .. deltaS1)
			    print('Humidity deltaS2: ' .. deltaS2)
			   end
            end
        end
    end
 
if PRINT_MODE == true then
    print('New values >>>>>>>>>>>')
    print('humidityS1Tmin5: ' .. humidityS1Tmin5)
    print('humidityS1Tmin10: ' .. humidityS1Tmin10)
    print('VMCMaxS1Timer: ' .. VMCMaxS1Timer)
    print('targetVMCOffS1Humidity:' .. targetVMCOffS1Humidity)
    print('humidityS2Tmin5: ' .. humidityS2Tmin5)
    print('humidityS2Tmin10: ' .. humidityS2Tmin10)
    print('VMCMaxS2Timer: ' .. VMCMaxS2Timer)
    print('targetVMCOffS2Humidity:' .. targetVMCOffS2Humidity)
    print('humCounter:' .. humCounter)
    print('VMCFollowsProgram:' .. VMCFollowsProgram)
end
 
end
 
-- save the globals
write_file(file)

return commandArray