Monday, July 8, 2013

Transferring files via bluetooth using python scripts

In a previous post, I wrote about bluetooth programming using python. A library called BlueZ is used for that. We can do various things including client-server programs using that library. However, today I had a requirement to send or receive a file from a python script via bluetooth. As usual I started to search through the web until I find some way. Finally I came through a solution. A python library called lightblue can be used for this task. So, I'm writing down the basics I learned today about file transferring via bluetooth.

First of all, we need to download the lightblue library from the website http://lightblue.sourceforge.net/. It's scary to see the notice "This project is no longer maintained" in the website but thankfully it worked for me. I'm running Ubuntu 12.04 in my machine. Download the file "lightblue-0.4.tar.gz" and uncompress it. Now move into it from the terminal. We need to install some packages before installing the library. Issue the following commands for that purpose.

sudo apt-get install libopenobex1-dev
sudo apt-get install bluez
sudo apt-get install python-bluez libbluetooth-dev python-dev

Now, issue the following command to install the downloaded library.

sudo python setup.py install

If everything goes fine, we can start programming. Save the following program as lightblue_test.py in your machine. The variable "target_name" should contain the name of the bluetooth device we are going to connect to. "file_to_send" variable should contain the path to the file which we are going to send. 

1:  import bluetooth  
2:  import lightblue  
3:    
4:  # we should know  
5:  target_name = "SHV-E210K"  
6:  file_to_send = "/home/asanka/Downloads/20130621_151742.jpg"  
7:    
8:  # we don't know yet  
9:  obex_port = None                 
10:  target_address = None  
11:    
12:  print "searching for nearby devices..."  
13:  nearby_devices = bluetooth.discover_devices()  
14:    
15:  for bdaddr in nearby_devices:  
16:    print bluetooth.lookup_name( bdaddr )  
17:    if target_name == bluetooth.lookup_name( bdaddr ):  
18:       print "found the target device!"  
19:      target_address = bdaddr  
20:      break  
21:    
22:  print "searching for the object push service..."  
23:  services = lightblue.findservices(target_address)  
24:  for service in services:  
25:       if service[2] == "OBEX Object Push":  
26:            obex_port = service[1]       
27:            print "OK, service '", service[2], "' is in port", service[1], "!"  
28:            break  
29:    
30:  print "sending a file..."  
31:  try:  
32:       lightblue.obex.sendfile( target_address, service[1], file_to_send )  
33:       print "completed!\n"  
34:  except:  
35:       print "an error occurred while sending file\n"  

Before running this program, we need to pair the two devices. For example since I'm going to send a file from my linux PC to an Android smart-phone, I paired the PC and Android phone first. Then issue the following command to run the script.

python lightblue_test.py

Some of the basic examples are available in the lightblue library website. I referred some other websites which are listed below to solve some issues I faced during this work.

http://bayo.opadeyi.net/2009/08/bluetooth-file-transfer-with-pybluez.html

https://code.google.com/p/bluespam/

https://groups.google.com/forum/#!msg/pybluez/XrPgYLeDej4/2Uf8za3oM4cJ

I didn't move into try file receiving functionality, however I hope it is also working properly. So far, this is all I know about file transferring via bluetooth using python.

Thursday, June 27, 2013

Using rtimer in Contiki for more accurate timing

In contiki programs, the usage of rtimer is important when we need a real-time functionality. While having different kinds of timers such as ctimer and etimer, the most accurate timing can be achieved by using rtimer. Recently had such a requirement where my program should have very accurate timing. So, I learned about rtimer and used it in my program. For the sake of remembering it, I'm writing down a simple program which use rtimer.

The program shown below is a modified version of the hellow-world program which is in /contiki-2.6/examples/hello-world directory. Therefore I can run it just by issuing the following command in terminal inside that directory.

make TARGET=cooja hello-world

1:  #include "contiki.h"  
2:  #include <stdio.h>  
3:  #include "sys/rtimer.h"  
4:  #define     PERIOD_T     5*RTIMER_SECOND  
5:    
6:  static struct rtimer my_timer;  
7:    
8:  PROCESS(hello_world_process, "Hello world process");  
9:  AUTOSTART_PROCESSES(&hello_world_process);  
10:    
11:  // the function which gets called each time the rtimer triggers  
12:  static char periodic_rtimer(struct rtimer *rt, void* ptr){  
13:    uint8_t ret;  
14:    rtimer_clock_t time_now = RTIMER_NOW();  
15:    
16:    printf("Hello from rtimer!!!\n");  
17:    
18:    ret = rtimer_set(&my_timer, time_now + PERIOD_T, 1,   
19:          (void (*)(struct rtimer *, void *))periodic_rtimer, NULL);  
20:    if(ret){  
21:     printf("Error Timer: %u\n", ret);  
22:    }  
23:    return 1;  
24:  }  
25:    
26:  PROCESS_THREAD(hello_world_process, ev, data)  
27:  {  
28:   PROCESS_BEGIN();  
29:    
30:   printf("Starting the application...\n");  
31:    
32:   periodic_rtimer(&my_timer, NULL);  
33:    
34:   while(1){             
35:    PROCESS_YIELD();  
36:   }  
37:   PROCESS_END();  
38:  }  

