Aller au contenu
sebcbien

Yaps - Présence Simulator, Un De Plus

Recommended Posts

C cool, ça me facilite le travail :-)

Je suis occupé à  faire la prochaine version, je l'ai déjà  inclus, mais j'ai toujours ce problème de simulation qui ne se lance plus le deuxième jour si on ne interromps pas entre-temps...

ça marchais pourtant.

Bref, dès que la 2.6.6 fonctionnera, je posterai ça avec free sms intégré.

 

edit:

Et la V3, ce sera avec l'extinction randomisée :-)

 

@pepite Oui c ça ;)

Partager ce message


Lien à poster
Partager sur d’autres sites

j'ai posté les icônes dans le premier post

Partager ce message


Lien à poster
Partager sur d’autres sites

sebcbien,

Il semble y avoir un stuuuut dans la version 2.6.5.

On est sorti hier soir, et voilàle résultat du log :


[DEBUG] 16:26:21: Sat 08/08 Presence Simulator | v2.6.5
[DEBUG] 16:26:21: Sat 08/08 --------------------------------
[DEBUG] 16:26:21: Sat 08/08 Waiting for next Sunset: 21:16 -> Simulation OFF.
[DEBUG] 18:26:22: Sat 08/08 Waiting for next Sunset: 21:16 -> Simulation OFF.
[DEBUG] 20:26:22: Sat 08/08 Waiting for next Sunset: 21:16 -> Simulation OFF.
[DEBUG] 00:26:23: Sun 09/08 Waiting for next Sunset: 21:16 -> Simulation OFF.
[DEBUG] 00:45:55: Scene already active, exiting this new occurence !!
[DEBUG] 00:46:23: Sun 09/08 Presence Simulator is Terminated
[DEBUG] 00:46:23: Sun 09/08 Simu = 0, Exit from scene

Partager ce message


Lien à poster
Partager sur d’autres sites

oui j'ai remarqué aussi :-/

Avec tous ces ajouts et modifications, il y a des problèmes de timing qui sont apparus.

Cela peut avoir un impact dépendant du temps à  laquelle le script à  été lancé, du temps d'attente entre les vérifications et de l'heure du coucher du soleil... un problème de timming et le script rate la vérification du coucher du soleil (problème qui sont apparus avec la fonctionnalité de bouclage sur plusieurs jours, et le besoin de recalculer les heures)

Je suis occupé avec la V3, j'ai ajouté la fonction d'extinction randomisée et progressive et je pense avoir trouvé le problème.

J'ai modifié la scène pour qu'elle tourne "comme si j'étais en vacances" afin de pouvoir débugger et vérifier ce qui se passe lorsque la simulation n'est pas désactivée sur plusieurs jours.

