Fernando Guillén

a Freelance Web Developer

cabecera decorativa

software development as an artistic expression

Archive for the ‘ruby’ Category

Sunday, March 14th, 2010

Arduino: Phixter Visits, blinking a led each time your website receives a visit

 Arduino I’m in

PhixterVisits is a way to convert an user visit on your web site into a blinking led on your desktop.

I have received for my birthday present one of the most awesome presents a geek can received: an Arduino Workshop Kit.

The first experiment I did was, of course, a Hello World, and after that I build something I was feeling like doing for long time: blink a led when someone visits my website.

This is very useless thing, I know and I don’t care, I just think that when something happens on the web and it become in something real on my table this is kind of magic.

On the beginning was a very simple experiment and withing an afternoon I build an small Sinatra project that received requests with a numerical parameter, the Sinatra webapp sent a signal to an script on my computer through a socket, and my computer finally sent this numerical value to the Arduino that knew with led to blink on depending the value.

This was awesome, I could to hidden an ‘img’ html element on my website asking for an image that in fact was a request to the Sinatra webapp and then the rest worked by it self.

Finally I wanted to play a competition with my girlfriend, she has a very most popular website than mine is, and then I was thinking to do all this stuff much easier to configure so this is because PhixterVisits born.

PhixterVisits is composed for three layers:

Arduino Sketch and Circuit

This is the most simple layer. It is a simple Arduino sketch that opens a Serial connection with your computer waiting for numerical values from 1 to 11, on depending the value received the Arduino will send a signal to one of its digital output connections.

The circuit is also very simple as you can see on the ‘How to Install It’ section.

Local Server

The local server is also very simple but I’ve complicated it becoming what was a simple console script on a wxRuby desktop application so you can configure it and test it visually.

Web Service

Is a Rails application where you can register your self and configure what I call ‘Phixters’. The Phixters are composed by an ‘URL:Port’ address what is your local computer public ip and the port where the Local Server is listening. You configure a value for each Phixter. And finally you can copy a very small piece of html code that you have to paste on whatever place of your website you want.

This piece of html code is the one that hides the Web Service request on an image so when your user visitors are watching an image a signal was sent to the Web Service.

How To Install It

I suppose you have a few experience with Arduino, at less you have obtained to operate the ‘Hello World’ with Arduino.

The Arduino Layer

Download the Arduino Sketch and upload it to your Arduino controller.

Build the circuit as show in this draw.

Phixter Visits Arduino Sketch

On this draw and on all my tests there are only 6 leds but you can fill all the digital outputs with leds and they suppose to work. Put atention that the digital outputs 0 and 1 are not being used, that is because on the circuit there is printed ‘RX’ and ‘TX’ on this out puts and I didn’t want any serial communication interference (I really don’t know if this interference was going to happened).

For test it you can open the ‘Serial Monitor’ of your Arduino app and send numerical values like ‘1′ or ‘2′ or ‘6′, the corresponding leds should blink for while.

Local Server

Download the ‘Local Server’ wxRuby desktop application.

You must to have Ruby installed on your computer and also the ‘wxruby’ gem:

$ sudo gem install wxruby

Go to the directory you have uncompressed the ‘Phixter Visits Local Server’ app and run on console:

$ ruby wx_tcp_server.rb

Yo should see something like on this picture:

Phixter Visits Local Server off

You have to know the name of the USB port of your Arduino and replace the text box named ‘Arduino Serial Port’ with yours one.

Select a port where you want the Local Server listens, for example ‘20000′.

Push ‘listen’.

You should see something like this bellow:

Phixter Visits Local Server

If you want to test it you can push ’stop’ and play with the ‘Send test value’ buttons. If you click on these buttons a corresponding led should blink.

Press ‘listen’ again and let the Local Server listening.

The Web Service

Go to PhixterVisits, register your self and create a Phixter for your web site like this:

Phixter Visits Web Service create Phixter

On URL:Port you have to put the public IP of your computer (or whatever computer your Local Server is listing), the Port is the port you have said to Local Server to listen.

Look that I’m using the ‘no-ip.com’ service so I don’t have to take care of my non-static public IP.

You can create any number of Phixters you want, one of them could be for a different website, just take care you are using the correct ‘code’ of each one.

