domingo, 29 de enero de 2012

Internet of things

Abstract

In this chapter we will describe pachube. This is a web based tool for showing graphics about values red from devices connected to internet.

This is intended to be short and concise, which will allows to understand the next entry of this blog, when we connect our arduino to this tool for track a temperature sensor.

The information described here was extracted from their URL: www.pachube.com

What is Pachube anyway?

Pachube is a realtime data infrastructure platform for the Internet of Things , managing millions of datapoints per day from thousands of individuals, organisations & companies around the world. Pachube's powerful and scalable infrastructure enables you to build 'Internet of Things' products and services, and store, share & discover realtime sensor, energy and environment data from objects, devices & buildings around the world.

What allows Pachube?

Manage realtime sensor & environment data :
Pachube is a data brokerage platform for the internet of things , managing millions of datapoints per day from thousands of individuals, organisations & companies around the world. Convenient, secure & economical, Pachube stores, converts & serves data in multiple data formats , which makes it interoperable with both established web protocols & existing construction industry standards. All feeds include contextual metadata (timestamps, geolocation, units, tags) that actually make datastreams valuable.

Graph, monitor & control remote environments :
Embed realtime graphs & widgets in your own website. Analyse & process historical data pulled from any public Pachube feed. Send realtime alerts from any datastream to control your own scripts, devices & environments. Out-of-the-box configurable tools include a zoomable graph , a mapping/tracking widget , anaugmented reality viewer , SMS alerts & apps for various smartphones . As soon as something is plugged into Pachube, you're ready to monitor & control it.

Build mobile & web apps that create value :
With a rapid development cycle & dozens of code examples & libraries, Pachube's simple yet sophisticated'physical-to-virtual' API makes it quick & easy to build applications that add value to networked objects & environments. That's because real value-creation comes from the applications that are built on top of sensor systems. Pachube handles the scalability & high-availability required for complex data management, so that you are empowered to develop applications that make decision-making more sophisticated.

Share data & create communities :
Pachube is built to encourage open ecosystems. Connect electricity meters , weather stations , building management systems , air quality monitors , biosensors , geiger counters — build communities around devices & data collection. While privacy options will soon be available, Pachube's unique openness promotes growth: most hardware & software libraries & real world applications are being created by its community!

Pachube's website is a little like YouTube, except that, rather than sharing videos , it enables people to monitor and share real time environmental data from sensors that are connected to the internet. Pachube acts between environments, able both to capture input data (from remote sensors) and serve output data (to remote actuators). Connections can be made between any two environments, facilitating even spontaneous or previously unplanned connections. Apart from being used in physical environments, it also enables people to embed this data in web-pages, in effect to "blog" sensor data. Through the extensive use of metadata, Pachube adds value to physical interconnectivity: it's not just about datastreams, but about the environments that make up the datastreams.



Pachube makes it simple to build applications, products and services that bridge physical and virtual worlds. With a rapid development cycle (it can take just one line of code to start prototyping ), and a sophisticated development path (working with both web-protocols and data formats that are interoperable with construction industry formats) people have used Pachube to build sensor-logging systems, remote monitoring apps, integrate building management systems, develop geo-tracking systems, create mashups and networked objects and a whole host of other things. For more on what you might do see What can I use Pachube for? .

Apart from CSV and JSON , Pachube also makes use of Extended Environments Markup Language (EEML) , which extends the construction industry protocol IFC. An extensive RESTful API makes it possible to both serve and request data in all formats. Data can be pushed to Pachube using an HTTP PUT request (especially useful for those operating behind firewalls or with non-static URLs) or Pachube can pull data from devices that are able to serve.

There are extensive tutorials and software and hardware libraries and examples available for all sorts of platforms.

Relevant URLs:

- http://www.pachube.com/ (main website)
- http://www.economist.com/node/17388392 "The Economist: Special Report on Smart Systems - Augmented Business"
- http://www.ugotrade.com/2009/01/28/pachube-patching-the-planet-interview... (interview with Pachube's founder)
- http://eeml.org/ (Extended Environments Markup Language)
- http://api.pachube.com/ (technical documentation) Read More......

Email Communication with Arduino (English Version)

Abstract

In the previous chapter we saw how to communicate with the micro using a chatting client. Very useful if you want to execute commands from a mobile client or from another PC, cities away.

