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.