Aller au contenu
darklite44

Telechargement Csv En Lua

Recommended Posts

Bonjour à  tous,

 
J'ai un souci pour télécharger un fichier CSV en LUA. En effet, le contenu n'est pas dans directement le body de la réponse HTTP. Du coup lorsque je parse, le contenu est nul.
--[[ 
%% properties 
%% globals 
--]] 
-- Replace the value with ID of this virtual module
selfId=fibaro:getSelfId();
ip = fibaro:get(selfId, 'IPAddress');
ECO = Net.FHttp(ip)


local response, status, errorCode = ECO:GET("/protect/download/xdata.csv")
fibaro:debug(response)


fibaro:debug("####Debut#########################")


-- check for error
if errorCode == 0 then
    if tonumber(status) == 200 then
 -- enregistrement du retour de l API dans une table
 fibaro:debug(response)


    else
fibaro:debug("HTTP response status: "..status);
    end
else
fibaro:debug("Communication error");
fibaro:log("Communication error");
    fibaro:call(selfId, "setProperty", "ui.Msg.value", "Comm. error", os.date("%d %b - %X"));
end


fibaro:debug(response)
Ce qui me donne en retour :
[DEBUG] 09:20:40: ####Debut#########################

 

Si je prend une trace réseau, on remarque bien que le contenu est un Content-Type: application/octet-stream

 
GET /protect/download/xdata.csv HTTP/1.1
Host: 192.168.1.10
Connection: keep-alive
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36
Accept-Encoding: gzip, deflate, sdch
Accept-Language: fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4

HTTP/1.1 200 OK
Connection: close
Content-Type: application/octet-stream
Cache-Control: no-cache

ANNEE,MOIS,JOUR,T1_BASE,T1_HCHP,T1_HCHC,T1_EJPHN,T1_EJPHPM,T1_BBRHPJB,T1_BBRHCJB,T1_BBRHPJW,T1_BBRHCJW,T1_BBRHPJR,T1_BBRHCJR,T1_PMAX,T1_ISOUSC,T1_IMAX,Counter1,T2_BASE,T2_HCHP,T2_HCHC,T2_EJPHN,T2_EJPHPM,T2_BBRHPJB,T2_BBRHCJB,T2_BBRHPJW,T2_BBRHCJW,T2_BBRHPJR,T2_BBRHCJR,T2_PMAX,T2_ISOUSC,T2_IMAX,Counter2
2015,1,21,0,437439,233912,0,0,0,0,0,0,0,0,0,45,31,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2024300,
2015,1,22,0,445749,251266,0,0,0,0,0,0,0,0,0,45,31,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2024300,

Partager ce message


Lien à poster
Partager sur d’autres sites

J'arrive maintenant à  télécharger et décoder une ligne du fichier  :60: . Je voudrais avoir de l'aide pour faire la boucle de lecture du buffer. Les stars du Lua, des idées ?

--[[
%% properties
%% globals
--]]

function getFileFromServer(tcp, path)
r, s, e = tcp:GET(path);
if (tonumber(s)~=200) then
return 0, nil;
else
return string.len(r), r;
end
return nil;
end


-- CHECK SERVER
fibaro:debug("---");
--setState(0, "CHECKING SERVER...");

-- connect to server
fibaro:debug("Connecting to [192.168.1.10]...");
tcpSERVER = Net.FHttp("192.168.1.10", 80);
if (not tcpSERVER) then
fibaro:debug("SERVER ERROR! Skipping...");
else
fibaro:debug("---");
size, content = getFileFromServer(tcpSERVER, "/protect/download/xdata.csv");
if (size>0) then
        fibaro:debug("Received file [" .. size .. " bytes].");
        fibaro:debug("content [" .. content .. "].");

        annee, mois, jour, hp, hc = content:match("(%d+),(%d+),(%d+),%d+,(%d+),(%d+),");
        fibaro:debug("content:match=" .. annee .. "-" .. mois .. "-" .. jour .. ", HP:" .. hp .. ", HC:" .. hc);
    
        fibaro:debug("DONE!");