In this chapter we will be exploring how to do it by e-mail, which allows both send and receive information from the micro using a very commonly mean used today.

Arduino code:   led-1.pde
Download: SCRIPT
VIDEO:   E-mail communication with Arduino

Communication with the Arduino using the e-mail

The really interesting part of the email is the ability to format the information we sent from the micro to the PC and then to the user. In this way we can create very good-looking reports to communicate the status of, for example,  open status of doors of a house, commercial establishments, factories, offices, etc..

In my search for options that would enable this capability, in a simple way, I found a thunderbird add-on called Mailbox-Alert . This add-on installs very easily (see link) and can configure your thunderbird to identify incoming messages, and then run scripts created by us to perform different tasks.

The information contained in this article applies not only to communicate with a microcontroller, but may be used in different situations to automate tasks as required. For example, if we need to ask our server for some event or information about resource utilization.

Let's see how to configure our components to enable communication via email. Here are the steps to follow to implement this configuration:

  1. Programmingthe microcontroller using the Arduino IDE
  2. Create the script that will send commands through the serial port
  3. Mail-Alert configuration to link a filter to the script indicated below

The flow chart shown indicates that an incoming message is filtered by thunderbird. In the event that the subject of the message do match the conditions specified in the filter, this will trigger a rule defined in the add-on Mail-Alert that will run the script which makes the interface to the serial port and to the arduino. This script is also capable of responding to the original email sender with the actions taken.

(1) Programming the arduino

Like the previous article we used a setting of 4 LEDs connected to the arduino. The firmware (software) that we use is the same as in the previous article which can be downloaded here .

(2) Python script to interact with Arduino

So far we have developed our scripts using ksh, which can run on any linux. To increase portability, in this example we have created a python script which is multiplatform.

This script takes as parameters the subject content of incoming mail, the sender of the email and the serial port with which it is interacting.

This script also interacts with a mail client installed on the PCs. In my case I use ssmtp for its simplicity and effectiveness. As I use Ubuntu as my operating system, ssmtp does the job very well and I point out a link where you can get information on how to install it.


Our script uses ssmtp making a call to the operating system using the subprocess library, which allows a fork of an operating system to execute a command, and we can the parameters to that command. The following excerpt shows the routine to send the mail back to sender.

send_email def (message):
try:
ssmtp = subprocess.Popen (('/ usr / sbin / ssmtp', recipient), stdin = subprocess.PIPE)
except OSError:
print 'I can not begin ssmtp, sothe email was not sent'

# Pass the contents of the mail through stdin
ssmtp.communicate (body% (recipient, sender, message))

# Wait until sending mail
ssmtp.wait ()

Download: SCRIPT

(3) Mail-Alert Settings

This step is one that allows everything to work. When you get a thunderbird mail through their filters, it can redirect it to a rule defined for Mail-Alert, which will execute the script that interacts with the Arduino.

(3.1) Create a Mailbox rule-Alert
(3.2) Create a filter that redirects to the MailboxAlert rule

After setting all the parties involved in the process we can try sending an email to the following features yadirganbot@gmail.com.
  • The message must contain the instructions on the subject
  • The subject must begin with "@, ->" string (without quotes)
  • You can specify more than one command in the subject separated by spaces
  • The commands supported are:
    • ledon, ledoff (Turn on all LEDs)
    • ledNon, ledNoff: (1 <N <4) (Light a LED at a time)
    • titilar (Run all LEDs flashing)
    • secuencia1 (Run an LED chaser from left to right)
    • secuencia2 (Run an LED chaser from right to left)
    • pN, N> 0 integer or decimal (indicating a pause in milliseconds)
    • xN, N> = 1 (to repeat N times a command)
In this example we see how to send a sequence of commands to arduino to yadirganbot@gmail.com.

To: yadirganbot@gmail.com
Subject: @,-> x3 secuencia1 p.5  x3 secuencia2 p.5 titilar p.5 ledon p2 ledoff

Thunderbird, through a filter, detects that sequence @,-> is in the subject of the mail and sends it to the rule created in Mailbox-Alert. Mailbox Alert shows up a pop-up indicating the sender and the message and also run the following command:

/ home/ydirgan/SCRIPTS/mailboxAlert/led-1.py %subject %sender /dev/ttyACM0

