Aller au contenu
Renan

Code Lua

Recommended Posts

Bonjour

J'ai une scène qui tourne tous les 5 mn pour récupérer la vitesse du vent sur une station Netatmo, le problème est que ça se plante au bout de quelque heures ou minutes, avec ce message dans le débogeur. 

Plantage.JPG.6aeb4f300f9267bbf2045abf27bec668.JPG auriez vous une idée de l'origine du PB.

Partager ce message


Lien à poster
Partager sur d’autres sites

Bonsoir, 

 

Partage ton code, ce sera plus simple ;-) 

Partager ce message


Lien à poster
Partager sur d’autres sites

Voici mon code, en fait c'est le code d'un membre du forum (Sur le pluviomètre), que j'ai adapté pour récupérer les données de l'Anémomètre de NETATMO.

Il me remonte bien les infos dans 1 VD. Mais se plante de temps en temps sur l'instruction "json"?

 

 

-[[
%% autostart
%% properties
%% events
%% globals
--]]

local sourceTrigger = fibaro:getSourceTrigger();

local currentDate = os.date("*t");
local lastrequest = os.date("%Y/%m/%d %H:%M:%S");
local affiche=true


Debug = function ( color, message )
  fibaro:debug(string.format('<%s style="color:%s;">%s', "span", color, message, "span"))
end
 
DebugError = function ( color, message )
  fibaro:debug(string.format('<%s style="color:%s;">%s', "span", color, message, "span"))
end

--Debug('red','ligne 21')

--Infos Netatmo
local n_client_id = "xx"
local n_client_secret = "xx"
local n_username = "xx"
local n_password = "xxx"

local hc2_module_virtuel = 97   -- le module virtuel "vent"

local debug = true -- affiche ou non les message dans la console

local refresh = 300
local version = 2.0

-- ------------------------------------------------------------------------
--   NE PAS TOUCHER
-- ------------------------------------------------------------------------
local request_body = ''
local token = ""
local int_id = ""
local wind_id = ""

local vent_vitesse=-1000
local vent_rafale=-1000
local vent_angle=-1000
local rafale_angle=-1000

---------------------------------------------------------------------------
function autotime()
  lastrequest = os.date("%Y/%m/%d %H:%M:%S");
  auth(getDevices)
end

-- ------------------------------------------------------------------------
-- Affichage dans la console
-- ------------------------------------------------------------------------
function log(message, force)
      force = force or false
    if (debug or force) then
        print(__convertToString(message))
       end
end
 

-- ------------------------------------------------------------------------
-- Interrogation de l'API
-- ------------------------------------------------------------------------
function getResponseData(url, body, func)
    
  local http = net.HTTPClient()
    http:request(url, { 
    options = { 
            method = 'POST', 
            headers = {
                ["Content-Type"] = "application/x-www-form-urlencoded;charset=UTF-8"
            },
            data = body
        },
        
      success = function(response) 
            func(json.decode(response.data))
                Debug('yellow',response.data)
            
      --  afterHttpRequest()
        end,
    error = function(response) Debug('red'," ERROR !!! " .. url, true) end,
    }) 
  
end
 
