Archive for the 'Uncategorized' Category

Riding the Turtle with Ruby

Friday, February 15th, 2008

Turtle graphics is all about making a ‘turtle’ to move around on the computer screen. The turtle leaves a trail while moving around. So if the Turtle is made to move in a straight line, it draws a straight line on the screen, if the turtle moves in a circle, it results in drawing a circle on the screen. As simple as that :)

Ruby has a lightweight turtle graphics library TkTurtle, which uses Tk. It can be downloaded from here. You need to have Tk and its Ruby bindings installed.

Getting started

Once tkturtle is installed, try the following in in irb. (Use the command ‘irb’ to open the interactive Ruby console) :

require 'tkturtle'
include TurtleGraphics

t = Turtle.new

A window pops up, with a small white triangle (arrow shaped), at the center. This is the ‘turtle’ !

t.left

turtle turns to the left.

t.right

turtle turns to the right.

t.forward 10

turtle moves 10 pixes forward (in the current direction)

t.turn 45

turtle turns 45 degrees in the anticlockwise direction.

These are the only basic commands needed for doing Turtle graphics.

Looping to draw some complex shapes

def one_line
forward(300);
end

This ruby method simply draws a straight line.

def two_perpendicular_lines
2.times { one_line ; turn 90 }
end

This method draws a pair of mutually perpendicular lines.

2.times {two_perpendicular_lines }

This will give a square.

10.times {two_perpendicular_lines}

This will also give the same square because lines go on overlapping. To avoid this, I introduced a small angle in beween consecutive “two_perpendicular_lines” like this :

def draw(a,b)
a.times { two_perpendicular_lines ; turn(b) ; wait }
end

wait is just to introduce a small delay in between, so that we can watch the turtle draw the lines.

Yea, thats it. Now lets go ahead and see the magic.

I have the code put into a file, for the sake of convenience, turtle1.rb

ruby turtle1.rb 0.1 1 20

0.1 is the time delay in to be introduced while drawing, 1 is is the number of times our basic building block (two perpendicualr lines) is to be repeated, and 20 is the angle in degrees between two consecuive building blocks.

This just gives a pair of perpendicular lines.

Now try

ruby turtle1.rb 0.1 3 20

Nothig much even now – 3 pairs of perpendicular lines, with an extra angle of 20 between them.

Now lets increases the number of times they are repeated.

ruby turtle1.rb 0.1 100 20

Wow.. See what i got..!

turtle.gif

Its more interesting to see the drawing process, how a pairs of perpendicular lines join together one by one to produce this figure, than watching this static image!

Now lets us try changing the parameters

ruby turtle1.rb 0.1 50 63

turtle2.gif

Try various combinations of parameters and observe the patterns produced.

Drawing with Multiple Turtles simultaneously

Idea is to make one turtle draw a circle. Then make six other turtles draw the same circle simultaneosly, but in six different orientations. Its great to see the drawing process, six turtles starting off from one single point, then travel in 6 different directions, do their work and come back to where they started.

Here is my program turtle2.rb

ruby turtle2.rb 6

turtle3.gif

Lets employ more number of turtles now

ruby turtle2.rb 15

turtle4.gif

Fractals , Recursion ad Turtles

Fractals when translated to computer language, to me it is Recursion..! I am trying to plot Koch curve which is a classical fractal curve.

koch.rb

turtle5.gif

Print

IPC with D-Bus in Linux

Friday, February 8th, 2008

D-bus is an interprocess communication mechanism using message buses. It is a way for running applications to communicate with one another.

Eg: We can write a program that communicates with Pidgin the IM program to get the buddy list.

Developers can enable D-bus support in their applications and expose a set of functionalities to be accessed via D-bus. Quite a few applications already have D-bus support.

Communicating to an D-Bus enabled Application

We can use a D-Bus API to communicate to a running application, that supports D-Bus. D-Bus APIs are available in many languages , starting from a very low level C API. Ruby D-Bus API is called Rbus.

Installing Rbus

sudo apt-get install dbus
sudo apt-get install libdbus-1-3
sudo apt-get install libdbus-glib-1-dev
sudo gem install rbus

Using Rbus to retrieve the ‘now playing’ songfrom Rhythmbox

Rhythmbox is a music player inspired by Apple ITunes, and is D-Bus enabled.

sudo apt-get install rhythmbox

The following code fragment establishes a D-bus connection with Rhythmbox and gets the currently playing song filename path from it.

session_bus = RBus.session_bus
rhythmbox = session_bus.get_object('org.gnome.Rhythmbox', '/org/gnome/Rhythmbox/Player')
p rhythmbox.getPlayingUri()

Refer this for more examples on Rbus

Using Rbus to set status message in Pidgin

Pidgin is an opensource Instan messenger program. A detailed document on Pidgin’s D-Bus support is available here.

session_bus = RBus.session_bus
pidgin = session_bus.get_object("im.pidgin.purple.PurpleService", "/im/pidgin/purple/PurpleObject")

status = pidgin.PurpleSavedstatusNew(test,2)
pidgin.PurpleSavedstatusSetMessage(status, "hello world")
pidgin.PurpleSavedstatusActivate(status)

  1. Connects to Pidgin via D-bus
  2. Creates a new status message with name “test” and type 2 (2 stands for ‘available’)
  3. Saves it with status message as “Hello World”
  4. Activates it.

Making Rhythmbox’s ‘now playing’ song the status message of Pidgin