in which we are passing as parameters  the email subject, which contains the commands.The sender and finally the serial port where the arduino is connected to.

The script runs led-1.py sending serial commands, logging at led-1.log and sending back a message to the sender via ssmtp.

In the video you can see the life-cycle of communication with the arduino.



Read More......

Communication with Arduino using chat client (english version)

Abstract 

In the previous article we saw the basic theory of how to communicate with the microcontroller using the serial port of your PC.

In this article we look at the basics to make the micro responds to commands sent using an instant messaging client, email, or twitter Pachube. 

Downloads: serialLed.pde , led1log.py , led-1.ksh , external 
VIDEO: Step by Step 

Communication with Arduino using chat client 

We have seen how to send or receive information to and from the microcontroller using the serial port. The next step is to use the micro to react to commands sent using our PC or analyze and react to information received from the micro. 

In a first study how to react to micro according to the orders that we can send to serial port we initially send orders directly through the port by using the direct method, but the idea is to use a interface. 

We will be working with some type of communication interfacing such as a chat client, email, twitter or Pachube to name the four that we will explore in this and the next 3 entries. 

Communication with micro via messenger 

Looking extensively on the Web for free software to use as a chat client I finally found CenterIM . This application is a lightweight chat client, which can be configured with a variety of public accounts as a messenger, yahoo, etc.. 

REF1: CenterIM home 
REF2: Installation CenterIM 

In the previous references  you can access the product home and a very good article on how to install it ubuntu. 

The documentation found in reference 1 is very broad and can be used to initially configure the package. In my case I set it up with an account especially created for this experiment. 

As a chat client, centerIM works like any other messaging client, but with additional features that fits well for our purpose. CenterIM allows us to program scripts to execute tasks according to the content of incoming messages.With this capability you can program different behaviors of how to send commands to the microcontroller via serial port. This allows us to communicate from the messenger to the home computer to perform some tasks such the activation of an alarm, turn on or off lights and appliances, and so on. 

This configuration must be done using a script that should be copied at $HOME/.centerim and whose name must be external. 

The format of the external script is very simple. 

% Action Action to take according to the following conditions 
msg event 
# Reacts only to messages 
proto msn 
# Only for the protocol messenger 
online status 
# It only if the status of the account is online 
stdin stdout options 
# .. external commands (below) read from 
# Stdin, stdout it's output is sent as a response 
# To a remote user 
% Exec 
msg = `cat` 
echo $(/ home/ydirgan/.centerim/commTest.ksh "$msg") 

% Exec redirects the message to a simple script that just returns the message via the same mean.

# CommTest.ksh 
#! /usr/ bin/ksh 
msg = `echo $ 1 | tr az AZ`; 
printf  "arduino-1 command received: $msg"; 

Upon receiving the message, CenterIM script redirects the output to commTest.ksh, it receives the title of the email as a parameter which we convert to uppercase and return it to the stdout via CenterIM (email).
From this simple example we can model a small script to turn on/off 4 LEDs connected to the digital pins 0 .. 3 of our teensy (arduino compatible microctroller).

Here are the steps that we have to follow:
  1. Creation of an arduino script that responds to commands recieved via serial (From the microcontroller)
  2. Creation of a logging script to log serial port output (from the PC)
  3. Creation of a script that is called from "external", which contains the execution logic
  4. Creation of the script "external" to be used by CenterIM
(1) Script for the Microcontroller

The script responds to commands received by the teensy serial port (like the Arduino micro).

The script turns on or off a LED on pin n (1 <= n <= 4). It waits for a character that is available on the serial port.

serial input = 1:LED 1 will be turned on
serial input = 2:LED 1 will be turned off
serial input = 3: LED 2 will be turned on
serial input = 4: LED 2 will be turned off
serial input = 5: 3 LED  will be turned on
serial input = 6: 3 LED will be turned off
serial input = 7: 4 LED  will be turned on
serial input = 8: 4 LED will be turned off

Once you download the program it must be loaded it into the arduino. Once loaded you can test the behavior directly interacting with the serial port, as seen in the video at the end of the article.

Download: serialLed.pde 

(2) logging script 
This script is intended to run on background and the purpose of it is to copy each line of output of /dev/ttyACM0 to a file. 