Un des soucis que j'avais identifié est que maintenant les jours raccourcissent, donc j'ai du rajouter un > en plus du < ainsi qu'une fourchette de test plus longue car le décalage est de plus d'une minute d'un jour a l'autre (le jours raccourcissent à  des vitesses différentes au cours de l'année)

Et dire que j'ai horreur de jouer avec les jours heures et dates :-/

La V3.0.1 est disponible sur github, je posterai la prochaine version d'ici  une bonne semaine probablement, j'espère alors que j'aurai pu tester et débugger tous les cas de figure.

En attendant, si tu veux, le code est sur github (V3.0.1)

Partager ce message


Lien à poster
Partager sur d’autres sites

@sebcibien,

Je vais attendre gentiment que tu sois prêt pour l'installer.

Il y a une question que je me suis toujours posée : "Pourquoi la scène tourne-t-elle toutes les deux heures pour vérifier l'heure du Sunset, alors qu'elle sait quand est le prochain SunSet" ?

Partager ce message


Lien à poster
Partager sur d’autres sites

Elle ne tourne pas toutes les 2 heures, il y a une notification toutes les deux heures.

elle fait un test toutes les 4 minutes et après 30 tests fait une notification

Partager ce message


Lien à poster
Partager sur d’autres sites

Merci pour l'explication, mais alors pourquoi plusieurs instances et qu'elle loupe le sunset ? Je suppose que le test doit être du genre si now()>= SunSet ALORS start simu ?

Partager ce message


Lien à poster
Partager sur d’autres sites

oui, mais à  minuit le sunset change d'heure et j'ai du trouver des parades pour que le script ne s'arrête pas à  minuit

 

une partie est calculée dans la function SimulatorPresenceEngine:EndTimeCalc() 

cette variable: wait_for_tomorrow permet de savoir si le recalcul des heures à  déjà  été effectué ou non

 

etc...

Si le endtime avait été toujours avant minuit, ça aurais grandement facilité les choses. mais certains veulent que ça puisse se terminer après minuit (dontm oi)

maintenant endtime n'est plus fixe et donc ça complique le recalcul.

 

bref... ce qui est bien c'est que ça garde mon neurône en activité ;-)

Partager ce message


Lien à poster
Partager sur d’autres sites

idée au passage. Merci de partager, cela me permet également mon neurône en activité ....

je me permets d'imaginer la logique de comment je le ferais. C'est peut-être la même que la tienne, ou ça te donnera un autre point de vue. Parfois sortir la tête du guidon, ça aide.

 

démarrage de la simu :

SI (Simu_presence = 1 AND now()>= SunSet) OR (Simu_preence = 1 AND overideSimuSunset = 1) THEN

  fonction start simu

ELSE

  on attend

END

arrêt de la simu :

SI (Simu_presence = 0) OR ( now() > heure de fin) THEN

  fonction stop simu

END

 

fonction start simu :

comme maintenant

 

fonction stop simu

on atteint toutes les lampes (avec le délais random que tu veux rajouter)

Si (Simu_presence = 0 AND (now() >= SunSet OR now() <= SunRise)) THEN

  on alume la lampe qu'on veut allumer à  la fin de la sim

END

 

Le GROS problème qui reste à  traiter est le test "now() > heure de fin" pour l'arrêt de la sim.

Je réfléchit à  un algorithme pour ce test.

Mais pour le reste, il faut garder un algorithme simple, je pense

Partager ce message


Lien à poster
Partager sur d’autres sites

pour le moment je ré-écris la partie endtime calc, ça simplifiera beaucoup.

Je laisse tomber la gestion du cas si on active la simulation entre minuit et l'heure de fin qui complique beaucoup (plus de wait for tomorrow)

function SimulatorPresenceEngine:EndTimeCalc()
    local start = os.date("%H:%M")
    local time = os.time()
    local date = os.date("*t", time)
    local year = date.year
    local month = date.month
    local day = date.day
    endtime = os.time{year=year, month=month, day=day, hour=stop_hour, min=stop_minute, sec=sec} -- generate endtime (changes at midnight)
    ExtraDebug ("debug info: Original planed EndTime: " ..endtime)
    if tonumber(stop_hour) <= 12 then
        endtime = endtime + 24*60*60
        ExtraDebug ("stop hour <= 12, Added 24H to Endtime (ending after midnignt)");
    end -- if stop hour is between 00 and 12h then add 24 hours to endtime
    -- if simu is launched between midnight and stop hour, may cause problem local currentHour = os.date("*t")
local sunrise = tonumber(string.sub (fibaro:getValue(1,'sunriseHour'), 1 , 2) ) * 60 + tonumber(string.sub(fibaro:getValue(1,'sunriseHour'), 4) )
local sunset = tonumber(string.sub (fibaro:getValue(1,'sunsetHour'), 1 , 2) ) * 60 + tonumber(string.sub(fibaro:getValue(1,'sunsetHour'), 4) )
local now = currentHour.hour * 60 + currentHour.min;
ExtraDebug ("debug info: Sunrise: " .. sunrise .. " Sunset: "..sunset .. " Now: " ..now);
ExtraDebug ("debug info: Current OS Time: " ..os.time()) 
ExtraDebug ("debug info: New planed EndTime: " ..endtime) 
ExtraDebug ("debug info: os.date: "..os.date("%H:%M").. " sunrisehour: "..fibaro:getValue(1, "sunriseHour"))

Concernant 

fonction stop simu

on atteint toutes les lampes (avec le délais random que tu veux rajouter)

Si (Simu_presence = 0 AND (now() >= SunSet OR now() <= SunRise)) THEN

  on alume la lampe qu'on veut allumer à  la fin de la sim

END

 

ici now est au format h:m alors que  endtime est au format complet (mois jour heure min secondes)

Partager ce message


Lien à poster
Partager sur d’autres sites

en fait je devrais tout mettre en heure universelle je pense

et convertir une fois pour toutes end time et sunset et sunrise en heure universelle...

Partager ce message


Lien à poster
Partager sur d’autres sites

tu veux dire en heure Unix (= sec depuis 1970 ?

exple : Sat 08/08/2015 = 1439028000

 

9a me paraît en effet beaucoup plus simple (en écrivant le petit algorithme quelques pots plus hauts, je pensais en effet à  comparer les temps sous cette form

Partager ce message


Lien à poster
Partager sur d’autres sites

Oui c ça, ça avance :)

Mais le lancement entre minuit et endtime c un beau casse tête

Sent from my SM-N910F using Tapatalk

Partager ce message


Lien à poster
Partager sur d’autres sites

cool, ton neuronen ne chauffe pas trop  :98:

Partager ce message


Lien à poster
Partager sur d’autres sites

deux jours de test et la V3.1.0 sur github a bien fonctionné jusqu'ici, premier lancement et boucle de 1 jour.

j'ai tout passé en UNIX time (merci jojo je savais plus comment ça s'appelais)

Je le laisse tourner encore un jour

le lancement entre minuit et endtime, je laisse tomber, je n'y arrive pas. conséquence, un start simu ne commencera que le lendemain si lancé dans ce laps de temps.. ce qui devrait être assez rare

 

je fais en parallèle la V3.2.0 qui aura en plus la possibilité de faire varier l'heure du sunset, donc du démarage (+XX minutes, ou -XX minutes)

  • Upvote 1

Partager ce message


Lien à poster
Partager sur d’autres sites

Cool, une nouvelle version ;-)

 

 

