script détection fuite d’eau

je souhaitais mettre en place un script pour « surveiller » ma consommation d’eau afin d’etre prévenu en cas de consommation anormale. Les impulsions remontent de mon compteur via snmp sur un compteur virtuel Domoticz, mais il est adaptable à n’importe quel compteur ayant une consommation non permanente (test de la valeur zéro) Possibilité de surveiller plusieurs compteurs.
2016-05-04 18_30_26-Domoticz

Le principe : Vérification de la consommation d’eau toutes les 5mn par comparaison avec l’index précédent présent dans une variable utilisateur
(créé automatiquement lors de la première exécution du script). si l’index compteur et l’index -5mn sont identique le device probabilité est remis à zéro (pas de fuite)
si l’index compteur et l’index-5mn sont différents = consommation d’eau, incrémentation du device probabilité de 8% et mise à jour de la variable associée
si une consommation continue pendant une heure le device probabilité aura été incrémenté 12 fois, le device probabilité sera donc à 96% => très forte probabilité
une notification est paramétrée dans Domoticz sur ce device à 80%.
Le script est lu toutes les minutes mais ne vérifie les données que toutes les 5 minutes

--[[script_time_detec_fuite_eau.lua
auteur : papoo
MAJ : 30/07/2017
Création : 25/04/2016
Principe : 
vérification de la consommation d'eau toutes les 5mn par comparaison avec l'index précédent, présent dans une variable utilisateur 
(créée automatiquement lors de la première exécution du script). si l'index compteur et l'index -5mn sont identique le device probabilité est remis à zéro (pas de fuite)
si l'index compteur et l'index -5mn sont différents = consommation d'eau, incrémentation du device probabilité de 8% et mise à jour de la variable associée
si il y a une consommation continue pendant une heure, le device probabilité aura été incrémenté 12 fois, le device probabilité sera donc à 96% => très forte probabilité
Le seuil de notification est paramétrable via la variable seuil_notificationication . Possibilité de surveiller plusieurs compteurs
Le script est lu toutes les minutes mais ne vérifie les données que toutes les 5 minutes
/script-detection-fuite-deau
http://easydomoticz.com/forum/viewtopic.php?f=8&t=1913&hilit=d%C3%A9tection+fuite+eau#p16950
]]--

--------------------------------------------
------------ Variables à éditer ------------
-------------------------------------------- 
local nom_script = "detection fuite d\'eau"
local version = "1.23"
local debugging = false  			-- true pour voir les logs dans la console log Dz ou false pour ne pas les voir
local url = '127.0.0.1:8080'   	-- user:pass@ip:port de domoticz
local les_compteurs = {};
-- 1er compteur : name ="nom du device compteur 1", idx=idx et  nom (dummy) du capteur pourcentage probabilité surconsommation associé, seuil_notification= seuil pour l'envoie des notifications
les_compteurs[1] = {name="Compteur Eau Froide", idx=643, dummy="Probabilité Fuite Eau Froide", seuil_notification=50}
-- 2eme compteur : name ="nom du device compteur 2", idx=idx du capteur pourcentage probabilité surconsommation associé ("" si inexistant), seuil_notification= seuil pour l'envoie des notifications
les_compteurs[2] = {name="Compteur Eau Chaude", idx=644, dummy="Probabilité Fuite Eau Chaude", seuil_notification=85}

--------------------------------------------
----------- Fin variables à éditer ---------
--------------------------------------------

--------------------------------------------
---------------- Fonctions -----------------
--------------------------------------------
package.path = package.path..";/home/pi/domoticz/scripts/lua/fonctions/?.lua"
require('fonctions_perso')
--------------------------------------------
-------------- Fin Fonctions ---------------
--------------------------------------------

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

-- ********************************************************************************

