Prévision de pluie en lua V2

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 <\>.
papoo
Messages : 2029
Inscription : 10 janv. 2016, 11:29
Localisation : Limoges (87)
Contact :

Prévision de pluie en lua V2

Message par papoo »

La version 2 permet , en plus des fonctions de la V1 (viewtopic.php?f=10&t=1991), d'afficher via les variables utilisateurs, les prédictions de précipitations sur une heure par pas de 5 mn sur la custom page avec création automatiques des variables nécessaire à l’exécution de ce script.
La V2 peut remplacer la V1.xx sans utilisation des variables (sélection du mode CustomPage oui/non)
mise en couleurs et texte des variables directement récupérés de l'api
actualisation toutes les 5 mn
choix simplifié du système d'exploitation pour l’exécution du fichier JSON.lua
page spéciale 6 colonnes pour custom page et fichier css
precipitations.png
precipitations.png (605.65 Kio) Consulté 11208 fois

Code : Tout sélectionner

--[[   
script_time_meteofrance_pluie.lua
Download JSON.lua : http://regex.info/blog/lua/json 
  
auteur : papoo

maj : 11/04/2017
date : 11/05/2016
Principe :	V1 récupérer via l'API non documentée de météo France, les informations de précipitation 
de votre commune sur un device text et/ou alert et/ou notifications. http://easydomoticz.com/forum/viewtopic.php?f=10&t=1991
			V2 en plus des fonctions de la V1, Afficher via les variables utilisateurs, les prédictions de précipitations sur une heure par pas de 5 mn sur la custom page
avec création automatiques des variables nécessaire à l'execution de ce script.	http://easydomoticz.com/forum/viewtopic.php?f=10&t=2788
Actualisation des données toutes les 5 minutes, couleurs et texte directement récupérés via l'api	
pour trouver le code de votre commune => http://www.insee.fr/fr/methodes/nomenclatures/cog/
									Dans le cas de l'utilisation de la variable ActivePage  il vous faut ajouter 
									dans la partie mqtt du fichier frontpage_settings.js de la Custom Page ceci :

											case "d4": // nom du bouton de la télécommande
					  
											  if (message.nvalue == 0){      // status On 
											  
												 memo = $("div").find("[data-index=4]").remove();   // memorisation page 5 et suppression
												 mySwipe.setup();                           // reorganisation
												 if (mySwipe.getPos() == 4)                     // si nous sommes sur la page supprimee
													mySwipe.slide(3);                        // deplacement vers la page precedente ( la 4 )
												 
											  }   
											  if (message.nvalue == 1){      // status Off
																
												 
												 $("div").find("[data-index=3]").after( memo );      // rajout de la page 5 juste après la page 4
												 mySwipe.setup();                           // reorganisation
												 mySwipe.slide(4);                           // deplacement vers la page rajoutee
												 
											  }  
									
									Si votre device ne s'appelle pas "d4" pnsez à modifier la variable ActivePage dans ce script avec  le meme nom de device dans le fichier frontpage_settings.js
]]--

--------------------------------------------
------------ Variables à éditer ------------
-------------------------------------------- 
local nom_script = "script_time_meteofrance_pluie"
local version = "2.30"
local debugging = false				-- true pour voir les logs dans la console log Dz ou false pour ne pas les voir
local ip = "127.0.0.1:8080" 		-- <username:password@>domoticz-ip<:port>
local CityCode = 870850 			-- le code de votre commune augmenté d'un 0 à la fin
local text_idx = 343 				-- renseigner l'id du device text associé si souhaité, sinon nil
local rain_alert_idx = 699  		-- renseigner l'id du device alert associé si souhaité, sinon nil
local send_notification = 0 		-- 0: aucune notification, 1: toutes, 2: précipitations faibles, modérées et fortes, 3: modérées et fortes, 4: seulement fortes
-- local system = "linux"			-- Systeme d'exploitation sur lequel est éxécuté ce script : linux, windows, synology pour le  chemin vers JSON.LUA	
local CustomPage = "oui"			-- pour afficher les prévisions de pluie à une heure sur la custom page via des variables, valeurs acceptées : oui ou nil
local ActivePage = "d4"				-- renseigner l'id du device switch associé si souhaité, sinon nil pour afficher ou masquer la page des prévisions de pluie sur la custom page	


--------------------------------------------
----------- Fin variables à éditer ---------
--------------------------------------------
local VariablesPluie={}
VariablesPluie[1]={nom = "Pluie à 5mn",Id = "1"} 
VariablesPluie[2]={nom = "Pluie à 10mn",Id = "2"}
VariablesPluie[3]={nom = "Pluie à 15mn",Id = "3"}
VariablesPluie[4]={nom = "Pluie à 20mn",Id = "4"}
VariablesPluie[5]={nom = "Pluie à 25mn",Id = "5"}
VariablesPluie[6]={nom = "Pluie à 30mn",Id = "6"}
VariablesPluie[7]={nom = "Pluie à 35mn",Id = "7"}
VariablesPluie[8]={nom = "Pluie à 40mn",Id = "8"}
VariablesPluie[9]={nom = "Pluie à 45mn",Id = "9"}
VariablesPluie[10]={nom = "Pluie à 50mn",Id = "10"}
VariablesPluie[11]={nom = "Pluie à 55mn",Id = "11"}
VariablesPluie[12]={nom = "Pluie à 60mn",Id = "12"}