La 3.2 sympa aussi ;-) avec modif de 'heure du démarrage, bonne idee !!

 

Super tu as rajoute freesms sur la 3.2 du github ;-)

 

merciii

Partager ce message


Lien à poster
Partager sur d’autres sites

La 3.2 fonctionne depuis hier soir, je continue les tests

Sent from my SM-N910F using Tapatalk

Partager ce message


Lien à poster
Partager sur d’autres sites

Je crois que je vais la mettre avant de partir ;-)

Partager ce message


Lien à poster
Partager sur d’autres sites

Je ne sais pas laquelle tu as mais la dernière postée ici est buggee :-/

Sent from my SM-N910F using Tapatalk

Partager ce message


Lien à poster
Partager sur d’autres sites

C'est celle que j'ai ;-)

 

Vais mettre la 3.2 du git alors ;-)

 

 

 

C'est fait, 3.2 en PROD ;-)

Modifié par pepite

Partager ce message


Lien à poster
Partager sur d’autres sites

Je croise les doigts, il y a tellement de changements... ;-) dès que tu as du feedback hésite pas :)

Sent from my SM-N910F using Tapatalk

Partager ce message


Lien à poster
Partager sur d’autres sites

Alors, la 3.1 a fonctionné 3 jours parfaitement en continu

la 3.2 a fonctionné 1,5 jours (2 cycles) parfaitement en continu

 

Je viens de terminer la 3.3 (fixé un dernier bug -> le override ne fonctionnait pas bien) et elle tourne bien également.

Si demain soir elle se relance, je pense que tout fonctionnera.

 

Toutes les versions sont sur github: https://github.com/sjauquet/YAPS/commits/master/YAPS.scene.lua

--[[ 
%% autostart
%% properties 
%% globals 
Simu_presence 
--]] 

