Wednesday, December 7, 2011

Using example blick application in TinyOS

TInyOS comes with some example applications to try out before we write a single NesC code. You can find them in the directory /opt/tinyos-2.1.1/apps. In this post I write down how to try the example blink application provided by TinyOS on a MicaZ mote.

If you still haven't installed TinyOS in your Ubuntu system do it. My previous post may help on this. This is the steps I follow to try the blink application.

1) Plug the MIB510 program board to power supply and switch it on. Plug a MicaZ mote to the program board via its 51pin connector.
MIB510 program board
MicaZ mote



2) Open the file located at /opt/tinyos-2.1.1/support/make/Makedefaults and add the following two lines to it,

DEFAULT_PROGRAM=mib510
MIB510=/dev/ttyUSB0


3) Now in the terminal give the following two commands to burn the example blink application to MicaZ mote.

cd /opt/tinyos-2.1.1/apps/Blink
sudo make micaz install


After the MicaZ motes flash memory is written with the app, you will see that three LEDs on the MIB510 program board are blinking. That is the output of the blink program which come to the program board since they are connected. If you remove the MicaZ mote from the program board, put batteries on it and switch it on, you will see the program output as blinking LEDs on the mote.

Installing TinyOS in Ubuntu 10.10




Even though almost all the works I was doing in sensor networks are implemented using Contiki OS, recently I had to install TinyOS and play with it as a course work. Therefore for the first time I used TinyOS and it seems OK. Even though NesC is a little bit painful than pure C used in Contiki, I think I can adapt to it.

I thought to write down the steps I followed to install TinyOS in my machine before my memory get overwritten by something new. There are different variations of TinyOS available and its installation is little bit complicated. This is the way I did as I was instructed. Here I have set up the required tool chains for AVR micro-controller based platforms. There may be different packages required to compile for different other platforms.

1) There are some repositories we have to put in our sources.list file to install TinyOS. Therefore add the two lines shown below to the sources.list file (/etc/apt/sources.list) of your Ubuntu system.





2) If you don't have synaptic package manager in your system, now it's better to install it before going further,

sudo apt-get update
sudo apt-get install synaptic 

3) Now in the terminal issue the following command to install TinyOS, (this step may take some time)

sudo apt-get install tinyos-2.1.1

4) The next step is to install avr-libc package. But there's problem. When you follow the previous step, some of the tools comes with avr-libc gets installed an therefore some package inconsistency problems may occur. Therefore its better to remove those unnecessary additional packages came with TunyOS installation.

sudo apt-get remove avr-binutils-tinyos avr-gcc-tinyos

5) Now lets install avr-libc package,

sudo apt-get install avr-libc

6) Now open .bashrc file of your home directory and add the following line.
To open the file,

 sudo gedit .bashrc

Add the following line to the end of that file, save and close.

source /opt/tinyos-2.1.1/tinyos.sh

7) Now python-dev package is required. So, we install it by issuing the command,

sudo apt-get install python-dev

8) Python version of the system is written in a configuration file of TinyOS. Therefore we have to edit it to make it have the current python version. To find it enter the following in the terminal,

python --version

There we can see the version of python. Open the configuration file by issuing the following command,

sudo gedit /opt/tinyos-2.1.1/support/make/sim.extra


There's a line in that file which starts as PYTHON_VERSION. Change it to have the correct python version in your system.



Now we have installed TinyOS in our system. I will write a separate post about burning an example TinyOS application to a mote.


Friday, November 11, 2011

System Proxy Problem in Ubuntu 11.10

Recently I installed Ubuntu 11.10 in a computer in our lab. Since we have to go through a proxy server in our university to access Internet, I set the system proxy for it.















But when I try to update the system or even try to install new software, it seemed the Internet connection was not working properly. After trying different things, I realized that the system proxy settings that I apply system wide is not worked properly. However when I set proxy settings in the Firefox web browser, it could go Internet. All the other things of the system that goes through the proxy settings didn't work.

After searching over the web I realized that this is a bug in Ubuntu 11.10 version that the system proxy is not applying system wide. The only option is to set the proxy manually without using the GUI. I found this from a forum in the web.

This is how to set proxy manually.

First open a command line and type this,

sudo gedit /etc/apt/apt.conf.d/02proxy

In the gedit editor enter the following lines,

1:  Acquire::http::Proxy "http://192.248.16.90:3128/";  
2:  Acquire::ftp::Proxy "ftp://http://192.248.16.90:3128/";   