commandArray = {}
--------------------------------------------
---------------- Fonctions -----------------
-------------------------------------------- 
 function voir_les_logs (s, debugging)
     if (debugging) then 
		 if s ~= nil then
         print ("<font color='#f3031d'>".. s .."</font>")
		 else
		 print ("<font color='#f3031d'>aucune valeur affichable</font>")
		 end
     end
 end	

 function format(str)
    if (str) then
       str = string.gsub (str, "De", "De ")
       str = string.gsub (str, " ", "&nbsp;")
       str = string.gsub (str, "Pas&nbsp;de&nbsp;précipitations", "<font color='#999'>Pas&nbsp;de&nbsp;précipitations</font>")
       str = string.gsub (str, "Précipitations&nbsp;faibles", "<font color='#fbda21'>Précipitations&nbsp;faibles</font>")
       str = string.gsub (str, "Précipitations&nbsp;modérées", "<font color='#fb8a21'>Précipitations&nbsp;modérées</font>")
       str = string.gsub (str, "Précipitations&nbsp;fortes", "<font color='#f3031d'>Précipitations&nbsp;fortes</font>")
    end
    return str   
 end
 function urlencode(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 
--------------------------------------------
-------------- Fin Fonctions ---------------
--------------------------------------------	
time = os.date("*t")
if ((time.min-1) % 5) == 0 then
--if time.min % 5 == 0 then -- toutes les 5 minutes

	voir_les_logs("=========== ".. nom_script .." (v".. version ..") ===========",debugging)

 local delay = os.time()
-- if system == "windows" then
	-- json = (loadfile "C:\\Domoticz\\scripts\\lua\\json.lua")()  -- For Windows
-- elseif system == "synology" then
	-- json = (loadfile "/volume1/@appstore/domoticz/var/scripts/lua/JSON.lua")()  -- For Synology
-- else
	-- json = (loadfile "/home/pi/domoticz/scripts/lua/JSON.lua")()  -- For Linux
-- end

-- 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 5 -u domoticzUSER:domoticzPSWD '		 	-- ne pas oublier l'espace à la fin
 json = assert(loadfile(luaDir..'JSON.lua'))()						-- chargement du fichier JSON.lua
   
   local indexArray=0
   local config=assert(io.popen('curl http://www.meteofrance.com/mf3-rpc-portlet/rest/pluie/'..CityCode..'.json'))
   local location = config:read('*all')
   config:close()
   local jsonLocation = json:decode(location)
   local niveauPluieText={}   
   niveauPluieText = jsonLocation.niveauPluieText
   -- concaténation des entrées de la table et formatage
   local PluieText = ''
	if niveauPluieText ~= nil then
	   for Index, Value in pairs( niveauPluieText ) do
		  PluieText = PluieText..format(Value)..' '
		  voir_les_logs("--- --- --- niveauPluieText["..Index.."] : ".. Value .." --- --- ---",debugging)  
	   end
   voir_les_logs("--- --- --- PluieText : ".. PluieText .. " --- --- ---",debugging)  
	end
		if CustomPage ~= nil then
			--Récuperation des informations toutes les 5mn pour rafraichir les données des variables
		   local dataCadran={}   
		   dataCadran = jsonLocation.dataCadran
		   local InfoNiveauPluieText = {}
		   local InfoNiveauPluie = {}
		   local InfoColor = {}
			if dataCadran ~= nil then
				for i, Result in ipairs( dataCadran ) do
				 InfoNiveauPluieText[i] = Result.niveauPluieText
				 InfoNiveauPluie[i] = Result.niveauPluie
				 InfoColor[i] = Result.color	
				 voir_les_logs("--- --- --- index : ".. i .. "  Info : "..  InfoNiveauPluieText[i].. " Niveau : "..  InfoNiveauPluie[i] .. " couleur :" ..  InfoColor[i] .. " --- --- ---",debugging) 
				end
			 end
			for key, valeur in pairs(VariablesPluie) do	
				if(uservariables[valeur.nom] == nil) then
					commandArray[indexArray]={['OpenURL']=ip..'/json.htm?type=command&param=saveuservariable&vname='..urlencode(valeur.nom)..'&vtype=2&vvalue='..urlencode(tostring("<font color='#".. InfoColor[key] .."'>".. InfoNiveauPluieText[key] .."</font>"))}
				   indexArray=indexArray+1
					voir_les_logs("--- --- --- creation variable manquante "..valeur.nom.."  --- --- --- ",debugging)
				else 
				voir_les_logs("--- --- --- key :" .. key .." - "..valeur.nom.."  --- --- --- ",debugging)
				commandArray['Variable:'..valeur.nom] =	tostring("<font color='#".. InfoColor[key] .."'>".. InfoNiveauPluieText[key] .."</font>")
				end
			end	
		end	
   if text_idx ~= nil and PluieText ~= nil then -- pour l'affichage dans un device text
      commandArray[indexArray] = {['UpdateDevice'] = text_idx .. '|0| ' .. PluieText}
      indexArray=indexArray+1
   end
        
   if string.find(niveauPluieText[1], "Pas de précipitations")  then
      if rain_alert_idx ~= nil then
         commandArray[indexArray] = {['UpdateDevice'] = rain_alert_idx..'|1|Pas de précipitations'}
         indexArray=indexArray+1
			 if CustomPage ~= nil and ActivePage ~= nil then 
			 commandArray[ActivePage]='Off'
			 end
      end
      if send_notification > 0 and send_notification < 2 then
         commandArray[indexArray] = {['SendNotification'] = 'Alerte Météo#Pas de précipitations prévue!'}
         indexArray=indexArray+1
      end
      voir_les_logs("--- --- --- Pas de précipitations --- --- ---",debugging)

   elseif string.find(niveauPluieText[1], "faibles")  then
      if rain_alert_idx ~= nil then
         commandArray[indexArray] = {['UpdateDevice'] = rain_alert_idx..'|2|Précipitations Faibles'}
         indexArray=indexArray+1
			 if CustomPage ~= nil and ActivePage ~= nil then 
			 commandArray[ActivePage]='On'
			 end
      end
      if send_notification > 0 and send_notification < 3 then
         commandArray[indexArray] = {['SendNotification'] = 'Alerte Météo#Précipitations Faibles!'}
         indexArray=indexArray+1
      end
      voir_les_logs("--- --- --- Précipitations Faibles --- --- ---",debugging)   


   elseif string.find(niveauPluieText[1], "modérées")  then
      if rain_alert_idx ~= nil then
         commandArray[indexArray] = {['UpdateDevice'] = rain_alert_idx..'|3|Précipitations modérées'}
         indexArray=indexArray+1
			 if CustomPage ~= nil and ActivePage ~= nil then 
			 commandArray[ActivePage]='On'
			 end
      end
      if send_notification > 0 and send_notification < 4 then
         commandArray[indexArray] = {['SendNotification'] = 'Alerte Météo#Précipitations modérées!'}
         indexArray=indexArray+1
      end
      voir_les_logs("--- --- --- Précipitations modérées --- --- ---",debugging)      


   elseif string.find(niveauPluieText[1], "fortes")  then
      if rain_alert_idx ~= nil then
         commandArray[indexArray] = {['UpdateDevice'] = rain_alert_idx..'|4|Précipitations fortes'}
         indexArray=indexArray+1
			 if CustomPage ~= nil and ActivePage ~= nil then 
			 commandArray[ActivePage]='On'
			 end
      end
      if send_notification > 0 and send_notification < 5 then
         commandArray[indexArray] = {['SendNotification'] = 'Alerte Météo#Précipitations fortes!'}
         indexArray=indexArray+1
      end
      voir_les_logs("--- --- --- Précipitations fortes --- --- ---",debugging)

   else
      print("niveau non defini")
   end

delay = os.time() - delay 
voir_les_logs("--- --- --- Delai d'execution du script : " .. delay .."ms --- --- ---",debugging)	
voir_les_logs("========= Fin ".. nom_script .." (v".. version ..") =========",debugging)
end --if time
return commandArray

Les modifications a apporter au fichier frontpage_setting.js de la custompage
dans la partie gestion des uservariables ajoutez : entre
$.PageArray_UserVariable = [
et
[]];
les 12 variables

Code : Tout sélectionner

		$.PageArray_UserVariable = [      // placez ci dessous vos userVariable
             
 			//['idx','value','cellule','description','override css'],

			 	['Pluie à 5mn','Value',         		'pluie_13',                     	'Pluie à 5mn','font-size:45%'], 
				['Pluie à 10mn','Value',         		'pluie_14',                     	'Pluie à 10mn','font-size:45%'], 
				['Pluie à 15mn','Value',         		'pluie_15',                     	'Pluie à 15mn','font-size:45%'], 
				['Pluie à 20mn','Value',       		'pluie_16',                      	'Pluie à 20mn','font-size:45%'],	
				['Pluie à 25mn','Value',         		'pluie_17',                     	'Pluie à 25mn','font-size:45%'],
				['Pluie à 30mn','Value',         		'pluie_18',                     	'Pluie à 30mn','font-size:45%'],
				['Pluie à 35mn','Value',         		'pluie_19',                     	'Pluie à 35mn','font-size:45%'],
				['Pluie à 40mn','Value',         		'pluie_20',                     	'Pluie à 40mn','font-size:45%'],
				['Pluie à 45mn','Value',         		'pluie_21',                     	'Pluie à 45mn','font-size:45%'],
				['Pluie à 50mn','Value',         		'pluie_22',                     	'Pluie à 50mn','font-size:45%'],
				['Pluie à 55mn','Value',         		'pluie_23',                     	'Pluie à 55mn','font-size:45%'],
				['Pluie à 60mn','Value',         		'pluie_24',                     	'Pluie à 60mn','font-size:45%'],
           
         []];
pour n'afficher la page prévision de pluie que lorsque il y a risque de pluie, il vous faut renseigner la variable ActivePage et ajouter dans la partie mqtt du fichier frontpage_settings.js de la Custom Page ceci :

Code : Tout sélectionner

											case "d4": // nom du bouton de la télécommande
					  
											  if (message.nvalue == 0){      // status On 
											  
												 memo = $("div").find("[data-index=4]").remove();   // memorisation page 5 et suppression
												 mySwipe.setup();                           // reorganisation
												 if (mySwipe.getPos() == 4)                     // si nous sommes sur la page supprimee
													mySwipe.slide(3);                        // deplacement vers la page precedente ( la 4 )
												 
											  }   
											  if (message.nvalue == 1){      // status Off
																
												 
												 $("div").find("[data-index=3]").after( memo );      // rajout de la page 5 juste après la page 4
												 mySwipe.setup();                           // reorganisation
												 mySwipe.slide(4);                           // deplacement vers la page rajoutee
												 
											  }  

Si votre device ne s'appelle pas "d4" pensez à modifier la variable ActivePage dans ce script avec le même nom de device dans le fichier frontpage_settings.js
Merci à vil1driver pour cette nouvelle fonctionnalité
Pièces jointes
pluiecss.zip
(753 octets) Téléchargé 354 fois
pluiehtml.zip
(841 octets) Téléchargé 358 fois
Dernière modification par papoo le 11 avr. 2017, 21:50, modifié 9 fois.
domoticz beta/RaspBerry PI3 stretch
https://pon.fr github
calouis
Messages : 109
Inscription : 08 nov. 2015, 10:34
Localisation : 62

Re: Prévision de pluie en lua V2

Message par calouis »

Bonjour Papoo

J'essaie en vain de mettre en place ton script. Voici le log :

2016-11-20 12:48:00.333 LUA: --- --- ---script_time_meteofrance_pluie_V2.lua --- --- ---
2016-11-20 12:48:00.576 LUA: --- --- --- niveauPluieText[1] : De12h50 à 13h50 : Pas de précipitations --- --- ---
2016-11-20 12:48:00.576 LUA: --- --- --- PluieText : De 12h50 à 13h50 : Pas de précipitations --- --- ---
2016-11-20 12:48:00.576 LUA: --- --- --- index : 1 Info : Pas de précipitations Niveau : 1 couleur :ffffff --- --- ---
2016-11-20 12:48:00.576 LUA: --- --- --- index : 2 Info : Pas de précipitations Niveau : 1 couleur :ffffff --- --- ---
2016-11-20 12:48:00.577 LUA: --- --- --- index : 3 Info : Pas de précipitations Niveau : 1 couleur :ffffff --- --- ---
2016-11-20 12:48:00.577 LUA: --- --- --- index : 4 Info : Pas de précipitations Niveau : 1 couleur :ffffff --- --- ---
2016-11-20 12:48:00.577 LUA: --- --- --- index : 5 Info : Pas de précipitations Niveau : 1 couleur :ffffff --- --- ---
2016-11-20 12:48:00.577 LUA: --- --- --- index : 6 Info : Pas de précipitations Niveau : 1 couleur :ffffff --- --- ---
2016-11-20 12:48:00.577 LUA: --- --- --- index : 7 Info : Pas de précipitations Niveau : 1 couleur :ffffff --- --- ---
2016-11-20 12:48:00.577 LUA: --- --- --- index : 8 Info : Pas de précipitations Niveau : 1 couleur :ffffff --- --- ---
2016-11-20 12:48:00.577 LUA: --- --- --- index : 9 Info : Pas de précipitations Niveau : 1 couleur :ffffff --- --- ---
2016-11-20 12:48:00.577 LUA: --- --- --- index : 10 Info : Pas de précipitations Niveau : 1 couleur :ffffff --- --- ---
2016-11-20 12:48:00.577 LUA: --- --- --- index : 11 Info : Pas de précipitations Niveau : 1 couleur :ffffff --- --- ---
2016-11-20 12:48:00.577 LUA: --- --- --- index : 12 Info : Pas de précipitations Niveau : 1 couleur :ffffff --- --- ---
2016-11-20 12:48:00.577 Error: EventSystem: in /home/pi/domoticz/scripts/lua/script_time_meteofrance_pluie_V2.lua: ...omoticz/scripts/lua/script_time_meteofrance_pluie_V2.lua:125: attempt to call global 'urlencode' (a nil value)

ma ligne 125----->commandArray[indexArray]={['OpenURL']=ip..'/json.htm?type=command&param=saveuservariable&vname='..urlencode(valeur.nom)..'&vtype=2&vvalue='..urlencode(otherdevices_lastupdate[valeur.nom])}

Je n'ai pas créé de variables, fallait-il le faire?

Etant autodidacte, j'atteins rapidement mes limites en programmation...
_ Raspberry Pi3 Stretch + Domoticz V4.11214
_ dzVents Version: 2.4.28
_ Python 3.5.3
_ usbZwave
_ RFX433XL USB Version: Pro XL1/1035
_ GW Xiaomi
_ station meteo Oregon & Netatmo
_ LMS
_ Yeelight
_ Tradfri
_ Zigate plugin 4.11.012 + Version : 031d
papoo
Messages : 2029
Inscription : 10 janv. 2016, 11:29
Localisation : Limoges (87)
Contact :

Re: Prévision de pluie en lua V2

Message par papoo »

calouis a écrit : Etant autodidacte ../..
on est quasiment tous ici dans ce cas la

pour ce qu'il s'agit du script il manquait apparemment une ligne dans les variables, c'est à n'y rien comprendre
la ligne en question

Code : Tout sélectionner

local ip = "monlogin:monmotdepasse@192.168.10.240:8080"; -- <username:password@>domoticz-ip<:port>
en effet la création de variable doit passer par une requête json il est donc nécessaire de renseigner l'adresse le port et les éventuels login/mot de passe

désolé du dérangement
domoticz beta/RaspBerry PI3 stretch
https://pon.fr github
calouis
Messages : 109
Inscription : 08 nov. 2015, 10:34
Localisation : 62

Re: Prévision de pluie en lua V2

Message par calouis »

J'ai complété local ip = "monlogin:monmotdepasse@192.168.10.240:8080";

toujours ce message :

2016-11-20 14:06:00.439 LUA: --- --- ---script_time_meteofrance_pluie_V2.lua --- --- ---
2016-11-20 14:06:00.695 LUA: --- --- --- niveauPluieText[1] : De14h10 à 15h10 : Pas de précipitations --- --- ---
2016-11-20 14:06:00.695 LUA: --- --- --- PluieText : De 14h10 à 15h10 : Pas de précipitations --- --- ---
2016-11-20 14:06:00.695 LUA: --- --- --- index : 1 Info : Pas de précipitations Niveau : 1 couleur :ffffff --- --- ---
2016-11-20 14:06:00.695 LUA: --- --- --- index : 2 Info : Pas de précipitations Niveau : 1 couleur :ffffff --- --- ---
2016-11-20 14:06:00.696 LUA: --- --- --- index : 3 Info : Pas de précipitations Niveau : 1 couleur :ffffff --- --- ---
2016-11-20 14:06:00.696 LUA: --- --- --- index : 4 Info : Pas de précipitations Niveau : 1 couleur :ffffff --- --- ---
2016-11-20 14:06:00.696 LUA: --- --- --- index : 5 Info : Pas de précipitations Niveau : 1 couleur :ffffff --- --- ---
2016-11-20 14:06:00.696 LUA: --- --- --- index : 6 Info : Pas de précipitations Niveau : 1 couleur :ffffff --- --- ---
2016-11-20 14:06:00.696 LUA: --- --- --- index : 7 Info : Pas de précipitations Niveau : 1 couleur :ffffff --- --- ---
2016-11-20 14:06:00.696 LUA: --- --- --- index : 8 Info : Pas de précipitations Niveau : 1 couleur :ffffff --- --- ---
2016-11-20 14:06:00.696 LUA: --- --- --- index : 9 Info : Pas de précipitations Niveau : 1 couleur :ffffff --- --- ---
2016-11-20 14:06:00.696 LUA: --- --- --- index : 10 Info : Pas de précipitations Niveau : 1 couleur :ffffff --- --- ---
2016-11-20 14:06:00.696 LUA: --- --- --- index : 11 Info : Pas de précipitations Niveau : 1 couleur :ffffff --- --- ---
2016-11-20 14:06:00.696 LUA: --- --- --- index : 12 Info : Pas de précipitations Niveau : 1 couleur :ffffff --- --- ---
2016-11-20 14:06:00.696 Error: EventSystem: in /home/pi/domoticz/scripts/lua/script_time_meteofrance_pluie_V2.lua: ...omoticz/scripts/lua/script_time_meteofrance_pluie_V2.lua:127: attempt to call global 'urlencode' (a nil value)

J'ai tenté sans le point virgule ou sans les guillemets ou sans login&mdp mais sans plus de succès...

Désolé pour le dérangement.
_ Raspberry Pi3 Stretch + Domoticz V4.11214
_ dzVents Version: 2.4.28
_ Python 3.5.3
_ usbZwave
_ RFX433XL USB Version: Pro XL1/1035
_ GW Xiaomi
_ station meteo Oregon & Netatmo
_ LMS
_ Yeelight
_ Tradfri
_ Zigate plugin 4.11.012 + Version : 031d
papoo
Messages : 2029
Inscription : 10 janv. 2016, 11:29
Localisation : Limoges (87)
Contact :

Re: Prévision de pluie en lua V2

Message par papoo »

Tu as personnalisé l'adresse avec l'adresse de ton domoticz ou tu as simplement copié collé l'exemple ?
Mets en copie ton script complet entre les balises [ code] [/code ] (sans les espaces)
domoticz beta/RaspBerry PI3 stretch
https://pon.fr github
Neutrino
Messages : 2662
Inscription : 10 juil. 2015, 15:42
Localisation : Les Herbiers(85)

Re: Prévision de pluie en lua V2

Message par Neutrino »

Il manque la fonction urlencode() dans le script.
@Papoo, tu peux la rajouter ?
Et merci pour ce script, il marche impec sinon en ce dimanche pluvieux :)
Ma maison à plein d'IP ! :mrgreen:
SAV Bonjour. Vous avez vidé le cache ?
calouis
Messages : 109
Inscription : 08 nov. 2015, 10:34
Localisation : 62