---------------------------------------
local version = "3.3.0"; 
-- YAPS Presence Simulator by SebcBien
-- August 2015
---------------------------------------
--V3.3.0
-- Fixed Override bug (no sleep time between lights)
--V3.2.3
-- added sunset shifting possibility (add or remove minutes to startime
-- added time stamp to push messages
-- formated messages
-- optimisation
-- cleanup
--V3.1.0
-- "complete" rewriting with unix times
-- modified end time notification impacted by random and smooth TurnOff (endtime impact)
-- exit is now exactly at endtime
-- added smooth cut off of lights at ending time (function not triggered with deactivation)
--V2.6.6
-- clean up debug messages
-- added free sms notifications
-- second fix to looping days bug
--V2.6.0 to V2.6.5 
-- Fixed bug when rndmaxendtime = 0
-- Probably fixed endtime bug calculation when looping for days du to days are shorter now than the previous day
-- Fixed bug not turning on ID_On_After_Simu when exiting simulation
-- added random end time + small stability changes and cleaning
-- Added array of lights to turn on after simu, ONLY if Simu_presence = 1 (normal ending, not ended by setting Simu_presence to 0)
-- Added the possibility to not have an always on lamp
-- Added naming of devices in the debug during simulation
-- Added the possibility to select always on light during simulation
--V2.2.0 to 2.5.0
-- fixed simulation starting if restarted between endtime & midnight
-- fixed big bug simulator restarting after end time
-- small notification and debug changes
-- Rewriting the engine
-- now relaunch automatically the next day, even if Simu_presence has not changed
-- Added Manual Stop variable
-- added list of mobiles

if (fibaro:countScenes() > 1) then 
	fibaro:debug("Scene already active! Aborting this new instance !!"); 
	fibaro:abort(); 
end 
--------------------- USER SETTINGS --------------------------------
local id = {
	LAMPE_SDB			= 16,
	LAMPE_CH_AMIS		= 24,
	LAMPE_SALON			= 45,
	LAMPE_BUREAU		= 49,
	LAMPE_HALL			= 52,
	LAMPE_CELLIER		= 56,
	LAMPE_CH_EMILIEN	= 58,
    LAMPE_COULOIR		= 1316,
	PHONE_SEB			= 1347,
    PHONE_GG			= 1327
	}
  
local stop_hour = "00"; -- Hour when you want simulation to stop 
local stop_minute = "15"; -- Minute of the hour you want simulation to stop 
-- note 1: the script will not exit while waiting the random time of the last light turned on. So end time can be longer than specified end time. (even more with var rndmaxendtime)
-- note 2: if the global variable changes during the same wait time as above, it will exit immediately (when back home while simulation runs)
local sunset_shift = -20 -- number of minutes before or after sunset to activate simulation
local rndmaxtime = 20; -- random time of light change in minutes --> here each device is on maximum 30min 
local rndmaxendtime = 15; -- random time to add at the stop hour+stop minute so the simulation can be more variable (0 to deactivate)
local ID_devices_lights_always_on = {id["LAMPE_BUREAU"],id["LAMPE_COULOIR"]} -- IDs of lights who will always stay on during simulation - leave empty array if none -> {}
--local ID_devices_lights = {id["LAMPE_SDB"],id["LAMPE_HALL"],id["LAMPE_CELLIER"],id["LAMPE_CH_AMIS"]} -- IDs of lights to use in simulation 
local ID_devices_lights = {id["LAMPE_HALL"],id["LAMPE_CELLIER"],id["LAMPE_CH_AMIS"]} -- Reduced set for test purposes
local activatePush = true; -- activate push when simulation starts and stops 
local FreeSms = false; -- activate push with FreeSms (activatePush must be true also) 
--local ID_Smartphones = {id["PHONE_SEB"],id["PHONE_GG"]}; 
local ID_Smartphones = {id["PHONE_SEB"]}; -- list of device receiving Push
local ID_On_After_Simu = 0; -- If next line is commented, no light will turn on after simulation ends
local ID_On_After_Simu = id["LAMPE_COULOIR"]; -- ID of a light (Only One) to turn on after simulation ends (at specified stop_hour & stop_minute). Comment this line to turn off this feature
local ID_On_When_Simu_Deactivated = 0; -- If next line is commented, no light will turn on after simulation is stopped (by putting Simu_presence to 0)
local ID_On_When_Simu_Deactivated = id["LAMPE_HALL"]; -- ID of a light (Only One) to turn on after simulation is stopped (Simu_). Comment this line to turn off this feature
--------------------- USER SETTINGS END ---------------------------- 
----------------------ADVANCED SETTINGS----------------------------- 
local showStandardDebugInfo = true; -- Debug displayed in white 
local showExtraDebugInfo = false; -- Debug displayed in orange 
-------------------------------------------------------------------- 
-------------------- DO NOT CHANGE CODE BELOW ---------------------- 
--------------------------------------------------------------------
local numbers_lights = #ID_devices_lights; -- numbers of light devices listed above 
local simu = fibaro:getGlobal("Simu_presence"); --value of the global value: simulation is on or off 
local manualOveride = fibaro:getGlobal("overideSimuSunset"); -- if = 1 then the simulation is forced
local start_simu = fibaro:getValue(1, "sunsetHour"); --Start simulation when sunset
local endtime,Sunrise_unix_hour,Sunset_unix_hour,converted_var,Midnight,endtime_with_rndmaxendtime,sleep_between_TurnOff;
local first_launch = true;
local NotifLoop = 0;

SimulatorPresenceEngine = {}; 

function Debug(color, message) 
		fibaro:debug(string.format('<%s style="color:%s;">%s</%s>', "span", color, os.date("%a %d/%m", os.time()).." "..message, "span")); 
end 

function ExtraDebug(debugMessage) 
	if ( showExtraDebugInfo ) then 
		Debug( "orange", debugMessage); 
	end 
end 

function StandardDebug(debugMessage) 
	if ( showStandardDebugInfo ) then 
		Debug( "white", debugMessage); 
	end 
end 

function round(num, idp)
  local mult = 10^(idp or 0)
  return math.floor(num * mult + 0.5) / mult
end

function pushMessage(sendPush) 
	if (activatePush) then 
		sendPush = os.date("%H:%M", os.time()).." "..sendPush -- add timestamp to push message
    	for i=1, #ID_Smartphones do 
      		fibaro:call(tonumber(ID_Smartphones[i]), 'sendPush', sendPush); 
      		ExtraDebug("Push message ("..sendPush..") sent to mobile: "..tonumber(ID_Smartphones[i])); 
    	end 
    	if (FreeSms) then 
    		fibaro:setGlobal("FreeSms", sendPush)
			ExtraDebug("Message ("..sendPush..") sent to FreeSms"); 
    	end
	end 
end

function SimulatorPresenceEngine:UniversalTimeCalc(converted_var, hour, min)
	local time = os.time() ;
	local date = os.date("*t", time) ;
	local year = date.year ;
	local month = date.month ;
	local day = date.day ;
	unix_hour = os.time{year=year, month=month, day=day, hour=hour, min=min, sec=sec};
	ExtraDebug("converted "..converted_var..": "..hour..":"..min.." to Unix Time: "..unix_hour..")")
	return unix_hour
end

function SimulatorPresenceEngine:ReverseUniversalTimeCalc(converted_var,hour)
	reverse_unix = os.date("%H:%M", hour)
	ExtraDebug("Reverse converted Unix Time of "..converted_var.." : "..hour.." To: "..reverse_unix)
	return reverse_unix
end

function SimulatorPresenceEngine:EndTimeCalc() 
	local hour,min
    ExtraDebug ("Current Unix Time: "..os.time()) 
	endtime = SimulatorPresenceEngine:UniversalTimeCalc("Original planed Endtime", stop_hour, stop_minute); -- generate endtime (changes at midnight) will not change during simulation, only when ended
	Midnight = SimulatorPresenceEngine:UniversalTimeCalc("Midnight", 00, 00);
	
	Sunset_unix_hour = fibaro:getValue(1,'sunsetHour');
	hour = string.sub(Sunset_unix_hour, 1 , 2);
	min = string.sub(Sunset_unix_hour,4);
	Sunset_unix_hour = (SimulatorPresenceEngine:UniversalTimeCalc("Sunset", hour, min))+sunset_shift*60;

	-- if stop hour is between 00 and 12h then add 24 hours to endtime
	if tonumber(stop_hour) <= 12 and (os.time() >= endtime) then
		endtime = endtime + 24*60*60 
		ExtraDebug ("stop hour <= 12, Added 24H to Endtime (endtime is ending after midnignt)");
		ExtraDebug ("New EndTime: "..endtime);
	end 
	
	if rndmaxendtime ~= 0 and numbers_lights > 1 then   -- if simu = 1 then slow turn off, else turn off all immediately
  		sleep_between_TurnOff = round((math.random(rndmaxendtime)/(numbers_lights-1)),1);
		sleep_between_TurnOff = math.random(rndmaxendtime)/(numbers_lights-1);
		ExtraDebug("Calculated sleeping between each turn off: "..sleep_between_TurnOff.." min");
    else
    	sleep_between_TurnOff = 0;
		ExtraDebug("No sleeping between turn off");
    end
	endtime_with_rndmaxendtime = endtime + ((sleep_between_TurnOff*(numbers_lights-1))*60)
	ExtraDebug("endtime_with_rndmaxendtime: "..endtime_with_rndmaxendtime);	
	
	-- To do: check if simu is launched between midnight and stop hour -> will be 24h later (simu will run trough the day)	
	--[[ essai prise en charge lancement entre minuit et stop hour
	if (os.time() < endtime) and (os.time() > Midnight) and first_launch == true then -- si calcul effectué entre minuit et endtime lors du premier lancement, alors reculer sunset de 24h
		Sunset_unix_hour = Sunset_unix_hour - 24*60*60;
		ExtraDebug ("stop hour <= 12, removed 24H to Sunset_unix_hour (endtime is ending after midnignt)");
		ExtraDebug ("New SunsetTime: "..Sunset_unix_hour);
	end 
	first_launch = false
	
				Sunrise_unix_hour = fibaro:getValue(1,'sunriseHour')
				hour = string.sub(Sunrise_unix_hour, 1 , 2)
				min = string.sub(Sunrise_unix_hour,4)
				Sunrise_unix_hour = SimulatorPresenceEngine:UniversalTimeCalc("Sunrise", hour, min)
			--]]
	-----------------------------------------------------------------------------------------------------		
	-- At first launch only, add 24h to endtime if endtime is after midnight and in the past
	--if ((wait_for_tomorrow == 0) and (endtime < os.time())) then -- if endtime + rndmaxendtime (+5 min to avoid sunset shifting) is gone and it's the first launch of simulator
		--endtime = endtime + 24*60*60 -- add 24h at endtime after the night is gone
		--start_simu = fibaro:getValue(1, "sunsetHour"); -- recalculate for next day (changes at midnight)
		--ExtraDebug ("wait_for_tomorrow = 0 Added 24H to Endtime (first start ending after midnignt)");
		--ExtraDebug ("Recalculated Simulation StartHour (Sunset): " .. start_simu); 		
		--wait_for_tomorrow = 1	
	--end
	--	adds 24h to endtime after the end of simulation (between sunrise and sunset)
	--if (wait_for_tomorrow == 1 and (endtime < os.time()) and ((now >= sunrise) and (now <= sunset))) then -- if it looping days and endtime is gone and we are daytime, then add 
		--endtime = endtime + 24*60*60 -- add 24h at endtime after the night is gone
		--start_simu = fibaro:getValue(1, "sunsetHour"); -- recalculate for next day
		--ExtraDebug ("wait_for_tomorrow = 1 Added One Day to Endtime: " .. endtime);
		--ExtraDebug ("Recalculated Simulation StartHour (Sunset): " .. start_simu); 	
	--end 
	--ExtraDebug ("debug info: Recalculated planed EndTime " ..endtime) 
end 
-- Presence Simulation actions Main loop
function SimulatorPresenceEngine:Launch() 
    pushMessage("Presence simulation started. Will stop at: "..SimulatorPresenceEngine:ReverseUniversalTimeCalc("endtime", endtime).." + rand("..rndmaxendtime.."min) : "..SimulatorPresenceEngine:ReverseUniversalTimeCalc("endtime_with_rndmaxendtime", endtime_with_rndmaxendtime));
    StandardDebug("Presence simulation started. Will stop at: "..SimulatorPresenceEngine:ReverseUniversalTimeCalc("endtime", endtime).." + rand("..rndmaxendtime.."min) : "..SimulatorPresenceEngine:ReverseUniversalTimeCalc("endtime_with_rndmaxendtime", endtime_with_rndmaxendtime));	
	if ID_devices_lights_always_on[1] ~= nil then SimulatorPresenceEngine:TurnOn(ID_devices_lights_always_on); end

    while ((os.time() <= endtime) and (simu == "1")) or ((manualOveride == "1")) do 
		local random_light = tonumber(ID_devices_lights[math.random(numbers_lights)]) --choose a random light in the list 
		local lightstatus = fibaro:getValue(random_light, 'value') --get the value of the random light in the list 
		-- turn on the light if off or turn off if on 
		if tonumber(lightstatus) == 0 then fibaro:call(random_light, 'turnOn') else fibaro:call(random_light, 'turnOff') end 
		fibaro:sleep(1000); -- necessary to get back the new status, because HC2 is too fast :-) 
		lightstatus = fibaro:getValue(random_light, 'value') --get the value of the random light after his update 
		StandardDebug('light ID:'.. fibaro:getName(random_light) ..' status:'..lightstatus);
		local sleeptime = math.random(rndmaxtime*60000) --random sleep 
		StandardDebug("Entering loop of " .. round(sleeptime/60000,2) .. " minutes");
		-- Allows to exit the scene if the Simu_presence global var changes to 0 during the random  sleep
			local counterexitsimu = 200
				while (counterexitsimu > 0) and ((os.time() <= endtime) or manualOveride == "1") do
					counterexitsimu = counterexitsimu - 1;
					test_presence_state = fibaro:getGlobal("Simu_presence");
					simu = tonumber(test_presence_state); --verify the global value, if the virtual device is deactivated, the loop stops. 
					--fibaro:debug("simu var state : " .. simu.." override var state : " .. manualOveride);
					if simu == 0 then
						manualOveride = fibaro:getGlobalValue("overideSimuSunset");
						if simu == 0 or manualOveride == "0" then
						counterexitsimu = 0
						end
					end
				fibaro:sleep(sleeptime/200);
				end
			ExtraDebug("Exiting loop of "..round(sleeptime/60000,2).." minutes");
		local sleeptimemin = math.abs(sleeptime/60000) 
		simu = fibaro:getGlobal("Simu_presence"); --verify the global value, if the virtual device is deactivated, the scene stops. 
		manualOveride = fibaro:getGlobalValue("overideSimuSunset");
	end 
