Jump to content

Welcome to Smart Home Forum by FIBARO

Dear Guest,

 

as you can notice parts of Smart Home Forum by FIBARO is not available for you. You have to register in order to view all content and post in our community. Don't worry! Registration is a simple free process that requires minimal information for you to sign up. Become a part of of Smart Home Forum by FIBARO by creating an account.

 

As a member you can:

  •     Start new topics and reply to others
  •     Follow topics and users to get email updates
  •     Get your own profile page and make new friends
  •     Send personal messages
  •     ... and learn a lot about our system!

 

Regards,

Smart Home Forum by FIBARO Team


  • 0

LUA code for Switch to toggle variable 0<>1


Question

Posted

I'm looking for a way (LUA code?) for a switch to change the state of a variable from 0 to 1 or from 1 to 0  with every press on the switch (independent of current state of the switch). 

 

Can anyone help me with a piece of LUA code?

18 answers to this question

Recommended Posts

  • 0
Posted

The topic has been moved from "

Please login or register to see this link.

" to "

Please login or register to see this link.

".

 

Temat został przeniesiony z "

Please login or register to see this link.

" do "

Please login or register to see this link.

".

  • 0
Posted

try this

 

Please login or register to see this code.

 

where ID is switch ID.

 

irrespective of the switch position everytime the switch is pressed the variable will toggle.

 