Very important also is that I’m not going to talk about how to configure the NAT of my home router. This is diferent on each router and is the same theory of ‘opening the ports’ for your emule. Although I’m not talking of this step, this step is very important and the Web Service won’t can talk with your Local Server if this is not well configured.

You can check the communication from your Phixter on the Web Server to your Local Server on your desktop computer by pushing the button ‘check’ as you see bellow:

Phixter Visits Web Service go to check

This will send a signal to the URL:Port configured on this Phixter sending the value indicated, if everything is connected and working a led will blink on your Arduino circuit and a Ok message will appear on the Web Server page.

The HTML code on your Web Site

Still on the Phixter Visits Web Site, go to the ‘code’ of your Phixter:

Phixter Visits Web Service go to code

Copy the code on the textarea:

Phixter Visits Web Service Phixter’s code

And paste it on some place on your web site, be intelligent here and don’t put it on a place that an image is not going to be loaded.

From now on each time your website is loaded this image will want to be loaded and a request will arrive to the Web Service which will send a signal to your Local Server which will send a signal to your Arduino which will make the corresponding led to blink.

What is next

The game now is to connect to the Arduino not leds but DC motors so when a signal arrive the motor will work for a while and then stop until the next signal arrive. The motor will move some kind of figure like a horse or something then the race can start.

Phixter Visits Horse Race

Also will be great not to depend on a computer to communicate with the Web Service, using a ethernet interface directly connected to Arduino could be great.

The Code

All the code of this project, even the the Phixter Visits Web Service is available on the Phixter Visits Github Repository.

Responsability

Play with this code and instructions on your own risk, I’m a very beginner on all of this Arduino stuff and some problems could happen to your loved kit.

License

You can do whatever you want with the code, attributions will be grateful.

Creative Commons License

Phixter Visits by Fernando Guillen is licensed under a Creative Commons Attribution 3.0 Unported License.

Sunday, September 27th, 2009

Conferencia Rails 2009, just around the corner

 Conferencia Rail 2008

Another year, another conference, the conference that opened my eyes to the amazing word of Ruby, there on 2007, is just tuning the last details.

Conferencia Rails 2009, this year bigger, more impressive, with new venue, bigger organization team, more energy, and asking to the english spoken community  to meet us with talks.

This year I am not being to much helpful on the organization team, I know they are not missing me: a big and strong bunch of people is helping this year with new energy and ideas. I am on the register application support one more year. You can check the code and help sending patches here on the ConfRor2009 github repository.

As more news arrive to me about the Conferencia Rails 2009 more sad I feel, this is because this year I will not can assists to the event, I will be on New York on an weird adventure.

The Call for Papers is almost closed. Be hurry and propose your talk to Conferencia Rails 2009 on the registration app.

Wednesday, August 12th, 2009

OneOfZombies a brutal stupid 2D game

OneOfZombies is an experiment proyect.

Don’t come here looking for game development knowledge or very pretty Ruby code design. This is just me playing with Ruby and with Gosu.

After a few weeks working and studding on my free time I can show you this brutal stupid 2D game.

This is not a quality project, this is not a professional stuff.

I am just enjoying my self and having fun, and by the way I hope you will have fun too!.

The game is very stupid, and the code is very ugly and dirty, I just wanted to test the Gosy library, and I have not experience on game development.

It is the first time I put my self on a pure Ruby project with more of one class. I have had such an experience with Rails and still learning! and I realize that I have got no idea about Ruby.

If you want you can go to the OneOfZombies official site and try to understand what is all of this about. You can also download the Mac OSX version, or the source code, so you will can test it on your own keyboard.

Monday, June 29th, 2009

Show me where am I

puts lambda {}
Sunday, June 28th, 2009

Show me what is inside you

puts class << self; self; end
Wednesday, May 6th, 2009

Ruby: EuRuKo 2009, new dose of inspiration.

This weekend is the EuRuKo 2009, a very concentrate juice of Ruby programmers. 230 tickets were sold withing 3 days almost two months ago.

I am one of the big bunch of people that is on charge of the organization of this edition, I am helping on whatever is in my hand, I am very proud of have been the developer of the registration application, with the help of very big mind people. You can download and use the code on the github repository.