end 
	
function SimulatorPresenceEngine:EndSimulation() 
	if ID_devices_lights_always_on[1] ~= nil then SimulatorPresenceEngine:TurnOff(ID_devices_lights,ID_devices_lights_always_on); end
	Debug("red","Presence simulation deactivated");
	if (simu == "1") then
		Debug("yellow","Presence simulator will restart tomorrow.");
		Debug("yellow","Sunset is around "..fibaro:getValue(1, "sunsetHour").." + Sunset Shift of "..sunset_shift.."min = Start Time around "..SimulatorPresenceEngine:ReverseUniversalTimeCalc("Sunset unix time", Sunset_unix_hour));
		pushMessage("Presence simulator will restart tomorrow. Sunset is around "..fibaro:getValue(1, "sunsetHour").." + Sunset Shift of "..sunset_shift.."min = Start Time around "..SimulatorPresenceEngine:ReverseUniversalTimeCalc("Sunset unix time", Sunset_unix_hour));
	end
	NotifLoop = 0; -- will force main loop notifications at end of simulation
end

function SimulatorPresenceEngine:ExitSimulation()
	pushMessage("Presence simulator is terminated");
	Debug("red","Simu_presence = 0, Aborting simulation scene");
	fibaro:abort(); 
end

function SimulatorPresenceEngine:TurnOff(group,group2) 
	Debug("red","TurnOff All Simulation lights!");
	local name, id2; 
	local ID_devices_group = group; 
	for i=1, #ID_devices_group do 
		simu = fibaro:getGlobal("Simu_presence"); --verify the global value, if simu presence is deactivated
		if simu == "0" then	sleep_between_TurnOff = 0; end; -- if simulation ended before endtime, then no turn off delay
		if i > 1 then -- wait Number of lights -1 (do not need to wait for the first TurnOff)
			StandardDebug("Sleeping "..sleep_between_TurnOff.." minute(s) before next TurnOff");
			fibaro:sleep(sleep_between_TurnOff*60000);
		end
		id2 = tonumber(ID_devices_group[i]); 
		fibaro:call(id2, "turnOff"); 
		name = fibaro:getName(id2); 
		if (name == nil or name == string.char(0)) then 
			name = "Unknown" 	
		end 
		StandardDebug("Device: "..name.." Off ");
	end 
	
	Debug("red","TurnOff All Always_On lights!");
	local ID_devices_group = group2; 
	for i=1, #ID_devices_group do 
		id2 = tonumber(ID_devices_group[i]); 
		fibaro:call(id2, "turnOff"); 
		name = fibaro:getName(id2); 
			if (name == nil or name == string.char(0)) then 
				name = "Unknown" 	
			end 
		StandardDebug("Device: "..name.." Off "); 
	end 
	if ID_On_After_Simu ~= 0 and simu == "1" then
		fibaro:call(ID_On_After_Simu, "turnOn");
		name = fibaro:getName(ID_On_After_Simu); 
			if (name == nil or name == string.char(0)) then 
				name = "Unknown" 	
			end 
		Debug("red","Turned On light ID_On_After_Simu:");
		Debug("white", name);
	end
	if ID_On_When_Simu_Deactivated ~= 0 and simu == "0" then
		fibaro:call(ID_On_When_Simu_Deactivated, "turnOn");
    	name = fibaro:getName(ID_On_When_Simu_Deactivated); 
			if (name == nil or name == string.char(0)) then 
				name = "Unknown" 	
			end 
		Debug("red","Turned On light ID_On_When_Simu_Deactivated:");
		Debug("white", name);
	end
