Variante script Ping avec variable a éditer pour 5 bouton de presence

Forum dédié aux problématiques concernant les scripts pour DomoticZ.
Entourez votre code et les logs avec les balises nommées code grâce au bouton <\>.
mulot35
Messages : 200
Inscription : 20 déc. 2014, 00:27

Variante script Ping avec variable a éditer pour 5 bouton de presence

Message par mulot35 »

Salut,
Une variante du script de ping de téléphone ou autre.
On créer 5 bouton virtuel via interrupteurs/ajout manuel/Matériel:Dummy/type d'interrupteur:on/off/x10/.......

Puis dans putty faire un:

Code : Tout sélectionner

sudo nano /home/pi/domoticz/scripts/lua/script_time_ping.lua
Puis on colle avec le bouton droit de la sourie ou un clic sur la molette le script:

Code : Tout sélectionner

--------------------------------
------ Variables à éditer ------
--------------------------------
ip1 = '192.168.0.20' --1er Ip a pinguer
local nom_inter1 = 'Présence_Titia' --Interrupteur activé par Ip1
ip2 = '192.168.0.14' --2eme Ip a pinguer
local nom_inter2 = 'Présence_Nas' --Interrupteur activé par Ip2
ip3 = '192.168.0.12' --3eme Ip a pinguer
local nom_inter3 = 'Présence_Ordi' --Interrupteur activé par Ip3
ip4 = '192.168.0.15' --4eme Ip a pinguer
local nom_inter4 = 'Présence_Kodi' --Interrupteur activé par Ip4
ip5 = '192.168.0.16' --5eme Ip a pinguer
local nom_inter5 = 'Présence_2DS' --Interrupteur activé par Ip5
--------------------------------
-- Fin des variables à éditer --
--------------------------------

commandArray={}

--Cette fonction calcule la différence de temps (en secondes) entre maintenant et la date passée en paramètre.
function timedifference (s)
  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)
  t1 = os.time()
  t2 = os.time{year=year, month=month, day=day, hour=hour, min=minutes, sec=seconds}
  difference = os.difftime (t1, t2)
  return difference
end
 
--Si le téléphone n'est pas détecté ou qu'il est présent depuis plus de 10 minutes (600 secondes),
--alors on vérifie à nouveau sa présence
if (otherdevices[nom_inter1]=='Off' or (otherdevices[nom_inter1]=='On' and timedifference(otherdevices_lastupdate[nom_inter1]) > 600)) then
ping_success_tel1=os.execute('ping -c1 -w1 '.. ip1 ..'')
	
if ping_success_tel1 then
commandArray[nom_inter1]='On'
print(' '.. nom_inter1 ..' détecté!')

else
print(' '.. nom_inter1 ..' absent!')
if otherdevices[nom_inter1]=='On' then --On ne passe l'interrupteur virtuel à Off que s'il est sur On.
commandArray[nom_inter1]='Off'
print(' '.. nom_inter1 ..' perdu!')
end
end
end
if (otherdevices[nom_inter1]=='On' and timedifference(otherdevices_lastupdate[nom_inter1]) < 600) then
print(' '.. nom_inter1 ..' Ping < a 10min!')
end

--Ping 2ème ip

if (otherdevices[nom_inter2]=='Off' or (otherdevices[nom_inter2]=='On' and timedifference(otherdevices_lastupdate[nom_inter2]) > 600)) then
ping_success_tel2=os.execute('ping -c1 -w1 '.. ip2 ..'')

if ping_success_tel2 then
commandArray[nom_inter2]='On'
print(' '.. nom_inter2 ..' détecté!')

else
print(' '.. nom_inter2 ..' absent!')
if otherdevices[nom_inter2]=='On' then --On ne passe l'interrupteur virtuel à Off que s'il est sur On.
commandArray[nom_inter2]='Off'
print(' '.. nom_inter2 ..' perdu!')
end
end
end
if (otherdevices[nom_inter2]=='On' and timedifference(otherdevices_lastupdate[nom_inter2]) < 600) then
print(' '.. nom_inter2 ..' Ping < a 10min!')
end

--Ping 3ème ip

if (otherdevices[nom_inter3]=='Off' or (otherdevices[nom_inter3]=='On' and timedifference(otherdevices_lastupdate[nom_inter3]) > 600)) then
ping_success_tel3=os.execute('ping -c1 -w1 '.. ip3 ..'')

if ping_success_tel3 then
commandArray[nom_inter3]='On'
print(' '.. nom_inter3 ..' détecté!')

else
print(' '.. nom_inter3 ..' absent!')
if otherdevices[nom_inter3]=='On' then --On ne passe l'interrupteur virtuel à Off que s'il est sur On.
commandArray[nom_inter3]='Off'
print(' '.. nom_inter3 ..' perdu!')
end
end
end
if (otherdevices[nom_inter3]=='On' and timedifference(otherdevices_lastupdate[nom_inter3]) < 600) then
print(' '.. nom_inter3 ..' Ping < a 10min!')
end

