Mostrando entradas con la etiqueta GNU. Mostrar todas las entradas
Mostrando entradas con la etiqueta GNU. Mostrar todas las entradas

21 sept 2016

Como guardar un archivo .xml "solo por un espacio de tiempo limitado" usando windows (¡y/o GNU/Linux!)

Hace poco me encontré en la tesitura de necesitar repetir un determinado comando -para el caso consistente en descargar y copiar un archivo de mi red local LAN, usando el siguiente archivo que pude masacrar de no recuerdo bien quién o qué fuentes en una de esas derivas existenciales que realizo en cada búsqueda abstracta de soluciones realistas por el internet.

En este caso mi difusa idea era guardar la emisión de un archivo llamado data.xml (que emite un dispositivo de esos que llaman IoT (o internet de las cosas)) pero solo por un rato (un log tan grande petaría mi sistema sin dudas, como bien me indicó un experto amigo). En resumen: Obtener el archivo (que en el mismo aparato se refresca cada segundo) cada cierto tiempo, y guardarlo ese mismo cierto tiempo y no mas. 

El archivo que realiza la primera función se llama getData.vbs (lo puedes repicar en el bloc de notas y guardar con dicha extensión) y es un equivalente al famoso comando get para linux. VBScript es un lenguaje para máquinas que corren windows.

' Set your settings
    strFileURL = "http://ipDeRedLocal/data.xml"
    strHDLocation = "C:\lugarDondeguardarArchivo\data.xml"

' Fetch the file
    Set objXMLHTTP = CreateObject("MSXML2.XMLHTTP")

    objXMLHTTP.open "GET", strFileURL, false
    objXMLHTTP.send()

If objXMLHTTP.Status = 200 Then
Set objADOStream = CreateObject("ADODB.Stream")
objADOStream.Open
objADOStream.Type = 1 'adTypeBinary

objADOStream.Write objXMLHTTP.ResponseBody
objADOStream.Position = 0    'Set the stream position to the start

Set objFSO = Createobject("Scripting.FileSystemObject")
If objFSO.Fileexists(strHDLocation) Then objFSO.DeleteFile strHDLocation
Set objFSO = Nothing

objADOStream.SaveToFile strHDLocation
objADOStream.Close
Set objADOStream = Nothing
End if

Set objXMLHTTP = Nothing

Así pues con este archivo creado y asimismo creando otro de nombre watch.bat (que emula el también famoso comando watch de linux) que diga:

@ECHO OFF
:loop
  cls
  %*
  timeout /t 30

goto loop
Ahora tenemos todo listo para el happening. 30 es el tiempo del loop en segundos. Una vez hecho todo esto, abrimos la consola en Inicio -> Ejecutar -> cmd y nos ubicamos en la carpeta donde creamos estos dos archivos, tecleando: 

cd C:\lugarDondeguardarArchivo\

Posteriormente lo ponemos a funcionar mediante las palabras mágicas:

watch getData.vbs

Si todo va bien el proceso se iniciará ad infinitum. ¿Y todo esto para qué? Se preguntarán algunos... Pues la verdad no sé exactamente que utilidad tiene. Eso si, el archivo, que en este caso concreto se sobreescribe una y otra vez en el tiempo, está disponible para que terceros (personas, máquinas,programas) extraigan información, la procesen y la analicen, incluso quizás creen un log con los datos que prefieran, dejando el resto de información perderse en la noche de los tiempos

...no se, voladas de la mente, supongo. Por si a alguno le sirve de algo, a mi me recuerda que una vez precisé estas lineas de código. ¡Saludos!

Update: Para hacer esto usando la terminal de tu máquina GNU/Linux tan solo teclea como usuario administrador(root):

watch -n 3 wget http://ipDeRedLocal/data.xml -O data.xml  
 

estando en la carpeta /lugarDondeguardarArchivo/ , o especificandolo tras la opción -O del comando wget



17 oct 2015

Arduino smart light response system - Basic concepts



Easy and impressive as usual, Arduino boards allow any ignorant such as me myself and I to develop a unique and relatively cheap controller capable of reading the light state surrounding a given sensor and translate it to some command, hereby light a brand new second hand led -that is on or off according to environmental needs-. Simple, fast and closed circuit. Adding a relay is just a matter of time isn't it?


Want to see it in action?. Check out this video of the gadget at work:


Here is the code that runs it. No more, no less:

//     ____                 //
//    /    /___             //
//   /    /    /___         //
//  /____/    /    /____    //
//  |   /____/    /    /|   //
//  |___|   /____/    / |   //
//      |___|   /____/  /   //
//          |___|    | /    //
//              |____|/     //


// ArduLightResponseSystem
// Led on only when the light is out.


int photoRPin = 0; 
int lightLevel;
int LEDpin = 13;


void setup() 
{
 Serial.begin(9600);
}

void loop()
{
 lightLevel=analogRead(photoRPin);

 Serial.println(lightLevel);{       
   
 if(lightLevel > 526)
 {
   digitalWrite(13, HIGH);

 }
 else if(lightLevel <= 526){
 digitalWrite(13, LOW);
 }


 delay(250);

}
}


//......................................................................
// Luis Rodriguez Alonso. October 2015. habitainer@gmail.com
// http://habican.blogspot.com.es/
// publicado bajo GNU GENERAL PUBLIC LICENSE
// https://gnu.org/licenses/gpl-3.0.en.html



Just enjoy it!