else
fibaro:debug("Connection problem!");
end
end

Partager ce message


Lien à poster
Partager sur d’autres sites

Je pense que l'idée est de découper "content" en matchant la fin de ligne et pousser les lignes dans un tableau.
 
Donc dans une boucle 

while i<=size do

et

c = string.sub(content, i, i);

pour avoir de quoi évoluer ensuite un cr avec

string.char(13)

ou bien un lf avec

string.char(10)

:)
 

Partager ce message


Lien à poster
Partager sur d’autres sites

Merci pour ta réponse mais je ne comprend pas bien l'utilisation du string.sub car on demande de retourner la sous-chaîne démarrant au caractère de position i et terminant au caractère de position i également.

Sélectionne une sous chaîne par index début et fin string.sub(s, I [, j ]) s:sub(i [,j ])

Renvoie une sous-chaîne de caractères de la chaîne passée en argument. Le début de sous-chaîne est précisé par i. Si le troisième argument j n'est pas donné, la sous-chaîne finira à  l'extrémité de les chaînes de caractères. Si le troisième argument est donné, la sous-chaîne finit à  et inclut j.

Partager ce message


Lien à poster
Partager sur d’autres sites

Krikroff,

 

Je suis parvenu à  stocker les valeurs  de chaque ligne dans un tableau et le parcourir ^_^ :

-- CHECK SERVER
fibaro:debug("---");
--setState(0, "CHECKING SERVER...");

-- connect to server
fibaro:debug("Connecting to [192.168.xx.xx]...");
local tcpSERVER = Net.FHttp("192.168.xx.xx", 80);
local i=0;

if (not tcpSERVER) then
  fibaro:debug("SERVER ERROR! Skipping...");
else
  fibaro:debug("---");
  size, content  = getFileFromServer(tcpSERVER, "/protect/download/xdata.csv");
  if (size>0) then
		fibaro:debug("Received file [" .. size .. " bytes].");
		fibaro:debug("content [" .. content .. "].");
		local table = split(content, "\n");
		if(not l)then l=0; end
		for i,j in pairs(table)do printr(j,(l+1),tostring(i)); end
		annee, mois, jour, hp, hc = content:match("(%d+),(%d+),(%d+),%d+,(%d+),(%d+),");
		
		day = annee .. "-" .. mois .. "-"  .. jour
		f_day = format_date(day, "dd/mm/yy");
		fibaro:debug("content:match=" .. f_day .. ", HP:" .. hp .. ", HC:" .. hc);
		fibaro:debug("DONE!");
  else
    fibaro:debug("Connection problem!");
  end
end

Maintenant il faut que je fasse les étapes suivantes :

  • triage des données dans le tableau
  • calcul de la consommation à  partie d'une date fournie jusqu'à  aujourd'hui
  • formatage de l'affichage
[DEBUG] 14:22:05: ---
[DEBUG] 14:22:05: Connecting to [192.168.xx.xx]...
[DEBUG] 14:22:05: ---
[DEBUG] 14:22:07: Received file [7988 bytes].
[DEBUG] 14:22:07:    1 = String[304] = "ANNEE,MOIS,JOUR,T1_BASE,T1_HCHP,T1_HCHC,T1_EJPHN,T"...
[DEBUG] 14:22:07:    2 = String[89] = "2015,1,21,0,437439,233912,0,0,0,0,0,0,0,0,0,45,31,"...
...
[DEBUG] 14:22:07:    87 = String[85] = "2015,4,18,0,1423908,1130804,0,0,0,0,0,0,0,0,0,45,3"...
[DEBUG] 14:22:07:    88 = String[85] = "2015,4,19,0,1432648,1135514,0,0,0,0,0,0,0,0,0,45,3"...
[DEBUG] 14:22:07:    89 = ""
[DEBUG] 14:22:07: content:match=21/01/15, HP:437439, HC:233912
[DEBUG] 14:22:07: DONE!

Partager ce message


Lien à poster
Partager sur d’autres sites
-- connect to server
fibaro:debug("Connecting to [192.168.xx.xx]...");
local tcpSERVER = Net.FHttp("192.168.xx.xx", 80);
​
local i=0;