I also sent a design proposal for the t-shirt conquest. Of course Marze was there for putting me on my place :)

EuRuKo 2009 t-shirt proposal

Of course I’ll be there this weekend, I love to attend such events. It’s not because I like the talks, or because I learn a lot.. it’s not that. I love and need the energy that flutters there. It’s some kind of battery recharger. A new dose of inspiration. Company, Cooperation, … Pride of Craftsman.

See you there people!

Monday, April 6th, 2009

Ruby on Rails, Scotland on Rails 2009

Un fin de semana en Edimburgo rodeado de amantes, curiosos y rock-stars de Ruby on Rails, además de un montón de colegas de profesión y pasión, no me lo podía perder: Scotland on Rails.

Gueto español en SoR 2009

El fin de semana comenzó el jueves con un curso de un montón de horas de lo que se esperaba fuera un acercamiento a RoR y se convirtió en curso avanzado de Ruby a base de demostraciones malabaristas de lo que con este lenguaje se puede hacer.

Allí estábamos Raul, Flype, Ray y yo mismo con la cabeza apunto de explotar. Todo el día en una especie de destripamiento de carnicero de las entrañas de Ruby.

Acabé con agujetas de tener la boca abierta.. bueno espera que la cierre para escribir estas otras 2 líneas. Nos acaban de mostrar una especie de trigers o callbacs que se disparan cada vez que incluyes un módulo o incluso cada vez que declaras un método de una clase. Pueden funcionar como filtros también.

OMG.. ahora nos acaban de mostrar una clase que inspecciona Ruby en sí mismo: ObjectSpace.

Todos los ejercicios que vimos están en un proyecto de github:

Los posteriores días transcurrieron entre interesantísimas charlas, otras no tanto, alguna otra en la que no me enteré de nada, chistes, gueto español, cenas, desayunos, paseos, cervezas.. una delicia vaya.

Unas de las partes de la conferencia con menos expectativas pero que resultó ser super interesante fueron las Lightning Talks. En ellas se hablaron de unas cuantas idas de olla, de varios generadores de back y de una gran premier: la presentación de RedCar, un editor TexMate-style para Linux desarrollado por un chaval que no aparentaba ni 20 años.

Los posteriores días post-conferencia fueron aún más dulces, acompañado de un ángel fui a visitar a un amigo en Glasgow que nos llevó de paseo por las highlands.

… Feliz de mi profesión.

PD: por cierto, terminé la conferencia siendo premiado en el sorteo de 250 libras en libros de O’Reilly :) .. que repartí gustoso con mis compañeros de gueto por mi imposibilidad de leérmelos todos antes de que se quedasen anticuados.

Thursday, January 29th, 2009

Ruby: El operador ‘~>’ y el Gem::Requirement

En un hilo de ror-es con título: ‘Problema con carga de rubygem en App rails al hacer rake db:create && rake db:migrate‘, Andrés Gutierrez se debatía con las versiones de las gemas solicitadas por un proyecto Rails que esta intentando arrancar.

La configuración del proyecto le requería tener instalada una gema y para indicarle la versión se utilizaba el operador ‘~>‘.. no el ‘==’, el ‘>’, el ‘>=’.. no, tenía el simbolito raro ese de la ñ.

En concreto la especificación de la gema requerida es tal que así:

config.gem 'mislav-will_paginate', :version => '~> 2.2.3', :lib => 'will_paginate', :source => 'http://gems.github.com'

Su duda venía de que él tenía instalada la versión 2.3.6 de la gema en concreto y no entendía porque no cumplía los requisitos.

El caso es que me piqué y al más puro ‘estilo Daniel R. Troitiño‘ ahí que fui a las tripas del código a ver que demonios hacía el operador ése..

Si miramos el fichero:

 $ mate rubygems/requirement.rb

Tenemos la lista de operadores y lo que se hace con cada uno:

 OPS = {
   "="  =>  lambda { |v, r| v == r },
   "!=" =>  lambda { |v, r| v != r },
   ">"  =>  lambda { |v, r| v > r },
   "<"  =>  lambda { |v, r| v < r },
   ">=" =>  lambda { |v, r| v >= r },
   "<=" =>  lambda { |v, r| v <= r },
   "~>" =>  lambda { |v, r| v >= r && v < r.bump }
 }