end 

function SimulatorPresenceEngine:TurnOn(group) 
	Debug("red","Turning On Always_On lights:");
	local name, id2; 
	local ID_devices_group = group; 
	for i=1, #ID_devices_group do 
		id2 = tonumber(ID_devices_group[i]); 
		fibaro:call(id2, "turnOn"); 
		name = fibaro:getName(id2); 
		if (name == nil or name == string.char(0)) then 
			name = "Unknown" 	
		end 
		StandardDebug("Device: "..name.." Turned On "); 
	end
	Debug("red","Now randomizing other lights...");
end 
	
Debug("green", "Presence Simulator | v" .. version .. " Starting up"); 
Debug( "green", "--------------------------------------------------------------------------");

------------------------ Main Loop ----------------------------------
-- first start notifications
SimulatorPresenceEngine:EndTimeCalc();
pushMessage("Scheduled presence simulation at "..SimulatorPresenceEngine:ReverseUniversalTimeCalc("Sunset unix time", Sunset_unix_hour).." (Sunset: "..fibaro:getValue(1, "sunsetHour")..")");
Debug("green","Sunset is at "..fibaro:getValue(1, "sunsetHour").." + Sunset Shift of "..sunset_shift.."min = Start Time at "..SimulatorPresenceEngine:ReverseUniversalTimeCalc("Sunset unix time", Sunset_unix_hour));
Debug("green","End of Simulation: "..SimulatorPresenceEngine:ReverseUniversalTimeCalc("End Simulation", endtime).." + random of "..rndmaxendtime.."min");
Debug("green", "Checking for actions every minute.");