Re: Prévision de pluie en lua V2

Message par calouis »

Voilà :

Code : Tout sélectionner

--[[   
script_time_meteofrance_pluie.lua
Download JSON.lua : http://regex.info/blog/lua/json 
  
auteur : papoo
version : 2.00
maj : 31/10/2016
date : 11/05/2016
Principe :   V1 récupérer via l'API non documentée de météo France, les informations de précipitation 
de votre commune sur un device text et/ou alert et/ou notifications. http://easydomoticz.com/forum/viewtopic.php?f=10&t=1991
         V2 en plus des fonctions de la V1, Afficher via les variables utilisateurs, les prédictions de précipitations sur une heure par pas de 5 mn sur la custom page
avec création automatiques des variables nécessaire à l'execution de ce script.   
Actualisation des données toutes les 5 minutes, couleurs et texte directement récupérés via l'api   
pour trouver le code de votre commune => http://www.insee.fr/fr/methodes/nomenclatures/cog/
]]--
--------------------------------------------
------------ Variables à éditer ------------
-------------------------------------------- 

local debugging = true            -- true pour voir les logs dans la console log Dz ou false pour ne pas les voir
-- local ip = "monlogin:monmotdepasse@192.168.10.240:8080"; -- <username:password@>domoticz-ip<:port>
local ip = "xxxx:yyyy@192.168.1.16:8082"; -- <username:password@>domoticz-ip<:port>
local CityCode = 621080          -- le code de votre commune augmenté d'un 0 à la fin
local text_idx = 764            -- renseigner l'id du device text associé si souhaité, sinon nil
local rain_alert_idx = 765        -- renseigner l'id du device alert associé si souhaité, sinon nil
local send_notification = 0       -- 0: aucune notification, 1: toutes, 2: précipitations faibles, modérées et fortes, 3: modérées et fortes, 4: seulement fortes
local system = "linux"            -- Systeme d'exploitation sur lequel est éxécuté ce script : linux, windows, synology pour le  chemin vers JSON.LUA   
local CustomPage = "oui"         -- pour afficher les prévisions de pluie à une heure sur la custom page via des variables, valeurs acceptées : oui ou nil