--------------------------------------------------------------------------------
--Mesure du vent
-------------------------------------------------------------------------------
function getmeasureWind()
   request_body_wind = 'access_token='..token..'&device_id='..int_id..'&module_id='..wind_id..'&scale=max&type=WindStrength,WindAngle,GustStrength,GustAngle&date_end=last'
   getResponseData('https://api.netatmo.net/api/getmeasure', request_body_wind, 
 function(getData)
   log("-229---------========== Module Vent ==========----------")
      if (getData.body ~= nil) then
      if debug  then
        Debug( 'green', 'Lecture anémometre.' );
         -- Debug( 'red', getData.body[1].value[1][1]);
      end
      
       vent_vitesse = getData.body[1].value[1][1]
       vent_angle = getData.body[1].value[1][2]
       vent_rafale = getData.body[1].value[1][3]
       rafale_angle= getData.body[1].value[1][4]
        
       if debug then
        Debug( 'green', 'vitesse du vent: ' .. vent_vitesse .. ' km/h' );
          Debug( 'green', 'direction du vent: ' .. vent_angle .. ' °'   );
          Debug( 'green', 'Rafale : ' .. vent_rafale .. ' km/h' );
          Debug( 'green', 'Direction Rafale: ' .. rafale_angle .. ' °'  );
       end
        if fibaro:getGlobalValue('vent_vitesse') ~= nil then
        fibaro:setGlobal('vent_vitesse', vent_vitesse)
       else
        DebugError( 'red', 'Variable vent_vitesse pas trouvé. a créer')
       end
       if fibaro:getGlobalValue('vent_angle') ~= nil then
        fibaro:setGlobal('vent_angle', vent_angle)
       else
        DebugError( 'red', 'Variable windrichtung pas trouvé. a créer')
       end
       if fibaro:getGlobalValue('rafale') ~= nil then
        fibaro:setGlobal('rafale', vent_rafale)
       else
        DebugError( 'red', 'Varible rafale pas trouvé. a créer')
       end
       if fibaro:getGlobalValue('rafale_angle') ~= nil then
        fibaro:setGlobal('rafale_angle', rafale_angle)
       else
        DebugError( 'red', 'Variable rafale_angle pas trouvé. a créer')
       end 
        if fibaro:getGlobalValue('lastreq') ~= nil then
        fibaro:setGlobal('lastreq',os.date('%T'))
       else
        DebugError( 'red', 'Variable lastreq inexistante')
       end 
        
       if debug  then
        Debug( 'green', ' Fin de Lecture anémometre.' );
       end
   else
     DebugError( 'red', 'API inaccessible!...  attendre ')
   end
    Debug('pink','ligne 60 press button')  
fibaro:call(97, 'pressButton', '6')  
 end
 )

end

-- ------------------------------------------------------------------------
-- Obtention des informations sur les devices
-- ------------------------------------------------------------------------
function getDevices()
Debug('pink','ligne 298')    
  getResponseData("https://api.netatmo.net/api/devicelist","access_token="..token, 
        function(data)
            log("---362-------==========     D  e  v  i  c  e  s    =========----------")
              for _, v in pairs(data.body.modules) do
                   Debug('red',v.data_type[1])
                    Debug ('yellow',v.module_name)
                
          ----------------------------------------------------------
          if (v.data_type[1] == 'Wind') then
              wind_id = v._id
              if (debug == 1) then
                Debug( 'green', 'Windmesser ' ..wind_id.. ' erkannt.' );
              end
         end   
          ----------------------------------------------------------
        end  
      int_id = data.body.devices[1]._id
     --    getMesuresInt()
     --     getMesuresCh()
    --    getMesuresExt()
      if wind_id ~= nil then  getmeasureWind() end
     
    end 
    )
end
 
-- ------------------------------------------------------------------------
-- Authentification
-- ------------------------------------------------------------------------
function auth(nextFunction)
    local request_body = "grant_type=password&client_id=" .. n_client_id .. "&client_secret=" .. n_client_secret .. "&username=" .. n_username .. "&password=" .. n_password .. "&scope=read_station"
       Debug('red', lastrequest)    
        getResponseData("https://api.netatmo.net/oauth2/token", request_body, 
        function(data) 
            token = data.access_token
              if (token ~= nil) then
                nextFunction()        
              else
                setTimeout(autotime, refresh*1000);
            end
          end
    )
  --Debug('green','ligne 318')
  
  setTimeout(autotime, refresh*1000);
end
if (sourceTrigger['type'] == 'autostart') then 
    auth(getDevices)
end    

log("Dernière requète : "  .. os.date("%x - %X"), true)

Partager ce message


Lien à poster
Partager sur d’autres sites

After many test i find that this is problem in LUA interpreter in HC2, when error or information about null data is send in html not classical json data. The Fibaro support confirmed my observation (13.02) and informed that add the patch to one of next system release. (not 4.111 because list of patch for this version is closed)

The problem internal ticket number in Fibaro is SFS-340 

In this moment I use watchdog for the scene with this problems with delayed restart.

Sorry I write answer in English because from phone for me is faster. 

  • Upvote 1

Partager ce message


Lien à poster
Partager sur d’autres sites

OK merci.

Partager ce message


Lien à poster
Partager sur d’autres sites

×