Our program will keep printing Hello from rtimer!!! as the output.

Saturday, June 15, 2013

Bluetooth Programming On Linux



Sometimes we need to write programs that run on a PC and communicate with an external bluetooth capable device such as a smartphone. In such cases we need some good programming library which provide the necessary capabilities to access bluetooth hardware components in our PC easily. While looking for a good programming library for this task I came across a library called Bluez. It seems it has been widely used for Bluetooth programming in linux based environments. So, I decided to take a look at it.

I tried it on a Ubuntu 12.04 system connected with a USB Bluetooth adaptor. First thing is to install the necessary packages. Give following commands to install those packages.

sudo apt-get install bluez
sudo apt-get install python-bluez

After these library packages completes the installation, we will first check whether our hardware setup works. Connect the bluetooth adaptor to the USB port and turn On bluetooth. I had some problems with the default bluetooth manager that comes with Ubuntu 12.04 as I mentioned in my previous post. Therefore I use Blueman bluetooth manager to turn on/off and do anything with bluetooth on my PC.

After turning bluetooth ON, first I checked whether every thing's fine by pairing my PC with a smartphone and sending and receiving some files. Then it's time to check our Bluez libray. Put the following code in the text editor and save as bluez_test.py somewhere in the file system.

1:  import bluetooth  
2:  target_name = "SHV-E210K"  
3:  target_address = None  
4:  nearby_devices = bluetooth.discover_devices()  
5:  for bdaddr in nearby_devices:  
6:    print bluetooth.lookup_name( bdaddr )  
7:    if target_name == bluetooth.lookup_name( bdaddr ):  
8:      target_address = bdaddr  
9:      break  
10:  if target_address is not None:  
11:    print "found target bluetooth device with address ", target_address  
12:  else:  
13:    print "could not find target bluetooth device nearby"  

Please note that the target name variable is set to the name of the external bluetooth device we are going to connect. "SHV-E210K" was the name of my smartphone for bluetooth connection. According to the program, it print the names of available Bluetooth devices around and check whether our target device is available.

Now go to the location of the file from terminal and issue following command to run the python program. 

sudo python bluez_test.py













If every thing is fine, it should print that target device is found just like the one shown above. That means simply our Bluez library is capable of accessing the Bluetooth adaptor and using it. Following link will be a good reference for learning to use Bluez library.

Reference:

Enjoy with Bluetooth  programming on Linux! :)

Wednesday, June 12, 2013

Problem of sending files from Android smartphones to Ubuntu 12.04 via Bluetooth

Recently I wanted to check a USB bluetooth adaptor on a Ubuntu 12.04 system. I plugged the adapter to machine and paired it with a Galaxy S3 smart-phone. Sending files from Ubuntu machine to smart-phone works fine with the default bluetooth application that comes with Ubuntu 12.04.  However when sending files from the phone to the machine, a failure message is shown in phone and Ubuntu system does not notice any incoming file from the paired device.