thanks 

 

 

 

  • 0
  • Inquirer
  • Posted

    Thanks for the reply, I tried this but ....

     

    Any idea why I get :  [DEBUG] 19:22:29: line 14: ')' expected near '='

    • 0
    Posted

    Sorry my bad supposed to be ==

    If (variable == '0') 

    Please amend both conditions with 2 == signs

    Apologies

    • 0
    Posted

    I need to do something similar, can anyone help me out?

     

    if variable "x" changes from 0 to 1 then set variable "y" to +1

    if variable "x" changes from 1 to 0 then set variable "y" to -1

     

    *notice I do not want to set variable y to 1 but plus/minus 1

    I got it never mind thanks

    • 0
    Posted
    23 minutes ago, amatt said:

    I need to do something similar, can anyone help me out?

     

    if variable "x" changes from 0 to 1 then set variable "y" to +1

    if variable "x" changes from 1 to 0 then set variable "y" to -1

     

    *notice I do not want to set variable y to 1 but plus/minus 1

     

    like this:

     

    if fibaro:getGlobalValue("wifiRob") == "0" 
    then
        fibaro:setGlobal("OccupancyCount", tonumber(fibaro:getGlobalValue("OccupancyCount")) - 1);
    end

    • Like 1
    • 0
    Posted

    Robert,

     

    I got it to somewhat work. but here is my problem. I have a VD setup to check if user is present every 15 minutes. everytime that runs (or the scene runs) it keeps adding or subtracting the "y" value. so for example if the user x is not present (0) then it will subtract 1 every 15 minutes. 

     

    how do I prevent it from subtracting or adding 1?

    • 0
    Posted
    6 hours ago, amatt said:

    Robert,

     

    I got it to somewhat work. but here is my problem. I have a VD setup to check if user is present every 15 minutes. everytime that runs (or the scene runs) it keeps adding or subtracting the "y" value. so for example if the user x is not present (0) then it will subtract 1 every 15 minutes. 

     

    how do I prevent it from subtracting or adding 1?

     

    In my case I have multiple variables for my family members, I have a button programmed on a VD for each family member with the MAC address of their phone, the code behind each button then checks my routers wireless client table to see if that MAC address is present in the table, if it finds it sets the variable for that use (wifiRob) to 1 if it doesn't find it it sets the variable to 0.

     

    I then have a seperate variable (occupancyCount) that serves as a counter for the amount of people home, Then I have a scene that runs that looks at the individual variables, the logic in the scene looks like this: IF wifiRob = 1 THEN occupancyCount +1 else IF wifiRob = 0 THEN occupancyCount - and so on... this means at any time my house knows exactly which family members are home and the total count.

     

    This method works for me however like all network based approaches its not perfect as on occasion your phone may run flat or it gets either left at home while your out or it gets left somewhere else and your home :-)

     

     

     

    • 0
    Posted

    Rob,

     

    I have the exact same setup as you :)  but I still experience this issue. I think it is this way because when the VD checks to see if  certain guests ( VD setup for each of them) are present and say 1 of them are already present then the scene says "hey they are present" so the scene triggers to add one to the "occupancycount") and the occupancy count goes to 2,3,4,5,6..... everytime that scene runs and it finds that the guest is present. 

    • 0
    Posted
    7 hours ago, amatt said:

    Rob,

     

    I have the exact same setup as you :)  but I still experience this issue. I think it is this way because when the VD checks to see if  certain guests ( VD setup for each of them) are present and say 1 of them are already present then the scene says "hey they are present" so the scene triggers to add one to the "occupancycount") and the occupancy count goes to 2,3,4,5,6..... everytime that scene runs and it finds that the guest is present. 

     If you post your code I’m happy to take a look for you 

    • 0
    Posted
    16 hours ago, Robert Folbigg said:

     If you post your code I’m happy to take a look for you 

    Rob,

     

    Here is my guest scene.

     

    --[[
    %% properties
    %% weather
    %% events
    %% globals
    Andy_Present
    --]]

    local startSource = fibaro:getSourceTrigger();
    if (
     ( tonumber(fibaro:getGlobalValue("Dad_Present")) == tonumber("1") )
    )
    then
        fibaro:setGlobal("Guests", tonumber(fibaro:getGlobalValue("Guests")) + 1);
      fibaro:debug("Guest +1");
      
      else
      
      if (
     ( tonumber(fibaro:getGlobalValue("Dad_Present")) == tonumber("0") )
          )
          then
        fibaro:setGlobal("Guests", tonumber(fibaro:getGlobalValue("Guests")) - 1);
    end
      end

    if (
     ( tonumber(fibaro:getGlobalValue("Mom_Present")) == tonumber("1") )
    )
        
       
    then
        fibaro:setGlobal("Guests", tonumber(fibaro:getGlobalValue("Guests")) + 1);
        fibaro:debug("Guest +1");
      else
      
      if (
     ( tonumber(fibaro:getGlobalValue("Mom_Present")) == tonumber("0") )
          )
          then
        fibaro:setGlobal("Guests", tonumber(fibaro:getGlobalValue("Guests")) - 1);
    end
        end

    if (
     ( tonumber(fibaro:getGlobalValue("Jacob_Present")) == tonumber("1") )
    )
    then
        fibaro:setGlobal("Guests", tonumber(fibaro:getGlobalValue("Guests")) + 1);
       fibaro:debug("Guest +1");
      
      else
      
      if (
     ( tonumber(fibaro:getGlobalValue("Jacob_Present")) == tonumber("0") )
          )
          then
        fibaro:setGlobal("Guests", tonumber(fibaro:getGlobalValue("Guests")) - 1);
    end
    end

     

     

     

    Here is the Code for one of my presence VDs

     

     

     

    -- IP Smartphone Presence Check V1.2 - check with ping on port sonos
    -- IP Smartphone Presence Check V2.0 - sonos not reliable anymore, using arp table
    -- IP Smartphone Presence Check V2.1 - removed Lock_Away
    -- Copyright © 2015 Sébastien Jauquet.
    --

    Please login or register to see this link.


    --Using code from:
    -- Ping v 1.0.1 [05-2013] Copyright © 2013 Jean-christophe Vermandé
    --

    Please login or register to see this link.


    -- mac adress check: Roman
    --

    Please login or register to see this link.

    -- local variable_globale_phone = "Phone_XXX_Present";
    -- local current_icon_absent = 1035 -- homme
    -- local current_icon_present = 1034 -- homme
    local variable_globale_phone = "Dad_Present";
    local current_icon_absent = 1002 -- femme
    local current_icon_present = 1001 -- femme

    local maxRetry_Process = 20;
    local scheduler_value = 30; -- (minutes) scheduled time of this process (must match the mainloop scheduled time)
    local check_wait = 5; -- (seconds) to wait between each poll device
    local debug = true
    -- local login = "admin";
    -- local pass = "not needed with port 11111";

    local selfId=fibaro:getSelfId();
    local time = tonumber(os.time());
    local maxtime = (scheduler_value*60) - (check_wait+1);
    local mac = fibaro:get(selfId, 'IPAddress');
    local HC2 = Net.FHttp("127.0.0.1", 11111);
    -- HC2:setBasicAuthentication(login, pass);

    function Debug(color, message)
    if debug then 
        if color and color ~= "" then
            fibaro:debug('<span style="color:'..color..';">'..message..'</span>');
        else
            fibaro:debug(message);
        end
    end
    end

    function SecondsToClock(sSeconds)
      local nSeconds = tonumber(sSeconds)
      if nSeconds == 0 then
        return "00:00:00";
      else
        nHours = string.format("%02.f", math.floor(nSeconds/3600));
        nMins = string.format("%02.f", math.floor(nSeconds/60 - (nHours*60)));
        nSecs = string.format("%02.f", math.floor(nSeconds - nHours*3600 - nMins *60));
        return nHours..":"..nMins..":"..nSecs
      end
    end

    local function _ping(retry)
    retry = retry or 0;

    -- notify state
      local elapsed = os.difftime(os.time(), tonumber(time));
      local msg = "Loop #".. retry .." since "..SecondsToClock(elapsed);
      fibaro:log(msg);  

      if elapsed > maxtime then
      return false; 
      end

    --open the socket
      local tcpSocket = Net.FTcpSocket(_deviceIp, _devicePort);
        fibaro:debug(_deviceIp .. " " .. _devicePort)
      --set the read timeout
      tcpSocket:setReadTimeout(250);
      --send packet
      local bytes, errorCode = tcpSocket:write("test");
      fibaro:debug(errorCode)
     
      --check for error      
      if errorCode == 0 then
        return true;
      else
        if retry < maxRetry_Process then
        --fibaro:log("Retry process, please wait...");
        fibaro:sleep(1*750);
        return _ping(retry + 1);
        end
        return false;
      end
    end

    local function FindMac(retry)
    retry = retry or 0;
    local foundUser = false;
    -- notify state
        local elapsed = os.difftime(os.time(), tonumber(time));
        local msg = "Loop #".. retry .." since "..SecondsToClock(elapsed);

    -- check for no more than maxtime seconds
      if elapsed > maxtime then
        return false; 
      end

        fibaro:log(msg);  
        Debug("yellow",msg)

        local response, status, errorCode = HC2.POST(HC2, "/api/networkDiscovery/arp", "{}");
        local jsonTable = json.decode(response) 
        --fibaro:debug("errorcode:"..errorCode.."status: "..status)
        if (tonumber(errorCode)==0 and tonumber(status)==200) then  
          for i, name in ipairs(jsonTable) do
            if foundUser == false then
            --Debug("grey",i.." found mac:"..name['mac'])
              if(name['mac'] == mac) then
                foundUser = true;
                Debug("green","Device "..name['mac'].." Has been found after "..elapsed.." s");
              end
            end
        end
        else Debug("red","error json decode")
        end

      --check for error
      if foundUser == true then
        return true;
      else
        if retry < maxRetry_Process then
            --fibaro:log("Retry process, please wait...");
            fibaro:sleep(check_wait*1000);
            return FindMac(retry + 1);
        end
      return false;
      end
    end

    fibaro:log("Starting process");
    Debug("yellow","Searching for Mac Address: "..mac)
    --ping device, secure with pcall to catch errors.
    --local f, result = pcall(_ping);
    local f, result = pcall(FindMac);


    if (f) then
      if (result == true) then
        fibaro:log("Device has been found.");
        fibaro:setGlobal(variable_globale_phone,"1")
        Debug("green","Global Var: "..variable_globale_phone.." Set to 1");
        fibaro:call(selfId, "setProperty", "currentIcon", current_icon_present)
        -- évolution future possible: stocker la date et l'heure de la dernière présence détectée
        -- fibaro:setGlobal("Present_Phones",os.time()) 
      else
        fibaro:log("Device was not found!");
        fibaro:setGlobal(variable_globale_phone,"0")
        Debug("red","Device "..mac.." Has been NOT been found");
        Debug("red","Global Var: "..variable_globale_phone.." Set to 0");
        fibaro:call(selfId, "setProperty", "currentIcon", current_icon_absent)
      end
    else
      fibaro:log("Error: " .. tostring(f));
    end

     

     

     

     

     

    MAIN LOOP:

     

     

     

    local selfId = fibaro:getSelfId();
    -- local current_icon_absent = 1035 -- homme
    -- local current_icon_present = 1034 -- homme
    local current_icon_absent = 1037 -- femme
    local current_icon_present = 1036 -- femme
    --local Verification = fibaro:get(selfId,"TCPPort");

    -- 1ère fois que le main loop s'exécute, on crée une variable nommée "instance" car elle n'existe pas. Elle existera au 2ème passage donc ne sera pas recrée.
    if (not instance) then
        -- on indique la fréquence d'execution souhaitée (en minutes)
        instance = { lastrun = 0, every = 30 }
        fibaro:debug("first run")
    end
     
    -- on vérifie la différence entre cette exéction et la dernière (stocké dans instance.lastrun)
    diff = os.date("*t", os.difftime(os.time(), instance.lastrun))
     
    -- si la différence en minutes et supérieure ou égale à la fréquence souhaitée (instance.every)
    if (diff.min >= instance.every) then
       -- TON CODE ---
              fibaro:call(selfId, "pressButton", "1")
              --[[local status = fibaro:getGlobal("Phone_GG_Present")

            if status == "0" then 
                fibaro:call(selfId, "setProperty", "currentIcon", current_icon_absent)
            end

            if status == "1" then 
                fibaro:call(selfId, "setProperty", "currentIcon", current_icon_present)
            end--]]
       -- FIN DE TON CODE ---
       -- on stock l'heure de la nouvelle exécution
       instance.lastrun = os.time()
       fibaro:debug("executed")
    end

    • 0
    Posted
    19 minutes ago, amatt said:

    Rob,

     

    Here is my guest scene.

     

    --[[
    %% properties
    %% weather
    %% events
    %% globals
    Andy_Present
    --]]

    local startSource = fibaro:getSourceTrigger();
    if (
     ( tonumber(fibaro:getGlobalValue("Dad_Present")) == tonumber("1") )
    )
    then
        fibaro:setGlobal("Guests", tonumber(fibaro:getGlobalValue("Guests")) + 1);
      fibaro:debug("Guest +1");
      
      else
      
      if (
     ( tonumber(fibaro:getGlobalValue("Dad_Present")) == tonumber("0") )
          )
          then
        fibaro:setGlobal("Guests", tonumber(fibaro:getGlobalValue("Guests")) - 1);
    end
      end

    if (
     ( tonumber(fibaro:getGlobalValue("Mom_Present")) == tonumber("1") )
    )
        
       
    then
        fibaro:setGlobal("Guests", tonumber(fibaro:getGlobalValue("Guests")) + 1);
        fibaro:debug("Guest +1");
      else
      
      if (
     ( tonumber(fibaro:getGlobalValue("Mom_Present")) == tonumber("0") )
          )
          then
        fibaro:setGlobal("Guests", tonumber(fibaro:getGlobalValue("Guests")) - 1);
    end
        end

    if (
     ( tonumber(fibaro:getGlobalValue("Jacob_Present")) == tonumber("1") )
    )
    then
        fibaro:setGlobal("Guests", tonumber(fibaro:getGlobalValue("Guests")) + 1);
       fibaro:debug("Guest +1");
      
      else
      
      if (
     ( tonumber(fibaro:getGlobalValue("Jacob_Present")) == tonumber("0") )
          )
          then
        fibaro:setGlobal("Guests", tonumber(fibaro:getGlobalValue("Guests")) - 1);
    end
    end

     

     

     

    Here is the Code for one of my presence VDs

     

     

     

    -- IP Smartphone Presence Check V1.2 - check with ping on port sonos
    -- IP Smartphone Presence Check V2.0 - sonos not reliable anymore, using arp table
    -- IP Smartphone Presence Check V2.1 - removed Lock_Away
    -- Copyright © 2015 Sébastien Jauquet.
    --

    Please login or register to see this link.


    --Using code from:
    -- Ping v 1.0.1 [05-2013] Copyright © 2013 Jean-christophe Vermandé
    --

    Please login or register to see this link.


    -- mac adress check: Roman
    --

    Please login or register to see this link.

    -- local variable_globale_phone = "Phone_XXX_Present";
    -- local current_icon_absent = 1035 -- homme
    -- local current_icon_present = 1034 -- homme
    local variable_globale_phone = "Dad_Present";
    local current_icon_absent = 1002 -- femme
    local current_icon_present = 1001 -- femme

    local maxRetry_Process = 20;
    local scheduler_value = 30; -- (minutes) scheduled time of this process (must match the mainloop scheduled time)
    local check_wait = 5; -- (seconds) to wait between each poll device
    local debug = true
    -- local login = "admin";
    -- local pass = "not needed with port 11111";

    local selfId=fibaro:getSelfId();
    local time = tonumber(os.time());
    local maxtime = (scheduler_value*60) - (check_wait+1);
    local mac = fibaro:get(selfId, 'IPAddress');
    local HC2 = Net.FHttp("127.0.0.1", 11111);
    -- HC2:setBasicAuthentication(login, pass);

    function Debug(color, message)
    if debug then 
        if color and color ~= "" then
            fibaro:debug('<span style="color:'..color..';">'..message..'</span>');
        else
            fibaro:debug(message);
        end
    end
    end

    function SecondsToClock(sSeconds)
      local nSeconds = tonumber(sSeconds)
      if nSeconds == 0 then
        return "00:00:00";
      else
        nHours = string.format("%02.f", math.floor(nSeconds/3600));
        nMins = string.format("%02.f", math.floor(nSeconds/60 - (nHours*60)));
        nSecs = string.format("%02.f", math.floor(nSeconds - nHours*3600 - nMins *60));
        return nHours..":"..nMins..":"..nSecs
      end
    end

    local function _ping(retry)
    retry = retry or 0;

    -- notify state
      local elapsed = os.difftime(os.time(), tonumber(time));
      local msg = "Loop #".. retry .." since "..SecondsToClock(elapsed);
      fibaro:log(msg);  

      if elapsed > maxtime then
      return false; 
      end

    --open the socket
      local tcpSocket = Net.FTcpSocket(_deviceIp, _devicePort);
        fibaro:debug(_deviceIp .. " " .. _devicePort)
      --set the read timeout
      tcpSocket:setReadTimeout(250);
      --send packet
      local bytes, errorCode = tcpSocket:write("test");
      fibaro:debug(errorCode)
     
      --check for error      
      if errorCode == 0 then
        return true;
      else
        if retry < maxRetry_Process then
        --fibaro:log("Retry process, please wait...");
        fibaro:sleep(1*750);
        return _ping(retry + 1);
        end
        return false;
      end
    end

    local function FindMac(retry)
    retry = retry or 0;
    local foundUser = false;
    -- notify state
        local elapsed = os.difftime(os.time(), tonumber(time));
        local msg = "Loop #".. retry .." since "..SecondsToClock(elapsed);

    -- check for no more than maxtime seconds
      if elapsed > maxtime then
        return false; 
      end

        fibaro:log(msg);  
        Debug("yellow",msg)

        local response, status, errorCode = HC2.POST(HC2, "/api/networkDiscovery/arp", "{}");
        local jsonTable = json.decode(response) 
        --fibaro:debug("errorcode:"..errorCode.."status: "..status)
        if (tonumber(errorCode)==0 and tonumber(status)==200) then  
          for i, name in ipairs(jsonTable) do
            if foundUser == false then
            --Debug("grey",i.." found mac:"..name['mac'])
              if(name['mac'] == mac) then
                foundUser = true;
                Debug("green","Device "..name['mac'].." Has been found after "..elapsed.." s");
              end
            end
        end
        else Debug("red","error json decode")
        end

      --check for error
      if foundUser == true then
        return true;
      else
        if retry < maxRetry_Process then
            --fibaro:log("Retry process, please wait...");
            fibaro:sleep(check_wait*1000);
            return FindMac(retry + 1);
        end
      return false;
      end
    end

    fibaro:log("Starting process");
    Debug("yellow","Searching for Mac Address: "..mac)
    --ping device, secure with pcall to catch errors.
    --local f, result = pcall(_ping);
    local f, result = pcall(FindMac);


    if (f) then
      if (result == true) then
        fibaro:log("Device has been found.");
        fibaro:setGlobal(variable_globale_phone,"1")
        Debug("green","Global Var: "..variable_globale_phone.." Set to 1");
        fibaro:call(selfId, "setProperty", "currentIcon", current_icon_present)
        -- évolution future possible: stocker la date et l'heure de la dernière présence détectée
        -- fibaro:setGlobal("Present_Phones",os.time()) 
      else
        fibaro:log("Device was not found!");
        fibaro:setGlobal(variable_globale_phone,"0")
        Debug("red","Device "..mac.." Has been NOT been found");
        Debug("red","Global Var: "..variable_globale_phone.." Set to 0");
        fibaro:call(selfId, "setProperty", "currentIcon", current_icon_absent)
      end
    else
      fibaro:log("Error: " .. tostring(f));
    end

     

     

     

     

     

    MAIN LOOP:

     

     

     

    local selfId = fibaro:getSelfId();
    -- local current_icon_absent = 1035 -- homme
    -- local current_icon_present = 1034 -- homme
    local current_icon_absent = 1037 -- femme
    local current_icon_present = 1036 -- femme
    --local Verification = fibaro:get(selfId,"TCPPort");

    -- 1ère fois que le main loop s'exécute, on crée une variable nommée "instance" car elle n'existe pas. Elle existera au 2ème passage donc ne sera pas recrée.
    if (not instance) then
        -- on indique la fréquence d'execution souhaitée (en minutes)
        instance = { lastrun = 0, every = 30 }
        fibaro:debug("first run")
    end
     
    -- on vérifie la différence entre cette exéction et la dernière (stocké dans instance.lastrun)
    diff = os.date("*t", os.difftime(os.time(), instance.lastrun))
     
    -- si la différence en minutes et supérieure ou égale à la fréquence souhaitée (instance.every)
    if (diff.min >= instance.every) then
       -- TON CODE ---
              fibaro:call(selfId, "pressButton", "1")
              --[[local status = fibaro:getGlobal("Phone_GG_Present")

            if status == "0" then 
                fibaro:call(selfId, "setProperty", "currentIcon", current_icon_absent)
            end

            if status == "1" then 
                fibaro:call(selfId, "setProperty", "currentIcon", current_icon_present)
            end--]]
       -- FIN DE TON CODE ---
       -- on stock l'heure de la nouvelle exécution
       instance.lastrun = os.time()
       fibaro:debug("executed")
    end

     

    can you post a screen shot of the VD debug window as well please? im trying to get my head around this code

    21 minutes ago, amatt said:

    Rob,

     

    Here is my guest scene.

     

    --[[
    %% properties
    %% weather
    %% events
    %% globals
    Andy_Present
    --]]

    local startSource = fibaro:getSourceTrigger();
    if (
     ( tonumber(fibaro:getGlobalValue("Dad_Present")) == tonumber("1") )
    )
    then
        fibaro:setGlobal("Guests", tonumber(fibaro:getGlobalValue("Guests")) + 1);
      fibaro:debug("Guest +1");
      
      else
      
      if (
     ( tonumber(fibaro:getGlobalValue("Dad_Present")) == tonumber("0") )
          )
          then
        fibaro:setGlobal("Guests", tonumber(fibaro:getGlobalValue("Guests")) - 1);
    end
      end

    if (
     ( tonumber(fibaro:getGlobalValue("Mom_Present")) == tonumber("1") )
    )
        
       
    then
        fibaro:setGlobal("Guests", tonumber(fibaro:getGlobalValue("Guests")) + 1);
        fibaro:debug("Guest +1");
      else
      
      if (
     ( tonumber(fibaro:getGlobalValue("Mom_Present")) == tonumber("0") )
          )
          then
        fibaro:setGlobal("Guests", tonumber(fibaro:getGlobalValue("Guests")) - 1);
    end
        end

    if (
     ( tonumber(fibaro:getGlobalValue("Jacob_Present")) == tonumber("1") )
    )
    then
        fibaro:setGlobal("Guests", tonumber(fibaro:getGlobalValue("Guests")) + 1);
       fibaro:debug("Guest +1");
      
      else
      
      if (
     ( tonumber(fibaro:getGlobalValue("Jacob_Present")) == tonumber("0") )
          )
          then
        fibaro:setGlobal("Guests", tonumber(fibaro:getGlobalValue("Guests")) - 1);
    end
    end

     

     

     

    Here is the Code for one of my presence VDs

     

     

     

    -- IP Smartphone Presence Check V1.2 - check with ping on port sonos
    -- IP Smartphone Presence Check V2.0 - sonos not reliable anymore, using arp table
    -- IP Smartphone Presence Check V2.1 - removed Lock_Away
    -- Copyright © 2015 Sébastien Jauquet.
    --

    Please login or register to see this link.


    --Using code from:
    -- Ping v 1.0.1 [05-2013] Copyright © 2013 Jean-christophe Vermandé
    --

    Please login or register to see this link.


    -- mac adress check: Roman
    --

    Please login or register to see this link.

    -- local variable_globale_phone = "Phone_XXX_Present";
    -- local current_icon_absent = 1035 -- homme
    -- local current_icon_present = 1034 -- homme
    local variable_globale_phone = "Dad_Present";
    local current_icon_absent = 1002 -- femme
    local current_icon_present = 1001 -- femme

    local maxRetry_Process = 20;
    local scheduler_value = 30; -- (minutes) scheduled time of this process (must match the mainloop scheduled time)
    local check_wait = 5; -- (seconds) to wait between each poll device
    local debug = true
    -- local login = "admin";
    -- local pass = "not needed with port 11111";

    local selfId=fibaro:getSelfId();
    local time = tonumber(os.time());
    local maxtime = (scheduler_value*60) - (check_wait+1);
    local mac = fibaro:get(selfId, 'IPAddress');
    local HC2 = Net.FHttp("127.0.0.1", 11111);
    -- HC2:setBasicAuthentication(login, pass);

    function Debug(color, message)
    if debug then 
        if color and color ~= "" then
            fibaro:debug('<span style="color:'..color..';">'..message..'</span>');
        else
            fibaro:debug(message);
        end
    end
    end

    function SecondsToClock(sSeconds)
      local nSeconds = tonumber(sSeconds)
      if nSeconds == 0 then
        return "00:00:00";
      else
        nHours = string.format("%02.f", math.floor(nSeconds/3600));
        nMins = string.format("%02.f", math.floor(nSeconds/60 - (nHours*60)));
        nSecs = string.format("%02.f", math.floor(nSeconds - nHours*3600 - nMins *60));
        return nHours..":"..nMins..":"..nSecs
      end
    end

    local function _ping(retry)
    retry = retry or 0;

    -- notify state
      local elapsed = os.difftime(os.time(), tonumber(time));
      local msg = "Loop #".. retry .." since "..SecondsToClock(elapsed);
      fibaro:log(msg);  

      if elapsed > maxtime then
      return false; 
      end

    --open the socket
      local tcpSocket = Net.FTcpSocket(_deviceIp, _devicePort);
        fibaro:debug(_deviceIp .. " " .. _devicePort)
      --set the read timeout
      tcpSocket:setReadTimeout(250);
      --send packet
      local bytes, errorCode = tcpSocket:write("test");
      fibaro:debug(errorCode)
     
      --check for error      
      if errorCode == 0 then
        return true;
      else
        if retry < maxRetry_Process then
        --fibaro:log("Retry process, please wait...");
        fibaro:sleep(1*750);
        return _ping(retry + 1);
        end
        return false;
      end
    end

    local function FindMac(retry)
    retry = retry or 0;
    local foundUser = false;
    -- notify state
        local elapsed = os.difftime(os.time(), tonumber(time));
        local msg = "Loop #".. retry .." since "..SecondsToClock(elapsed);

    -- check for no more than maxtime seconds
      if elapsed > maxtime then
        return false; 
      end

        fibaro:log(msg);  
        Debug("yellow",msg)

        local response, status, errorCode = HC2.POST(HC2, "/api/networkDiscovery/arp", "{}");
        local jsonTable = json.decode(response) 
        --fibaro:debug("errorcode:"..errorCode.."status: "..status)
        if (tonumber(errorCode)==0 and tonumber(status)==200) then  
          for i, name in ipairs(jsonTable) do
            if foundUser == false then
            --Debug("grey",i.." found mac:"..name['mac'])
              if(name['mac'] == mac) then
                foundUser = true;
                Debug("green","Device "..name['mac'].." Has been found after "..elapsed.." s");
              end
            end
        end
        else Debug("red","error json decode")
        end

      --check for error
      if foundUser == true then
        return true;
      else
        if retry < maxRetry_Process then
            --fibaro:log("Retry process, please wait...");
            fibaro:sleep(check_wait*1000);
            return FindMac(retry + 1);
        end
      return false;
      end
    end

    fibaro:log("Starting process");
    Debug("yellow","Searching for Mac Address: "..mac)
    --ping device, secure with pcall to catch errors.
    --local f, result = pcall(_ping);
    local f, result = pcall(FindMac);


    if (f) then
      if (result == true) then
        fibaro:log("Device has been found.");
        fibaro:setGlobal(variable_globale_phone,"1")
        Debug("green","Global Var: "..variable_globale_phone.." Set to 1");
        fibaro:call(selfId, "setProperty", "currentIcon", current_icon_present)
        -- évolution future possible: stocker la date et l'heure de la dernière présence détectée
        -- fibaro:setGlobal("Present_Phones",os.time()) 
      else
        fibaro:log("Device was not found!");
        fibaro:setGlobal(variable_globale_phone,"0")
        Debug("red","Device "..mac.." Has been NOT been found");
        Debug("red","Global Var: "..variable_globale_phone.." Set to 0");
        fibaro:call(selfId, "setProperty", "currentIcon", current_icon_absent)
      end
    else
      fibaro:log("Error: " .. tostring(f));
    end

     

     

     

     

     

    MAIN LOOP:

     

     

     

    local selfId = fibaro:getSelfId();
    -- local current_icon_absent = 1035 -- homme
    -- local current_icon_present = 1034 -- homme
    local current_icon_absent = 1037 -- femme
    local current_icon_present = 1036 -- femme
    --local Verification = fibaro:get(selfId,"TCPPort");

    -- 1ère fois que le main loop s'exécute, on crée une variable nommée "instance" car elle n'existe pas. Elle existera au 2ème passage donc ne sera pas recrée.
    if (not instance) then
        -- on indique la fréquence d'execution souhaitée (en minutes)
        instance = { lastrun = 0, every = 30 }
        fibaro:debug("first run")
    end
     
    -- on vérifie la différence entre cette exéction et la dernière (stocké dans instance.lastrun)
    diff = os.date("*t", os.difftime(os.time(), instance.lastrun))
     
    -- si la différence en minutes et supérieure ou égale à la fréquence souhaitée (instance.every)
    if (diff.min >= instance.every) then
       -- TON CODE ---
              fibaro:call(selfId, "pressButton", "1")
              --[[local status = fibaro:getGlobal("Phone_GG_Present")

            if status == "0" then 
                fibaro:call(selfId, "setProperty", "currentIcon", current_icon_absent)
            end

            if status == "1" then 
                fibaro:call(selfId, "setProperty", "currentIcon", current_icon_present)
            end--]]
       -- FIN DE TON CODE ---
       -- on stock l'heure de la nouvelle exécution
       instance.lastrun = os.time()
       fibaro:debug("executed")
    end

     

    can you post a screen shot of the VD debug window as well please? im trying to get my head around this code

     

    Just also noticed this line:

    Please login or register to see this code.

    this is taking the IP address entered into VD and trying to use it as the MAC address.

     

    Try declaring

    local Mac = XX:XX:XX:XX:XX:XX where the XX is replaced with your devices MAC Address.

    • 0
    Posted

    Here you go

    Please login or register to see this attachment.

    • 0
    Posted

    was the device present on the network at this point in time? the Red line says it was not found?

    • 0
    Posted

    this is just one example (guest) that I have. this is a current debug and the guest is not here at the moment so it will say they are not present. even when the guest is not present it will put the guestcount in the negative 

    • 0
    Posted

    @amaa1981z,

     

    ill try to get this method running on my system so I can help you work this out. it may take little while though as I'm away from home for a while

    • 0
    Posted
    5 hours ago, Robert Folbigg said:

    @amaa1981z,

     

    ill try to get this method running on my system so I can help you work this out. it may take little while though as I'm away from home for a while

     

    no worries Rob, i appreciate all you help!

    • 0
    Posted

    @amatt,

     

    Try running seperate scenes for each person you are tracking presence for with this code:

     

    Please login or register to see this code.

     

    Join the conversation

    You can post now and register later. If you have an account, sign in now to post with your account.

    Guest
    Answer this question...

    ×   Pasted as rich text.   Paste as plain text instead

      Only 75 emoji are allowed.

    ×   Your link has been automatically embedded.   Display as a link instead

    ×   Your previous content has been restored.   Clear editor

    ×   You cannot paste images directly. Upload or insert images from URL.

    ×
    ×
    • Create New...