You have to replace the "address" field and "port" field with the actual IP address and port number of the proxy server. Then save and close the editor. Now you should be able to update the system and install software from the software center.





Tuesday, October 25, 2011

Uploading an executable program to MSB430 mote

 Even though most of the times I write programs for sensor motes with Contiki operating system, there are situations where we have to write applications that can run independently on motes without an operating system.

When working with Contiki OS, we don't have to worry about uploading our program to mote. As an example if we have a Contiki program named my_app.c we can compile it and upload to a MSB430 mote by issuing the following commnad.

make TARGET=msb430 my_app.u

It will compile our program with the Contiki OS and burn it to the flash memory of the MSB430 mote. But if we write applications without Contiki, we have to take care of compiling and burning it to mote separately. As an example take a look at the following program saved as blink.c which can blink the LEDs of MSB430 motes. It doesn't rely on any operating system routines.

1:  #include <msp430x16x.h>  
2:  int main () {  
3:  int i,j=0;  
4:  P5SEL = 0x00;  
5:  P5DIR = 0xff;  
6:  while (1) {  
7:       for (i=0 ; i<2000 ; i++){  
8:            P5OUT = 0x00;  
9:       }  
10:       for (j=0 ; j<2000 ; j++){  
11:            P5OUT = 0xff;  
12:       }  
13:  }  
14:  return 1;  
15:  }  




We can compile this program by issuing the following command.

msp430-gcc -mmcu=msp430x1612 blink.c

The parameter -mmcu is used to specify the architecture type of the microcontroller that our executable code is intended to run. Here we have given the type of MCU that resides in the MSB430 mote. This command will create an executable file as a.out which can run on MSB430 motes. So it's time to upload it to mote.   

For this, I use a little trick. Contiki source code contains a tool named as PyJTAG which will be used to write a compiled Contiki application to motes flash memory. We can use the same tool to upload our program to mote. You can find that tool in the following location in the Contiki source code.

contiki-2.x/platform/msb430/buildscripts/jtag/pyjtag

Copy that whole pyjtag directory to some other place like your desktop. Now copy the executable program that we got (a.out) to the inside of that new pyjtag
directory. Now open a terminal and goto this pyjtag directory from it.



Connect the MSB430 mote to the parallel port of the PC and give permissions to access it by issuing the commnd,

sudo chmod 777 /dev/parport0

Issue the following command to erase the current content of flash memory of MSB430 mote.

python jtag.py -l /dev/parport0 -m

Then issue the following command to burn our a.out program to mote.

python jtag.py -l /dev/parport0 -D -D -S -R 2048 -p a.out

 After this command completed you will notice that LED of the mote is blinking. If so, you have successfully burnt an independent program to a MSB430 mote without an operating system.
 

Monday, October 24, 2011

Ending Words of a Chapter

Life is so much exiting and interesting. Last seven months of my life offered me so much things and added a new value to me. My time spent in the WASN laboratory was a dream that I had from a long time to be a real Computer Science researcher. It offered me to explore the potential of my capabilities. I received the opportunity to work with so many really intersting people and learn from them every bit and byte that I should have known to be a real scientist.
















The project works that I have been involved through the internship period belongs to two different areas in Computer Science. First one is Computer Forensics and the other is Wireless Sensor Networks(WSN). From these two different fields I'm in love with the second one which contains almost all the things that impressed me all over my journey in Computer Science. 

    At first hand, WSN takes you to really a lower level in computers. You have to deal with embedded platforms where your capabilities are very limited. The processing power of your CPU, the capacity of your RAM are really limited. Therefore your program codes can't be written in too much highlevel languages with heavy APIs. Your preferred laguage will be C or something below it :). In simple terms, you are naked on the Silicon wafer. You are on your own.

    This is where everything that they taught you in Computer Systems, Operating Systems and System Programming courses comes to help you. If you were sleeping at those lecture halls, you will feel sorry at such a resource constraind environment like Wireless Sensor Networks.
