ydirgan@pragma-systems:~/scripts/$CenterIM led1log.py /dev/ttyACM0 & 
Download: led1log.py 

(3) Script with the execution logic


The third script allows you to execute sequences of commands that needs to be sent to the arduino. With the limited instructions that are defined on the micro script we can actually increase the funcionalities using this script.

In this program we can turn on or off individual LEDs, but also we can light them all, turn off them all, make a blink or running a sequence. All this using the primitives that we have programmed into the micro. 

In addition to the instruction set defined, we have programmed an instruction to obtain information of using by typing HELP from the chat window, and the result becomes: 

arduino-1: This is a finite state machine to interact with an Arduino microcontroller type. Its use is intended only as an example. The microcontroller re-weight when it recognizes the command to execute. They have 4 LEDs on and off each of them. The commands you can use are: ledNon, where n is the number of LEDs (1 <= N <= 4). ledNoff, where n is the number of LEDs (1 <= N <= 4). ledon, all LEDs will light. ledoff, all the LEDs go out. Tilite, all LED's will flash 20 times.stream1, all the LEDs light up in sequence (LED chaser) from left to right. stream2, all the LEDs light up in sequence (LED chaser) from right to left. help shows this help. 

Download: led-1.ksh 

(4) external script to CenterIM 
Finally, the script that runs CenterIM when we send a message. This will trigger the execution of the script led-1.ksh that will be sending our commands to arduino using the serial port. The microcontroller will process it and respond according to the script. 

Download: external 

Finally run CenterIM from our terminal to activate the robot.

The video to show the sequence of steps is as follows:

VIDEO: Step by Step

Read More......

Serial Communication with Arduino (English Version)

Abstract

One of the main advantages of a micro is the chance we have of communicating with it via serial port.

In this article, and next we will have an idea of ​​what we can do, and some of the tools I have found interesting to interact with a microcontrollers, involving internet ...

Unless a micro is programmed with a standalone implementation, ie, that its operation is limited to actions that do not depend on external interaction (beyond digital or analog inputs) is not necessary to implement the mechanisms that this article describes. It is true that many applications do not require microcontrollers to get outside the inner environment, but it is increasingly common to think of communication as a tool of interaction with applications designed for these environments. Consider the following example.
...
Arduino microcontroller communication type

If we have a house with panoramic windows (these that open by sliding horizontally), such that a person can enter smoothly through when opened, and we often like to go on vacation, we will have a security problem. The probability of breaking into our home at that time in the house alone is very high.

For someone who wants to design your security system, first of all probably think of placing motion sensors to trigger a very noisy alarm when an intrusion into the residence is detected.This may be a solution, but the alarm will alert only to the immediate surroundings of the house, and intruders.

But we can also think of a silent security system emiting an alarm message to the house's owner via the Internet, sending a text message alert to a receiving means, either email, client chat (IM) or twitter!.

Another example of remote communication is the possibility of creating a system that could  controls lights or appliances in our home. These can be automated from the microcontroller defining scheduled events for turning on or off lights, moving a sun-oriented solar cell efficiently, to power a window for the entry of light according to ambient brightness or just turn on air conditioning in our room near the hour of our arrival.

With this last example, what if we come home early?. We could communicate with our microcontroller using the cellular using our messenger by sending a message like the following:

AC: turn on

In this way, and through the proper software, this message can be received and executed online.

To perform tasks like explained above, we must start from the simple to the complex. The first thing to know is that with microcontrollers like the Arduino, pinguino, teensy, etc.. we can communicate to a server via serial port .

With arduino or teensy serial communication is established via USB interface from which we have to connect the microcontroller to the computer. Once serial port is initialized from the microcontroller environments, linux / unix directory is mapped to / dev / ttyXXXn that will give us the opportunity to send or receive information.

The following code, using Arduino, defines the sequential output of a message to our computer's serial port.

int i = 0;
void setup ()
{
   Serial.begin (9600);
}
void loop ()
{
   Serial.print ("test message");
   Serial.println (++ i);
   delay (1000);
}

In block setup () we initialize the serial port to 9600 baud with Serial.begin (9600). In the block loop () we send the message via serial port followed by a number sequencially updated by ++ i.

From the computer we will see this output if we properly interrogate the port mapping in /dev/ttyACMn.Where n> = 0.