if (not tcpSERVER) then
  fibaro:debug("SERVER ERROR! Skipping...");
else
  fibaro:debug("---");
  size, content  = getFileFromServer(tcpSERVER, "/protect/download/xdata.csv");

  if (size>0) then
		fibaro:debug("Received file [" .. size .. " bytes].");
		fibaro:debug("content [" .. content .. "].");
		local table = split(content, "\n");
		if(not l)then l=0; end
    
		for i,j in pairs(table)do
			-- test du pattern
				annee, mois, jour, hp, hc = j:match("(%d+),(%d+),(%d+),%d+,(%d+),(%d+),");			
			if(annee) then 
				-- insertion dans le tableau
      			day = annee .. "-" .. mois .. "-"  .. jour
				f_day = format_date(day, "dd/mm/yy");
				energylist[#energylist + 1] = { date = f_day, hp = hp, hc = hc }
				--fibaro:debug("content:match=" .. f_day .. ", HP:" .. hp .. ", HC:" .. hc);
            end
      	end
		printr(energylist);
		fibaro:debug("DONE!");
  else
    fibaro:debug("Connection problem!");
  end
end

Les donnés vont bien dans la structure, reste à  les traiter:

[DEBUG] 15:50:41: ---
[DEBUG] 15:50:43: Received file [7988 bytes].
[DEBUG] 15:50:43: {
[DEBUG] 15:50:43:    1 = {
[DEBUG] 15:50:43:       date = "21/01/15"
[DEBUG] 15:50:43:       hc = "233912"
[DEBUG] 15:50:43:       hp = "437439"
[DEBUG] 15:50:43:    }
...
[DEBUG] 15:50:44:    87 = {
[DEBUG] 15:50:44:       date = "19/04/15"
[DEBUG] 15:50:44:       hc = "1135514"
[DEBUG] 15:50:44:       hp = "1432648"
[DEBUG] 15:50:44:    }
[DEBUG] 15:50:44: }
[DEBUG] 15:50:44: DONE!

Partager ce message


Lien à poster
Partager sur d’autres sites

Well done!

 

;)

Partager ce message


Lien à poster
Partager sur d’autres sites

Prise en compte des dates après la dernière facture réalisée (2015-04-05) :

local LastBill =os.time{year=2015, month=04, day=05}

if (not tcpSERVER) then
  fibaro:debug("SERVER ERROR! Skipping...");
else
  fibaro:debug("---");
  size, content  = getFileFromServer(tcpSERVER, "/protect/download/xdata.csv");


  if (size>0) then
fibaro:debug("Received file [" .. size .. " bytes].");
fibaro:debug("content [" .. content .. "].");
local table = split(content, "\n");
if(not l)then l=0; end
    
for i,j in pairs(table)do
-- test du pattern
annee, mois, jour, hp, hc = j:match("(%d+),(%d+),(%d+),%d+,(%d+),(%d+),");


if(annee) then 
         local seconds = os.time{year=annee, month=mois, day=jour};
local diff = tonumber(os.difftime(seconds, LastBill));
-- insertion dans le tableau
       day = annee .. "-" .. mois .. "-"  .. jour
       f_day = format_date(day, "dd/mm/yy");
       if(diff > 0) then
              energylist[#energylist + 1] = { date = f_day, hp = hp, hc = hc }
              fibaro:debug("date=" .. f_day .. ", HP:" .. hp .. ", HC:" .. hc .. ", sec_diff=" .. diff);
           end
            end
       end
fibaro:debug("DONE!");
  else
    fibaro:debug("Connection problem!");
  end
end

 

Ce qui donne dans le debug:
[DEBUG] 16:28:27: Received file [7988 bytes].
[DEBUG] 16:28:27: date=06/04/15, HP:1325477, HC:1050730, sec_diff=86400
...
[DEBUG] 16:28:27: date=19/04/15, HP:1432648, HC:1135514, sec_diff=1209600
[DEBUG] 16:28:27: DONE!

Partager ce message


Lien à poster
Partager sur d’autres sites

×