Thursday, August 25, 2011

GUI Programming with C Language on Linux Platform

When you say you gonna write a GUI application in C for Linux platform, some people may laugh at you saying it is really really hard to write GUI applications in C and you will have to write thousands of lines of codes to get even simple GUI components working. However it is not true. You can write very nice GUI applications with C and you don't have to put that much big effort for it.
   
There are different libraries available for writing GUI applications in Linux. Among all these, GTK+ is an interesting library which I have been explored recently. GTK stands for GIMP Tool Kit and it was originally developed for GIMP(GNU Image Manipulation Program). Currently GTK+ has been used for so many applications and specially it has been used for developing GNOME desktop environment.

Before developing applications with GTK+, you have to install it. You can install it by typing the following on the terminal.

sudo apt-get install build-essential
sudo apt-get install libgtk2.0-doc devhelp


Now it's time write some codes and explore. Open your favourite text editor and add the following code into it. Save this file as "first.c".
1:  #include <gtk/gtk.h>  
2:  int main( int  argc,  
3:       char *argv[] )  
4:  {  
5:    GtkWidget *window;  
6:    gtk_init (&argc, &argv);  
7:    window = gtk_window_new (GTK_WINDOW_TOPLEVEL);  
8:    gtk_widget_show (window);  
9:    gtk_main ();  
10:    return 0;  
11:  }  