For this example the port was mapped to / dev/ttyACM0. In my case I use ubuntu, but for any Linux / MAC should be very similar.

When the microcontroller is plugged into any USB port on our computer it can be accessed via command line from a terminal or through a program made for this purpose. A third option is to create our own program of reading and / or writing to the serial port. This last option is appropriate if we want to interact withthe microcontroller to get information or instruct it to perform any action.

For our simple example, we can initially examine the serial port using the tool that comes with the Arduino IDE or through gtkterminal or minicom.


From the microcontroller you can also read from the serial port so there is the posibility to make decisions and run actions according to the input.

The following program simply read the serial input and return the string obtained by detecting the end of line.

char character;
byte i = 0;
char string [100];
void setup ()
{
   Serial.begin (9600);
}
void loop ()
{
   if (Serial.available ())
   {
     caracter=Serial.read();
     if (character == 10)
     {
       string [i ++]=' \ 0 ';
       i = 0;
       Serial.println (string);
     }
     else
       string [i ++] = character;
   }
}

In setup() block we initialize the port, then in the loop()  block we check for the port buffer using Serial.available ().

If there are characters available Serial.read sequentially reads each one. If we detect the end of line caracter (10) we add it to the string and reset the counter, sending back the string to the port.

If the character received is not an end of line (10) then we attach it to the end of the string updating the counter.


Now let's see how to use the latter program to bring to power on or off to the air conditioning in the second example shown in this article.

# Include string.h 
# Define ON 1 
# Define OFF 0 
char caracter; 
byte i = 0; 
char string [100]; 
AC_Action void (int action) 
{   
   if (action == ON)   
   { 
     Serial.println ("Turning AC ON ...");
   / / Action to light
   / / Wait for result
       delay (500);
       Serial.println ("Air conditioning was activated ... Status OK");
   }   
   if (action == OFF)   
   {     
     Serial.println ("Turning OFF AC ...");
   / / Shutdown action
   / / Wait for result
       delay (500);
       Serial.println ("Air conditioning was deactivated ... Status OK");
   }
} 
void setup () 
{ 
   Serial.begin (9600); 
} 
void loop () 
{   
   if (Serial.available ())   
   {     
      caracter= Serial.read();
       if (caracter == 10)
       {
           string [i ++]=' \ 0 ';
           i = 0;
           if (strcmp (string, "AC: On"))
             AC_Action (ON);
           if (strcmp (string, "AC: OFF"))
             AC_Action (OFF);
       }
       else
         string [i + +] = caracter;
     }
}

We have created a procedure depending on the action parameter to turn on or off the air conditioning, assuming we have a device that controls the AC connected to the microcontroller. In our case the microcontroller, via serial port, return the message on and off accordingly.

The block loop () maintains the same pattern, except that when you match a specific string runs AC_Action function () passing the parameter set ON or OFF at the beginning of the program.

VIDEO: Serial Communication 3

The next step will be communicating ourselves from outside to PC using several means to interact with the microcontroller.

In future articles we will continue to explore possibilities for communication, interaction and execution.

Read More......

sábado, 21 de enero de 2012

Comunicación vía email con Arduino

Abstract

(go to English Version)

En el capítulo anterior vimos como comunicarnos con el micro a través del chat de msn. Muy útil si queremos ejecutar órdenes  desde un cliente móvil o desde otro PC a ciudades de distancia. ref: Comunicación con microControladores tipo Arduino. Enviando órdenes al micro a través del chat, email, pachube o twitter

En este capítulo exploraremos la forma de hacerlo por medio del correo electrónico, lo cual permite tanto enviar, como recibir información del micro por un medio utilizado muy comúnmente en la actualidad.

Código Arduino:  led-1.pde
Download: SCRIPT
VIDEO: Comunicación por email con Arduino

Comunicación con el Arduino vía correo Electrónico

Lo realmente interesante del email es la capacidad de darle formato a la información que podemos enviar desde el micro al PC y luego al usuario. De esta forma podemos crear reportes de muy buen aspecto para informar del status de, por ejemplo, los puntos de seguridad de una casa particular, establecimiento comercial, fábrica, oficina, etc.

