Aller au contenu

Yaps - Présence Simulator, Un De Plus


sebcbien

Messages recommandés

Bonjour,

 

merci de repondre si vite!

 

Il faut le "turnOn", mais avant il faut les paramètres comme décrit.

Car YAPS marche avec un array, il n´est pas possible de donner des instructions pour les modules Fibaro et les Hue dans un seul array.

(Ou je ne sais pas comment faire...)

Si j´utilise deux arrays (HUE / Fibaro), je ne vois pas comment les faire fonctionner ensemble.

Voici les commandes d´une scène où j´utilise les deux sortes de lumière pour créer des ambiances differentes:

 

 --Hues      

    fibaro:call(532, "changeBrightness", 255)
    fibaro:call(532, "changeHue", 7680)
    fibaro:call(532, "changeSaturation", 210) 
    fibaro:call(532, "turnOn")
        
    fibaro:call(533, "changeBrightness", 255)
    fibaro:call(533, "changeHue", 13500)
    fibaro:call(533, "changeSaturation", 210) 
    fibaro:call(533, "turnOn")


-- Hue ambient white  
    fibaro:call(612, "changeBrightness", 150)
    fibaro:call(612, "changeSaturation", 210) 
    fibaro:call(612, "turnOn")
        
-- normale Lampen (modules fibaro)
    fibaro:call(138, "turnOn")
    fibaro:call(140, "turnOff")
        
    fibaro:debug("Licht hell")

 


J ´espère que j´ai bien décris mon problème (je ne suis pas Francais...)

 

Merci

Thilo

 

Lien vers le commentaire
Partager sur d’autres sites

Je reviens Avec mon problème:

 

Voici mon Debug: J'ai la lampe "LAMPE_LED_SALON" qui reste allumé toute le temps quand YAPS ET SUR "on" OU "on OVER". Mais quand je désactive le YAPS ça devrait allumer "LAMPE_HALL" et éteindre tous le autres allumé y compris "LAMPE_LED_SALON".

 

yaps_debug.jpg.284d48f0f232d0d5b2a784a345dba9dc.jpg

 J'ai une erreur sur la ligne 334:

 Voici la ligne 334:   if (name == nil or name == string.char(0)) then

 

Voici mon Code complet. Les ID je les ai controlé 2 fois et elles sont justes.

 

Citation

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

---------------------------------------
local version = "3.6.1";
-- YAPS Presence Simulation by SebcBien
-- August 2015
---------------------------------------
--V3.6.1 -- added new notifications engine (sms, freesms, push, email)
-- fixed bug "attempt to concatenate local 'deviceID' (a nil value)"
--V3.5.2 - start push sent by email
--V3.5.1
-- Fixed launch between midnight and endtime (if endtime is after midnight)
-- clean up code midnight-endtime
--V3.3.2
-- renamed all variables for more readability
--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 (End_simulation_time impact)
-- exit is now exactly at End_simulation_time
-- 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 Random_max_TurnOff_duration = 0
-- Probably fixed End_simulation_time bug calculation when looping for days du to days are shorter now than the previous day
-- Fixed bug not turning on Lights_On_at_end_Simulation when exiting Simulation
-- added random end time + small stability changes and cleaning
-- Added array of lights to turn on after Simulation, 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 End_simulation_time & midnight
-- fixed big bug Simulation 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_SALON_SPOT = 81,
 LAMPE_TERR_GAUCHE = 191,
 LAMPE_TABLE   = 197,
 LAMPE_CUISINE  = 198,
 LAMPE_HALL   = 202,
 LAMPE_LED_SALON  = 203,
 LAMPE_TERR_DROITE = 206,
 LAMPE_ESCALIER  = 213,
 PHONE_PAPA   = 227,
 ADMIN     = 2,
 }

local Stop_hour = "01";     -- Hour when you want Simulation to stop
local Stop_minute = "30";    -- 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 Random_max_TurnOff_duration)
-- 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_offset = -15    -- number of minutes before or after sunset to activate Simulation
local Random_max_duration = 18;   -- random time of light change in minutes --> here each device is on maximum 30min
local Random_max_TurnOff_duration = 22; -- random time to add at the stop hour+stop minute so the Simulation can be more variable (0 to deactivate)
local Lights_always_on = {id["LAMPE_LED_SALON"]} -- IDs of lights who will always stay on during Simulation - leave empty array if none -> {}
local Random_lights = {id["LAMPE_SALON_SPOT"],id["LAMPE_HALL"],id["LAMPE_TAPLE"],id["LAMPE_CUISINE"]} -- IDs of lights to use in Simulation
--local Random_lights = {id["LAMPE_HALL"],id["LAMPE_CELLIER"],id["LAMPE_CH_AMIS"]} -- Reduced set for test purposes
local Lights_On_at_end_Simulation = 0; -- If next line is commented, no light will turn on after Simulation ends
-- local Lights_On_at_end_Simulation = 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 Lights_On_if_Simulation_deactivated = 0; -- If next line is commented, no light will turn on after Simulation is stopped (by putting Simu_presence to 0)
local Lights_On_if_Simulation_deactivated = id["LAMPE_HALL"]; -- ID of a light (Only One) to turn on after Simulation is stopped (Simulation_). Comment this line to turn off this feature
YAPS_Engine = {};
 YAPS_Engine.notifications = true;     -- send notifications
 YAPS_Engine.notificationTypes = {"push", "email"}; --notification types {"push", "email", "sms"} but they are overriden in the code
 YAPS_Engine.Activate_FreeSms = false;    -- activate push with Activate_FreeSms (Activate_Push must be true also)
 YAPS_Engine.smartphoneID = {id["PHONE_PAPA"]};  -- Smartphone Id to send push to. {id1, id2, id3}
 YAPS_Engine.userID = {id["ADMIN"]};     -- User Id to send email to. {id1, id2, id3}
 YAPS_Engine.sms = {
  ["VD_ID"] = 0,         -- Virtual Device ID
  ["VD_Button"] = "1",       -- Virtual Device Button
  ["VG_Name"] = "SMS"};       -- Global Variable Name
--------------------- USER SETTINGS END ----------------------------
----------------------ADVANCED SETTINGS-----------------------------
local Show_standard_debug = true; -- Debug displayed in white
local Show_extra_debug = true;  -- Debug displayed in orange
--------------------------------------------------------------------
-------------------- DO NOT CHANGE CODE BELOW ----------------------
--------------------------------------------------------------------
local Number_of_lights = #Random_lights;      -- numbers of light devices listed above
local Simulation = fibaro:getGlobal("Simu_presence");   --value of the global value: Simulation is on or off
local Manual_overide = fibaro:getGlobal("overideSimuSunset"); -- if = 1 then the Simulation is forced
local Start_simulation_time = fibaro:getValue(1, "sunsetHour"); --Start Simulation when sunset
local End_simulation_time,Sunrise_unix_hour,Sunset_unix_hour,Converted_var,Midnight,End_simulation_time_with_random_max_TurnOff,Sleep_between_TurnOff;
local Is_first_launch = true;
local NotifLoop = 0;

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 ( Show_extra_debug ) then
  Debug( "orange", debugMessage);
 end
end

function StandardDebug(debugMessage)
 if ( Show_standard_debug ) 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 YAPS_Engine:notification(message, subject, param)
 local message = os.date("%H:%M", os.time()).." "..message or "<vide>";
 if YAPS_Engine.debug_messages then
  ExtraDebug("yellow", "Notification : "..message);
 end
  if Activate_FreeSms then
   fibaro:setGlobal("Activate_FreeSms", message)
   ExtraDebug("Message ("..message..") sent to Activate_FreeSms");
  end
 if param then
  for _, notif in ipairs(param) do
   if YAPS_Engine.debug_messages then
    ExtraDebug("grey", notif);
   end
   -- Envoi Push
   if notif == "push" and YAPS_Engine.smartphoneID then
    for _, id in ipairs(YAPS_Engine.smartphoneID) do
     if YAPS_Engine.debug_messages then
      ExtraDebug("grey", "Send Push smartphone ID : "..id);
     end
     fibaro:call(id, "sendPush", message);
    end
   -- Envoi Email
   elseif notif == "email" and YAPS_Engine.userID then
    for _, id in ipairs(YAPS_Engine.userID) do
     if YAPS_Engine.debug_messages then
      ExtraDebug("grey", "Send Email user ID : "..id);
     end
     fibaro:call(id, "sendEmail", subject, message);
    end
   -- Envoi SMS
   elseif notif == "sms" and YAPS_Engine.sms then
    if YAPS_Engine.debug_messages then
     ExtraDebug("grey", "Send SMS : VD_ID="..(YAPS_Engine.sms["VD_ID"] or 0).." VD_Button="..(YAPS_Engine.sms["VD_Button"] or "0").." VG_Name="..(YAPS_Engine.sms["VG_Name"] or ""));
    end
    fibaro:setGlobal(YAPS_Engine.sms["VG_Name"], message);
    if YAPS_Engine.sms["VD_ID"] and tonumber(YAPS_Engine.sms["VD_ID"])>0 and YAPS_Engine.sms["VD_Button"] and tonumber(YAPS_Engine.sms["VD_Button"])>0 then
     fibaro:call(YAPS_Engine.sms["VD_ID"], "pressButton", YAPS_Engine.sms["VD_Button"]);
    end
   end
  end
 else
  Debug("orange", "Warning : no notification options given");
 end
end