Donde ‘v‘ parece ser la versión disponible y ‘r‘ la requerida
Lo raro del operador ~> es que a la versión requerida le hace un bump
y el código de esto está en otro fichero:

 $ mate rubygems/version.rb

Aquí lo pego:

 # Return a new version object where the next to the last revision
 # number is one greater. (e.g.  5.3.1 => 5.4)
 def bump
   ints = build_array_from_version_string
   ints.pop if ints.size > 1
   ints[-1] += 1
   self.class.new(ints.join("."))
 end

Al parecer a la versión requerida en la aplicación, en este caso ‘2.2.6‘, le hace un bump y la deja en ‘2.3‘ y por lo tanto la
condición:

 '2.3.6' < '2.3'

No se cumple .. como podemos comprobar aquí:

irb>
>> req = Gem::Requirement.create("~> 2.2.3")
>> req.satisfied_by?( Gem::Version.new('2.3.6') )
=> false
>> req.satisfied_by?( Gem::Version.new('2.2.6') )
=> true
>> req.satisfied_by?( Gem::Version.new('2.1.6') )
=> false

Lo que parece que quiere el operador ~> es que la gema disponible esté
en la misma familia X.X que la gema requerida.

Hasta aquí he llegado. Si por favor conoces la documentación oficial donde se explica pásame el link para darme bien de tollejas.

Saturday, January 10th, 2009

Monsters of Ruby!!!

No estaban todos los que eran ni eran todos los que estábamos pero si es cierto que se logró reunir a un buen grupo de Monstruos del Ruby.

Sábado 13 de Diciembre de 2008, 14horas, una convocatoria vía email logró reunir a rubistas de todo el estado en una sola habitación para enfrentarse a un reto por equipos.

Se trataba de enfrentarse a un fast-code de una aplicación web usando para el desarrollo de cada una de las capas herramientas que empiezan a emerger y de las que carecíamos de ningún dominio.

Nos mostraron como especificación una aplicación hecha en Rails llamada Frankenstein, para cuyo desarrollo emplearon un par de horas y otro poco para otorgarle un sugerente diseño.

Nos dividimos por equipos atendiendo a la suerta y también por sorteo se fueron repartiendo las herramientas (librerías) que cada equipo podía emplear.

A nuestro monstruoso equipo (los nosferatu) nos tocó:

Pero hubo combinaciones mucho más dolorosas.. :) que ahora no logro recordar.

Nuestro resultado lo podéis encontrar aquí: Nosferatu, pero está totalmente incompleto y dudo que logréis hacerlo funcionar sin nuestras explicaciones. El resto de  grupos y resultados los tenéis en el grupo monstersofruby de github.

A mi parecer no se puede entender lo logrado en esta reunión viendo el código generado. Lo que se ha conseguido va mucho más lejos del código, para mí ha sido una apertura de mente hacia las tecnologías que desconozco pues me da una pereza horrible enfrentarme a la primera línea de código, pero esta experiencia me ha demostrado que no es tan complicado y que hay muchas estrellas en el cielo por conocer.

Además también ha sido otra demostración más de la amigabilidad, sociabilidad, apertura y deseo de compartir que embriaga a toda esta peña entusiasmada con la programación.

Muchas gracias a todos.. ¡hasta la próxima! .. qué por cierto ya se está cociendo.

Tuesday, January 6th, 2009

Looking for _why

La gente que estamos intentando que se haga realidad la Euruko 2009 y entre todos ellos especialmente Marze y yo, nos gustaría mucho traer a _why a Barcelona a alegrar con sus excentricidades y genialidades alguna de las sesiones.

El caso es que no está resultando nada fácil dar con él, no nos quiere contestar a los mails. Incluso hemos contactado con DrNic a ver si él es capaz de hacerle llegar alguno de nuestros mensajes.

La mejor idea la ha tenido Marze que se ha currado una carta al más estilo un-plugged para intentar llamar su atención:

looking for _why

Si por favor ves a _why por algún ricón de la red dile que la gente de la SRUG le estamos buscando.

a Freelance Web Developer is proudly powered by WordPress
Entries (RSS) and Comments (RSS).