I searched in web and found that many people have faced this problem. I tried the solution suggested in this link [http://askubuntu.com/questions/211006/unable-to-transfer-file-via-bluetooth-from-android-phone]. According to that, instead of using default bluetooth application, I installed Blueman Bluetooth Manager from software center. Now, sending files from Ubuntu to Android and Android to Ubuntu works fine.

Friday, March 22, 2013

The NS-3 simulator

While the NS-2 is the most widely used simulator for research works in the literature, a newer simulator is now under rapid development. That is NS-3 simulator. Initially I thought NS-3 is a newer version of NS-2 but it is a misunderstanding. NS-3 is a complete new implementation from scratch to suit the requirements of modern network simulations.  It is said that NS-3 is more maintainable and easily extendable comparing to old NS-2 because of it's sophisticated design. Anyway in the future most probably NS-2 will go deprecated and NS-3 simulator will take the lead. Therefore it is better to have some hands on experiences in NS-3 simulator.

To try NS-3 simulator, I installed it on Ubuntu 12.04 LTS and tried some example applications. Since NS-3 is written completely on C++, it seems it is convenient to read though the source code and explore it's implementation comparing to NS-2 which is implemented using C++ and OTcl. In the following paragraphs I'm writing down the steps I followed to install and try NS-3 simulator.
Figure - 1











Download the latest release of NS-3 as a tarball file from the link - http://www.nsnam.org/releases/. Uncompress it to a new directory in your home directory and go in to it from a terminal. In the content of the uncompressed file you should see the file named as build.py which is going to be used for building our NS-3 source code.

Issue the following command to install some necessary packages before we build NS-3.

    sudo apt-get install build-essential

Then issue the following command to build NS-3.

    ./build.py --enable-examples --enable-tests

Now some processing will take place and finally it should say that 'build' finished successfully. Now move it to the ns-3.1x directory inside the uncompressed directory where you would find the file test.py. This script will be used to run some tests on NS-3 to make sure all the modules are working as expected. So, issued the following command to run those tests.

     ./test.py -c core

 After completing those tests successfully, we can try some example scripts in NS-3 to learn how to build and run scripts in NS-3. So, while staying in the  ns-3.1x directory, issue the following command to copy the hello-simulator script to a new place where we will try those examples.

    cp examples/tutorial/hello-simulator.cc scratch/myhello.cc

Now issue the following commands to build and run this script.

    ./waf

    ./waf --run myhello

So, in the terminal you should see the output of this myhello script as Hello Simulator. That is the very first example we ran on NS-3. Now issue the following command to copy another example scripts to our working place.

    cp examples/tutorial/first.cc scratch/my-point-to-point.cc

This example script creates a sever and a client in the simulation and send a packet from the client to the server. Server replies with the echo of the same packet it received from the client. If you open the file my-point-to-point.cc and it won't be hard to understand how it works.

1:  #include "ns3/core-module.h"  
2:  #include "ns3/network-module.h"  
3:  #include "ns3/internet-module.h"  
4:  #include "ns3/point-to-point-module.h"  
5:  #include "ns3/applications-module.h"  
6:  using namespace ns3;  
7:  NS_LOG_COMPONENT_DEFINE ("FirstScriptExample");  
8:  int  
9:  main (int argc, char *argv[])  
10:  {  
11:   LogComponentEnable ("UdpEchoClientApplication", LOG_LEVEL_INFO);  
12:   LogComponentEnable ("UdpEchoServerApplication", LOG_LEVEL_INFO);  
13:   NodeContainer nodes;  
14:   nodes.Create (2);  
15:   PointToPointHelper pointToPoint;  
16:   pointToPoint.SetDeviceAttribute ("DataRate", StringValue ("5Mbps"));  
17:   pointToPoint.SetChannelAttribute ("Delay", StringValue ("2ms"));  
18:   NetDeviceContainer devices;  
19:   devices = pointToPoint.Install (nodes);  
20:   InternetStackHelper stack;  
21:   stack.Install (nodes);  
22:   Ipv4AddressHelper address;  
23:   address.SetBase ("10.1.1.0", "255.255.255.0");  
24:   Ipv4InterfaceContainer interfaces = address.Assign (devices);  
25:   UdpEchoServerHelper echoServer (9);  
26:   ApplicationContainer serverApps = echoServer.Install (nodes.Get (1));  
27:   serverApps.Start (Seconds (1.0));  
28:   serverApps.Stop (Seconds (10.0));  
29:   UdpEchoClientHelper echoClient (interfaces.GetAddress (1), 9);  
30:   echoClient.SetAttribute ("MaxPackets", UintegerValue (1));  
31:   echoClient.SetAttribute ("Interval", TimeValue (Seconds (1.0)));  
32:   echoClient.SetAttribute ("PacketSize", UintegerValue (1024));  
33:   ApplicationContainer clientApps = echoClient.Install (nodes.Get (0));  
34:   clientApps.Start (Seconds (2.0));  
35:   clientApps.Stop (Seconds (10.0));  
36:   Simulator::Run ();  
37:   Simulator::Destroy ();  
38:   return 0;  
39:  }  

This simulation creates a topology as shown in the Figure-1. You can run this application similarly to the previous example by running the following commands.

    ./waf
    ./waf --run scratch/my-point-to-point

That's it. This is the beginning and I need to learn more things in NS-3 simulator in the near future. Most importantly I need to explore how we use it to simulate wireless networks.

Wednesday, March 20, 2013

System Programming: From Exciting World of Linux to (exciting ??) World of Windows

I was a Linux lover for a long time and used to do everything on Linux in my university academic works and research works back in Sri Lanka. However after moving to my new university, things changed so rapidly. Our research group is working mostly on Windows platform and therefore it is better for me to work on Windows just like others. In this way it's easier to work together.


So, now I'm running on Windows 7. Initially it wasn't easy for me to adapt but now I'm feeling comfortable on Windows. In this very first semester there is a course on System Programming on Windows. Well, I have done so much system programming on Linux but Windows is new to me. So, I decided to take the course and see.

In this course we are using the same C compiler which comes bundled with MS Visual Studio but without using the high-level application frameworks we are writing codes directly using Windows API. This way we get the understanding about the internal architecture and functionality of Windows OS.

Here's how we create a new copy of a file using Windows API. Of course I have used some standard C library functions (i.e- printf() ) inside the code but if we want we can write those functionality also using much lower Windows API.

1:  /* Basic cp file copy program                */  
2:  /* cpW file1 file2: Copy file1 to file2           */  
3:  #include <windows.h> /* Always required for Windows */  
4:  #include <stdio.h>  
5:  #define BUF_SIZE 256 /* Increase for faster copy */  
6:  int main(int argc, LPTSTR argv [])  
7:  {  
8:       HANDLE hIn, hOut; /* Input and output handles */  
9:       DWORD nIn, nOut; /* Number bytes transferred */  
10:       CHAR Buffer[BUF_SIZE];  
11:       if (argc != 3) {  
12:            printf ("Usage: cp file1 file2\n");  
13:            return 1;  
14:  }  
15:  /* Create handles for reading and writing. Many     */  
16:  /*     default values are used                */  
17:  hIn = CreateFile (argv[1], GENERIC_READ, 0, NULL,  
18:       OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);  
19:  if (hIn == INVALID_HANDLE_VALUE) {  
20:       printf ("Cannot open input file\n");  
21:       return 2;  
22:  }  
23:  hOut = CreateFile (argv[2], GENERIC_WRITE, 0, NULL,  
24:       CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);  
25:  if (hOut == INVALID_HANDLE_VALUE) {  
26:       printf ("Cannot open output file\n");  
27:       return 3;  
28:  }  
29:  /*     Input and output file handles are open.     */  
30:  /*     Copy file. Note end-of-file detection      */  
31:  while (ReadFile (hIn, Buffer, BUF_SIZE,     &nIn, NULL) && nIn > 0)  
32:       WriteFile (hOut, Buffer, nIn, &nOut, NULL);  
33:  /*     Deallocate resources, such as open handles */  
34:       CloseHandle (hIn); CloseHandle (hOut);  
35:       return 0;  
36:  }  

Save this file as cpW.c in somewhere in your home directory. Additionally create a text file (eg- file1.txt) in the same place with some content. Open the Visual Studio command prompt and go to the place where these files are saved. Issue the following command to compile the program.

               cl cpW.c

Now there should be a file as cpW.exe in that directory. You can use that executable to create a new copy of our text file. Let's do that by using following way.

               cpW file1.txt file2.txt

Now you will find the new text file file2.txt in the same directory with the same content of the first file. This is the very first program I had to write using Windows API. More interesting things will come ahead of time.

I will write those new things I learn on Windows API in the future.



Tuesday, March 5, 2013

Towards Intelligent Transportation Systems (ITS)

Day by day, the amount of vehicles in the roads is increasing. Proportionally to it, the amount of road side accidents and the traffic jams are increasing. Those traditional traffic controlling mechanisms, rules and regulations are unable to control this increasing issue anymore. This is where the need for intelligent transportation systems arise. We need smarter ways to coordinate vehicles on the road so that our transportation system becomes more efficient, safe and human friendly.

Vehicles mounted with sensors and wireless communication units are such a way towards implementing intelligent transportation systems. While moving on the road these vehicles can exchange valuable information to supplement safe and efficient driving. In addition to the vehicles, some base station units mounted in road sides can provide and gather information. These kinds of networks builds the new research field called Vehicular Ad-hoc Networks (VANET) which is a special case of the Mobile Ad-hoc Networks (MANET). VANETs differ from MANETs in various ways. One important aspect is the high mobility of nodes in vehicular networks since motor vehicles are moving so fast from each other on the road. VANETs differ from Wireless Sensor Networks (WSN) since VANET nodes virtually does not suffer from any resource constraint since power and hardware resources are easily available to nodes mounted in automobiles.

A key challenge faced by VANET researchers is how to provide communication links between vehicles as they are travelling very fast from each other on the road. As an example when two vehicles move to opposite directions passing each other at a high speed, the amount of time they are in each others wireless transmission range can be few seconds or less. Therefore if messages has to be passed from one to another, it should be done so quickly. But in traditional wireless networks, the connection establishment take some considerable time which is not acceptable in VANET scenarios. For example if the network uses IEEE 802.11 for communication, the two vehicles might not be able set up the connection before they go far away from the transmission ranges of each other.

On addressing these issues, researchers have made some improvements to the above standard which is considered as IEEE 802.11p and it is specifically designed to cope with high node mobility condition in VANETs. Another standard called IEEE 1609 is also have introduced which runs on top of IEEE 802.11p layer to provide further necessary functionality for IEEE 802.11p protocol. Altogether we call this WAVE (Wireless Access in Vehicular Environments) protocol. There are lot of active research going on in this area, so we can hope we will have VANET equipped automobiles in our roads in the near future.