--Ping 4ème ip

if (otherdevices[nom_inter4]=='Off' or (otherdevices[nom_inter4]=='On' and timedifference(otherdevices_lastupdate[nom_inter4]) > 600)) then
ping_success_tel4=os.execute('ping -c1 -w1 '.. ip4 ..'')

if ping_success_tel4 then
commandArray[nom_inter4]='On'
print(' '.. nom_inter4 ..' détecté!')

else
print(' '.. nom_inter4 ..' absent!')
if otherdevices[nom_inter4]=='On' then --On ne passe l'interrupteur virtuel à Off que s'il est sur On.
commandArray[nom_inter4]='Off'
print(' '.. nom_inter4 ..' perdu!')
end
end
end
if (otherdevices[nom_inter4]=='On' and timedifference(otherdevices_lastupdate[nom_inter4]) < 600) then
print(' '.. nom_inter4 ..' Ping < a 10min!')
end

--Ping 5ème ip

if (otherdevices[nom_inter5]=='Off' or (otherdevices[nom_inter5]=='On' and timedifference(otherdevices_lastupdate[nom_inter5]) > 600)) then
ping_success_tel5=os.execute('ping -c1 -w1 '.. ip5 ..'')

if ping_success_tel5 then
commandArray[nom_inter5]='On'
print(' '.. nom_inter5 ..' détecté!')

else
print(' '.. nom_inter5 ..' absent!')
if otherdevices[nom_inter5]=='On' then --On ne passe l'interrupteur virtuel à Off que s'il est sur On.
commandArray[nom_inter5]='Off'
print(' '.. nom_inter5 ..' perdu!')
end
end
end
if (otherdevices[nom_inter5]=='On' and timedifference(otherdevices_lastupdate[nom_inter5]) < 600) then
print(' '.. nom_inter5 ..' Ping < a 10min!')
end

return commandArray
Si vous ne voulez pas d'écriture dans les log supprimer les Print

Editer vos variables dans la zone "variables a éditer"

Puis ctrl+O
puis entree
puis ctrl+x
puis un:

Code : Tout sélectionner

sudo chmod +x /home/pi/domoticz/scripts/lua/script_time_ping.lua
Donc si le téléphone est "Pinguer" le bouton passe a ON et le prochain Ping seras exécuté dans 10min, si non détecté prochain Ping dans 1 minute.

Si vous aussi vous avez un raspberry avec kodi d'installé sur votre TV vous pouvez éditer votre interrupteur et dans Off mettre:

Code : Tout sélectionner

http://192.168.0.15/jsonrpc?request=%7B%22jsonrpc%22:%222.0%22,%22method%22:%22System.Shutdown%22,%22id%22:1%7D
Un clic sur votre interrupteur vous eteindra le Pi gérant Kodi.
Tranquilou.
Raspi B+ avec Domoticz ,6 Chacon 2300W , 6 Sondes Oregon, 1 Sonde DIY Oregon ds18b20, Téléinfo sur photovoltaique, script backup ftp & anti offline.
vil1driver
Messages : 5661
Inscription : 30 janv. 2015, 11:07
Localisation : Rennes (35)

Re: Variante script Ping avec variable a éditer pour 5 bouton de presence

Message par vil1driver »

Salut,

Alors putty pour les scripts lua, certain de te rater sur l'encodage.. :?

Et ton script... Pourquoi ?

Pourquoi vouloir réinventer la roue ?
Il y en a sur le wiki et un peu partout sur ce forum...
Et plus optimisés, usage de tables boucles... De sorte à ne pas avoir 15 lignes à rajouter pour chaque nouvelle ip à pinguer..

Mon préféré :

Code : Tout sélectionner

--[[

name: script_time_ping.lua

ip = ip à pinguer
device = périphérique à mettre à jour
loops = ping toutes les X minutes
count = nombre d'échecs successifs avant de valider offLine

--]]


--------------------------------
------ Tableau à éditer ------
--------------------------------

local url = '192.168.22.100:8080'	-- user:pass@ip:port de domoticz
  
local ping={
--{ip,device,loops,count} 
{'192.168.22.153','room',1,1},
{'192.168.22.200','nas',5,2},
{'www.free.fr','adsl',5,2},
{'192.168.22.70','sms gateway',5,2}	-- pas de , à la dernière ligne !
--etc..
}

		
--------------------------------
-- Fin du tableau à éditer --
--------------------------------
 
function url_encode(str)
  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 
 
commandArray={}

date = os.date("*t")