Another intersting thing that I met in WSN related works is that there are lots of networking stuff. You have to deal with different routing protocols, data packets etc. All the communication that you will do inside a wireless sensor network has to be done in an energy efficient way. This is because it is not only the CPU power and memory capacity that puts you in trouble. You are running on a battery and it's capacity to power you is also limited. The deadliest thing that can happen to you is running out of battery power. And thats all about WSNs.

    My internship is over. Now I'm infront of another change. I'm starting my fourth year which is obviously the final one. It is a very rare opportunity since they select only 40 people out of a batch of 160 people to do a fourth year. So, I feel I'm privileged to do it. There are so many things in my mind that I have to do during that year. Specially I have to work for more publications. Publishing only final year research is not enough. I need more. Therefore I hope to continue my works in the WASN laboratory during the year ahead also. Our WASN laboratory is my fountain for new research experiences.

    Before ending this chapter I would like to remind here someone who helped me to climb the ladder of life so far. She is my grandmother. Our family have came across really hard situations from my childhood with financial problems. Aachchi(grandmother) was with us and she gave her helping hand to us when we were down. She always wanted us to study hard and achieve the best things of life. She passed away on 25th of last September. When life was hard she was with us. But when life is becoming better she isn't with us. She couldn't wait to see the best things and best achievements of her grandsons'. Thank you Aachchi for everything you've added to our lives.




















Thats all about a chapter in the book of my life. Hope this book will have more chapters.

"Life is a school and we are here to learn.  Problems are simply part of the curriculum that appear and fade away like algebra class but the lessons we learn will last a lifetime"

                    - by Someone

Thursday, October 13, 2011

Working With XEN Virtualization

Recently I faced to a situation of loggin in to a Xen server and managing the domains of it. Our SVN version control system and a lot more runs on a linux server which is not actually running on real hardware. It runs on another linux operating system with the Xen virtualization. Our SVN recently got stuck due to lack of memory provided by the Xen virtual machine for it. This is where I have been asked to fix it by logging in to our main server where all these Xen virtualizations runs.

In simple terms, Xen is a virtual machine monitor for X86 architecture. You can install it on top of a linux operating system and then more guest operating systems can be installed on this host operating system to be run simultaneously on the host operating system. Xen provides tools to manage these guest operating systems. Xen is an open source software with GNU general public license.

Xen is very useful to utilize the actual hardware resources we have at the bottom level. As an example we have several servers with different public IPs running on the same computer under Xen virtualization. I think there may be so many advantages of Xen virtualization like security on the virtualized guest systems. However I know very few things about it because I just came through it very recently. There are so many things that I have learnt by experience rather by a formal method. This is another one of that experience list.

Since I'm not the guy who installed Xen on our main server, I have no proper knowledge about how to install and do the initial things with it. What had to do is to log into the main server and do different things with the currently running Xen virtualization. Xen provides a nice command called 'xm' which it the command that we use to do most of the things with the Xen server.

First I log in to the main server remotely using secure socket layer.

   ssh user_name@xxx.xxx.xxx.xxx


(these x values are representing the servers IP address)

After entering the password correctly I'm in. Then I can look at the current domains or the guest systems running on this main server. They can be listed by running this command.

    xm list

Each domain has a name. These domains are created by using configuration files that are resides in /etc/xen directory. Each configuration file name ends with the extension '.cfg'. Those configuration files can be used to create domains. Content of the configuration files can be viewed by openning them using the VI editer. The path to the kernel of the guest operating system, the mount of memory assigned to it, name of the domain are few of the information that is written in the configuration files.

The below command can be used to reboot a current domain which was listed by the previous command.

    xm reboot domain_name

You can destroy a current domain by issuing the following command.

    xm destroy domain_name

When you want to create a destroyed domain again with the help of available configuration file of it, you can do it with the follwing command.

    xm create -c configuration_file_name.cfg

This create command may take some time to complete.

These are the things that I've learnt unexpectedly. I know that I should read more about the Xen servers to have a more complete understanding about how the installation and configuration stuff is carried on. I will do it in the future. This is for now.

Monday, October 3, 2011

Tmote Sky Sensor Boards



Tmote Sky is a widely used sensor board in wireless sensor network research area. It is very light weight and operates with very ultra-low power. It contains Texas Instruments MSP430F1611 MCU module at the heart of the sensor board. This MCU contains 10kb of RAM and 48kb of flash memory. Tmote Sky is powered by 2 AA batteries. However unlike most of the other sensor boards, Sky motes contains a USB port on board which makes it possible to directly plug in to a PC.
Front Side

When connected to a PC, Sky motes can be powered from the power supply of the USB port. When using Sky motes as sink node(base station) in a sensor network, communication can be done with the PC through USB port. Wireless communication can be done with the CC2420 radio module. For sensing instruments Sky mote contains humidity, temparature and radiation sensors.

