Foros Club Delphi

Foros Club Delphi (https://www.clubdelphi.com/foros/index.php)
-   Trucos (https://www.clubdelphi.com/foros/forumdisplay.php?f=52)
-   -   Obtener temperatura a través de internet (https://www.clubdelphi.com/foros/showthread.php?t=80792)

seoane 27-04-2007 15:21:21

Obtener temperatura a través de internet
 
Quiza os habeis preguntado alguna vez como hacen esos programas que se colocan en la barra de tareas y dan informacion sobre el tiempo (temperatura, humedad, etc). Pues lo que hacen es consultar una base de datos a traves de internet con informacion proporcionada por difenetes centros como, por ejemplo, los aeropuertos. Esta es la forma en la que, por ejemplo, aptua el gweather de gnome, que consulta al "National Weather Service" http://www.weather.gov/

Pues bien, podemos hacer una pequeña funcion que nos devuelva la temperatura, a partir del codigo del aeropueto. Algo asi:
Código Delphi [-]
uses WinInet;

function Bajar(Url: string): String;
var
  hNet: HINTERNET;
  hUrl: HINTERNET;
  Buffer: PChar;
  BytesRead: Cardinal;
begin
  Result := '';
  hNet := InternetOpen('agent', INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0);
  if (hNet <> nil) then
  begin
    hUrl := InternetOpenUrl(hNet, PChar(Url), nil, 0,
      INTERNET_FLAG_RELOAD, 0);
    if (hUrl <> nil) then
    begin
      GetMem(Buffer,1024);
      try
        FillChar(Buffer^,1024,0);
        while (InternetReadFile(hUrl, Buffer, 1023, BytesRead)) do
        begin
          if (BytesRead = 0) then
            break;
          Result:= Result + String(Buffer);
          FillChar(Buffer^,1024,0);
        end;
      finally
        FreeMem(Buffer);
      end;
      InternetCloseHandle(hUrl);
    end;
    InternetCloseHandle(hNet);
  end;
end;

function GetNum(Str: String): Integer;
var
  i,j: Integer;
  Menos: Boolean;
begin
  // Inicializamos el resultado
  Result:= 0;
  i:= 1;
  if AnsiSameText(Copy(Str,1,1),'M') then
  begin
    Menos:= TRUE;
    inc(i);
  end else
    Menos:= FALSE;
  while TryStrToInt(Copy(Str,i,1),j) do
  begin
    Result:= (Result * 10) + j;
    inc(i);
  end;
  if Menos then
    Result:= - Result;
end;

function Temperatura(Estacion: String): Integer;
var
  Fecha: TDateTime;
  Hora: TDateTime;
  FormatSettings: TFormatSettings;
begin
  Result:= MAXINT;
  GetLocaleFormatSettings(GetThreadLocale,FormatSettings);
  with FormatSettings do
  begin
    DateSeparator:= '/';
    ShortDateFormat:= 'yyyy/MM/dd';
    TimeSeparator:= ':';
    ShortTimeFormat:= 'hh:mm';
  end;
  with TStringList.Create do
  try
    DelimitedText:= Bajar(Format(
      'ftp://tgftp.nws.noaa.gov/data/observations/metar/stations/%s.TXT',
      [Estacion]));
    if Count > 0 then
      if TryStrToDate(Strings[0],Fecha,FormatSettings)  then
      begin
        Delete(0);
        if Count > 0 then
          begin
            if Count > 0 then
              if TryStrToTime(Strings[0],Hora,FormatSettings)  then
              begin
                Delete(0);
                Fecha:= Fecha + Hora;
                if Count > 0 then
                  if AnsiSameText(Strings[0],Estacion) then
                  begin
                    Delete(0);
                    if Count > 0 then
                      if AnsiSameText(FormatDateTime('ddhhnn"Z"',Fecha),
                        Strings[0]) then
                      begin
                        Delete(0);
                        if Count > 0 then
                        begin
                          while (pos('/',Strings[0]) = 0) do
                          begin
                            Delete(0);
                            if Count = 0 then
                              exit;
                          end;
                          Result:= GetNum(Strings[0]);
                        end;
                      end;
                  end;
              end;
          end;
      end;
  finally
    Free;
  end;
end;

Por ejemplo para obtener la temperatura de La Coruna (Alvedro), tenemos que usar el codigo LECO. Algo asi:
Código Delphi [-]
var
  T: Integer;
begin
  T:= Temperatura('LECO');
  if T <> MAXINT then  
    ShowMessage(IntToStr(T) + ' ºC')
  else
    ShowMessage('No puedo obtener la temperatura');
end;

Para obtener el código del aeropuerto mas cercano a nuestra ciudad, puedes usar esta pagina:
http://weather.noaa.gov/weather/ES_cc.html
En esta pagina puedes escoger el aeropuerto, y en la pagina de cada aeropuerto tienes el código entre paréntesis, junto a las coordenadas.

Este es solo un pequeño ejemplo de lo que se puede conseguir. Analizando mejor el texto podemos obtener, además de la temperatura, la humedad, el viento, la presión, etc ... pero como delphi no cuenta con esa maravilla de las "expresiones regulares", el analizar la cadena se me hacia un poco tedioso. Pero si alguien se anima que lo ponga por aquí. El formato en el que esta codificado es el siguiente:
http://weather.cod.edu/notes/metar.html

Edito:
Aquí dejo una versión recortada de la función Temperatura:
Código Delphi [-]
function Temperatura(Estacion: String): Integer;
begin
  Result:= MAXINT;
  with TStringList.Create do
  try
    DelimitedText:= Bajar(Format(
      'ftp://tgftp.nws.noaa.gov/data/observations/metar/stations/%s.TXT',
      [Estacion]));
    Delete(0);
    Delete(0);
    if Count > 0 then
    begin
      while (pos('/',Strings[0]) = 0) do
      begin
        Delete(0);
        if Count = 0 then
          exit;
      end;
      Result:= GetNum(Strings[0]);
    end;
  finally
    Free;
  end;
end;

MaMu 01-05-2007 12:34:10

Esta muy bueno, yo lo probe para el caso de Buenos Aires, Argentina, y funciona muy bien, todavia no lo logre hacer andar con los demas datos, es bastante feo tener que recorrer todo el string.

Saludos

fedeloko 25-05-2007 20:05:10

yo lo hice de manera mas sencilla bajando el xml con indy http por ejemplo bajar este xml http://weather.yahooapis.com/forecastrss?p=ARMS0120&u=C.xml
es de puerto iguazu argentina, una vez que lo tenemos lo tratas igual que a un txt y con readln, lo voy leyendo linea por linea, despues busco con pos() la cadena, temp, humidity, etc y listo, es muy sencillo y menos complicado creo yo...bueno un saludo a todos...FEDE


La franja horaria es GMT +2. Ahora son las 15:46:47.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
Traducción al castellano por el equipo de moderadores del Club Delphi