--------------------------------------------
----------- Fin variables à éditer ---------
--------------------------------------------
local VariablesPluie={}
VariablesPluie[1]={nom = "Pluie à 5mn",Id = "1"} 
VariablesPluie[2]={nom = "Pluie à 10mn",Id = "2"}
VariablesPluie[3]={nom = "Pluie à 15mn",Id = "3"}
VariablesPluie[4]={nom = "Pluie à 20mn",Id = "4"}
VariablesPluie[5]={nom = "Pluie à 25mn",Id = "5"}
VariablesPluie[6]={nom = "Pluie à 30mn",Id = "6"}
VariablesPluie[7]={nom = "Pluie à 35mn",Id = "7"}
VariablesPluie[8]={nom = "Pluie à 40mn",Id = "8"}
VariablesPluie[9]={nom = "Pluie à 45mn",Id = "9"}
VariablesPluie[10]={nom = "Pluie à 50mn",Id = "10"}
VariablesPluie[11]={nom = "Pluie à 55mn",Id = "11"}
VariablesPluie[12]={nom = "Pluie à 60mn",Id = "12"}

commandArray = {}
--------------------------------------------
---------------- Fonctions -----------------
-------------------------------------------- 
function voir_les_logs (s, debugging)
    if (debugging) then 
      if s ~= nil then
        print ("<font color='#f3031d'>".. s .."</font>")
      else
      print ("<font color='#f3031d'>aucune valeur affichable</font>")
      end
    end