while true do -- Infinite loop of actions checking, hours calculations, notifications
	SimulatorPresenceEngine:EndTimeCalc(); 
	-- local Sunset_unix_hour = Midnight  -- un-comment this line when testing to force a start hour (or use sunset_shift)

	if os.time() >= Sunset_unix_hour then -- define if nighttime (sunset = 1)
		sunset = 1 
	else 
		sunset = 0 
	end 
	
	if (simu == "1") then 
		if sunset == 1 and (os.time() <= endtime) then 
			Debug("yellow", "It's sunset time -> Simulation ON");
			SimulatorPresenceEngine:Launch();
			SimulatorPresenceEngine:EndSimulation();
		end 
		if manualOveride == "1" then 
			Debug("yellow", "Manual Override Activated -> Simulation ON");
			SimulatorPresenceEngine:Launch();
			SimulatorPresenceEngine:EndSimulation();
		end
		if manualOveride == "0" and sunset == 0 and NotifLoop == 0 then 
			Debug("yellow", "Sunset is at "..fibaro:getValue(1, "sunsetHour").." + Sunset Shift of "..sunset_shift.."min = Start Time at "..SimulatorPresenceEngine:ReverseUniversalTimeCalc("Sunset unix time", Sunset_unix_hour));
			Debug("yellow", "End of Simulation: "..SimulatorPresenceEngine:ReverseUniversalTimeCalc("End Simulation", endtime).." + random of "..rndmaxendtime.."min = "..SimulatorPresenceEngine:ReverseUniversalTimeCalc("End Simulation", endtime_with_rndmaxendtime));
		end
	end

	if (simu == "0") then -- Condition to end simulation 
		SimulatorPresenceEngine:ExitSimulation();
	end
	
	if NotifLoop <= 120 then --a waiting xx times the fibaro sleep below (2 hours) before resetting counter (and notifying)
    	if NotifLoop == 120 then NotifLoop = 0 end
		if NotifLoop == 0 then
		ExtraDebug("Now, checking for actions every minute. Next notify: in 2 hours");
		end
	end
		
	fibaro:sleep(1*60*1000); -- wait 1 minutes before testing again the global vars below
	simu = fibaro:getGlobal("Simu_presence"); 
	manualOveride = fibaro:getGlobal("overideSimuSunset"); 
	NotifLoop = NotifLoop + 1;