WSN operating systems like TinyOS and Contiki can be burnt into Tmote Sky motes for using in various wireless sensor network applications. Here I write down the way to burn a Contiki program into the Tmote Sky motes. The most advantages fact of Contiki programming in Tmote Sky sensor boards is that there exists hardware simulators to test programs before deploying on real motes.

Back Side


1) Since Sky motes contains a MSP430 MCU, we need GCC compiler tool chain to compile our program into Sky motes. If you haven't installed the toolchain yet, issue the following command on the Linux terminal to install these tools.

    apt-get update
    apt-get install binutils-msp430 gcc-msp430 msp430-libc msp430-jtag


2) We need Contiki operating system for this testing program. Therefore download it from here (http://www.contiki-os.org/p/download.html). Uncompress it to somewhere in your Linux machine.

3) In Contiki-2.4 there is an example LED blink application in the "contiki-2.4/platform/sky/apps" directory named blink.c. Copy this file to the "contiki-2.4/examples/sky" directory. Now go to that direcorty ("contiki-2.4/examples/sky") from the Linux terminal.

4) It's time to compile and test out program. Here we have two options. First one is to compile the program and run on MSPSIM simulators Tmote Sky mode. The other option is to run our program directly on real Tmote Sky sensor boards. To compile and run on MSPSIM simulator, issue the following command.
    make TARGET=sky blink.mspsim

Now the MSPSIM simulator will open up in the Sky mote mode. Simulator will show a graphical representation of the Tmote Sky sensor board and you will notice that its LEDs are blinking. To stop the simulator, type "exit" on the MSPSIM simulators prompt.


MSPSIM Simulator

5) Now we are going to run our application on real Tmote Sky sensor boards. For that purpose, connect a Tmote Sky mote to a USB port of the Linux machine and issue the following command.
    make TARGET=sky blink.upload

Now it will take few seconds to compile and burn the flash memeory of the Tmote Sky mote. Then it will start running. So, you will see its LEDs are blinking.

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.

A journey to bring research world to real world

From the day I joined the SCoRe group and worked volunteerly, I have been working on different computer science reseach projects for about one and a half years. The experiences I collected during that period are priceless. I have been working on wireless sensor networks projects and also on computer forensic projects. The common thing that I saw on those research works is that those innovations are mostly for highly technical purposes.

Those things were far away from the poor citizens in the island who expects some thing that imporve their lives, some thing that helps them to survive and some thing that helps their children to grow. Among all those research works, the SCoRe(Sustainable Computing Research) group has introduced solutions that seems to be interested at the aforementioned people even though I hadn't a chance to contribute. PokuruPC is a one such example that I never thought this much helpful. It all started few months ago. While working at the WASN lab, I got to know that one small school in Ampara district had requested from Dr. Kasun to deploy PokuruPCs in their lab. They have received a grant from the government to buy computers. However the amount of money thay got was only enough to buy about 4 or 5 computers, not more than that. They believed that our PokuruPCs will offer them 12 computers at the expence of 4.

PokuruPC is a specially configured linux operating system which supports multiple users to login and use a single system unit with the help of multiple monitors, keyboards, mouses and other stuff. When the PokuruPC is installed on a computer system unit and properly configured, four people can sit infront of 4 separate monitor which are plugged into the same system unit. Users of each terminal gets the feeling that he or she is using his own hardware including the system unit which is actually shared. Researchers at SCoRe research group attached to Wireless Ad-Hoc Sensor Network laboratory in UCSC developed it and currently imporving with more user friendly functionalities.

To deploy PokuruPCs at the School in Ampara we left University of Colombo on 25th June night at about 8.30pm with all the computers and other stuff loaded into a Van hired from Colombo. Five people from the SCoRe group joined to this journey. Chathura, Lakmal, Eranga, Prabath and I were the crew of it. As I heard it takes about 8 hours to go to Ampara from Colombo. Therefore we planned to visit the school early in the morning so that we can start our works from the morning. But we faced to to an unexpected run time error ;) on our way. When it was about 1.30am we were at Pelmadulla area and our vehicle broke down. The driver said that it was something related to pistons of the vans engine and he can't do anything till the morning. So, we were stuck there. 