end   

function format(str)
   if (str) then
      str = string.gsub (str, "De", "De ")
      str = string.gsub (str, " ", "&nbsp;")
      str = string.gsub (str, "Pas&nbsp;de&nbsp;précipitations", "<font color='#999'>Pas&nbsp;de&nbsp;précipitations</font>")
      str = string.gsub (str, "Précipitations&nbsp;faibles", "<font color='#fbda21'>Précipitations&nbsp;faibles</font>")
      str = string.gsub (str, "Précipitations&nbsp;modérées", "<font color='#fb8a21'>Précipitations&nbsp;modérées</font>")
      str = string.gsub (str, "Précipitations&nbsp;fortes", "<font color='#f3031d'>Précipitations&nbsp;fortes</font>")
   end
   return str   
end
--------------------------------------------
---------------------------------------------------------------------------   
time = os.date("*t")
if time.min % 2 == 0 then -- toutes les 5 minutes
--if time.hour % 1 == 0 then -- toutes les heures


voir_les_logs("--- --- ---script_time_meteofrance_pluie_V2.lua --- --- --- ",debugging)
 local delay = os.time()
if system == "windows" then
   json = (loadfile "D:\\Domoticz\\scripts\\lua\\json.lua")()  -- For Windows
elseif system == "synology" then
   json = (loadfile "/volume1/@appstore/domoticz/var/scripts/lua/JSON.lua")()  -- For Synology