Dentro de mi búsqueda por opciones que permitiesen esta capacidad, de manera simple, encontré un add-on de thunderbird llamado Mailbox-Alert. Este add-on se instala de forma muy sencilla (ver enlace) y permite configurar nuestro thunderbird para identificar mensajes entrantes, para luego ejecutar scripts creados por nosotros para ejecutar diferentes tareas.

La información contenida en este artículo no solo aplica para la comunicación con un microcontrolador, sino que puede ser empleada en diversas situaciones para automatizar tareas que requiramos. Por ejemplo, si necesitamos interrogar nuestro servidor por algún evento, o información de utilización del mismo.

Por lo pronto veamos como configurar nuestros componentes para activar la comunicación vía email. A continuación los pasos a seguir para ejecutar esta configuración:

  1. Programación del micro vía Arduino IDE
  2. Creación del script que enviará los comandos a través del puerto serial
  3. Configuración de Mail-Alert el cual enlaza una regla con el script que creamos ateriormente

El diagrama de flujo mostrado indica como un mensaje entrante es filtrado por thunderbird. En el caso que el subject del mensaje haga match con las condiciones indicadas en el filtro, este activará una regla definida en el add-on Mail-Alert la cual ejecutará el script que hace la interfaz con el puerto serial y hacia el micro. Este script también es capaz de responder al remitente del correo original con las acciones tomadas.

(1) Programación del micro

Al igual que el artículo anterior estaremos utilizando una configuración de 4 leds conectados al micro. El firmware (programa) que utilizaremos es el mismo que en el artículo anterior el cual puede ser bajado aquí.

(2) Script de interacción con Arduino en python

Hasta ahora hemos programados nuestros scripts con ksh, el cual puede ejecutarse desde cualquier linux. Para aumentar la portabilidad hemos creado para este ejemplo un script en python el cual es multiplataforma.

Este script recibe como parámetros el contenido del subject del correo entrante, el remitente de dicho correo y el puerto serial con el cual se estará interactuando.

Este script también tiene interacción con algún cliente de correo que tengan instalado en sus PCs. En mi caso utilizo ssmtp por su simplicidad y efectividad. Como yo utilizo Ubuntu como sistema operativo, ssmtp hace el trabajo muy bien y les indico un link en donde se puede obtener información de como instalarlo.


Nuestro script hace uso de ssmtp haciendo una llamada al sistema operativo utilizando la libreria subprocess, la cual permite hacer un fork de una llamada al sistema operativo para ejecutar un comando, y además podemos hacerle llegar los parámetros indicados. El siguiente extracto muestra la rutina para enviar el correo de vuelta al remitente.

def send_email(mensaje):
    try:
        ssmtp = subprocess.Popen(('/usr/sbin/ssmtp', destinatario), stdin=subprocess.PIPE)
    except OSError:
        print 'No se puedo iniciar sSMTP, por lo que el email no fue enviado'

    #pasamos el contenido del mail a traves del stdin
    ssmtp.communicate(cuerpo % (destinatario, remitente, mensaje))

    # Esperamos a que termine de enviar el correo
    ssmtp.wait()

Download: SCRIPT

(3) Configuración de Mail-Alert

Este paso es el que permite que todo funcione. Cuando llega un correo thunderbird a través de sus filtros permite redireccionar el mismo a una regla que definimos para Mail-Alert, el cual ejecutará el script que interactua con el Arduino.

(3.1) Creamos una regla en Mailbox-Alert
(3.2) Creamos un Filtro que direccione a la regla de Mailbox-Alert

Una vez configuradas todas las partes involucradas en el proceso podemos probar enviando un email a yadirganbot@gmail.com con las siguientes características.
  • El mensaje debe contener las instrucciones en el subject
  • El subject debe empezar con @;->
  • Se puede indicar más de un comando en el subject
  • Los comandos permitidos son:
    • ledon, ledoff (Enciende o apaga todos los leds)
    • ledNon, ledNoff: (1<N<4) (Enciende un led a la vez)
    • titilar (Ejecuta intermitencia de todos los leds)
    • secuencia1 (Ejecuta un led chaser de izquierda a derecha)
    • secuencia2 (Ejecuta un led chaser de derecha a izquierda)
    • pN, N>0 entero o decimal (indica una pausa en milisegundos)
    • xN, N>=1 (permite repetir un comando)