function YAPS_Engine:UnixTimeCalc(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 YAPS_Engine:ReverseUnixTimeCalc(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 YAPS_Engine:EndTimeCalc()
 local hour,min
 ExtraDebug ("Current Unix Time: "..os.time())
 End_simulation_time = YAPS_Engine:UnixTimeCalc("Original planed End_simulation_time", Stop_hour, Stop_minute); -- generate End_simulation_time (changes at midnight) will not change during Simulation, only when ended
 Midnight = YAPS_Engine:UnixTimeCalc("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 = (YAPS_Engine:UnixTimeCalc("Sunset", hour, min))+Sunset_offset*60;

 -- if stop hour is between 00 and 12h then add 24 hours to End_simulation_time
 if tonumber(Stop_hour) <= 12 and (os.time() >= End_simulation_time) then
  End_simulation_time = End_simulation_time + 24*60*60
  ExtraDebug ("stop hour <= 12, Added 24H to End_simulation_time (End_simulation_time is ending after midnignt)");
  ExtraDebug ("New End_simulation_time: "..End_simulation_time);
 end
 
 if Random_max_TurnOff_duration ~= 0 and Number_of_lights > 1 then   -- if Simulation = 1 then slow turn off, else turn off all immediately
  Sleep_between_TurnOff = round((math.random(Random_max_TurnOff_duration)/(Number_of_lights-1)),1);
  Sleep_between_TurnOff = math.random(Random_max_TurnOff_duration)/(Number_of_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
 End_simulation_time_with_random_max_TurnOff = End_simulation_time + ((Sleep_between_TurnOff*(Number_of_lights-1))*60)
 ExtraDebug("End_simulation_time_with_random_max_TurnOff: "..End_simulation_time_with_random_max_TurnOff); 
 
 if ((os.time() < End_simulation_time) and (Sunset_unix_hour - End_simulation_time > 0) and (Is_first_launch == true)) then -- if calculation is done between midnight and End_simulation_time and sunset is wrongly calculated after endtime (at first start only)
  Sunset_unix_hour = Sunset_unix_hour - (24*60*60) + 70; -- remove 24h58m50s of sunsettime
  ExtraDebug ("launch after Midnight and before End_simulation_time, removed 24H to Sunset_unix_hour (Only at the first start)");
  ExtraDebug ("New SunsetTime: "..Sunset_unix_hour);
 end
 Is_first_launch = false
end
-- Presence Simulation actions Main loop
function YAPS_Engine:Launch()
 YAPS_Engine:notification("Presence Simulation started. Will stop at: "..YAPS_Engine:ReverseUnixTimeCalc("End_simulation_time", End_simulation_time).." + rand("..Random_max_TurnOff_duration.."min) : "..YAPS_Engine:ReverseUnixTimeCalc("End_simulation_time_with_random_max_TurnOff", End_simulation_time_with_random_max_TurnOff), "Presence Simulator", {"push"}); -- push only
 StandardDebug("Presence Simulation started. Will stop at: "..YAPS_Engine:ReverseUnixTimeCalc("End_simulation_time", End_simulation_time).." + rand("..Random_max_TurnOff_duration.."min) : "..YAPS_Engine:ReverseUnixTimeCalc("End_simulation_time_with_random_max_TurnOff", End_simulation_time_with_random_max_TurnOff)); 
 if Lights_always_on[1] ~= nil then YAPS_Engine:TurnOn(Lights_always_on); end

 while ((os.time() <= End_simulation_time) and (Simulation == "1")) or ((Manual_overide == "1")) do
  local random_light = tonumber(Random_lights[math.random(Number_of_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(Random_max_duration*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 counterexitSimulation = 200
    while (counterexitSimulation > 0) and ((os.time() <= End_simulation_time) or Manual_overide == "1") do
     counterexitSimulation = counterexitSimulation - 1;
     test_presence_state = fibaro:getGlobal("Simu_presence");
     Simulation = tonumber(test_presence_state); --verify the global value, if the virtual device is deactivated, the loop stops.
     --fibaro:debug("Simulation var state : " .. Simulation.." override var state : " .. Manual_overide);
     if Simulation == 0 then
      Manual_overide = fibaro:getGlobalValue("overideSimuSunset");
      if Simulation == 0 or Manual_overide == "0" then
      counterexitSimulation = 0
      end
     end
    fibaro:sleep(sleeptime/200);
    end
   ExtraDebug("Exiting loop of "..round(sleeptime/60000,2).." minutes");
  local sleeptimemin = math.abs(sleeptime/60000)
  Simulation = fibaro:getGlobal("Simu_presence"); --verify the global value, if the virtual device is deactivated, the scene stops.
  Manual_overide = fibaro:getGlobalValue("overideSimuSunset");
 end
end
 
function YAPS_Engine:EndSimulation()
 if Lights_always_on[1] ~= nil then YAPS_Engine:TurnOff(Random_lights,Lights_always_on); end
 Debug("red","Presence Simulation deactivated");
 if (Simulation == "1") then
  Debug("yellow","Presence Simulation will restart tomorrow.");
  Debug("yellow","Sunset is around "..fibaro:getValue(1, "sunsetHour").." + Sunset Shift of "..Sunset_offset.."min = Start Time around "..YAPS_Engine:ReverseUnixTimeCalc("Sunset unix time", Sunset_unix_hour));
  YAPS_Engine:notification("Presence Simulation will restart tomorrow. Sunset is around "..fibaro:getValue(1, "sunsetHour").." + Sunset Shift of "..Sunset_offset.."min = Start Time around "..YAPS_Engine:ReverseUnixTimeCalc("Sunset unix time", Sunset_unix_hour), "Presence Simulator", {"push"}); -- push only
 end
 NotifLoop = 0; -- will force main loop notifications at end of Simulation
end

function YAPS_Engine:ExitSimulation()
 --YAPS_Engine:notification("Presence Simulation is terminated", "Presence Simulator", {"push"}); -- push only
 Debug("red","Simu_presence = 0, Aborting Simulation scene");
 fibaro:abort();
end

function YAPS_Engine:TurnOff(group,group2)
 Debug("red","TurnOff All Simulation lights!");
 local name, id2;
 local ID_devices_group = group;
 if ID_devices_group ~= 0 then
  for i=1, #ID_devices_group do
   Simulation = fibaro:getGlobal("Simu_presence"); --verify the global value, if Simulation presence is deactivated
   if Simulation == "0" then Sleep_between_TurnOff = 0; end; -- if Simulation ended before End_simulation_time, 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);
   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
 end
 Debug("red","TurnOff All Always_On lights!");
 local ID_devices_group = group2;
 if ID_devices_group ~= 0 then
  for i=1, #ID_devices_group do
   id2 = tonumber(ID_devices_group);
   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
 end
 if Lights_On_at_end_Simulation ~= 0 and Simulation == "1" then
  fibaro:call(Lights_On_at_end_Simulation, "turnOn");
  name = fibaro:getName(Lights_On_at_end_Simulation);
   if (name == nil or name == string.char(0)) then
    name = "Unknown"  
   end
  Debug("red","Turned On light Lights_On_at_end_Simulation:");
  Debug("white", name);
 end
 if Lights_On_if_Simulation_deactivated ~= 0 and Simulation == "0" then
  fibaro:call(Lights_On_if_Simulation_deactivated, "turnOn");
  name = fibaro:getName(Lights_On_if_Simulation_deactivated);
   if (name == nil or name == string.char(0)) then
    name = "Unknown"
   end
  Debug("red","Turned On light Lights_On_if_Simulation_deactivated:");
  Debug("white", name);
 end
end

function YAPS_Engine: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);
  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 Simulation | v" .. version .. " Starting up");
Debug("green", "--------------------------------------------------------------------------");

------------------------ Main Loop ----------------------------------
-- first start notifications
YAPS_Engine:EndTimeCalc();
YAPS_Engine:notification("Scheduled presence Simulation at "..YAPS_Engine:ReverseUnixTimeCalc("Sunset unix time", Sunset_unix_hour).." (Sunset: "..fibaro:getValue(1, "sunsetHour")..")", "Presence Simulator", {"email"}); -- mail only
Debug("green","Sunset is at "..fibaro:getValue(1, "sunsetHour").." + Sunset Shift of "..Sunset_offset.."min = Start Time at "..YAPS_Engine:ReverseUnixTimeCalc("Sunset unix time", Sunset_unix_hour));
Debug("green","End of Simulation: "..YAPS_Engine:ReverseUnixTimeCalc("End Simulation", End_simulation_time).." + random of "..Random_max_TurnOff_duration.."min");
Debug("green", "Checking for actions every minute.");
Is_first_launch = true

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

 if os.time() >= Sunset_unix_hour then -- define if nighttime (sunset = 1)
  sunset = 1
 else
  sunset = 0
 end
 
 if (Simulation == "1") then
  if sunset == 1 and (os.time() <= End_simulation_time) then
   Debug("yellow", "It's sunset time -> Simulation ON");
   YAPS_Engine:Launch();
   YAPS_Engine:EndSimulation();
  end
  if Manual_overide == "1" then
   Debug("yellow", "Manual Override Activated -> Simulation ON");
   YAPS_Engine:Launch();
   YAPS_Engine:EndSimulation();
  end
  if Manual_overide == "0" and sunset == 0 and NotifLoop == 0 then
   Debug("yellow", "Sunset is at "..fibaro:getValue(1, "sunsetHour").." + Sunset Shift of "..Sunset_offset.."min = Start Time at "..YAPS_Engine:ReverseUnixTimeCalc("Sunset unix time", Sunset_unix_hour));
   Debug("yellow", "End of Simulation: "..YAPS_Engine:ReverseUnixTimeCalc("End Simulation", End_simulation_time).." + random of "..Random_max_TurnOff_duration.."min = "..YAPS_Engine:ReverseUnixTimeCalc("End Simulation", End_simulation_time_with_random_max_TurnOff));
  end
 end

 if (Simulation == "0") then -- Condition to end Simulation
  YAPS_Engine: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
 Simulation = fibaro:getGlobal("Simu_presence");
 Manual_overide = fibaro:getGlobal("overideSimuSunset");
 NotifLoop = NotifLoop + 1;
end

 

Merci pour vos aides :-)

Lien vers le commentaire
Partager sur d’autres sites

Bonjour,

 


@speedoxx007

Essaie cela j'ai juste commente. En effet, on a l 'impression que ce n'est pas le bon id, donc il ne recupere pas le nom. enfin je crois.

 

dans une scene :
 

local name = fibaro:getName(202)

print("Name : " ..name)

Sinon la scene commentee
 

-------------------- USER SETTINGS --------------------------------
local id = {
 LAMPE_SALON_SPOT = 81,
 LAMPE_TERR_GAUCHE = 191,
 LAMPE_TABLE   = 197,
 LAMPE_CUISINE  = 198,
 LAMPE_HALL   = 202,
 LAMPE_LED_SALON  = 203,
 LAMPE_TERR_DROITE = 206,
 LAMPE_ESCALIER  = 213,
 PHONE_PAPA   = 227,
 ADMIN     = 2,
 }

local Stop_hour = "01";     -- Hour when you want Simulation to stop
local Stop_minute = "30";    -- 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 Random_max_TurnOff_duration)
-- 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_offset = -15    -- number of minutes before or after sunset to activate Simulation
local Random_max_duration = 18;   -- random time of light change in minutes --> here each device is on maximum 30min
local Random_max_TurnOff_duration = 22; -- random time to add at the stop hour+stop minute so the Simulation can be more variable (0 to deactivate)
local Lights_always_on = {id["LAMPE_LED_SALON"]} -- IDs of lights who will always stay on during Simulation - leave empty array if none -> {}
local Random_lights = {id["LAMPE_SALON_SPOT"],id["LAMPE_HALL"],id["LAMPE_TAPLE"],id["LAMPE_CUISINE"]} -- IDs of lights to use in Simulation
--local Random_lights = {id["LAMPE_HALL"],id["LAMPE_CELLIER"],id["LAMPE_CH_AMIS"]} -- Reduced set for test purposes
local Lights_On_at_end_Simulation = 0; -- If next line is commented, no light will turn on after Simulation ends
-- local Lights_On_at_end_Simulation = 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 Lights_On_if_Simulation_deactivated = 0; -- If next line is commented, no light will turn on after Simulation is stopped (by putting Simu_presence to 0)
local Lights_On_if_Simulation_deactivated = id["LAMPE_HALL"]; -- ID of a light (Only One) to turn on after Simulation is stopped (Simulation_). Comment this line to turn off this feature
YAPS_Engine = {};
 YAPS_Engine.notifications = true;     -- send notifications
 YAPS_Engine.notificationTypes = {"push", "email"}; --notification types {"push", "email", "sms"} but they are overriden in the code
 YAPS_Engine.Activate_FreeSms = false;    -- activate push with Activate_FreeSms (Activate_Push must be true also)
 YAPS_Engine.smartphoneID = {id["PHONE_PAPA"]};  -- Smartphone Id to send push to. {id1, id2, id3}
 YAPS_Engine.userID = {id["ADMIN"]};     -- User Id to send email to. {id1, id2, id3}
 YAPS_Engine.sms = {
  ["VD_ID"] = 0,         -- Virtual Device ID
  ["VD_Button"] = "1",       -- Virtual Device Button
  ["VG_Name"] = "SMS"};       -- Global Variable Name
--------------------- USER SETTINGS END ----------------------------
----------------------ADVANCED SETTINGS-----------------------------
local Show_standard_debug = true; -- Debug displayed in white
local Show_extra_debug = true;  -- Debug displayed in orange
--------------------------------------------------------------------
-------------------- DO NOT CHANGE CODE BELOW ----------------------
--------------------------------------------------------------------
local Number_of_lights = #Random_lights;      -- numbers of light devices listed above
local Simulation = fibaro:getGlobal("Simu_presence");   --value of the global value: Simulation is on or off
local Manual_overide = fibaro:getGlobal("overideSimuSunset"); -- if = 1 then the Simulation is forced
local Start_simulation_time = fibaro:getValue(1, "sunsetHour"); --Start Simulation when sunset
local End_simulation_time,Sunrise_unix_hour,Sunset_unix_hour,Converted_var,Midnight,End_simulation_time_with_random_max_TurnOff,Sleep_between_TurnOff;
local Is_first_launch = true;
local NotifLoop = 0;

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 ( Show_extra_debug ) then
  Debug( "orange", debugMessage);
 end
end

function StandardDebug(debugMessage)
 if ( Show_standard_debug ) 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 YAPS_Engine:notification(message, subject, param)
 local message = os.date("%H:%M", os.time()).." "..message or "<vide>";
 if YAPS_Engine.debug_messages then
  ExtraDebug("yellow", "Notification : "..message);
 end
  if Activate_FreeSms then
   fibaro:setGlobal("Activate_FreeSms", message)
   ExtraDebug("Message ("..message..") sent to Activate_FreeSms");
  end
 if param then
  for _, notif in ipairs(param) do
   if YAPS_Engine.debug_messages then
    ExtraDebug("grey", notif);
   end
   -- Envoi Push
   if notif == "push" and YAPS_Engine.smartphoneID then
    for _, id in ipairs(YAPS_Engine.smartphoneID) do
     if YAPS_Engine.debug_messages then
      ExtraDebug("grey", "Send Push smartphone ID : "..id);
     end
     fibaro:call(id, "sendPush", message);
    end
   -- Envoi Email
   elseif notif == "email" and YAPS_Engine.userID then
    for _, id in ipairs(YAPS_Engine.userID) do
     if YAPS_Engine.debug_messages then
      ExtraDebug("grey", "Send Email user ID : "..id);
     end
     fibaro:call(id, "sendEmail", subject, message);
    end
   -- Envoi SMS
   elseif notif == "sms" and YAPS_Engine.sms then
    if YAPS_Engine.debug_messages then
     ExtraDebug("grey", "Send SMS : VD_ID="..(YAPS_Engine.sms["VD_ID"] or 0).." VD_Button="..(YAPS_Engine.sms["VD_Button"] or "0").." VG_Name="..(YAPS_Engine.sms["VG_Name"] or ""));
    end
    fibaro:setGlobal(YAPS_Engine.sms["VG_Name"], message);
    if YAPS_Engine.sms["VD_ID"] and tonumber(YAPS_Engine.sms["VD_ID"])>0 and YAPS_Engine.sms["VD_Button"] and tonumber(YAPS_Engine.sms["VD_Button"])>0 then
     fibaro:call(YAPS_Engine.sms["VD_ID"], "pressButton", YAPS_Engine.sms["VD_Button"]);
    end
   end
  end
 else
  Debug("orange", "Warning : no notification options given");
 end
end

function YAPS_Engine:UnixTimeCalc(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 YAPS_Engine:ReverseUnixTimeCalc(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 YAPS_Engine:EndTimeCalc()
 local hour,min
 ExtraDebug ("Current Unix Time: "..os.time())
 End_simulation_time = YAPS_Engine:UnixTimeCalc("Original planed End_simulation_time", Stop_hour, Stop_minute); -- generate End_simulation_time (changes at midnight) will not change during Simulation, only when ended
 Midnight = YAPS_Engine:UnixTimeCalc("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 = (YAPS_Engine:UnixTimeCalc("Sunset", hour, min))+Sunset_offset*60;

 -- if stop hour is between 00 and 12h then add 24 hours to End_simulation_time
 if tonumber(Stop_hour) <= 12 and (os.time() >= End_simulation_time) then
  End_simulation_time = End_simulation_time + 24*60*60
  ExtraDebug ("stop hour <= 12, Added 24H to End_simulation_time (End_simulation_time is ending after midnignt)");
  ExtraDebug ("New End_simulation_time: "..End_simulation_time);
 end
 
 if Random_max_TurnOff_duration ~= 0 and Number_of_lights > 1 then   -- if Simulation = 1 then slow turn off, else turn off all immediately
  Sleep_between_TurnOff = round((math.random(Random_max_TurnOff_duration)/(Number_of_lights-1)),1);
  Sleep_between_TurnOff = math.random(Random_max_TurnOff_duration)/(Number_of_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
 End_simulation_time_with_random_max_TurnOff = End_simulation_time + ((Sleep_between_TurnOff*(Number_of_lights-1))*60)
 ExtraDebug("End_simulation_time_with_random_max_TurnOff: "..End_simulation_time_with_random_max_TurnOff);
 
 if ((os.time() < End_simulation_time) and (Sunset_unix_hour - End_simulation_time > 0) and (Is_first_launch == true)) then -- if calculation is done between midnight and End_simulation_time and sunset is wrongly calculated after endtime (at first start only)
  Sunset_unix_hour = Sunset_unix_hour - (24*60*60) + 70; -- remove 24h58m50s of sunsettime
  ExtraDebug ("launch after Midnight and before End_simulation_time, removed 24H to Sunset_unix_hour (Only at the first start)");
  ExtraDebug ("New SunsetTime: "..Sunset_unix_hour);
 end
 Is_first_launch = false
end
-- Presence Simulation actions Main loop
function YAPS_Engine:Launch()
 YAPS_Engine:notification("Presence Simulation started. Will stop at: "..YAPS_Engine:ReverseUnixTimeCalc("End_simulation_time", End_simulation_time).." + rand("..Random_max_TurnOff_duration.."min) : "..YAPS_Engine:ReverseUnixTimeCalc("End_simulation_time_with_random_max_TurnOff", End_simulation_time_with_random_max_TurnOff), "Presence Simulator", {"push"}); -- push only
 StandardDebug("Presence Simulation started. Will stop at: "..YAPS_Engine:ReverseUnixTimeCalc("End_simulation_time", End_simulation_time).." + rand("..Random_max_TurnOff_duration.."min) : "..YAPS_Engine:ReverseUnixTimeCalc("End_simulation_time_with_random_max_TurnOff", End_simulation_time_with_random_max_TurnOff));
 if Lights_always_on[1] ~= nil then YAPS_Engine:TurnOn(Lights_always_on); end

 while ((os.time() <= End_simulation_time) and (Simulation == "1")) or ((Manual_overide == "1")) do
  local random_light = tonumber(Random_lights[math.random(Number_of_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(Random_max_duration*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 counterexitSimulation = 200
    while (counterexitSimulation > 0) and ((os.time() <= End_simulation_time) or Manual_overide == "1") do
     counterexitSimulation = counterexitSimulation - 1;
     test_presence_state = fibaro:getGlobal("Simu_presence");
     Simulation = tonumber(test_presence_state); --verify the global value, if the virtual device is deactivated, the loop stops.
     --fibaro:debug("Simulation var state : " .. Simulation.." override var state : " .. Manual_overide);
     if Simulation == 0 then
      Manual_overide = fibaro:getGlobalValue("overideSimuSunset");
      if Simulation == 0 or Manual_overide == "0" then
      counterexitSimulation = 0
      end
     end
    fibaro:sleep(sleeptime/200);
    end
   ExtraDebug("Exiting loop of "..round(sleeptime/60000,2).." minutes");
  local sleeptimemin = math.abs(sleeptime/60000)
  Simulation = fibaro:getGlobal("Simu_presence"); --verify the global value, if the virtual device is deactivated, the scene stops.
  Manual_overide = fibaro:getGlobalValue("overideSimuSunset");
 end
end
 
function YAPS_Engine:EndSimulation()
 if Lights_always_on[1] ~= nil then YAPS_Engine:TurnOff(Random_lights,Lights_always_on); end
 Debug("red","Presence Simulation deactivated");
 if (Simulation == "1") then
  Debug("yellow","Presence Simulation will restart tomorrow.");
  Debug("yellow","Sunset is around "..fibaro:getValue(1, "sunsetHour").." + Sunset Shift of "..Sunset_offset.."min = Start Time around "..YAPS_Engine:ReverseUnixTimeCalc("Sunset unix time", Sunset_unix_hour));
  YAPS_Engine:notification("Presence Simulation will restart tomorrow. Sunset is around "..fibaro:getValue(1, "sunsetHour").." + Sunset Shift of "..Sunset_offset.."min = Start Time around "..YAPS_Engine:ReverseUnixTimeCalc("Sunset unix time", Sunset_unix_hour), "Presence Simulator", {"push"}); -- push only
 end
 NotifLoop = 0; -- will force main loop notifications at end of Simulation
end

function YAPS_Engine:ExitSimulation()
 --YAPS_Engine:notification("Presence Simulation is terminated", "Presence Simulator", {"push"}); -- push only
 Debug("red","Simu_presence = 0, Aborting Simulation scene");
 fibaro:abort();
end

function YAPS_Engine:TurnOff(group,group2)
 Debug("red","TurnOff All Simulation lights!");
 local name, id2;
 local ID_devices_group = group;
 if ID_devices_group ~= 0 then
  for i=1, #ID_devices_group do
   Simulation = fibaro:getGlobal("Simu_presence"); --verify the global value, if Simulation presence is deactivated
   if Simulation == "0" then Sleep_between_TurnOff = 0; end; -- if Simulation ended before End_simulation_time, 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);
   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
 end
 Debug("red","TurnOff All Always_On lights!");
 local ID_devices_group = group2;
 if ID_devices_group ~= 0 then
  for i=1, #ID_devices_group do
   id2 = tonumber(ID_devices_group);
   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
 end
 if Lights_On_at_end_Simulation ~= 0 and Simulation == "1" then
  fibaro:call(Lights_On_at_end_Simulation, "turnOn");
  name = fibaro:getName(Lights_On_at_end_Simulation);
  --[[if (name == nil or name == string.char(0)) then
    name = "Unknown"  
   end--]]
  Debug("red","Turned On light Lights_On_at_end_Simulation:");
  --Debug("white", name);
 end
 if Lights_On_if_Simulation_deactivated ~= 0 and Simulation == "0" then
  fibaro:call(Lights_On_if_Simulation_deactivated, "turnOn");
  name = fibaro:getName(Lights_On_if_Simulation_deactivated);
   if (name == nil or name == string.char(0)) then
    name = "Unknown"
   end
  Debug("red","Turned On light Lights_On_if_Simulation_deactivated:");
  Debug("white", name);
 end
end

function YAPS_Engine: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);
  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 Simulation | v" .. version .. " Starting up");
Debug("green", "--------------------------------------------------------------------------");

------------------------ Main Loop ----------------------------------
-- first start notifications
YAPS_Engine:EndTimeCalc();
YAPS_Engine:notification("Scheduled presence Simulation at "..YAPS_Engine:ReverseUnixTimeCalc("Sunset unix time", Sunset_unix_hour).." (Sunset: "..fibaro:getValue(1, "sunsetHour")..")", "Presence Simulator", {"email"}); -- mail only
Debug("green","Sunset is at "..fibaro:getValue(1, "sunsetHour").." + Sunset Shift of "..Sunset_offset.."min = Start Time at "..YAPS_Engine:ReverseUnixTimeCalc("Sunset unix time", Sunset_unix_hour));
Debug("green","End of Simulation: "..YAPS_Engine:ReverseUnixTimeCalc("End Simulation", End_simulation_time).." + random of "..Random_max_TurnOff_duration.."min");
Debug("green", "Checking for actions every minute.");
Is_first_launch = true

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

 if os.time() >= Sunset_unix_hour then -- define if nighttime (sunset = 1)
  sunset = 1
 else
  sunset = 0
 end
 
 if (Simulation == "1") then
  if sunset == 1 and (os.time() <= End_simulation_time) then
   Debug("yellow", "It's sunset time -> Simulation ON");
   YAPS_Engine:Launch();
   YAPS_Engine:EndSimulation();
  end
  if Manual_overide == "1" then
   Debug("yellow", "Manual Override Activated -> Simulation ON");
   YAPS_Engine:Launch();
   YAPS_Engine:EndSimulation();
  end
  if Manual_overide == "0" and sunset == 0 and NotifLoop == 0 then
   Debug("yellow", "Sunset is at "..fibaro:getValue(1, "sunsetHour").." + Sunset Shift of "..Sunset_offset.."min = Start Time at "..YAPS_Engine:ReverseUnixTimeCalc("Sunset unix time", Sunset_unix_hour));
   Debug("yellow", "End of Simulation: "..YAPS_Engine:ReverseUnixTimeCalc("End Simulation", End_simulation_time).." + random of "..Random_max_TurnOff_duration.."min = "..YAPS_Engine:ReverseUnixTimeCalc("End Simulation", End_simulation_time_with_random_max_TurnOff));
  end
 end

 if (Simulation == "0") then -- Condition to end Simulation
  YAPS_Engine: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
 Simulation = fibaro:getGlobal("Simu_presence");
 Manual_overide = fibaro:getGlobal("overideSimuSunset");
 NotifLoop = NotifLoop + 1;
end


@Thilo

C'est faisable, mais faut modifier un peu la scene. Partage ta scene complete stp.

Modifié par pepite
Lien vers le commentaire
Partager sur d’autres sites

Hi Speedox,

 

c´est peut-etre juste un probleme d´orthographe?

Ta Lampe_Table 197 revient dans le array avec un p (taple)

local Random_lights = {id["LAMPE_SALON_SPOT"],id["LAMPE_HALL"],id["LAMPE_TAPLE"],id["LAMPE_CUISINE"]}

 

TT

  • Upvote 2
Lien vers le commentaire
Partager sur d’autres sites

@pepite

 

Ma scène YAPS ou celle ou j´ulitilise le melange?

Mon YAPS est comme d´hab, actuellement j´ai inclus que des modules Fibaro, ca marche très bien.

Si je donne les ID des Hue il n´y a pas d´erreur dans la scène, les lampes ne reagissent tout simplement pas. En fait le ID Hue pointe sur un VD, qui a justement besoin des parametres marques en haut. Sinon il ne donne pas d´erreur, mais il ignore un simple "turnOn". A quel endroit dois je implementer les parametres HUE?

 

Merci!

Thilo

Lien vers le commentaire
Partager sur d’autres sites

@Thilo, regarde j'ai commence ca vite fait.

Jette un oeil ou il a le commentaire "test pepite"

 

On ne devrait pas etre loin de ton besoin ;-)

 

 

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,
    ADMIN                 = 2,
    PHONE_GG            = 1327
    }

local Stop_hour = "01";                    -- Hour when you want Simulation to stop
local Stop_minute = "30";                -- 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 Random_max_TurnOff_duration)
-- 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_offset = -15                -- number of minutes before or after sunset to activate Simulation
local Random_max_duration = 30;            -- random time of light change in minutes --> here each device is on maximum 30min
local Random_max_TurnOff_duration = 25;    -- random time to add at the stop hour+stop minute so the Simulation can be more variable (0 to deactivate)
local 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 Random_lights = {id["LAMPE_SDB"],id["LAMPE_HALL"],id["LAMPE_CELLIER"],id["LAMPE_CH_AMIS"]} -- IDs of lights to use in Simulation
-- test pepite --
local Random_Lights_Hue = {} --IDs of lights "HUE" to use in Simulation
-- fin test pepite --
--local Random_lights = {id["LAMPE_HALL"],id["LAMPE_CELLIER"],id["LAMPE_CH_AMIS"]} -- Reduced set for test purposes
local Lights_On_at_end_Simulation = 0;    -- If next line is commented, no light will turn on after Simulation ends
local Lights_On_at_end_Simulation = 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 Lights_On_if_Simulation_deactivated = 0; -- If next line is commented, no light will turn on after Simulation is stopped (by putting Simu_presence to 0)
local Lights_On_if_Simulation_deactivated = id["LAMPE_HALL"]; -- ID of a light (Only One) to turn on after Simulation is stopped (Simulation_). Comment this line to turn off this feature
YAPS_Engine = {};
    YAPS_Engine.notifications = true;                    -- send notifications
    YAPS_Engine.notificationTypes = {"push", "email"};    --notification types {"push", "email", "sms"} but they are overriden in the code
    YAPS_Engine.Activate_FreeSms = false;                -- activate push with Activate_FreeSms (Activate_Push must be true also)
    YAPS_Engine.smartphoneID = {id["PHONE_SEB"]};        -- Smartphone Id to send push to. {id1, id2, id3}
    YAPS_Engine.userID = {id["ADMIN"]};                    -- User Id to send email to. {id1, id2, id3}
    YAPS_Engine.sms = {
        ["VD_ID"] = 0,                                    -- Virtual Device ID
        ["VD_Button"] = "1",                            -- Virtual Device Button
        ["VG_Name"] = "SMS"};                            -- Global Variable Name
--------------------- USER SETTINGS END ----------------------------
----------------------ADVANCED SETTINGS-----------------------------
local Show_standard_debug = true;    -- Debug displayed in white
local Show_extra_debug = false;        -- Debug displayed in orange
--------------------------------------------------------------------
-------------------- DO NOT CHANGE CODE BELOW ----------------------
--------------------------------------------------------------------

-- test pepite --
local Number_of_lights_hue = #Random_Lights_Hue -- number of lights hue
-- fin test pepite --
local Number_of_lights = #Random_lights;                        -- numbers of light devices listed above
local Simulation = fibaro:getGlobal("Simu_presence");            --value of the global value: Simulation is on or off
local Manual_overide = fibaro:getGlobal("overideSimuSunset");    -- if = 1 then the Simulation is forced
local Start_simulation_time = fibaro:getValue(1, "sunsetHour");    --Start Simulation when sunset
local End_simulation_time,Sunrise_unix_hour,Sunset_unix_hour,Converted_var,Midnight,End_simulation_time_with_random_max_TurnOff,Sleep_between_TurnOff;
local Is_first_launch = true;
local NotifLoop = 0;

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 ( Show_extra_debug ) then
        Debug( "orange", debugMessage);
    end
end

function StandardDebug(debugMessage)
    if ( Show_standard_debug ) 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 YAPS_Engine:notification(message, subject, param)
    local message = os.date("%H:%M", os.time()).." "..message or "<vide>";
    if YAPS_Engine.debug_messages then
        ExtraDebug("yellow", "Notification : "..message);
    end
        if Activate_FreeSms then
            fibaro:setGlobal("Activate_FreeSms", message)
            ExtraDebug("Message ("..message..") sent to Activate_FreeSms");
        end
    if param then
        for _, notif in ipairs(param) do
            if YAPS_Engine.debug_messages then
                ExtraDebug("grey", notif);
            end
            -- Envoi Push
            if notif == "push" and YAPS_Engine.smartphoneID then
                for _, id in ipairs(YAPS_Engine.smartphoneID) do
                    if YAPS_Engine.debug_messages then
                        ExtraDebug("grey", "Send Push smartphone ID : "..id);
                    end
                    fibaro:call(id, "sendPush", message);
                end
            -- Envoi Email
            elseif notif == "email" and YAPS_Engine.userID then
                for _, id in ipairs(YAPS_Engine.userID) do
                    if YAPS_Engine.debug_messages then
                        ExtraDebug("grey", "Send Email user ID : "..id);
                    end
                    fibaro:call(id, "sendEmail", subject, message);
                end
            -- Envoi SMS
            elseif notif == "sms" and YAPS_Engine.sms then
                if YAPS_Engine.debug_messages then
                    ExtraDebug("grey", "Send SMS : VD_ID="..(YAPS_Engine.sms["VD_ID"] or 0).." VD_Button="..(YAPS_Engine.sms["VD_Button"] or "0").." VG_Name="..(YAPS_Engine.sms["VG_Name"] or ""));
                end
                fibaro:setGlobal(YAPS_Engine.sms["VG_Name"], message);
                if YAPS_Engine.sms["VD_ID"] and tonumber(YAPS_Engine.sms["VD_ID"])>0 and YAPS_Engine.sms["VD_Button"] and tonumber(YAPS_Engine.sms["VD_Button"])>0 then
                    fibaro:call(YAPS_Engine.sms["VD_ID"], "pressButton", YAPS_Engine.sms["VD_Button"]);
                end
            end
        end
    else
        Debug("orange", "Warning : no notification options given");
    end
end

function YAPS_Engine:UnixTimeCalc(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 YAPS_Engine:ReverseUnixTimeCalc(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 YAPS_Engine:EndTimeCalc()
    local hour,min
    ExtraDebug ("Current Unix Time: "..os.time())
    End_simulation_time = YAPS_Engine:UnixTimeCalc("Original planed End_simulation_time", Stop_hour, Stop_minute); -- generate End_simulation_time (changes at midnight) will not change during Simulation, only when ended
    Midnight = YAPS_Engine:UnixTimeCalc("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 = (YAPS_Engine:UnixTimeCalc("Sunset", hour, min))+Sunset_offset*60;

    -- if stop hour is between 00 and 12h then add 24 hours to End_simulation_time
    if tonumber(Stop_hour) <= 12 and (os.time() >= End_simulation_time) then
        End_simulation_time = End_simulation_time + 24*60*60
        ExtraDebug ("stop hour <= 12, Added 24H to End_simulation_time (End_simulation_time is ending after midnignt)");
        ExtraDebug ("New End_simulation_time: "..End_simulation_time);
    end
    
    if Random_max_TurnOff_duration ~= 0 and Number_of_lights > 1 then   -- if Simulation = 1 then slow turn off, else turn off all immediately
        Sleep_between_TurnOff = round((math.random(Random_max_TurnOff_duration)/(Number_of_lights-1)),1);
        Sleep_between_TurnOff = math.random(Random_max_TurnOff_duration)/(Number_of_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
    End_simulation_time_with_random_max_TurnOff = End_simulation_time + ((Sleep_between_TurnOff*(Number_of_lights-1))*60)
    ExtraDebug("End_simulation_time_with_random_max_TurnOff: "..End_simulation_time_with_random_max_TurnOff);    
    
    if ((os.time() < End_simulation_time) and (Sunset_unix_hour - End_simulation_time > 0) and (Is_first_launch == true)) then -- if calculation is done between midnight and End_simulation_time and sunset is wrongly calculated after endtime (at first start only)
        Sunset_unix_hour = Sunset_unix_hour - (24*60*60) + 70; -- remove 24h58m50s of sunsettime
        ExtraDebug ("launch after Midnight and before End_simulation_time, removed 24H to Sunset_unix_hour (Only at the first start)");
        ExtraDebug ("New SunsetTime: "..Sunset_unix_hour);
    end
    Is_first_launch = false
end
-- Presence Simulation actions Main loop
function YAPS_Engine:Launch()
    YAPS_Engine:notification("Presence Simulation started. Will stop at: "..YAPS_Engine:ReverseUnixTimeCalc("End_simulation_time", End_simulation_time).." + rand("..Random_max_TurnOff_duration.."min) : "..YAPS_Engine:ReverseUnixTimeCalc("End_simulation_time_with_random_max_TurnOff", End_simulation_time_with_random_max_TurnOff), "Presence Simulator", {"push"}); -- push only
    StandardDebug("Presence Simulation started. Will stop at: "..YAPS_Engine:ReverseUnixTimeCalc("End_simulation_time", End_simulation_time).." + rand("..Random_max_TurnOff_duration.."min) : "..YAPS_Engine:ReverseUnixTimeCalc("End_simulation_time_with_random_max_TurnOff", End_simulation_time_with_random_max_TurnOff));    
    if Lights_always_on[1] ~= nil then YAPS_Engine:TurnOn(Lights_always_on); end

    while ((os.time() <= End_simulation_time) and (Simulation == "1")) or ((Manual_overide == "1")) do
        local random_light = tonumber(Random_lights[math.random(Number_of_lights)]) --choose a random light in the list
        -- test pepite --
        local random_light_hue = tonumber(Random_Lights_Hue[math.random(Number_of_lights_hue)]) --choose a random light hue in the list
        local lightstatushue = fibaro:getValue(random_light_hue, 'value') --get the value of the random light HUE in the list
        -- fin test pepite --
        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
        --- test pepite --
        if tonumber(lightstatushue) == 0 then
            fibaro:call(random_light_hue, "changeBrightness", 255)
            fibaro:call(random_light_hue, "changeHue", 7680)
            fibaro:call(random_light_hue, "changeSaturation", 210)
            fibaro:call(random_light_hue, 'turnOn')
        else
            fibaro:call(random_light_hue, 'turnOff')
        end
        -- fin test pepite --
        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
        -- test pepite --
        lightstatushue = fibaro:getValue(random_light_hue, 'value') --get the value of the random light HUE after his update
        StandardDebug('light HUE ID:'.. fibaro:getName(random_light_hue) ..' status:'..lightstatushue);
        -- fin test
        StandardDebug('light ID:'.. fibaro:getName(random_light) ..' status:'..lightstatus);
        local sleeptime = math.random(Random_max_duration*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 counterexitSimulation = 200
                while (counterexitSimulation > 0) and ((os.time() <= End_simulation_time) or Manual_overide == "1") do
                    counterexitSimulation = counterexitSimulation - 1;
                    test_presence_state = fibaro:getGlobal("Simu_presence");
                    Simulation = tonumber(test_presence_state); --verify the global value, if the virtual device is deactivated, the loop stops.
                    --fibaro:debug("Simulation var state : " .. Simulation.." override var state : " .. Manual_overide);
                    if Simulation == 0 then
                        Manual_overide = fibaro:getGlobalValue("overideSimuSunset");
                        if Simulation == 0 or Manual_overide == "0" then
                        counterexitSimulation = 0
                        end
                    end
                fibaro:sleep(sleeptime/200);
                end
            ExtraDebug("Exiting loop of "..round(sleeptime/60000,2).." minutes");
        local sleeptimemin = math.abs(sleeptime/60000)
        Simulation = fibaro:getGlobal("Simu_presence"); --verify the global value, if the virtual device is deactivated, the scene stops.
        Manual_overide = fibaro:getGlobalValue("overideSimuSunset");
    end
end
    
function YAPS_Engine:EndSimulation()
    if Lights_always_on[1] ~= nil then YAPS_Engine:TurnOff(Random_lights,Lights_always_on); end
    -- test pepite
    for i= 1, Number_of_lights_hue do
        if tonumber(lightstatushue) > 0 then
            fibaro:call(Random_Lights_Hue[i], "turnOff")
        end
    end
    -- fin test pepite --
    Debug("red","Presence Simulation deactivated");
    if (Simulation == "1") then
        Debug("yellow","Presence Simulation will restart tomorrow.");
        Debug("yellow","Sunset is around "..fibaro:getValue(1, "sunsetHour").." + Sunset Shift of "..Sunset_offset.."min = Start Time around "..YAPS_Engine:ReverseUnixTimeCalc("Sunset unix time", Sunset_unix_hour));
        YAPS_Engine:notification("Presence Simulation will restart tomorrow. Sunset is around "..fibaro:getValue(1, "sunsetHour").." + Sunset Shift of "..Sunset_offset.."min = Start Time around "..YAPS_Engine:ReverseUnixTimeCalc("Sunset unix time", Sunset_unix_hour), "Presence Simulator", {"push"}); -- push only
    end
    NotifLoop = 0; -- will force main loop notifications at end of Simulation
end

function YAPS_Engine:ExitSimulation()
    --YAPS_Engine:notification("Presence Simulation is terminated", "Presence Simulator", {"push"}); -- push only
    Debug("red","Simu_presence = 0, Aborting Simulation scene");
    fibaro:abort();
end

function YAPS_Engine:TurnOff(group,group2)
    Debug("red","TurnOff All Simulation lights!");
    local name, id2;
    local ID_devices_group = group;
    if ID_devices_group ~= 0 then
        for i=1, #ID_devices_group do
            Simulation = fibaro:getGlobal("Simu_presence"); --verify the global value, if Simulation presence is deactivated
            if Simulation == "0" then    Sleep_between_TurnOff = 0; end; -- if Simulation ended before End_simulation_time, 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
    end
    Debug("red","TurnOff All Always_On lights!");
    local ID_devices_group = group2;
    if ID_devices_group ~= 0 then
        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
    end
    if Lights_On_at_end_Simulation ~= 0 and Simulation == "1" then
        fibaro:call(Lights_On_at_end_Simulation, "turnOn");
        name = fibaro:getName(Lights_On_at_end_Simulation);
            if (name == nil or name == string.char(0)) then
                name = "Unknown"     
            end
        Debug("red","Turned On light Lights_On_at_end_Simulation:");
        Debug("white", name);
    end
    if Lights_On_if_Simulation_deactivated ~= 0 and Simulation == "0" then
        fibaro:call(Lights_On_if_Simulation_deactivated, "turnOn");
        name = fibaro:getName(Lights_On_if_Simulation_deactivated);
            if (name == nil or name == string.char(0)) then
                name = "Unknown"
            end
        Debug("red","Turned On light Lights_On_if_Simulation_deactivated:");
        Debug("white", name);
    end
end

function YAPS_Engine: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 Simulation | v" .. version .. " Starting up");
Debug("green", "--------------------------------------------------------------------------");

------------------------ Main Loop ----------------------------------
-- first start notifications
YAPS_Engine:EndTimeCalc();
YAPS_Engine:notification("Scheduled presence Simulation at "..YAPS_Engine:ReverseUnixTimeCalc("Sunset unix time", Sunset_unix_hour).." (Sunset: "..fibaro:getValue(1, "sunsetHour")..")", "Presence Simulator", {"email"}); -- mail only
Debug("green","Sunset is at "..fibaro:getValue(1, "sunsetHour").." + Sunset Shift of "..Sunset_offset.."min = Start Time at "..YAPS_Engine:ReverseUnixTimeCalc("Sunset unix time", Sunset_unix_hour));
Debug("green","End of Simulation: "..YAPS_Engine:ReverseUnixTimeCalc("End Simulation", End_simulation_time).." + random of "..Random_max_TurnOff_duration.."min");
Debug("green", "Checking for actions every minute.");
Is_first_launch = true

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

    if os.time() >= Sunset_unix_hour then -- define if nighttime (sunset = 1)
        sunset = 1
    else
        sunset = 0
    end
    
    if (Simulation == "1") then
        if sunset == 1 and (os.time() <= End_simulation_time) then
            Debug("yellow", "It's sunset time -> Simulation ON");
            YAPS_Engine:Launch();
            YAPS_Engine:EndSimulation();
        end
        if Manual_overide == "1" then
            Debug("yellow", "Manual Override Activated -> Simulation ON");
            YAPS_Engine:Launch();
            YAPS_Engine:EndSimulation();
        end
        if Manual_overide == "0" and sunset == 0 and NotifLoop == 0 then
            Debug("yellow", "Sunset is at "..fibaro:getValue(1, "sunsetHour").." + Sunset Shift of "..Sunset_offset.."min = Start Time at "..YAPS_Engine:ReverseUnixTimeCalc("Sunset unix time", Sunset_unix_hour));
            Debug("yellow", "End of Simulation: "..YAPS_Engine:ReverseUnixTimeCalc("End Simulation", End_simulation_time).." + random of "..Random_max_TurnOff_duration.."min = "..YAPS_Engine:ReverseUnixTimeCalc("End Simulation", End_simulation_time_with_random_max_TurnOff));
        end
    end

    if (Simulation == "0") then -- Condition to end Simulation
        YAPS_Engine: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
    Simulation = fibaro:getGlobal("Simu_presence");
    Manual_overide = fibaro:getGlobal("overideSimuSunset");
    NotifLoop = NotifLoop + 1;
end

 

Lien vers le commentaire
Partager sur d’autres sites

@pepite: Super. Merci! Ca parrait très bien! Je vais tester ton script ce soir et donner suite!

 

@speedoxx007: C´est une des mes propres fautes préféré, donc je regarde toujours les fautes de frappe, les ""., les ;; etc.

90% des erreurs chez moi sont dus a ca.....

 

A+

Thilo

Lien vers le commentaire
Partager sur d’autres sites

Cool, ca marche!

Fallait remplacer dans lightstatus_hue "value" contre "on", c´est le "status hue" pour demander aux hues si ils sont allumés.

Merci beaucoup pepite!

 

A+

Thilo

 

Voila tout le script pour ceux qui utilisent des lampes Philips Hue:

 

 

--[[ 
%% autostart
%% properties 
%% globals 
Simu_presence 
--]] 
---------------------------------------
local version = "3.6.1"; 
-- YAPS Presence Simulation by SebcBien
-- August 2015
-- modifications Hue de Pepite, merci!
----------------------

if (fibaro:countScenes() > 1) then
    fibaro:debug("Scene already active! Aborting this new instance !!");
    fibaro:abort();
end
--------------------- USER SETTINGS --------------------------------
local id = {
    LAMPE_SCHLAF        = 152,
    HUE_BUERO            = 549,
    LAMPE_FLUR_OBEN        = 150,
    LAMPE_WOZI            = 138,
    LAMPE_MOON_WOZI        = 140,
      HUE_ESSZI            = 555,
    LAMPE_FLUR_UNTEN    = 146,
    HUE_FLUR_UNTEN        = 534,
    LAMPE_FLUR_HINTEN    = 348,
      HUE_MILAN            = 535,
      LAMPE_KLEIN_ZI        = 12,
      LAMPE_LOUIS            = 448,
      LAMPE_KUECH_STECK    = 6,
      HUE_JEANNE            = 569,
    PHONE_MILAN            = 162,
    ADMIN                 = 2,
    PHONE_TT            = 158
    }

local Stop_hour = "01";                    -- Hour when you want Simulation to stop
local Stop_minute = "30";                -- 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 Random_max_TurnOff_duration)
-- 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_offset = -15                -- number of minutes before or after sunset to activate Simulation
local Random_max_duration = 30;            -- random time of light change in minutes --> here each device is on maximum 30min
local Random_max_TurnOff_duration = 25;    -- random time to add at the stop hour+stop minute so the Simulation can be more variable (0 to deactivate)
local Lights_always_on = {id["LAMPE_FLUR_OBEN"],id["LAMPE_FLUR_UNTEN"]} -- IDs of lights who will always stay on during Simulation - leave empty array if none -> {}
local Random_lights = {id["LAMPE_SCHLAF"],id["LAMPE_WOZI"],id["LAMPE_MOON_WOZI"],id["LAMPE_FLUR_HINTEN"],id["LAMPE_KLEIN_ZI"],id["LAMPE_LOUIS"],id["LAMPE_KUECH_STECK"]} -- IDs of lights to use in Simulation
-- test pepite --
local Random_Lights_Hue = {id["LAMPE_SCHLAF"],id["HUE_BUERO"],id["HUE_ESSZI"],id["HUE_FLUR_UNTEN"],id["HUE_MILAN"],id["HUE_JEANNE"]} --IDs of lights "HUE" to use in Simulation
-- fin test pepite --
--local Random_lights = {id["LAMPE_HALL"],id["LAMPE_CELLIER"],id["LAMPE_CH_AMIS"]} -- Reduced set for test purposes
local Lights_On_at_end_Simulation = 0;    -- If next line is commented, no light will turn on after Simulation ends
--local Lights_On_at_end_Simulation = 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 Lights_On_if_Simulation_deactivated = 0; -- If next line is commented, no light will turn on after Simulation is stopped (by putting Simu_presence to 0)
--local Lights_On_if_Simulation_deactivated = id["LAMPE_HALL"]; -- ID of a light (Only One) to turn on after Simulation is stopped (Simulation_). Comment this line to turn off this feature
YAPS_Engine = {};
    YAPS_Engine.notifications = true;                    -- send notifications
    YAPS_Engine.notificationTypes = {"push", "email"};    --notification types {"push", "email", "sms"} but they are overriden in the code
    YAPS_Engine.Activate_FreeSms = false;                -- activate push with Activate_FreeSms (Activate_Push must be true also)
    YAPS_Engine.smartphoneID = {id["PHONE_TT"]};        -- Smartphone Id to send push to. {id1, id2, id3}
    YAPS_Engine.userID = {id["ADMIN"]};                    -- User Id to send email to. {id1, id2, id3}
    YAPS_Engine.sms = {
        ["VD_ID"] = 0,                                    -- Virtual Device ID
        ["VD_Button"] = "1",                            -- Virtual Device Button
        ["VG_Name"] = "SMS"};                            -- Global Variable Name
--------------------- USER SETTINGS END ----------------------------
----------------------ADVANCED SETTINGS-----------------------------
local Show_standard_debug = true;    -- Debug displayed in white
local Show_extra_debug = true;       -- Debug displayed in orange
--------------------------------------------------------------------
-------------------- DO NOT CHANGE CODE BELOW ----------------------
--------------------------------------------------------------------

-- test pepite --
local Number_of_lights_hue = #Random_Lights_Hue -- number of lights hue
-- fin test pepite --
local Number_of_lights = #Random_lights;                        -- numbers of light devices listed above
local Simulation = fibaro:getGlobal("Simu_presence");            --value of the global value: Simulation is on or off
local Manual_overide = fibaro:getGlobal("overideSimuSunset");    -- if = 1 then the Simulation is forced
local Start_simulation_time = fibaro:getValue(1, "sunsetHour");    --Start Simulation when sunset
local End_simulation_time,Sunrise_unix_hour,Sunset_unix_hour,Converted_var,Midnight,End_simulation_time_with_random_max_TurnOff,Sleep_between_TurnOff;
local Is_first_launch = true;
local NotifLoop = 0;

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 ( Show_extra_debug ) then
        Debug( "orange", debugMessage);
    end
end

function StandardDebug(debugMessage)
    if ( Show_standard_debug ) 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 YAPS_Engine:notification(message, subject, param)
    local message = os.date("%H:%M", os.time()).." "..message or "<vide>";
    if YAPS_Engine.debug_messages then
        ExtraDebug("yellow", "Notification : "..message);
    end
        if Activate_FreeSms then
            fibaro:setGlobal("Activate_FreeSms", message)
            ExtraDebug("Message ("..message..") sent to Activate_FreeSms");
        end
    if param then
        for _, notif in ipairs(param) do
            if YAPS_Engine.debug_messages then
                ExtraDebug("grey", notif);
            end
            -- Envoi Push
            if notif == "push" and YAPS_Engine.smartphoneID then
                for _, id in ipairs(YAPS_Engine.smartphoneID) do
                    if YAPS_Engine.debug_messages then
                        ExtraDebug("grey", "Send Push smartphone ID : "..id);
                    end
                    fibaro:call(id, "sendPush", message);
                end
            -- Envoi Email
            elseif notif == "email" and YAPS_Engine.userID then
                for _, id in ipairs(YAPS_Engine.userID) do
                    if YAPS_Engine.debug_messages then
                        ExtraDebug("grey", "Send Email user ID : "..id);
                    end
                    fibaro:call(id, "sendEmail", subject, message);
                end
            -- Envoi SMS
            elseif notif == "sms" and YAPS_Engine.sms then
                if YAPS_Engine.debug_messages then
                    ExtraDebug("grey", "Send SMS : VD_ID="..(YAPS_Engine.sms["VD_ID"] or 0).." VD_Button="..(YAPS_Engine.sms["VD_Button"] or "0").." VG_Name="..(YAPS_Engine.sms["VG_Name"] or ""));
                end
                fibaro:setGlobal(YAPS_Engine.sms["VG_Name"], message);
                if YAPS_Engine.sms["VD_ID"] and tonumber(YAPS_Engine.sms["VD_ID"])>0 and YAPS_Engine.sms["VD_Button"] and tonumber(YAPS_Engine.sms["VD_Button"])>0 then
                    fibaro:call(YAPS_Engine.sms["VD_ID"], "pressButton", YAPS_Engine.sms["VD_Button"]);
                end
            end
        end
    else
        Debug("orange", "Warning : no notification options given");
    end
end

function YAPS_Engine:UnixTimeCalc(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 YAPS_Engine:ReverseUnixTimeCalc(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 YAPS_Engine:EndTimeCalc()
    local hour,min
    ExtraDebug ("Current Unix Time: "..os.time())
    End_simulation_time = YAPS_Engine:UnixTimeCalc("Original planed End_simulation_time", Stop_hour, Stop_minute); -- generate End_simulation_time (changes at midnight) will not change during Simulation, only when ended
    Midnight = YAPS_Engine:UnixTimeCalc("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 = (YAPS_Engine:UnixTimeCalc("Sunset", hour, min))+Sunset_offset*60;

    -- if stop hour is between 00 and 12h then add 24 hours to End_simulation_time
    if tonumber(Stop_hour) <= 12 and (os.time() >= End_simulation_time) then
        End_simulation_time = End_simulation_time + 24*60*60
        ExtraDebug ("stop hour <= 12, Added 24H to End_simulation_time (End_simulation_time is ending after midnignt)");
        ExtraDebug ("New End_simulation_time: "..End_simulation_time);
    end
    
    if Random_max_TurnOff_duration ~= 0 and Number_of_lights > 1 then   -- if Simulation = 1 then slow turn off, else turn off all immediately
        Sleep_between_TurnOff = round((math.random(Random_max_TurnOff_duration)/(Number_of_lights-1)),1);
        Sleep_between_TurnOff = math.random(Random_max_TurnOff_duration)/(Number_of_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
    End_simulation_time_with_random_max_TurnOff = End_simulation_time + ((Sleep_between_TurnOff*(Number_of_lights-1))*60)
    ExtraDebug("End_simulation_time_with_random_max_TurnOff: "..End_simulation_time_with_random_max_TurnOff);    
    
    if ((os.time() < End_simulation_time) and (Sunset_unix_hour - End_simulation_time > 0) and (Is_first_launch == true)) then -- if calculation is done between midnight and End_simulation_time and sunset is wrongly calculated after endtime (at first start only)
        Sunset_unix_hour = Sunset_unix_hour - (24*60*60) + 70; -- remove 24h58m50s of sunsettime
        ExtraDebug ("launch after Midnight and before End_simulation_time, removed 24H to Sunset_unix_hour (Only at the first start)");
        ExtraDebug ("New SunsetTime: "..Sunset_unix_hour);
    end
    Is_first_launch = false
end
-- Presence Simulation actions Main loop
function YAPS_Engine:Launch()
    YAPS_Engine:notification("Presence Simulation started. Will stop at: "..YAPS_Engine:ReverseUnixTimeCalc("End_simulation_time", End_simulation_time).." + rand("..Random_max_TurnOff_duration.."min) : "..YAPS_Engine:ReverseUnixTimeCalc("End_simulation_time_with_random_max_TurnOff", End_simulation_time_with_random_max_TurnOff), "Presence Simulator", {"push"}); -- push only
    StandardDebug("Presence Simulation started. Will stop at: "..YAPS_Engine:ReverseUnixTimeCalc("End_simulation_time", End_simulation_time).." + rand("..Random_max_TurnOff_duration.."min) : "..YAPS_Engine:ReverseUnixTimeCalc("End_simulation_time_with_random_max_TurnOff", End_simulation_time_with_random_max_TurnOff));    
    if Lights_always_on[1] ~= nil then YAPS_Engine:TurnOn(Lights_always_on); end

    while ((os.time() <= End_simulation_time) and (Simulation == "1")) or ((Manual_overide == "1")) do
        local random_light = tonumber(Random_lights[math.random(Number_of_lights)]) --choose a random light in the list
        -- test pepite --
        local random_light_hue = tonumber(Random_Lights_Hue[math.random(Number_of_lights_hue)]) --choose a random light hue in the list
        local lightstatushue = fibaro:getValue(random_light_hue, 'on') --get the value of the random light HUE in the list
        -- fin test pepite --
        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
        --- test pepite --
        if tonumber(lightstatushue) == 0 then
            fibaro:call(random_light_hue, "changeBrightness", 255)
            fibaro:call(random_light_hue, "changeHue", 7680)
            fibaro:call(random_light_hue, "changeSaturation", 210)
            fibaro:call(random_light_hue, 'turnOn')
        else
            fibaro:call(random_light_hue, 'turnOff')
        end
        -- fin test pepite --
        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
        -- test pepite --
        lightstatushue = fibaro:getValue(random_light_hue, 'on') --get the value of the random light HUE after his update
        StandardDebug('light HUE ID:'.. fibaro:getName(random_light_hue) ..' status:'..lightstatushue);
        -- fin test
        StandardDebug('light ID:'.. fibaro:getName(random_light) ..' status:'..lightstatus);
        local sleeptime = math.random(Random_max_duration*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 counterexitSimulation = 200
                while (counterexitSimulation > 0) and ((os.time() <= End_simulation_time) or Manual_overide == "1") do
                    counterexitSimulation = counterexitSimulation - 1;
                    test_presence_state = fibaro:getGlobal("Simu_presence");
                    Simulation = tonumber(test_presence_state); --verify the global value, if the virtual device is deactivated, the loop stops.
                    --fibaro:debug("Simulation var state : " .. Simulation.." override var state : " .. Manual_overide);
                    if Simulation == 0 then
                        Manual_overide = fibaro:getGlobalValue("overideSimuSunset");
                        if Simulation == 0 or Manual_overide == "0" then
                        counterexitSimulation = 0
                        end
                    end
                fibaro:sleep(sleeptime/200);
                end
            ExtraDebug("Exiting loop of "..round(sleeptime/60000,2).." minutes");
        local sleeptimemin = math.abs(sleeptime/60000)
        Simulation = fibaro:getGlobal("Simu_presence"); --verify the global value, if the virtual device is deactivated, the scene stops.
        Manual_overide = fibaro:getGlobalValue("overideSimuSunset");
    end
end
    
function YAPS_Engine:EndSimulation()
    if Lights_always_on[1] ~= nil then YAPS_Engine:TurnOff(Random_lights,Lights_always_on); end
    -- test pepite
    for i= 1, Number_of_lights_hue do
        if tonumber(lightstatushue) > 0 then
            fibaro:call(Random_Lights_Hue, "turnOff")
      
        end
    end
    -- fin test pepite --
    Debug("red","Presence Simulation deactivated");
    if (Simulation == "1") then
        Debug("yellow","Presence Simulation will restart tomorrow.");
        Debug("yellow","Sunset is around "..fibaro:getValue(1, "sunsetHour").." + Sunset Shift of "..Sunset_offset.."min = Start Time around "..YAPS_Engine:ReverseUnixTimeCalc("Sunset unix time", Sunset_unix_hour));
        YAPS_Engine:notification("Presence Simulation will restart tomorrow. Sunset is around "..fibaro:getValue(1, "sunsetHour").." + Sunset Shift of "..Sunset_offset.."min = Start Time around "..YAPS_Engine:ReverseUnixTimeCalc("Sunset unix time", Sunset_unix_hour), "Presence Simulator", {"push"}); -- push only
    end
    NotifLoop = 0; -- will force main loop notifications at end of Simulation
end

function YAPS_Engine:ExitSimulation()
    --YAPS_Engine:notification("Presence Simulation is terminated", "Presence Simulator", {"push"}); -- push only
    Debug("red","Simu_presence = 0, Aborting Simulation scene");
    fibaro:abort();
end

function YAPS_Engine:TurnOff(group,group2)
    Debug("red","TurnOff All Simulation lights!");
    local name, id2;
    local ID_devices_group = group;
    if ID_devices_group ~= 0 then
        for i=1, #ID_devices_group do
            Simulation = fibaro:getGlobal("Simu_presence"); --verify the global value, if Simulation presence is deactivated
            if Simulation == "0" then    Sleep_between_TurnOff = 0; end; -- if Simulation ended before End_simulation_time, 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);
            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
    end
    Debug("red","TurnOff All Always_On lights!");
    local ID_devices_group = group2;
    if ID_devices_group ~= 0 then
        for i=1, #ID_devices_group do
            id2 = tonumber(ID_devices_group);
            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
    end
    if Lights_On_at_end_Simulation ~= 0 and Simulation == "1" then
        fibaro:call(Lights_On_at_end_Simulation, "turnOn");
        name = fibaro:getName(Lights_On_at_end_Simulation);
            if (name == nil or name == string.char(0)) then
                name = "Unknown"     
            end
        Debug("red","Turned On light Lights_On_at_end_Simulation:");
        Debug("white", name);
    end
    if Lights_On_if_Simulation_deactivated ~= 0 and Simulation == "0" then
        fibaro:call(Lights_On_if_Simulation_deactivated, "turnOn");
        name = fibaro:getName(Lights_On_if_Simulation_deactivated);
            if (name == nil or name == string.char(0)) then
                name = "Unknown"
            end
        Debug("red","Turned On light Lights_On_if_Simulation_deactivated:");
        Debug("white", name);
    end
end

function YAPS_Engine: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);
        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 Simulation | v" .. version .. " Starting up");
Debug("green", "--------------------------------------------------------------------------");

------------------------ Main Loop ----------------------------------
-- first start notifications
YAPS_Engine:EndTimeCalc();
YAPS_Engine:notification("Scheduled presence Simulation at "..YAPS_Engine:ReverseUnixTimeCalc("Sunset unix time", Sunset_unix_hour).." (Sunset: "..fibaro:getValue(1, "sunsetHour")..")", "Presence Simulator", {"email"}); -- mail only
Debug("green","Sunset is at "..fibaro:getValue(1, "sunsetHour").." + Sunset Shift of "..Sunset_offset.."min = Start Time at "..YAPS_Engine:ReverseUnixTimeCalc("Sunset unix time", Sunset_unix_hour));
Debug("green","End of Simulation: "..YAPS_Engine:ReverseUnixTimeCalc("End Simulation", End_simulation_time).." + random of "..Random_max_TurnOff_duration.."min");
Debug("green", "Checking for actions every minute.");
Is_first_launch = true

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

    if os.time() >= Sunset_unix_hour then -- define if nighttime (sunset = 1)
        sunset = 1
    else
        sunset = 0
    end
    
    if (Simulation == "1") then
        if sunset == 1 and (os.time() <= End_simulation_time) then
            Debug("yellow", "It's sunset time -> Simulation ON");
            YAPS_Engine:Launch();
            YAPS_Engine:EndSimulation();
        end
        if Manual_overide == "1" then
            Debug("yellow", "Manual Override Activated -> Simulation ON");
            YAPS_Engine:Launch();
            YAPS_Engine:EndSimulation();
        end
        if Manual_overide == "0" and sunset == 0 and NotifLoop == 0 then
            Debug("yellow", "Sunset is at "..fibaro:getValue(1, "sunsetHour").." + Sunset Shift of "..Sunset_offset.."min = Start Time at "..YAPS_Engine:ReverseUnixTimeCalc("Sunset unix time", Sunset_unix_hour));
            Debug("yellow", "End of Simulation: "..YAPS_Engine:ReverseUnixTimeCalc("End Simulation", End_simulation_time).." + random of "..Random_max_TurnOff_duration.."min = "..YAPS_Engine:ReverseUnixTimeCalc("End Simulation", End_simulation_time_with_random_max_TurnOff));
        end
    end

    if (Simulation == "0") then -- Condition to end Simulation
        YAPS_Engine: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
    Simulation = fibaro:getGlobal("Simu_presence");
    Manual_overide = fibaro:getGlobal("overideSimuSunset");
    NotifLoop = NotifLoop + 1;
end

  • Upvote 2
Lien vers le commentaire
Partager sur d’autres sites

  • 3 mois après...

@Thilo

Merci à @pepite et à toi pour cette modification de script intégrant les hue...

 

Cependant, chez moi, j'ai un souci à la fin du script à la ligne 245 : attempt to compare number with nil

C'est , a priori à l'extinction des hue que ça déconne..

 La ligne 245 :
        if tonumber(lightstatushue) > 0 then

Peut être un problème de syntaxe??.. j'ai vu qu'il y avait des majuscules à Lights et des fois non dans le script intéressant les hue...

Est ce que ça fonctionne correctement chez toi?

Lien vers le commentaire
Partager sur d’autres sites

  • 1 mois après...

Bonjour,

j ´ai eu le meme problème et je l´ai resolu de facon un peu parresseux: 

 

juste rajouté une ligne avant l´erreur, donc au 234: 

if tonumber(lightstatushue) == 0 then

pour etre sur que c´est pas "nil"...

 

Ce sera surement plus élégant de chercher dans le script plus haut pour éviter ou definir lightstatushue en tete du script....

 

Lien vers le commentaire
Partager sur d’autres sites

@Thilo ,

 

suis content d'avoir de tes nouvelles pour ce script...

Suis en vacances et je viens de voir ta réponse...

 

J'ai regardé mon script et c'est le même que le tien...

Bizarre..

 

Tu parles bien des lignes : 

 

 if tonumber(lightstatushue) == 0 then
            fibaro:call(random_light_hue, "changeBrightness", 255)
            fibaro:call(random_light_hue, "changeHue", 7680)
            fibaro:call(random_light_hue, "changeSaturation", 210)
            fibaro:call(random_light_hue, 'turnOn')
        else
            fibaro:call(random_light_hue, 'turnOff')
        end

 

Si je comprends bien ça veut dire que c'est aucune Hue n'est allumée, il en allume une et sinon il l'éteint donc on repasse à 0 et là ça déconne ? 

En même temps, je suis un novice en lua...

 

D'autre part, aucune lampe même autre que Hue ne s'éteint à la fin du cycle... J'ai une notification comme quoi c'est fini et qu'il restart le lendemain.. Qu'est ce que j'ai raté?

Lien vers le commentaire
Partager sur d’autres sites

  • 3 semaines après...

bon ben quelques nouvelles quand même...

J'ai pris le code sans intégrer les phillips hue et ça fonctionne correctement... 

 

Et finalement, ça me convient parfaitement comme ça...

Ce genre de fonction est pour moi l'essence de la domotique... ça fonctionne tout seul en autonome sans interaction...

Au top...

Merci au créateur de ce code...:60:

  • Upvote 2
Lien vers le commentaire
Partager sur d’autres sites

  • 3 mois après...
  • 1 mois après...

Salut!
Merci pour cet excellent code LUA!
Je me demandais s'il y avait un moyen de définir une valeur sur un gradateur dans:

local Lights_always_on = {id["XXX"],id["YYY"]} 
local Random_lights = {id["ZZZ"]}


Et s'il est possible de randomiser l'heure de départ de la même manière que dans

local Random_max_TurnOff_duration

Merci d'avance!
Mike

 

Traduit avec Google Translate

 

Lien vers le commentaire
Partager sur d’autres sites

Bonjour, oui il y a certainement moyen.
Pour le moment je suis occupé à tout autre chose que la domotique et je n'ai pas trop envie de me replonger dans le code.
Si vous faites des modifications qui fonctionnent, je peux rajouter ce code à github.
Désolé,
Seb

Envoyé avec mon pouce via Tapatalk

Lien vers le commentaire
Partager sur d’autres sites

en fait, le simulateur n'allume "que" des lampes. Alors si ton téléviseur LED est commandé par un WP (ou un FGS), oui tu rajoutes juste l'ID du WP (ou du FGS) (le téléviseur sera considéré comme une lampe derrière le WP ou le FGS)

  • Like 1
Lien vers le commentaire
Partager sur d’autres sites

  • 10 mois après...
×
×
  • Créer...