else
   json = (loadfile "/home/pi/domoticz/scripts/lua/JSON.lua")()  -- For Linux
end

   
   local indexArray=0


   local config=assert(io.popen('curl http://www.meteofrance.com/mf3-rpc-portlet/rest/pluie/'..CityCode..'.json'))
   local location = config:read('*all')
   config:close()
   local jsonLocation = json:decode(location)


   local niveauPluieText={}   
   niveauPluieText = jsonLocation.niveauPluieText
   -- concaténation des entrées de la table et formatage
   local PluieText = ''
   if niveauPluieText ~= nil then
      for Index, Value in pairs( niveauPluieText ) do
        PluieText = PluieText..format(Value)..' '
        voir_les_logs("--- --- --- niveauPluieText["..Index.."] : ".. Value .." --- --- ---",debugging)  
      end
   voir_les_logs("--- --- --- PluieText : ".. PluieText .. " --- --- ---",debugging)  
   end
      if CustomPage ~= nil then
         --Récuperation des informations toutes les 5mn pour rafraichir les données des variables
         local dataCadran={}   
         dataCadran = jsonLocation.dataCadran
         local InfoNiveauPluieText = {}
         local InfoNiveauPluie = {}
         local InfoColor = {}
         if dataCadran ~= nil then
            for i, Result in ipairs( dataCadran ) do
             InfoNiveauPluieText[i] = Result.niveauPluieText
             InfoNiveauPluie[i] = Result.niveauPluie
             InfoColor[i] = Result.color   
             voir_les_logs("--- --- --- index : ".. i .. "  Info : "..  InfoNiveauPluieText[i].. " Niveau : "..  InfoNiveauPluie[i] .. " couleur :" ..  InfoColor[i] .. " --- --- ---",debugging) 
            end
          end
         for key, valeur in pairs(VariablesPluie) do   
            if(uservariables[valeur.nom] == nil) then
               commandArray[indexArray]={['OpenURL']=ip..'/json.htm?type=command&param=saveuservariable&vname='..urlencode(valeur.nom)..'&vtype=2&vvalue='..urlencode(otherdevices_lastupdate[valeur.nom])}
               indexArray=indexArray+1
               voir_les_logs("--- --- --- creation variable manquante "..valeur.nom.."  --- --- --- ",debugging)
            else 
            voir_les_logs("--- --- --- key :" .. key .." - "..valeur.nom.."  --- --- --- ",debugging)
            commandArray['Variable:'..valeur.nom] =   tostring("<font color='#".. InfoColor[key] .."'>".. InfoNiveauPluieText[key] .."</font>")
            end
         end   
      end   
   if text_idx ~= nil and PluieText ~= nil then
      commandArray[indexArray] = {['UpdateDevice'] = text_idx .. '|0| ' .. PluieText}
      indexArray=indexArray+1
   end
        
   if string.find(niveauPluieText[1], "Pas de précipitations")  then
      if rain_alert_idx ~= nil then
         commandArray[indexArray] = {['UpdateDevice'] = rain_alert_idx..'|1|Pas de précipitations'}
         indexArray=indexArray+1
      end
      if send_notification > 0 and send_notification < 2 then
         commandArray[indexArray] = {['SendNotification'] = 'Alerte Météo#Pas de précipitations prévue!'}
         indexArray=indexArray+1
      end
      voir_les_logs("--- --- --- Pas de précipitations --- --- ---",debugging)

   elseif string.find(niveauPluieText[1], "faibles")  then
      if rain_alert_idx ~= nil then
         commandArray[indexArray] = {['UpdateDevice'] = rain_alert_idx..'|2|Précipitations Faibles'}
         indexArray=indexArray+1
      end
      if send_notification > 0 and send_notification < 3 then
         commandArray[indexArray] = {['SendNotification'] = 'Alerte Météo#Précipitations Faibles!'}
         indexArray=indexArray+1
      end
      voir_les_logs("--- --- --- Précipitations Faibles --- --- ---",debugging)   


   elseif string.find(niveauPluieText[1], "modérées")  then
      if rain_alert_idx ~= nil then
         commandArray[indexArray] = {['UpdateDevice'] = rain_alert_idx..'|3|Précipitations modérées'}
         indexArray=indexArray+1
      end
      if send_notification > 0 and send_notification < 4 then
         commandArray[indexArray] = {['SendNotification'] = 'Alerte Météo#Précipitations modérées!'}
         indexArray=indexArray+1
      end
      voir_les_logs("--- --- --- Précipitations modérées --- --- ---",debugging)      


   elseif string.find(niveauPluieText[1], "fortes")  then
      if rain_alert_idx ~= nil then
         commandArray[indexArray] = {['UpdateDevice'] = rain_alert_idx..'|4|Précipitations fortes'}
         indexArray=indexArray+1
      end
      if send_notification > 0 and send_notification < 5 then
         commandArray[indexArray] = {['SendNotification'] = 'Alerte Météo#Précipitations fortes!'}
         indexArray=indexArray+1
      end
      voir_les_logs("--- --- --- Précipitations fortes --- --- ---",debugging)

   else
      print("niveau non defini")
   end