for i, switch in pairs(ping) do

	ip = switch[1]
	device = switch[2]
	loops = switch[3]
	count = switch[4]


	if (date.min % loops == 0) then	
		-- Le Ping ! : -c1 = Un seul ping  ,   -w3 délai de 3 seconde d'attente de réponse
		ping_success=os.execute('ping -c1 -w3 '..ip)
	 
	 
		-- création des variables utilisateur pour comptabiliser les échecs de ping
		if(uservariables['PING_'..device] == nil) then
			commandArray[i]={['OpenURL']=url..'/json.htm?type=command&param=saveuservariable&vname=PING_'..url_encode(device)..'&vtype=2&vvalue=0'}
			print('PING : création variable manquante PING_'..device)
			print('PING : script supendu')
	 
		-- Si le ping à répondu
		elseif ping_success then
			-- remise à zéro du compteur d'échec
			commandArray[i]={['Variable:PING_'..device] = '0'}
			print('PING : ' .. device .. ' -> success')
	   
		-- si le device etait sur off on l'allume
			if(otherdevices[device] == 'Off') then
				commandArray[i+1]={[device] = 'On'}
			end
	   
		else	-- Si pas de réponse
			-- on incrémente le compteur d'échec
			commandArray[i]={['Variable:PING_'..device] = tostring(uservariables['PING_'..device] + 1)}
			print('PING : ' .. device .. ' -> fail ('..(uservariables['PING_'..device]+1)..')')
		   
			-- si le device etait sur On et que le compt total est atteint, on l'éteind
			if(otherdevices[device] == 'On' and tonumber(uservariables['PING_'..device]) >= count - 1) then
				commandArray[i+1]={[device] = 'Off'}
			end
		end
		 		 
	end
end  
 
return commandArray
MAJ = VIDER LE CACHE(<-Clicable)
/!\Les mises à jour de Domoticz sont souvent sources de difficultés, ne sautez pas dessus
modules.lua

Un ex domoticzien
Grincheux

Re: Variante script Ping avec variable a éditer pour 5 bouton de presence

Message par Grincheux »

Pour ma part, le script de vil1driver ne marche pas sur cette partie

-- si le device etait sur off on l'allume
if(otherdevices[device] == 'Off') then
commandArray[i+1]={[device] = 'On'}

Malgré un ping success et le passage dans ce if (confirmé par un print) il ne met pas à jour mon switch, seulement le dernier ping (-- pas de , à la dernière ligne !)
Un mystère !

J'ai donc repris l'ancien script qui fait bien l'affaire

Code : Tout sélectionner

-- script_time_ping.lua

commandArray={}
 
 
 
--Tableau des périphériques à "pinguer"
-- Key = adresse ip à pinguer
-- Value = périphérique virtuel à switcher
local ping={}
ping['192.168.1.24']='Peggy'
ping['192.168.1.20']='Jeff'
ping['192.168.1.39']='PC bureau'
ping['192.168.1.18']='TV LG'
ping['192.168.1.38']='Tab Samsung'
--ping['192.168.1.17']='Tab Asus'
--ping['www.google.com']='adsl'

 
--pour chaque entree du tableau
for ip, switch in pairs(ping) do
 
 --Le Ping ! : -c1 = Un seul ping  ,   -w1 délai d'une seconde d'attente de réponse
 ping_success=os.execute('ping -c1 -w3 '..ip)
 
 
 --Si le ping à répondu
 if ping_success then
   
    print('PING : ' .. switch .. ' -> success')
   
   --si le switch etait sur off on l'allume
   if(otherdevices[switch]=='Off') then
      commandArray[switch]='On'
   end
 else
 
 --Si pas de réponse
   
    print('PING : ' .. switch .. ' -> fail')
   
   --si le switch etait sur on on l'eteind
   if(otherdevices[switch]=='On') then
      commandArray[switch]='Off'
   end
 end
 
 
end
  
 
return commandArray
Par contre trop de ping fail arrête le script au bout de 10sec... sans conséquence pour ma part ou je vais couper le script en 2 script :)
vil1driver
Messages : 5661
Inscription : 30 janv. 2015, 11:07
Localisation : Rennes (35)

Re: Variante script Ping avec variable a éditer pour 5 bouton de presence

Message par vil1driver »

J'avoue, pas bien clair

pas de , à la dernière ligne

Signifie que les groupes
{ip,device,loops,count}
Sont séparés par des virgules
Mais le dernier groupe ne doit pas être suivi par une virgule.
local ping={
--{ip,device,loops,count}
{'192.168.22.153','room',1,1},
{'192.168.22.200','nas',5,2},
{'www.free.fr','adsl',5,2},
{'192.168.22.70','sms gateway',5,2} -- pas de , à la dernière ligne !
--etc..
}
MAJ = VIDER LE CACHE(<-Clicable)
/!\Les mises à jour de Domoticz sont souvent sources de difficultés, ne sautez pas dessus
modules.lua

Un ex domoticzien
Répondre