-- if time.min % 5 == 0 then
if ((time.min-1) % 5) == 0 then
	voir_les_logs("=========== ".. nom_script .." (v".. version ..") ===========",debugging)
			    for i,d in ipairs(les_compteurs) do
	voir_les_logs("--- --- ---  Boucle ".. i .." --- --- --- ",debugging)

    v=otherdevices[d.name]                        
					if v==nil or v=="" then                  -- multi valued ?
					v=otherdevices_svalues[d.name] or ""
					voir_les_logs("--- --- --- "..d.name.." = "..v,debugging);
					end
		
			if(uservariables[d.name] == nil) then -- Création de la variable  car elle n'existe pas
				voir_les_logs("--- --- --- La Variable " .. d.name .." n'existe pas --- --- --- ",debugging)
				commandArray['OpenURL']=url..'/json.htm?type=command¶m=saveuservariable&vname='..url_encode(d.name)..'&vtype=2&vvalue=1'
				adresse = url_encode(d.name)
				voir_les_logs("--- --- --- adresse " .. adresse .."  --- --- --- ",debugging);
				voir_les_logs("--- --- --- Création de la Variable " .. d.name .." manquante --- --- --- ",debugging)
				print('script supendu')
			else
				--voir_les_logs("--- --- --- la Variable : "..d.name.." existe",debugging);
			
					if (tonumber(uservariables[d.name]) < tonumber(v) ) then --La  variable est inferieure au compteur => consommation d'eau
						conso = tonumber(v) - tonumber(uservariables[d.name])
						voir_les_logs("--- --- --- sur le "..d.name.." il a été consommé  : " .. conso .." Litre(s) --- --- --- ",debugging)		
						commandArray[#commandArray+1] = {['Variable:'..d.name] = tostring(v)} -- Mise à jour Variable
						voir_les_logs("--- --- ---  Mise à jour de la variable "..d.name.." --- --- --- ",debugging)
						
							if(d.idx ~= "" and d.dummy ~= "") then
								voir_les_logs("--- --- --- valeur de la variable pourcentage "..otherdevices_svalues[d.dummy].."%  --- --- --- ",debugging)	--tonumber(otherdevices_svalues['lamp dimmer'])
								local result = tonumber(otherdevices_svalues[d.dummy]) + 8
								commandArray[#commandArray+1] = {['UpdateDevice'] = d.idx .. "|0|" .. result} -- Mise à jour probabilité => 8% * (60/5) = 96% en 1 heure
								
							end
					end
					if (tonumber(uservariables[d.name]) == tonumber(v) ) then -- aucune consommation 
							if(d.idx ~= "" and d.dummy ~= "") then
								local result = "0"
								commandArray[#commandArray+1] = {['UpdateDevice'] = d.idx .. "|0|" .. result} -- Mise à jour probabilité à 0%
						voir_les_logs("--- --- ---  Aucune consommation sur le "..d.name..", Mise à jour du device ".. d.idx .." ".. d.dummy .." à zéro --- --- --- ",debugging)		
								
							end				
						voir_les_logs("--- --- ---  Aucune consommation sur le "..d.name.." --- --- --- ",debugging)
					end
					
					if tonumber(uservariables[d.name])~= nil and tonumber(uservariables[d.name]) > tonumber(v)  then --La  variable est supérieure au compteur => Mise à jour index consommation d'eau
						conso =  tonumber(uservariables[d.name]) - tonumber(v)
						voir_les_logs("--- --- --- sur le "..d.name.." il a un écart de  : " .. conso .." Litre(s) --- --- --- ",debugging)		
						commandArray[#commandArray+1] = {['Variable:'..d.name] = tostring(v)} -- Mise à jour Variable
						
						voir_les_logs("--- --- ---  Mise à jour de la variable "..d.name.." --- --- --- ",debugging)
					end					
					
					
			end
   
					voir_les_logs("--- --- --- Probabilité à  ".. 	otherdevices[d.dummy] .."% sur le "..d.name.." --- --- --- ",debugging) 
					if tonumber(otherdevices[d.dummy]) ~= nil and tonumber(otherdevices[d.dummy]) > d.seuil_notification then
					commandArray[#commandArray+1] = {['SendNotification'] = 'Alerte surconsommation#surconsommation sur le ' ..d.name.. '! Probabilité à ' ..tonumber(otherdevices[d.dummy]).. '%'}
					
					end
	end                                            
   voir_les_logs("========= Fin ".. nom_script .." (v".. version ..") =========",debugging)
end -- if time


-- ********************************************************************************

return commandArray


7 thoughts on “script détection fuite d’eau

  1. Bonjour,
    Merci, le script fonctionne correctement maintenant

    2017-10-14 11:15:00.119 LUA: =========== detection fuite d’eau (v1.21) ===========
    2017-10-14 11:15:00.119 LUA: — — — Boucle 1 — — —
    2017-10-14 11:15:00.119 LUA: — — — sur le Eau Froide il a un écart de : 305.7 Litre(s) — — —
    2017-10-14 11:15:00.119 LUA: — — — Mise à jour de la variable Eau Froide — — —
    2017-10-14 11:15:00.119 LUA: — — — Probabilité à 0.0% sur le Eau Froide — — —
    2017-10-14 11:15:00.119 LUA: ========= Fin detection fuite d’eau (v1.21) =========

  2. ton script n’arrive pas à créer la variable nécessaire à son fonctionnement
    peut être parce que tu n’as pas autorisé dans domoticz l’utilisation de l’ip 127.0.0.1
    via l’onglet réglage => Paramètres => système =>
    Réseaux locaux (pas d’identification):
    Réseaux:
    192.168.1.*;127.0.0.*
    (Séparez par un point-virgule, par exemple: 127.0.0.*;192.168.0.*)
    si ça ne fonctionne toujours pas , essai de creer manuellement la variable « Eau Froide »
    dans l’onglet réglage => plus d’options => variables utilisateur (variable de type chaine)

  3. Merci pour le script fonctions_perso.lua
    Il y a maintenant du mieux, toutefois il me manque maintenant une variable :

    2017-08-05 23:05:00.268 LUA: =========== detection fuite d’eau (v1.21) ===========
    2017-08-05 23:05:00.268 LUA: — — — Boucle 1 — — —
    2017-08-05 23:05:00.268 LUA: — — — La Variable Eau Froide n’existe pas — — —
    2017-08-05 23:05:00.268 Error: EventSystem: in /home/pi/domoticz/scripts/lua/script_time_detec_fuite_eau.lua: …/pi/domoticz/scripts/lua/script_time_detec_fuite_eau.lua:63: attempt to call global ‘url_encode’ (a nil value)

    Je ne vois pas trop ce qu’il manque…

  4. voici le script fonctions_perso.lua à placer dans le répertoire /home/pi/domoticz/scripts/lua/fonctions/

    
    -- domoticz
    domoticzIP = '127.0.0.1'
    domoticzPORT = '8080'
    domoticzUSER = ''		-- nom d'utilisateur
    domoticzPSWD = ''		-- mot de pass
    domoticzPASSCODE = ''	-- pour interrupteur protégés
    domoticzURL = 'http://'..domoticzIP..':'..domoticzPORT
    -- chemin vers le dossier lua
    -- if (package.config:sub(1,1) == '/') then
    	-- luaDir = debug.getinfo(1).source:match("@?(.*/)")
    -- else
        -- luaDir = string.gsub(debug.getinfo(1).source:match("@?(.*\\)"),'\\','\\\\')
    -- end
    curl = '/usr/bin/curl -m 15 -u domoticzUSER:domoticzPSWD '		 	-- ne pas oublier l'espace à la fin
    --json = assert(loadfile(luaDir..'JSON.lua'))()						-- chargement du fichier JSON.lua
    
    --------------------------------------------
    -------------Fonctions----------------------
    -------------------------------------------- 
    function voir_les_logs (s, debugging) -- nécessite la variable local debugging
        if (debugging) then 
    		if s ~= nil then
            print ("".. s .."")
    		else
    		print ("aucune valeur affichable")
    		end
        end
    end	-- usage voir_les_logs("=========== ".. nom_script .." (v".. version ..") ===========",debugging)
    --============================================================================================== 
    function format(str)
       if (str) then
          str = string.gsub (str, "De", "De ")
          str = string.gsub (str, " ", " ")
          str = string.gsub (str, "Pas de précipitations", "Pas de précipitations")
          str = string.gsub (str, "Précipitations faibles", "Précipitations faibles")
          str = string.gsub (str, "Précipitations modérées", "Précipitations modérées")
          str = string.gsub (str, "Précipitations fortes", "Précipitations fortes")
       end
       return str   
    end
    --============================================================================================== 
    function print_r ( t )  -- afficher le contenu d'un tableau
        local print_r_cache={}
        local function sub_print_r(t,indent)
            if (print_r_cache[tostring(t)]) then
                print(indent.."*"..tostring(t))
            else
                print_r_cache[tostring(t)]=true
                if (type(t)=="table") then
                    for pos,val in pairs(t) do
                        if (type(val)=="table") then
                            print(indent.."["..pos.."] => "..tostring(t).." {")
                            sub_print_r(val,indent..string.rep(" ",string.len(pos)+8))
                            print(indent..string.rep(" ",string.len(pos)+6).."}")
                        elseif (type(val)=="string") then
                            print(indent.."["..pos..'] => "'..val..'"')
                        else
                            print(indent.."["..pos.."] => "..tostring(val))
                        end
                    end
                else
                    print(indent..tostring(t))
                end
            end
        end
        if (type(t)=="table") then
            print(tostring(t).." {")
            sub_print_r(t,"  ")
            print("}")
        else
            sub_print_r(t,"  ")
        end
        print()
    end
    --============================================================================================== 
    function urlencode(str) -- encode la chaine str pour la passer dans une url 
       if (str) then
       str = string.gsub (str, "\n", "\r\n")
       str = string.gsub (str, "([^%w ])",
       function (c) return string.format ("%%%02X", string.byte(c)) end)
       str = string.gsub (str, " ", "+")
       end
       return str
    end 
    --============================================================================================== 
    function sans_accent(str) -- supprime les accents de la chaîne str
        if (str) then
    	str = string.gsub (str,"Ç", "C")
    	str = string.gsub (str,"ç", "c")
        str = string.gsub (str,"[-èéêë']+", "e")
    	str = string.gsub (str,"[-ÈÉÊË']+", "E")
        str = string.gsub (str,"[-àáâãäå']+", "a")
        str = string.gsub (str,"[-@ÀÁÂÃÄÅ']+", "A")
        str = string.gsub (str,"[-ìíîï']+", "i")
        str = string.gsub (str,"[-ÌÍÎÏ']+", "I")
        str = string.gsub (str,"[-ðòóôõö']+", "o")
        str = string.gsub (str,"[-ÒÓÔÕÖ']+", "O")
        str = string.gsub (str,"[-ùúûü']+", "u")
        str = string.gsub (str,"[-ÙÚÛÜ']+", "U")
        str = string.gsub (str,"[-ýÿ']+", "y")
        str = string.gsub (str,"Ý", "Y")
         end
        return (str)
    end
    --============================================================================================== 
    function accent_html(str)
        if (str) then
    	str = string.gsub(str, "'", "'");
    	str = string.gsub(str, "â",	"â")
    	str = string.gsub(str, "à",	"à")
    	str = string.gsub(str, "é",	"é")
    	str = string.gsub(str, "ê",	"ê")
    	str = string.gsub(str, "è",	"è")
    	str = string.gsub(str, "ë",	"ë")
    	str = string.gsub(str, "î",	"î")
    	str = string.gsub(str, "ï",	"ï")
    	str = string.gsub(str, "ô",	"ô")
    	str = string.gsub(str, "œ",	"œ")
    	str = string.gsub(str, "û",	"û")
    	str = string.gsub(str, "ù",	"ù")
    	str = string.gsub(str, "ü",	"ü")
    	str = string.gsub(str, "ç",	"ç")
    	str = string.gsub(str, "[-ÈÉÊË']+", "E")
        str = string.gsub(str, "[-@ÀÁÂÃÄÅ']+", "A")
        str = string.gsub(str, "[-ÌÍÎÏ']+", "I")
        str = string.gsub(str, "[-ÒÓÔÕÖ']+", "O")
        str = string.gsub(str, "[-ÙÚÛÜ']+", "U")
        str = string.gsub(str, "Ý", "Y")
         end
        return (str)
    end
    --============================================================================================== 
       function GetUserVar(UserVar) -- Get UserVar and Print when missing
          variable=uservariables[UserVar]
          if variable==nil then
             print(".  User variable not set for : " .. UserVar)
             UserVarErr=UserVarErr+1
          end
          return variable
    	  
    	  --[[
    Get value of a user variable, but when the user variable not exist the function prints print (". User variable not set for : " .. UserVar) to the log.
    When you use this function for all the variables users who copy your script gets in logging a message which variables they must make.]]--
       end
    --============================================================================================== 
       function File_exists(file)  --Check if file exist
         local f = io.open(file, "rb")
         if f then f:close() end
         return f ~= nil
    	--   if not File_exists(LogFile) then
       end
    --============================================================================================== 
    function round(value, digits) -- arrondi
    	
      local precision = 10^digits
      return (value >= 0) and
          (math.floor(value * precision + 0.5) / precision) or
          (math.ceil(value * precision - 0.5) / precision)
    end
    --============================================================================================== 
    function fahrenheit_to_celsius(fahrenheit, digits) 
        return round((5/9) * (fahrenheit - 32), digits or 2)
    end
    --============================================================================================== 
    function miles_to_km(miles, digits) 
        return round((miles * 1.609344), digits or 2)
    end
    --============================================================================================== 
       function GetValue(Text, GetNr)  -- Get the X value of a device
          Part=1	 --[[5 in this example can you change in the number of the value.
    my Wind meter gives: 207.00;SSW;9;18;16.4;16.4 so I need fift value for temperature]] --
          for match in (Text..';'):gmatch("(.-)"..';') do
             if Part==GetNr then MyValue = tonumber(match) end
             Part=Part+1
          end
          return MyValue
    -- Variable      = GetValue(otherdevices_svalues[DeviceName],5)  
       end
    --==============================================================================================   
       function EnumClear(Text)   -- replace the last character
          a=string.len(Text)
          b=string.sub(Text,a,a)
          if b=="," or b==" " then Text=string.sub(Text,1,a-1) end
          a=string.len(Text)
          b=string.sub(Text,a,a)
          if b=="," or b==" " then Text=string.sub(Text,1,a-1) end
          return Text
       end
    --==============================================================================================   
     function XML_Capture(cmd,flatten)
       local f = assert(io.popen(cmd, 'r'))
       local s = assert(f:read('*a'))
       f:close()
       if flatten  then
          s = string.gsub(s, '^%s+', '')
          s = string.gsub(s, '%s+$', '')
          s = string.gsub(s, '[\n\r]+', ' ')
       end
       return s
    end  
    --============================================================================================== 
    	function unescape(str)
    	   	if string.match (str, "&") ~= nil then
    	   		str = string.gsub( str, '<', '<' )
    	   		str = string.gsub( str, '>', '>' )
    	   		str = string.gsub( str, '"', '"' )
    	   		str = string.gsub( str, ''', "'" )
    	   		str = string.gsub( str, '’', "'" )
    	   		str = string.gsub( str, '«', "«" )
    	   		str = string.gsub( str, '»', "»" )
    	   		str = string.gsub( str, ' ', " " )
    	   		str = string.gsub( str, 'Ç', "Ç" )
    	   		str = string.gsub( str, 'ç', "ç" )
    	   		str = string.gsub( str, 'Â', "Â" )
    	   		str = string.gsub( str, 'Ê', "Ê" )
    	   		str = string.gsub( str, 'Î', "Î" )
    	   		str = string.gsub( str, 'Ô', "Ô" )
    	   		str = string.gsub( str, 'Û', "Û" )
    	   		str = string.gsub( str, '&#(%d+);', function(n) if tonumber(n) < 256 then return string.char(tonumber(n)) else return "" end end )
    	   		str = string.gsub( str, '&#x(%d+);', function(n) if tonumber(n) < 256 then return string.char(tonumber(n,16)) else return "" end end )
    	   		str = string.gsub( str, '&', '&' ) -- Be sure to do this after all others
    	   	end
    	   	return str
    	end
    --============================================================================================== 
      function Pushbullet(pb_title,pb_body)  -- séparer titre et message par un ;
        local pb_token = ''
        --local pb_total = Message
        --local val=string.find(pb_total,";")
        --local pb_title = string.sub(pb_total,1,val-1)
        --local pb_body = string.sub(pb_total,val+1)
    	--Pour Windows
        --local pb_command = 'c:\\Programs\\Curl\\curl -u ' .. pb_token .. ': "https://api.pushbullet.com/v2/pushes" -d type=note -d title="' .. pb_title .. '" -d body="' .. pb_body ..'"'
        --pour Linux
       local pb_command = '/usr/bin/curl -m 15 -u ' .. pb_token .. ': "https://api.pushbullet.com/v2/pushes" -d type=note -d title="' .. pb_title .. '" -d body="' .. pb_body ..'"'
        -- Run curl command
        exec_success = os.execute(pb_command)
    	-- usage : Pushbullet('message')
      end
      
      
    --notification pushbullet
    --usage:
    --pushbullet('test','ceci est un message test')
    function pushbullet(title,body)
    --	local settings = assert(io.popen(curl..'-u '..domoticzUSER..':'..domoticzPSWD..' "'..domoticzURL..'/json.htm?type=settings"'))
    	local settings = assert(io.popen(curl..'-u "'..domoticzURL..'/json.htm?type=settings"'))    
    	local list = settings:read('*all')
    	settings:close()
    	local pushbullet_key = json:decode(list).PushbulletAPI
    	os.execute(curl..'-H \'Access-Token:'..pushbullet_key..'\' -H \'Content-Type:application/json\' --data-binary \'{"title":"'..title..'","body":"'..body..'","type":"note"}\' -X POST "https://api.pushbullet.com/v2/pushes"')
    end
    --============================================================================================== 
    function split(inputstr, sep)
            if sep == nil then
                    sep = "%s"
            end
            local t={} ; i=1
            for str in string.gmatch(inputstr, "([^"..sep.."]+)") do
                    t[i] = str
                    i = i + 1
            end
            return t
    end -- usage : valeurs = split(variable,";")
    --============================================================================================== 
    
    function calc_wind_chill(temperature, wind_speed)-- Calculate wind chill.
    -- If temperature is low but it's windy, the temperature
    -- @param temperature Temperature in Fahrenheit, must be 50 or less
    -- @param wind_speed Wind speed in miles per hour
    -- @return Wind chill of the given conditions, or nil if invalid input received	
    	local apparent = nil
    	if (temperature ~= nil and wind_speed ~= nil and temperature <= 50) then
    		if (wind_speed > 3) then
    			local v = math.pow(wind_speed, 0.16)
    			apparent = 35.74 + 0.6215 * temperature - 35.75 * v + 0.4275 * temperature * v
    		elseif (wind_speed >= 0) then
    			apparent = temperature
    		end
    	end
    	return apparent
    end
    --============================================================================================== 
    function calc_heat_index(temperature, humidity)-- Calculate heat index.
    -- If it's hot and humidity is high,
    -- temperature feels higher than what it actually is. Heat index is
    -- the approximation of the human-perceived temperature in hot and moist
    -- conditions. Heat index formula from
    -- http://www.ukscience.org/_Media/MetEquations.pdf.
    -- @param temperature Temperature in Fahrenheit, must be 80 or more
    -- @param humidity Relative humidity as a percentage value between 40 and 100
    -- @return Heat index of the given conditions, or nil if invalid input received
    local apparent = nil
    	if (temperature ~= nil and humidity ~= nil and temperature >= 80 and humidity >= 40) then
    		local t2 = temperature * temperature
    		local t3 = t2 * temperature
    		local h2 = humidity * humidity
    		local h3 = h2 * temperature
    
    		apparent = 16.923
    		+ 0.185212 * temperature
    		+ 5.37941 * humidity
    		- 0.100254 * temperature * humidity
    		+ 9.41695e-3 * t2
    		+ 7.28898e-3 * h2
    		+ 3.45372e-4 * t2 * humidity
    		- 8.14971e-4 * temperature * h2
    		+ 1.02102e-5 * t2 * h2
    		- 3.8646e-5 * t3
    		+ 2.91583e-5 * h3
    		+ 1.42721e-6 * t3 * humidity
    		+ 1.97483e-7 * temperature * h3
    		- 2.18429e-8 * t3 * h2
    		+ 8.43296e-10 * t2 * h3
    		- 4.81975e-11 * t3 * h3
    	end
    
    	return apparent
    end
    --==============================================================================================
    function calc_apparent_temperature(temperature, wind_speed, humidity) -- Calculate wind chill or heat index corrected temperature
    -- @param temperature Temperature in Fahrenheit
    -- @param wind_speed Wind speed in miles per hour
    -- @param humidity Relative humidity as a percentage value between 0 and 100
    -- @return Apparent temperature given the weather conditions
    -- @see calc_wind_chill
    -- @see calc_heat_index	
    	-- Wind chill
    	if (temperature ~= nil and wind_speed ~= nil and temperature <= 50) then
    		return calc_wind_chill(temperature, wind_speed)
    	-- Head index
    	elseif (temperature ~= nil and humidity ~= nil and temperature >= 80 and humidity >= 40) then
    		return calc_heat_index(temperature, humidity)
    	end
    
    	return temperature
    end
    --============================================================================================== 
    function getdevname4idx(deviceIDX)
    	for i, v in pairs(otherdevices_idx) do
       if v == deviceIDX then
         return i
       end
     end
     return 0
    end
    --============================================================================================== 
    function ConvTime(timestamp) -- convertir un timestamp 
       y, m, d, H, M, S = timestamp:match("(%d+)-(%d+)-(%d+) (%d+):(%d+):(%d+)")
       return os.time{year=y, month=m, day=d, hour=H, min=M, sec=S}
    end
    --============================================================================================== 
    function timeDiff(dName,dType) -- retourne le temps en seconde depuis la dernière maj du péréphérique (Variable 'v' ou Device 'd' 
            if dType == 'v' then 
                updTime = uservariables_lastupdate[dName]
            elseif dType == 'd' then
                updTime = otherdevices_lastupdate[dName]
            end 
            t1 = os.time()
    	y, m, d, H, M, S = updTime:match("(%d+)-(%d+)-(%d+) (%d+):(%d+):(%d+)")	
        t2 = os.time{year=y, month=m, day=d, hour=H, min=M, sec=S}
            tDiff = os.difftime(t1,t2)
            return tDiff
        end -- usage: timeDiff(name,'v|d')	
    --============================================================================================== 
    function TimeDiff2(Time1,Time2)  --gave to difference between now and the time that a devices is last changed in minutes 
          if string.len(Time1)>12 then Time1 = ConvTime(Time1) end
          if string.len(Time2)>12 then Time2 = ConvTime(Time2) end   
          ResTime=os.difftime (Time1,Time2)
          return ResTime
    --usage : TDiff = Round(TimeDiff(os.time(),otherdevices_lastupdate[DeviceManual])/60,0)
       end
    --============================================================================================== 
    function TronquerTexte(texte, nb)  -- texte à tronquer, Nb maximum de caractère 
    local sep ="[;!?.]"
    local DernierIndex = nil
    texte = string.sub(texte, 1, nb)
    local p = string.find(texte, sep, 1)
    DernierIndex = p
    while p do
        p = string.find(texte, sep, p + 1)
        if p then
            DernierIndex = p
        end
    end
    return(string.sub(texte, 1, DernierIndex))
    end
    --============================================================================================== 
    function creaVar(name,value) -- pour créer une variable nommée toto comprenant la valeur 10
    	os.execute(curl..'"'..domoticzURL..'/json.htm?type=command&param=saveuservariable&vname='..url_encode(name)..'&vtype=2&vvalue='..url_encode(value)..'" &')
    end -- usage :  creaVar('toto','10')  
    --============================================================================================== 
    function typeof(var) -- retourne le type de la variable 'string' ou 'number'
        local _type = type(var);
        if(_type ~= "table" and _type ~= "userdata") then
            return _type;
        end
        local _meta = getmetatable(var);
        if(_meta ~= nil and _meta._NAME ~= nil) then
            return _meta._NAME;
        else
            return _type;
        end
    end
    --============================================================================================== 
    function speak(TTSDeviceName,txt) -- envoie dans un capteur text une chaîne de caractères qui sera intercepté et lu par la custom page grâce à sa fonction MQTT
    	commandArray['OpenURL'] = domoticzIP..":"..domoticzPORT..'/json.htm?type=command&param=udevice&idx='..otherdevices_idx[TTSDeviceName]..'&nvalue=0&svalue='..url_encode(txt)
    end -- usage: speak('tts','bonjour nous sommes dimanche')
    --============================================================================================== 
    local BinaryFormat = package.cpath:match("%p[\\|/]?%p(%a+)")
    --print(BinaryFormat)
    if BinaryFormat == "dll" then
        function os.name()
            return "Windows"
        end
    elseif BinaryFormat == "so" then
        function os.name()
            return "Linux"
        end
    elseif BinaryFormat == "dylib" then
        function os.name()
            return "MacOS"
        end
    end
    BinaryFormat = nil
    --==============================================================================================
    
    --==============================================================================================
    -------------------------------------------
    -------------Fin Fonctions-----------------
    -------------------------------------------
    
  5. Bonjour,

    Je tente d’utiliser ce script. J’ai activé les logs et sur Domoticz, je constate les erreurs suivantes :

    module ‘fonctions_perso’ not found:
    no field package.preload[‘fonctions_perso’]
    no file ‘/usr/local/share/lua/5.2/fonctions_perso.lua’
    no file ‘/usr/local/share/lua/5.2/fonctions_perso/init.lua’
    no file ‘/usr/local/lib/lua/5.2/fonctions_perso.lua’
    no file ‘/usr/local/lib/lua/5.2/fonctions_perso/init.lua’
    no file ‘./fonctions_perso.lua’
    no file ‘/home/pi/domoticz/scripts/lua/fonctions/fonctions_perso.lua’
    no file ‘/usr/local/lib/lua/5.2/fonctions_perso.so’
    no file ‘/usr/local/lib/lua/5.2/loadall.so’
    no file ‘./fonctions_perso.so’

    J’ai compris qu’il manquait ‘fonctions_perso’ décrit à la ligne 36 du script. Mais comment faire pour ajouter cela ?

    Merci d’avance

Laisser un commentaire