En este ejemplo vemos como enviamos una secuencia de comandos en el subject de un email cuyo destinatario es yadirganbot@gmail.com.

To: yadirganbot@gmail.com
Subject: @;-> x3 secuencia1 p.5 x3 secuencia2 p.5 titilar p.5 ledon p2 ledoff

Thunderbird a través del filtro creado detecta que la secuencia @;-> se encuentra en el subject del correo y lo envía a la regla creada en Mailbox-Alert. Por su parte Mailbox-Alert en su regla sabe que tiene que mostrar un pop-up indicando el remitente y el mensaje, además ejecutar el siguiente comando:

/home/ydirgan/SCRIPTS/mailboxAlert/led-1.py  %subject %sender /dev/ttyACM0

en el cual se le pasan como parámetros (%subject) el título del correo, el cual contiene los comandos. El remitente (%sender), y finalmente el puerto serial por donde el micro está conectado al PC.

El script led-1.py se ejecuta enviándole los comandos vía serial al micro, dejando huella en led-1.log y devolviendo el correo vía ssmtp al remitente.

En el video que verán a continuación se puede observar el ciclo de comunicación con el micro.







Read More......

domingo, 15 de enero de 2012

Comunicación con Arduino usando un cliente de mensajería

Abstract

(go to English Version)

En el artículo anterior vimos la teoría básica de como comunicarnos con el microcontrolador a través del puerto serial de nuestro PC. ref: Comunicación con microcontroladores tipo Arduino

En este artículo veremos lo básico para hacer que el micro responda a órdenes enviadas a través de un cliente de mensajería, correo electrónico, pachube o twitter.

Downloads: serialLed.pdeled1log.pyled-1.kshexternal
VIDEO: Paso a Paso

Sesión Interactiva: 
Agregar contacto vía messenger (msn) ydirganbot@hotmail.com y Verificar el broadcast del circuito montado para ver los leds AQUI.

Intrucción

Ya hemos visto como enviar o recibir información hacia y desde el micro utilizando el puerto serial. El paso a seguir es utilizar el micro para hacerlo reaccionar a órdenes enviadas a través de nuestro PC o analizar y reaccionar a información recibida del micro.

En una primera instancia estudiaremos la forma de hacer reaccionar al micro de acuerdo a las órdenes que le podamos enviar por el puerto serial. Inicialmente hicimos enviar directamente las órdenes a través del puerto utilizando la modalidad directa, pero la idea de fondo es poder utilizar alguna interfaz que nos haga el trabajo más sencillo.

Por ejemplo, trabajar con algún tipo de interfaz de comunicación, como un cliente de chat, correo electrónico, pachube o twitter, por nombrar los cuatro que vamos a explorar en este y los próximos 3 artículos.

Comunicación con el micro a través de messenger

Buscando extensamente en la Web por software gratuito para utilizar algún cliente de chat me encontré con centerIM. Esta aplicación es un cliente muy ligero de chat, el cual puede configurarse con una variedad de cuentas públicas como messenger, yahoo, etc.

REF1: CenterIM home
REF2: centerIM Installation

En la referencia anterior puede accederse la página del producto así como un muy buen artículo de como instalarlo en ubuntu.

La documentación que encuentran en la referencia 1 es muy amplia y con ella pueden configurar inicialmente el paquete. En mi caso yo lo configure con una cuenta que cree especialmente para este experimento.

Siendo un cliente de chat funciona como cualquier otro cliente de mensajería, pero con un adicional que encaja muy bien para nuestro objetivo. El centerIM permite programar scripts para ejecutar tareas de acuerdo al contenido de los mensajes entrantes. Con esta capacidad se pueden programar diferentes comportamientos de forma de enviar vía serial comandos al microcontrolador. Esto permite comunicarnos desde el messenger con el computador de la casa para por ejemplo ejecutar alguna tarea de activación de alarma, encender luces o apagarlas, etc.

Esta configuración se debe hacer a través de un script que debe copiarse en $HOME/.centerim y cuyo nombre debe ser external.

El formato del script external es muy simple.


%action         Acción a tomar de acuerdo a las siguientes condiciones

