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

domingo, 29 de enero de 2012

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......

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......