At about 4.30am in the morning Lakmal, Chathura and Eranga walked to Pelmadulla town to find some other van to continue our journey. Me and Prabath stayed in van to protect our computers and other stuff :). Our people who went out found a new van and came with it to where we were broken down. So, unloaded all the stuff in our old van and loaded them into the new van. The driver of the new van was Shashika, a nice guy who became a part of our crew during the rest of our journey. So, we started running again at about 6.30am. We arrived to the school at about 10.00am in the morning. The principle madam, some of the members of the staff and few parents of the school children were waiting there for us.

Kethsirigama Kanishta Vidyalaya, Koknahara is a very small poor school at Ampara district. It has only about 150 students and classes are available only upto grade 9. Having a computer lab was a dream to them and they have been waiting for it from a long time. Finally they found some money for it. It was on enough to buy few computers. This is where PokuruPC came to the stage. After arriving to the school we first we moved all the stuff we brought from the van to the room where the computer lab is supposed to be set up. Actually that room was the principles office room of the school and they had to move the office to some other place in school since there wasn't any other good place like that to setup the computer lab.


After placing every thing inside the lab, we accepted our breakfast. They had prepared it very nicely. After having the breakfast we unpacked monitors and system units in the computer room and placed them properly. Then it began the hardest task. We switched on one PokuruPC and started testing it. As we expected there were few problems in it. The main issue was the sounds. When a user logged into it and started playing a music file, most of the times the output came from different headphones other than this users one. Assigning hardware to each user is the most complecated thing I found in PokuruPC. It took some time for us to fix problems in that PokuruPC. After our struggle with that PokuruPC we came out from the lab and went for lunch. It seemed they had been taken a big effort to prepare our meals.  



After the lunch we went to a stream of water near the school where all the people of the village have bath and wash cloths. Some of the students of the school came with us. It was very enjoyable to have a bath in that stream. When we retern back to school it was about 5.00pm. Two village women, most probably mothers of some school children brought us the evening tea. While having tea we walked over the school and explored it. We knew that we have to work all the night most probably to prepare PokuruPCs for the next days session with the school children. The village where the school is situated is far away from the town and very isolated. I could see only few house of the villagers from schools play ground. Everything else was the jungle.

As we thought we had to do so many things during the night. Some teachers of the school came were present at night to offer us the dinner. We had our dinner at about 9.30pm. Teachers were very friendly to us and they were talking with us for about half an hour after the dinner. They asked us about our next days program plan. We thought we should give the students and the teachers a brief introduction about PokuruPC and Linux since every things are new to them. Before the teachers left the school they brought some mattersses to the lab for us to sleep. At about 1.30pm I went to sleep after doing to work. But Chathura and Lakmal were still working when I quit.

I woke up at about 5.30am in the next day morning which is a Monday. As I got to know from a teacher previously students starts coming to the school from about 7.00am. Therefore we had to dress up before the school children arrives. We all wore the SCoRe t-shirts, denims and shoes as we had discussed before. After the school started we did the first session for the Grade 9 students of the school which is the highest class in that school. Principle and some of the members of the staff were present there for that first session. Lakmal started it by giving an introduction about the UCSC and about our SCoRe research group. Then I talked about the PokuruPC and Linux. Since almost all of them haven't even touched a computer before, I don't thing they understood most of the things I said. But it wasn't a big issue since the next step was the practical session.

We offered them some of the educational packages available in GNU/Linux to play around. I felt that they really enjoyed it and most of them won't forget that experience for a long time. Even though they hadn't used a computer before they quickly adapted to it and some of them mastered the games like Tux Math. They proved to us that if enough facilities are provided thay are capable of doing anything that a child in a well developed country can do. Those little boys and girls were very smart. We involved in those practicle sessions with children from different grades until the evening. The zonal educational director of that area who is also a nice guy visited the school to see the new computer lab. It's the last day we stayed there. At night we had to return to Colombo. Principle madam invited us to come for dinner at her home.




After finishing the days works we loaded our back packs to the van and said good bye to all. We directly went near the water stream by the van. After having a bath and get dressed we went to principle madams home for the dinner. She offered us a very nice dinner. At about 9.30pm we left her home and started returning to Colombo. On next days morning at about 5.30am we arrived to Colombo. This journey tought me lot of things. It was the first time I went out some where to do a task that is worth while to the society and our country. The most important thing is that this is some thing developed inside our university and by our research community. Our research works are not limited to the WASN lab any more. The benifits of our efforts are now out there in the society and it increases our confidence to work more and produce new things with our innovations.