You can compile this program in the terminal by issuing the following command. You should note that the single quote used here is this (`) one, not this (') one.

gcc first.c -o first `pkg-config --cflags --libs gtk+-2.0`

Run the executable program by typing ./first on the terminal. You will see a window like the one showed in the Figure:1. But when you close the window you will notice that the program doesn't exit from the terminal even the window disappears. You have to put a CTRL+C to exit. This is because our simple program doesn't handle events such as mouse click in different places.

Figure-1















Lets explore much improved program. Copy the following code to a new file and save it as "second.c".

1:  #include<gtk/gtk.h>  
2:  void hello(GtkWidget* widget, gpointer data){  
3:       g_print("Hello World\n");  
4:  }  
5:  gint delete_event_handler(GtkWidget* widget, GdkEvent* event, gpointer data){  
6:       g_print("delete event occured\n");  
7:       return FALSE;  
8:  }  
9:  void destroy(GtkWidget* widget, gpointer data){  
10:       gtk_main_quit();  
11:  }  
12:  int main(int argc, char *argv[]){  
13:       GtkWidget *window;  
14:       GtkWidget *button;  
15:       gtk_init(&argc, &argv);  
16:       window = gtk_window_new(GTK_WINDOW_TOPLEVEL);  
17:       g_signal_connect(G_OBJECT(window), "delete_event", G_CALLBACK(delete_event_handler), NULL);  
18:       g_signal_connect(G_OBJECT(window), "destroy", G_CALLBACK(destroy), NULL);  
19:       gtk_container_set_border_width(GTK_CONTAINER(window), 10);  
20:       button = gtk_button_new_with_label("Hello World");  
21:       g_signal_connect(G_OBJECT(button), "clicked", G_CALLBACK(hello), NULL);  
22:       gtk_container_add(GTK_CONTAINER(window), button);  
23:       gtk_widget_show(button);  
24:       gtk_widget_show(window);  
25:       gtk_main();  
26:       return 0;  
27:  }  

Compile and run this program by issuing following commands in the terminal.

gcc second.c -o second `pkg-config --cflags --libs gtk+-2.0`
./second


This time you have a window with a button. Click on the "Hello World" button and seen how the mouse click event is handled by the hello() function that we have declared and it prints "Hello World" string in the terminal. Click the close button for issuing a delete event and see how the program get exited by calling gtk_main_quit() function inside the destroy() event handler function.

Figure-2 







Having a good understanding about how to register event handlers with the widgets and how to pack the widgets inside the window is necessary for learning to use GTK+. There's a good GTK+ tutorial here that can be viewed online or even off-line by downloading. Different example codes are also included in it and is very helpful. Go though it and explore what are the things you can do with GTK+.

Enjoy GUI programming in C!


Tuesday, August 23, 2011

Running Contiki on MSPSIM simulator

Running with lack of hardware is a big issue for people who are working in wireless sensor network related areas. Before burning a program into real hardware it is necessary to test the programs we write whether everything is OK. This is where hardware simulators are useful.

MSPSIM is a tool which can emulate Texas Instruments MSP430 micro-controller based sensor motes from the instruction level. It can be used independently or with the Contiki operating system. When writing programs for Contiki operating system and hopes to run these programs in MSP430 based sensor motes like MSB430, Tmote Sky, ESB, etc we can use MSPSIM simulator.

Running your Contiki programs on MSPSIM is really easy. Goto the examples directory of the Contiki operating system from the terminal and issue the following commands. (If you don't have Contiki source yet, download it first from here)


cd contiki-2.x/examples/hello-world/

make TARGET=sky hello-world.mspsim

By the second command, the hello-world program will be compiled into Tmote Sky motes platform and will run that executable code on MSPSIM simulator. These images shows what you will see in newly opened windows.
 














In the USART Port Output window you will see the hello-world programs output. It prints Hello, world! To exit the program type
exit 
on the command line prompt.

You can even compile the program into ESB motes platform. For that, you have to issue the command as,

make TARGET=esb hello-world.mspsim


This is the ESB motes window that you will see.
















There are lot of things that you can do with the MSPSIM simulator. You can learn more things in the web. This is a good resource to learn about MSPSIM.

Monday, August 8, 2011

Cooja Sensor Network Simulator

Cooja is a simuator that comes with the Contiki operating system. It is very useful for testing sensor network applications written for Contiki platform without having to put them in real sensor network hardware. If we use real hardware motes for testing our Contiki programs, we will have to burn the flash memory of the motes sevaral times until we get a nicely tested program without any known bug. But is not easy to program motes which is a time consuming task. Even if we are ready for that, it may be not good for a mote to reburn its flash memory so many times since the number of read write cycles possible in flash memory is limited.

    Because of these reasons whenever we write a Contiki program, we better try it running on the Cooja simulator first and later on we can go for real hardware. Cooja is written in Java language and has a very modular structure which enables it to be extended with custom made plugins for it. When we compile a Contiki program for running on Cooja, it actually gets compiled into an executable of the native platform which is the operating system where our Cooja simulator is running on. Cooja runs these executables using Java Native Interface(JNI) from a higher level.

    Before using Cooja simulator for testing our programs we have to setup the Environment for it to work properly. First of all download the Contiki source code from here. Let's say you have downloaded it. Inside the contiki source code you can find the Cooja simulators source code in the path /contiki-2.4/tools/cooja. Go through the following steps to prepare the environment. You may skip some steps if your platform already have such configurations. Here I assume you are using Ubuntu Linux as your operating system since it is where I have tested all these stuff.

1) Installing Java
    Since Cooja is written in java, you have to have java installed in your platform. Do the following to install Java. If you have already installed Java, you can skip this step. Open a terminal and issue the following command with an active internet connection.

    sudo apt-get install java-6-openjdk

2) Installing Apache ant
    We use ant as the build tool to compile and build the Cooja simulator from its source. Therefore to install it, issue the following command in a termianl.

    sudo apt-get install ant

3) Setting JAVA_HOME and PATH variables
    Cooja simulator requires the environmental variables JAVA_HOME and PATH to work properly. Therefore follow this link to set those variables.

Now you have the proper environment for running Cooja simuator. It's time to deal directly with Cooja. Open a terminal and goto the downloaded Contiki source code. From there, goto Cooja source code directory which should be in the path /contiki-2.4/tools/cooja. From there issue the following commands.

    ant jar
    ant run

Figure-1





















    If everything went fine, you'll get a window like the one showed in the figure-1. It contains only a menu bar. You can test whether all the environment setup has done correctly by using a simple testing wizard provided by Cooja. Open this testing wizard by going through this way.

 menubar >> Settings >> Compiler configuration wizard

Figure-2





















You will see the wizard showed in the figure-2 now. Click on the "Start tests" button to begin the test. The first test will be "Compile and link Contiki library" as showed in fugure-3 and click on "Run test" button. If it prints "Test OK", you have done with first test. Click on "Close" button and then "Next test" button. In this way you should go through all the four tests. The final test window will be like the one showed in figure-4. After passing though the final test, you can "Close Wizard".

Figure-3





















Figure-4





















If one of these test is failed, that means you have missed something when setting up the environment as mentioned above. After passing the tests you can start using Cooja simulator for testing your Contiki programs.

To run the hello-world example which resides inside the examples directory of Contiki source code, do the following steps. Goto "File" menu and clieck on "New simulation" menu item. It will bring a window to create a new simulation. Enter a name for the simulation and click "Create". Now you'll get something like the figure-5. From there goto the menu "Mote Types" and from it click on "Contiki Mote Type". Now from that window, browse for the hello-world.c file in Contiki examples directory. Then click "Compile". After compilation completed, click on "Create" button.

Figure-5





















A new window will ask you to add the number of motes for simulation. For now lets type 1 on the text field and then click "Create and Add". In the simulation visualizer window you can see a mote now like a circle. Now in the Control Panel window, set the Delay value to 1ms and click "Start" button. Now you can see the output of the virtual motes that run your program in the Log listener window. You can stop the simulation by clicking on "Pause" button in the Control Panel window.

Figure-6





    Alternatively you have another easy way to quick start your Contiki program with Cooja. To try it, close the Cooja simulator window first. From the terminal goto the hello-world directory in the examples directory of Contiki. From there type the following on the terminal.

       make TARGET=cooja hello-world

This will start the hello-world program with Cooja simulator. There are so many things to explore in Cooja simulator. With the current understanding find about different things you can do with Cooja simulator.

Friday, July 22, 2011

Writing Contiki Programs

Here I write down some simple instructions on how to program WSN motes on the Contiki operating system platform. If you are familier with C programming even for a little bit, you can write programs for Contiki operating system easily after learning the basics which are specific to Contiki operating system. After writing the very first Contiki program, most of the convensions that we have to follow will be clear.

As I have mentioned in a previous post, the most exiting thing we can find as a WSN programmer is the proto-threads in Contiki. Proto-threads allow us to write multi-threaded applications on top of the Contiki operating system. Therefore we can get rid of writing codes to implement state machines to run on the event driven kernel. The below program is the most simplest Contiki program you can write which contains most of the necessary components that should be included in any Contiki program.
1:  #include "contiki.h"  
2:  #include <stdio.h>   
3:  PROCESS(my_first_process, "Hello World Process");  
4:  AUTOSTART_PROCESSES(&my_first_process);  
5:  PROCESS_THREAD(my_first_process, ev, data)  
6:  {  
7:   PROCESS_BEGIN();  
8:   printf("Hello WSN World!\n");  
9:   PROCESS_END();  
10:  }   

Save this file as hello_world.c
The header file "contiki.h" which is included at the very first contains all the declarations of the Contiki operating systems abstractions. stdio.h is included only because I have used printf() function inside the program. The Macro in third line declares a new Contiki process. First parameter of it is the variable for the process and the second parameter is a string name for the process. Fourth line specify that this process should be started in the startup of the Contiki operating system. Therefore when the hardware device which will be the destination of compiled code switches on, our process also begins running.

Fifth line of the code opens the definition of our process. As the first parameter, we pass the process' variable which is my_first_process in this scenario. The second parameter is 'ev' which is the event parameter. It can be used to make the program responding to events that occur in the system. The third parameter 'data' can be used to receive some data which are coming with those events.

The rest of the instructions of the Contiki process will be included inside two important lines which are  PROCESS_BEGIN() and PROCESS_END(). In our Contiki process we just print a string. This output goes to the standard output in the platform where our code will be running. If you compile this code to native platform and run in the terminal, the output will be printed in the terminal. If you run this in a mote, the output most probably will goto the UART port of the mote. However this behavier depends on the design of a particular WSN mote.

Now we have a Contiki program with us. To compile it, we need a Makefile which contains the instructions for the compilation tools to do the task. Therefore create a new file with your text editer and put the below content in it. Save it as Makefile. No file extention needed for it.
1:  CONTIKI=../contiki-2.4  
2:  include $(CONTIKI)/Makefile.include  

Lets compile our code. Before everything you have to have downloaded the Contiki source code. So, goto here and download the latest Contiki source code. Uncompress the zipped file and place in some where in your PC. First we compile the code to native platform. For that, do the following steps.

1) Put the hello_world.c and Makefile files in a new directory. Lets say you place them in a directory named "my_app". 

2) In the first line of your Makefile, put the correct path to the directory where your downloaded and unzipped Contiki source code resides. As an example if your Contiki source code is located in the path "/home/aps/Desktop/contiki-2.4", your first line of the Makefile should look like below.
1:  CONTIKI=/home/aps/Desktop/contiki-2.4  

You don't have to give absolute paths always. It's ok to give relative paths also.

3) Now goto "my_app" directory from the terminal and issue the following commands,

make TARGET=native hello_world

./hello-world.native

If everythings ok, terminal will give an output like this,
Starting Contiki
Hello WSN World!


4) To stop running Contiki, give a CTRL + C on the terminal.

As I have mentioned previously, compiling to the native platform is the simplest way. But I assume that you have real hardware also to test this. Lets say you have a MSB430 motes. Put the batteries to it and switch on. Plug it to your PC with the serial cable provided with the motes. Now goto "my_app" directory from the terminal and issue the following commands,

sudo chmod 777 /dev/parport0

make TARGET=msb430 hello_world.u


Now the compiled code will be written to the flash memory of the MSB430 mote. After it completed writing to flash, remove the mote from the serial cable. Actually as soon as the flash memory writing is complete, Contiki OS will be running with your application on the mote. But you can't see the output it generates on it's pins. To see it, connect the mote with the provided USB cable to the PC. Now open a termianl and issue the following command.

ls /dev/

Check whether there's a device in the listed output named something like ttyUSB0 or ttyUSB1. Lets say it's ttyUSB0. This is the mote that is connected to your PC. So, issue this command now. 

cat /dev/ttyUSB0

Terminal will now hang and listen to any output coming from there. Switch off the mote and on again. You will see the output from the terminal now. The way we connect different types of motes to the PC are different. But the command you issue in the terminal to compile and upload the Contiki source differ only from very small things. When you compile this application to the MicaZ motes, the command you issue will be,

make TARGET=micaz hello_world.upload PORT=/dev/ttyUSB0


Now you have a basic understanding on writing programs for Contiki. You can find more code examples in the 'examples' directory of the Contiki source code. If you don't have real sensor network hardware to run and test Contiki applications you write, you have another way to fulfill your requirement. There are Simulators for that purpose. Some simulators are instruction level simulators like MSPSIM and Avrora while some simulators are network level simulators like Cooja. I'll write about how to use these simulators for testing our Contiki programs later.

Contiki Operating System



Contiki is an operating system which is specially designed for networked embedded systems. It was implemented as a research for the Ph.D thesis of Adam Dunkels at Swedish Institute of Computer Science(SICS). Contiki contains almost all the features that is necessary to develop applications using it for networked embedded systems. Therefore Contiki operating system has became the choice of so many industrial and academic communities for their commercial embedded systems or for educational research works. According to the Contiki developers, Contiki has been deployed in routers, automobile electronic systems and even in satellites.

It includes some specially designed TCP/IP stacks called uIP and lwIP which is not an available feature in most of the other embedded operating systems. Contiki supports dynamic loading and linking for applications. Among all these things, Contiki provides a thread programming model called Proto-threads on top of its event driven kernel. Because of these proto-threads, Contiki programmers can write multithreaded applications without worrying about implementing state machines. This is a very straightforward approach unlike other embedded operating systems.



Contiki operating system has been ported to so many platforms and porting it to newer platforms also seems to be not that hard. Since the major usage of Contiki according to my view is Wireless Sensor Networks(WSN), I will talk a little bit more about WSN platforms. Contiki runs on most of the available sensor network platforms like Sky, ESB, MSB430, Micaz and so on. When working on different wireless sensor network researches like writing WSN applications, implementing new routing protocols etc, we can use Contiki as our operating system abstraction since it provides so many facilities for the programmer rather than writing programs to run directly on hardware.

Writing programs for Contiki is a very easy and intersting task. However you have to have the necessary development tools to compile your program codes. Ok, lets say you have written a code and got the required development tools to compile it. Where will you run it ? You have to have some kind of a wireless sensor board or what we call a mote. If you don't have such a device platform that I have named above, don't worry! You have more options.

The simplest thing to do is to compile your code into native platform which is your PC. Then you can run the program in the command line. But this option has limitations. Most of the peripheral devices that a real WSN mote contains are not available in your PC and therefore you can't try out all the features of Contiki. The only thing you can do on PC is to write a Contiki program to print some thing and run on terminal to see what it prints on terminal. You can't have sensor readings, led blinks and other stuff on your PC.

So, the second option is the most interesting one. You have hardware simulators. You can run your compiled Contiki programs on such a simulator and test just as you run your code on real hardware. Sometimes even if you have real hardware with you, it's better to run your codes first on a simulator for testing and debugging purposes before putting those codes on a real hardware. I hope to write more about WSN hardware simulators and about contiki programming in future posts.

Saturday, July 9, 2011

Running TikiriDB with MicaZ motes

Since I had been using just MSB430 motes to run and test TikiriDB, I thought I should try out the MicaZ motes in our lab. So, after doing a trial and error session I managed to setup the MicaZ motes with its programmer board and compile TikiriDB to that platform. Here I write down what I did with MicaZs.

First I have to setup the MicaZ motes with the MIB510CA programmer board. The images below shows the Both instruments.

MicaZ mote

MIB510 programmer board



Preparing the compilation environment

To be able to compile TikiriDB application with the Contiki OS to the MicaZ motes platform, I have to prepare the development environment for it. I did this in a Ubuntu PC. We need the compiler tool chain for AVR microcontrollers.  For that install these packages from a terminal.

sudo apt-get install gcc-avr binutils-avr gdb-avr avr-libc avrdude 

Then we need a tool called uisp which helps to upload the compiled code to the MicaZ mote. I did some thing wrong here. First I apt-get installed the uisp package. But when I tried to compile Contiki, it terminated with an error saying,
"Direct Parallel Access not defined". So, I searched the web for this error and finally found this helpful page.
    
        Somewhere in that page has mentioned that the official version of uisp tool which I installed doesn't work with MIB510 programmer boards. The modified version for TinyOS should be used according to it. So, I apt-get removed the installed uisp package and downloaded the TinyOS version of it from here. To install it, issue the commands showed below.
# tar -xvzf uisp.tar.gz
# cd uisp
# ./bootstrap
# ./configure
# make
# sudo make install
Now, the development environment is ready.

Setting up the hardware

I found this video useful to understand how to setup the hardware platform for programming a MicaZ mote. Follow the steps written below.

1. Put the mib510 programmer board's power switch in off position.

2. Plug power to the mib510 programmer board. The a green LED lights now.
Keep the power button off position.

3. Put a MicaZ mote switched off and plug it onto the mib510 programmer board.

4. Connect the mib510 programmer board to the PC with the provided serial to USB cable.
Now hardware is ready for our task.

Compiling and writing tikiriDB to MicaZ

Now I hope you have the source codes of both TikiriDB and Contiki OS. This article which I have written some time back may be helpful to understand something about TikiriDB. Follow these steps for compilation.

1. From a terminal goto test app directory of tikiridb source code and issue the command,
 make TARGET=micaz test-app.upload PORT=/dev/ttyUSB0

If every things fine, the mote in the programmer board will get programmed with the compiled code of Contiki with the TikiriDB application.

2. From above way, burn 2 or more motes with tikiridb. Then keep one mote on the mib510 programmer board. Switch that mote and all the other motes on.
But the mib510 programmer board must remain switched off.

2. From another termianl goto serial forwarder directory and issue command,
./sf -s /dev/ttyUSB1 -b 115200 -p 10000

3. From another terminal goto tikirisql directory and issue command,
./tikirisql -H localhost -P 10000

Now TikiriDB is running. You can put queries in the terminal prompt of the third instruction above and get data.

Tuesday, July 5, 2011

Sending e-mails with php

Sending e-mails can be easily done using the mail() function provided by php. This function has  4 main parameters and an optional parameter.

mail(arg1, arg2, arg3, arg4, arg5)

arg1 = email address of the receiver
arg2 = subject string of the email
arg3 = body of the email message
arg4 = headers of the email message

Following code segment demonstrates the use of this function.

1:  <?php  
2:  $email_recipient = "reciever@domain.com";  
3:  $email_subject = "This is a test";  
4:  $email_contents = "Hello, this is the content of this email message.";  
5:  $email_sender = "sender@domain.com";  
6:  $email_return_to = "sender@domain.com";  
7:  $email_content_type = "text/html; charset=us-ascii";  
8:  $email_client = "PHP/" . phpversion();  
9:  $email_header = "From: " . $email_sender . "\r\n";  
10:  $email_header .= "Reply-To: " . $email_return_to . "\r\n";  
11:  $email_header .= "Return-Path: " . $email_return_to . "\r\n";  
12:  $email_header .= "Content-type: " . $email_content_type . "\r\n";  
13:  $email_header .= "X-Mailer: " . $email_client . "\r\n";  
14:  $email_result = mail($email_recipient, $email_subject, $email_contents, $email_header);  
15:  if ($email_result) {  
16:       echo "E-mail sent successfully!";  
17:  } else {  
18:       echo "Failed to send e-mail!";  
19:  }  
20:  ?>  

Fill the receivers e-mail address with any valid email address. Then save this file in your apache servers www or htdocs directory with a file name ending with .php extension. Now access this file from a web browser. If every thing went fine the string
E-mail sent successfully!
will appear.
However I noticed that when I sent this emails to a Gmail based email account, the e-mail doesn't get into the recipients inbox even though the script shows that the message has been sent. I think the Gmail server drops the message due to some reason. I have no idea about that. When I sent an email to an email server which runs Zimbra email server, it worked fine.