end

Partager ce message


Lien à poster
Partager sur d’autres sites

Excellent,

 

Je viens de mettre la 3.3, j'avais la 3.2 que j'avais testé que sur 1 cycle, sans bug, mais pas teste sur plusieurs cycles.je pars ce soir en conges..tests grandeur nature ;-)

 

encore merci

Partager ce message


Lien à poster
Partager sur d’autres sites

bonne nouvelle, la 3.3 a fonctionné chez moi très bien.

 

Je suis occupé à  tester la 3.5.1, dernière version, pour moi car je ne trouve plus de bugs et j'ai réussi à  résoudre le dernier petit problème (lancement entre minuit et endtim ne fonctionnait pas)

 

J'ai fait dans la 3.5.1 un très grand nettoyage, renommage des variables, fonctions etc. c'est beaucoup plus propre et lisible maintenant.

 

Comme d'habitude, elle est ici:

https://github.com/sjauquet/YAPS/blob/master/YAPS.scene.lua

 

Comme il y a beaucoup de chose qui ont changé depuis la première version, j'hésite à  modifier le premier post de ce fil... si je trouve le temps.

 

A+

Partager ce message


Lien à poster
Partager sur d’autres sites

:74: , j'aime les codes propres avec du nettoyage !

Comme je suis fainéant ces temps-ci, je vous ai laissé faire les tests des dernières version (je sui passé en mode profiteur  :o )

Tu me dis quand je peux installer une version stable ? 

A propos, es-tu déjà  en V4.x ou toujours en v3.600 ?

Partager ce message


Lien à poster
Partager sur d’autres sites

×