event           msg
# Reacciona solo a mensajes
proto           msn
# Solamente  para el protocolo messenger
status          online
# responde solo si el status de la cuenta es online
options         stdin stdout
# .. los comandos externos (abajo) leen de
# stdin, luego su salida stdout es enviada como una respuesta 
# a un usuario remoto
%exec
msg=`cat`
echo $(/home/ydirgan/.centerim/commTest.ksh "$msg")

%exec redirecciona el mensaje a un simple script que solo devuelve el mensaje por la misma vía.

#commTest.ksh
#!/usr/bin/ksh
msg=`echo $1 | tr a-z A-Z`;
printf "arduino-1 orden rebibida: $msg";

Al momento de recibir el mensaje, centerIM redirecciona la salida al script commTest.ksh, este recibe el mismo como un parámetro el cual lo convertimos en mayúsculas y lo devolvemos a centerIM por el stdout.

A partir de este simple ejemplo podemos modelar un pequeño script para encender/apagar 4 leds conectados a los pines digitales 0..3 de nuestro teensy.

A continuación los pasos que deberemos seguir:
  1. Crear un script ara el micro que responda a las órdenes enviadas vía serial
  2. Crear un script de logging del puerto serial
  3. Crear el script que es llamado desde "external", el cual contiene la lógica de ejecución
  4. Crear el script "external" para centerIM
(1) Script para el Microcontrolador

Este script responde a los comandos recibidos por el puerto serial del teensy (micro como el arduino).

El script enciende o apaga un led en el pin n (1<=n<=4). Espera por un caracter que esté disponible en el puerto serial. 

entrada serial = 1: enciende el led 1
entrada serial = 2: apaga el led 1
entrada serial = 3: enciende el led 2
entrada serial = 4: apaga el led 2
entrada serial = 5: enciende el led 3
entrada serial = 6: apaga el led 3
entrada serial = 7: enciende el led 4
entrada serial = 8: apaga el led 4

Una vez que descarguemos el programa debemos cargarlo en el micro. Una vez cargado podemos probar su comportamiento interactuando directamente conb el puerto, como se puede apreciar en el video al final del artículo.

Download:
 serialLed.pde
(2) Script de logging

Este script tiene como objetivo copiar cada línea de salida de /dev/ttyACM0 a un archivo.log y deberemos ejecutarlo en background para que se mantenga recopilando la salida del puerto.

ydirgan@pragma-systems:~/SCRIPTS/centerIM$ led1log.py /dev/ttyACM0 &
Download: led1log.py
(3) Script con la lógica de ejecución


El tercer script permite ejecutar las secuencias de los comandos que requerimos enviarle al micro. Con las reducidas instrucciones que definimos en el micro podemos desde este script aumentar las funcionalidades.

En este programa podemos encender o apagar leds individuales, pero también podemos encenderlos todos, apagarlos todos, hacer que titilen o que ejecuten una secuencia. Todo esto utilizando las primitivas que hemos programado en el micro.

Además de las instrucciones propias de ejecución, se ha programado una ayuda que puede obtenerse al tipear HELP desde la ventana de chat, y su resultado será:

arduino-1: este es una maquina de estado finita que permite interactuar con un microcontrolador tipo Arduino. Su uso esta destinado solo como ejemplo. El microcontrolador repondera cuando reconozca la orden a ejecutar. Se tienen 4 led, para encender y apagar cada uno de ellos. Los comandos que puedes utilizar son: ledNon, en donde n es el numero del led (1<=N<=4). ledNoff, en donde n es el numero del led (1<=N<=4). ledon, todos los leds se encenderan. ledoff, todos los led se apagaran. tilitar, todos los led titilaran 20 veces. secuencia1, todos los led encienden en secuencia (tipo led chaser) de izquierda a derecha. secuencia2, todos los led encienden en secuencia (tipo led chaser) de derecha a izquierda. help, muestra esta ayuda.

Download: led-1.ksh
(4) Script external para centerIM
Por último el script que ejecuta centerIM cuando le enviamos un mensaje. Este será el que dispare la ejecución del script led-1.ksh, que enviará nuestros comandos vía serial. El micro los procesará y responderá de acuerdo a la secuencia de comandos.


Download: external

Finalmente ejecutamos centerim desde nuestro terminal para activar el robot.

El video para mostrar la secuencia de pasos es el siguiente:


Para probarlo solo habría que agregar a ydirganbot@hotmail.com al messenger. Este responderá cuando esté online.

Read More......