delay = os.time() - delay 
voir_les_logs("--- --- --- Delai d'execution du script : " .. delay .."ms --- --- ---",debugging)   
end --if time
return commandArray
_ Raspberry Pi3 Stretch + Domoticz V4.11214
_ dzVents Version: 2.4.28
_ Python 3.5.3
_ usbZwave
_ RFX433XL USB Version: Pro XL1/1035
_ GW Xiaomi
_ station meteo Oregon & Netatmo
_ LMS
_ Yeelight
_ Tradfri
_ Zigate plugin 4.11.012 + Version : 031d
papoo
Messages : 2029
Inscription : 10 janv. 2016, 11:29
Localisation : Limoges (87)
Contact :

Re: Prévision de pluie en lua V2

Message par papoo »

Merci Neutrino
je viens de mettre le script du premier post à jour
avec la fonction manquante

Code : Tout sélectionner

function urlencode(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 
je suis pas bien bon en copié collé on dirait
désolé
domoticz beta/RaspBerry PI3 stretch
https://pon.fr github
papoo
Messages : 2029
Inscription : 10 janv. 2016, 11:29
Localisation : Limoges (87)
Contact :

Re: Prévision de pluie en lua V2

Message par papoo »

calouis a écrit : -- local ip = "monlogin:monmotdepasse@192.168.10.240:8080"; -- <username:password@>domoticz-ip<:port>
ce n'est pas bon
il ne faut pas que la ligne soit commenté (les deux tirets devant)
et il te faut personnaliser l'e contenu de la variable avec l'adresse ip de ton raspberry ainsi que les éventuels login/mot de passe
si tu n'en as pas (de login/mot de passe) l’adresse sera alors du type 192.168.10.240:8080
ce qui donnera

Code : Tout sélectionner

local ip = "192.168.10.240:8080"; -- <username:password@>domoticz-ip<:port>
domoticz beta/RaspBerry PI3 stretch
https://pon.fr github
calouis
Messages : 109
Inscription : 08 nov. 2015, 10:34
Localisation : 62

Re: Prévision de pluie en lua V2

Message par calouis »

toujours en échec :
6-11-20 14:54:00.330 LUA: --- --- ---script_time_meteofrance_pluie_V2.lua --- --- ---
2016-11-20 14:54:00.719 LUA: --- --- --- niveauPluieText[1] : De14h55 à 15h55 : Pas de précipitations --- --- ---
2016-11-20 14:54:00.719 LUA: --- --- --- PluieText : De 14h55 à 15h55 : Pas de précipitations --- --- ---
2016-11-20 14:54:00.719 LUA: --- --- --- index : 1 Info : Pas de précipitations Niveau : 1 couleur :ffffff --- --- ---
2016-11-20 14:54:00.720 LUA: --- --- --- index : 2 Info : Pas de précipitations Niveau : 1 couleur :ffffff --- --- ---
2016-11-20 14:54:00.720 LUA: --- --- --- index : 3 Info : Pas de précipitations Niveau : 1 couleur :ffffff --- --- ---
2016-11-20 14:54:00.720 LUA: --- --- --- index : 4 Info : Pas de précipitations Niveau : 1 couleur :ffffff --- --- ---
2016-11-20 14:54:00.720 LUA: --- --- --- index : 5 Info : Pas de précipitations Niveau : 1 couleur :ffffff --- --- ---
2016-11-20 14:54:00.720 LUA: --- --- --- index : 6 Info : Pas de précipitations Niveau : 1 couleur :ffffff --- --- ---
2016-11-20 14:54:00.720 LUA: --- --- --- index : 7 Info : Pas de précipitations Niveau : 1 couleur :ffffff --- --- ---
2016-11-20 14:54:00.720 LUA: --- --- --- index : 8 Info : Pas de précipitations Niveau : 1 couleur :ffffff --- --- ---
2016-11-20 14:54:00.720 LUA: --- --- --- index : 9 Info : Pas de précipitations Niveau : 1 couleur :ffffff --- --- ---
2016-11-20 14:54:00.720 LUA: --- --- --- index : 10 Info : Pas de précipitations Niveau : 1 couleur :ffffff --- --- ---
2016-11-20 14:54:00.720 LUA: --- --- --- index : 11 Info : Pas de précipitations Niveau : 1 couleur :ffffff --- --- ---
2016-11-20 14:54:00.720 LUA: --- --- --- index : 12 Info : Pas de précipitations Niveau : 1 couleur :ffffff --- --- ---
2016-11-20 14:54:00.721 Error: EventSystem: in /home/pi/domoticz/scripts/lua/script_time_meteofrance_pluie_V2.lua: ...omoticz/scripts/lua/script_time_meteofrance_pluie_V2.lua:135: attempt to concatenate a nil value
6-11-20 14:54:00.330 LUA: --- --- ---script_time_meteofrance_pluie_V2.lua --- --- ---
2016-11-20 14:54:00.719 LUA: --- --- --- niveauPluieText[1] : De14h55 à 15h55 : Pas de précipitations --- --- ---
2016-11-20 14:54:00.719 LUA: --- --- --- PluieText : De 14h55 à 15h55 : Pas de précipitations --- --- ---
2016-11-20 14:54:00.719 LUA: --- --- --- index : 1 Info : Pas de précipitations Niveau : 1 couleur :ffffff --- --- ---
2016-11-20 14:54:00.720 LUA: --- --- --- index : 2 Info : Pas de précipitations Niveau : 1 couleur :ffffff --- --- ---
2016-11-20 14:54:00.720 LUA: --- --- --- index : 3 Info : Pas de précipitations Niveau : 1 couleur :ffffff --- --- ---
2016-11-20 14:54:00.720 LUA: --- --- --- index : 4 Info : Pas de précipitations Niveau : 1 couleur :ffffff --- --- ---
2016-11-20 14:54:00.720 LUA: --- --- --- index : 5 Info : Pas de précipitations Niveau : 1 couleur :ffffff --- --- ---
2016-11-20 14:54:00.720 LUA: --- --- --- index : 6 Info : Pas de précipitations Niveau : 1 couleur :ffffff --- --- ---
2016-11-20 14:54:00.720 LUA: --- --- --- index : 7 Info : Pas de précipitations Niveau : 1 couleur :ffffff --- --- ---
2016-11-20 14:54:00.720 LUA: --- --- --- index : 8 Info : Pas de précipitations Niveau : 1 couleur :ffffff --- --- ---
2016-11-20 14:54:00.720 LUA: --- --- --- index : 9 Info : Pas de précipitations Niveau : 1 couleur :ffffff --- --- ---
2016-11-20 14:54:00.720 LUA: --- --- --- index : 10 Info : Pas de précipitations Niveau : 1 couleur :ffffff --- --- ---
2016-11-20 14:54:00.720 LUA: --- --- --- index : 11 Info : Pas de précipitations Niveau : 1 couleur :ffffff --- --- ---
2016-11-20 14:54:00.720 LUA: --- --- --- index : 12 Info : Pas de précipitations Niveau : 1 couleur :ffffff --- --- ---
2016-11-20 14:54:00.721 Error: EventSystem: in /home/pi/domoticz/scripts/lua/script_time_meteofrance_pluie_V2.lua: ...omoticz/scripts/lua/script_time_meteofrance_pluie_V2.lua:135: attempt to concatenate a nil value
_ Raspberry Pi3 Stretch + Domoticz V4.11214
_ dzVents Version: 2.4.28
_ Python 3.5.3
_ usbZwave
_ RFX433XL USB Version: Pro XL1/1035
_ GW Xiaomi
_ station meteo Oregon & Netatmo
_ LMS
_ Yeelight
_ Tradfri
_ Zigate plugin 4.11.012 + Version : 031d
Répondre