Idea is to write a ruby program that communicates with Rhythmbox and pidgin

  1. to get the current song from pidgin

2. get the song’s details from its mp3 tags (assuming its an mp3 file)

3. set pidgin’s status message with the extracted details, like song title, artist, album etc.

Extracting details from mp3 tags is extremely simple using the mp3info library

Mp3Info.open("myfile.mp3") do |mp3|
   puts mp3.tag.title
   puts mp3.tag.artist
   puts mp3.tag.album
   puts mp3.tag.tracknum

   mp3.tag.title = "track title"
   mp3.tag.artist = "artist name"
end

Complete program is available for download here

After starting pidgin and rhythmbox (play some mp3file with non-empty tags !), run the program as “ruby now_playing.rb”. Pidgin’s status message will now start showing the title of the playing song in Rhythm box :)

Print

Listening and Talking to your Linux Box

Friday, January 25th, 2008

Traditional ways in which our computer applications ‘talks’ to us is by displaying lines of text or may be images or animations/videos. Apart from the occasional beep/alert sounds, the normal computer applications try to communicate to the user only visually. I wanted to go a few steps ahead and write some applications that would literally ‘talk’ to the user.

A tool that could translate text to speech was what i needed and i found a brilliant open source tool called Festival.

Installing Festival

sudo apt-get install festival

sudo apt-get install festvox-don

Turn on your speakers and try the following :

$ echo “Hello World” | festival –tts

Its so simple..!

Festival and the Shell

Festival when combined with the capabilities of the powerful Unix Shell gives awesome results.

$ cat filename.txt | festival –tts

$ man festival | festival –tts

$ echo “Hello $(whoami), $(who | wc -l) people are logged into $(hostname) now” | festival –tts
Festival and Ruby

I wouldn’t be satifisfied with anything unless i mix it with Ruby..!

Laptop lid program

A program that says “come back soon” when you close your laptop’s lid, and says “Welcome back” when you open it back.

Linux’s elegant /proc interface provides an easy way to sense closing and opening of laptop lid.

Try “cat /proc/acpi/button/lid/LID/state”

My ruby script polls this file for ‘state’ change, and uses festival to speak out the corresponding message, whenever lid is opened/closed.

Festival and IM

I couldn’t stop before i tried using Festival with my Instant messenger programs :)

Idea was to make the IM programs read the received messages aloud, rather than me having to read it. It was fairly straight forward.

Voice chat

The Reverse process : Reading data from PC’s microphone

I wanted to read raw sound data from my laptop’s microphone and dump it into a disk file. In other words, i wanted to write a sound recording program.

In Linux systems, PC’s soundcard is represented by /dev/dsp (or /dev/dsp or /dev/sound). Reading from /dev/dsp, we will get raw audio data from the ‘line-in’ or the ‘built-in microphone’. We can dump raw digital audio data to /dev/dsp and it will be played on the speakers.

The sound input circuitry of the soundcard is an Analog to Digital Converter (ADC), which digitize the analog audio signals.

Programming the soundcard’s ADC

The ADC has a few parameters which needs to be set before reading data from it, namely Sampling Rate and Sample Size.

  • Sampling rate decides the number of samples to be taken from the analog input per second.
  • Sample size is the precision with which each of these samples needs to be saved in digital format(to be precise, its the number of bits used per sample of data)

Ioctl() system call is used to set these paramters after opening “/dev/dsp”. Ruby has a wrapper for ioctl(), but it dint work satisfactorily. So I used my all time favorite, the mighty C.

Recorder Program

You can compile the program using

cc record.c -o recorder

Then run it as

./recorder

It starts recording and records 10 seconds of audio (duration can be changed by editing the DURATION parameter in the code) and saves at sound.pcm in the current directory.

We cant use the usual media players to play it since its raw digital data. But we can simply dump into the “/dev/dsp” !!

cat sound.pcm > /dev/dsp

Its a demonstration of the beauty and power of the Unix architecture.

Necessary data for programming the soundcard were obtained from here and here

Print

Is new necessarily better?

Wednesday, September 19th, 2007

I know, most of you would immediately reply “no” to that. But it seems many software products, especially online ones, seem to be forgetting that. I am not sure if I am ranting, but what brought this on? One of my favorite online services, actually. I am an avid user of Bloglines, and I am normally wasting more time than I should be reading all the wonderful stuff that is out there on the intar-webs.

Suddenly, out of the blue, the Bloglines folks come up with a “new and improved” Beta, which I’m not sure it is either of them. Of course you can still continue to use “classic” interface, but I am guessing clearly there is a plan to merge them soon. It ‘s all Ajaxy and cool, but not necessarily more accessible or simple to read like the former version. It means new shortcuts (some of them, at least) and when I use the Beta and go back to the classic interface, it is like a breath of fresh air.

Inspite of being a geek and having an affinity for all things new and shiny, I am surprised that I prefer a plain-jane interface rather than the gee-whiz Ajax thingy. Perhaps  I shouldn’t be so surprised. Most of my projects involve a very simple interface, and I don’t use Ajax except in the places where it is almost a no-brainer that it will improve the user experience. Say, autosuggest, or things that should be updated on the fly, etc.

Some how, I am still not majorly convinced with the new “rich” internet stuff. Flash, Ajax and similar technologies no doubt make the web a lot more visually appealing, with “all that jazz”, but do they make the web a friendlier place? I have my doubts. At least for me, in Bloglines case, I prefer the older, simpler interface.

Is it just me, or do other folks feel the same way too?

Print