Send Email when IP Address Changes

I have a ubuntu linux box in my office that I occasionally access from home. But unfortunately its IP address is constantly changing due to the dynamic IP allocation policy. Here’s how I set up a “daemon” that will send myself an email upon the change of the machine’s IP address.

1. Setup Gmail and sSMTP

This time we are using sSMTP because it’s easy, and Gmail because it’s free.

I would prefer to create a new Gmail account specific only for this purpose. Use your creativity to create long and obfuscated password, e.g. with mkpasswd -m sha-512 yOuRp4ssW0rD you can get a long string which is should be very nice for password.

Next, install sSMTP and its mail “client”:

sudo apt-get install ssmtp mailutils

Then edit the config file at /etc/ssmtp/ssmtp.conf:

root=youremail@gmail.com

mailhub=smtp.gmail.com:587
AuthUser=youremail@gmail.com
AuthPass=yOuRfUnKyP4ssWorD
UseTLS=YES
UseSTARTTLS=YES
AuthMethod=LOGIN

sSMTP is not a daemon, so don’t worry about starting the service or such.

Next, test your setup:

echo "test message" | mail -s "testing ssmtp" yourothermail@gmail.com

2. The Script

This time we use Bash, because you might not realize that you’re already fluent with Bash.

#!/bin/bash
# check and send ip address to email

MYIP=`ifconfig eth0 | grep 'inet addr'| awk '{print $2}' | cut -d ':' -f 2`;
TIME=`date`;

LASTIPFILE='/home/yourUserName/.last_ip_addr';
LASTIP=`cat ${LASTIPFILE}`;

if [[ ${MYIP} != ${LASTIP} ]]
then
        echo "New IP = ${MYIP}"
        echo "sending email.."
        echo -e "Hello\n\nTimestamp = ${TIME}\nIP = ${MYIP}\n\nBye" | \
                /usr/bin/mail -s "[INFO] New IP" yourothermail@gmail.com;
        echo ${MYIP} > ${LASTIPFILE};
else
        echo "no IP change!"
fi

Save this anywhere in your home folder. I personally have my own /home/username/bin/ to keep my small scripts and tools, and I have it in the system path ($PATH).

This script will save your current eth0‘s IP address to the hidden file .last_ip_addr. The next time this script is called, it will check the last IP address, if it’s different then it will notify to the given email address.

3. Cron
To make this run periodically, add the script as a cron job. More detail on cron you can STFG (Search The Fine Google).

crontab -e

Then add this to run the script every 30 minutes

*/30 * * * * /home/username/bin/emailipaddr.sh

Sources:

ROS + OpenNI2 + NiTE2

After weeks banging my head with OpenNI version 1.5.4 that comes with my ROS fuerte installation, I finally come to the conclusion that OpenNI 1.5.4 is highly frustrating, difficult to use, and has very low code readability. Or maybe it is just me.

It is time to migrate to OpenNI2, the latest version of the library that has been completely hauled with new architecture, with (much) better code readability. And another good thing about this release is that this will not mess the other version of OpenNI, so we can still work with both version in the same time.

The installation process is pretty straight forward. We can get the installation files after registering on OpenNI website. Then just simply run the install script from each folder.

Then, to use OpenNI2 and NiTE2 with ROS, we need to add some parameters to the CMakeLists.txt of our ROS project/package to link them with the libraries. Here’s mine:

cmake_minimum_required(VERSION 2.4.6)
include($ENV{ROS_ROOT}/core/rosbuild/rosbuild.cmake)

# Change two lines below according to your installation
#
set(OPENNI2_DIR /home/ariandy/src/OpenNI-Linux-x64-2.2/)
set(NITE2_DIR /home/ariandy/src/NiTE-Linux-x64-2.2/)
rosbuild_init()

#set the default path for built executables to the "bin" directory
set(EXECUTABLE_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/bin)
#set the default path for built libraries to the "lib" directory
set(LIBRARY_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/lib)

link_directories(${OPENNI2_DIR}/Redist)
include_directories(${OPENNI2_DIR}/Include)

link_directories(${NITE2_DIR}/Redist)
include_directories(${NITE2_DIR}/Include)

rosbuild_add_executable(testing src/main.cpp)
target_link_libraries(testing OpenNI2 NiTE2)

Now grab any sample program codes from the OpenNI2 or NiTE2 and put it inside our ROS package for testing. It should compile just fine.

There’s still one issue though. NiTE2 uses machine learning method for the human recognition and also skeleton fitting, which relies heavily on training data. It keeps the training data on NiTE2 folder inside NiTE-Linux-*/Samples/Bin folder. And somehow, when NiTE2 initializes it will look for the training data relative to the path (e.g. your executable is at /home/user, then it will look for /home/user/NiTE2/*). That is a bummer, since we can run ROS executable (node) regardless of the path and this NiTE2 thing defeats the purpose. Workaround is by navigating first to NiTE-Linux-*/Samples/Bin/ or NiTE-Linux-*/Redist/ then do rosrun your_package your_node, otherwise it won’t find the training data.

Running roscore and Launching ROS nodes as Background Process

I access my ROS running robot wirelessly using secure shell (SSH). To run my program, I have to first run all the startup scripts such as roscore and my robot’s driver. It’s kind of tedious to open a lot of shells just to keep this services on. And I can’t simply run this on background by using & operator because sometimes I need to check the node’s output.

So to keep it simple and neat, I made simple script to run roscore and robot driver on background, but still be able to check the outputs of this two (e.g. error messages).

First thing first, I like to have my own bin folder, to keep my own scripts.

cd ~
mkdir bin
echo "export PATH=$PATH:/home/ariandy/bin" >> ~/.bashrc
source ~/.bashrc

Then all this scripts will be kept inside this folder. If you need to run roscore and some nodes as a startup script, it will be better if you keep this scripts in /usr/local/bin/ folder.

#!/bin/bash
# file: youbot-roscore.sh

source /opt/ros/fuerte/setup.bash
export ROS_PACKAGE_PATH=$ROS_PACKAGE_PATH:/home/ariandy/youbot_driver:/home/ariandy/applications:/home/ariandy/ros_stacks

roscore

This is for my node:

#!/bin/bash
# file: youbot-oodl.sh

source /opt/ros/fuerte/setup.bash
export ROS_PACKAGE_PATH=$ROS_PACKAGE_PATH:/home/ariandy/youbot_driver:/home/ariandy/applications:/home/ariandy/ros_stacks

# this is my driver
roslaunch youbot_oodl youbot_oodl_driver.launch
# or your own node/launch script
#roslaunch {your_package} {your_thing}

The main tool for our topic is linux’ “screen“. Install it first if you don’t have it.

#!/bin/bash
# file: run-youbot-ros-startup.sh

echo "running roscore daemon.."
screen -dmS roscore youbot-roscore.sh
sleep 2
echo "running youbot oodl daemon"
screen -dmS oodl youbot-oodl.sh
echo "done. view with screen -ls"

The format is screen -dmS [any_name] [your_script]. The -dm argument will tell screen to run this session as a daemon. Then we use -S argument to give the session a name, so it will be easier for later. Please note that if your_script is not located on system path folder (e.g. /usr/bin/, /usr/local/bin/, etc.), you have to give the full path for the screen argument.

roscore needs some time (1-2 seconds) to reach its full operational state. That is why I give 2 seconds delay (with sleep 2) before running my node.

With this done, then we can run the things on the background:

ariandy@youbot$ run-youbot-ros-startup.sh 
running roscore daemon..
running youbot oodl daemon
done. view with screen -ls

To view what are the running sessions, call screen -ls

There are screens on:
	9285.oodl	(05/08/2013 05:01:50 PM)	(Detached)
	9224.roscore	(05/08/2013 05:01:49 PM)	(Detached)
2 Sockets in /var/run/screen/S-ariandy.

The format is [pid].[name]. Use this name if you want to go to each session: screen -r name.

When we’re inside the screen session, Ctrl-C will send a signal to the program we are running inside screen, makes it quitting and then the screen session closes. We don’t want this. What we want is to go back to our original shell session, and put the screen session back as background process. We do that by using key combination Ctrl-A-D, that is while holding Ctrl, press A, then press D.

WiFi Access Point with TP-Link TL-WN722n on Ubuntu 12.04

My system’s configuration:
– Ubuntu 12.04 Precise Pangolin
– TP-Link TL-WN722n USB WiFi Dongle

TO DO:
– Slow network performance, getting only 3-10Mbit/s
– With N-Mode activated, connection drops after a while

Sources:
http://forum.doozan.com/read.php?2,6300

Steps:

1. Network configuration

First edit /etc/network/interfaces, remove anything related to wlan0 (or whatever your device’s name) and add this lines to set the IP address of the wlan device as static:

auto wlan0
iface wlan0 inet static
    address 10.0.0.1
    network 10.0.0.0
    netmask 255.255.255.0
    broadcast 10.0.0.255

Although the configuration is already set, but in my system somehow it fails to set the IP address. So to make sure the setting will work, add ifup wlan0 inside /etc/rc.local file just before the exit 0:

#!/bin/sh -e
#
# rc.local

...

ifup wlan0

exit 0

2. hostapd installation

hostapd is the daemon who is responsible for broadcasting the access point and managing the connections. Rather than using hostapd package provided by Ubuntu repository, I would prefer to get the latest revision of hostapd from the developer’s git, then compile it manually. I do this because I want to enable the WiFi N-mode support.

But, installation from source will only give hostapd binaries, while we need several config files to run hostapd automatically as a service. I am no linux/Debian expert so I will just install hostapd from the repository, just to get the service configuration at /etc/default/, /etc/init.d/, and other places, then uninstall or remove the hostapd binaries.

git clone git://w1.fi/srv/git/hostap.git
cd hostap/hostapd

Then inside this folder, copy the defconfig file into a new file named .config, then open it using your favorite editor. For my setup I only need to activate (by uncommenting) the nl80211 driver and the N-Mode:

...
CONFIG_DRIVER_NL80211=y
...
CONFIG_IEEE80211N=y

Before installing hostapd, we need to install some dependencies:

sudo apt-get install libnl1 libnl1-dev

Then after that, compile and install hostapd:

make
sudo make install

The resulting binaries are hostapd and hostapd_cli located by default at /usr/local/bin/.

Now we can do a test run. Edit the config file /etc/hostapd/hostapd.conf:

interface=wlan0
ssid=MyAccessPoint
hw_mode=g
channel=6
auth_algs=1

# to enable N-Mode
# UPDATE: N-Mode is still problematic
#ieee80211n=1
#wmm_enabled=1

# config for WPA security
macaddr_acl=0
ignore_broadcast_ssid=0
wpa=2
wpa_passphrase=MyPassphrase123
wpa_key_mgmt=WPA-PSK
wpa_pairwise=TKIP
rsn_pairwise=CCMP

Make sure you don’t have trailing whitespaces, because hostapd is very sensitive. Now run hostapd:

sudo hostapd -dd /etc/hostapd/hostapd.conf

If nl80211 driver fails to start, quite possibly because NetworkManager is still managing the wireless network. Turn off the wlan management from NetworkManager by doing this on terminal (ref.):

sudo nmcli nm wifi off
sudo rfkill unblock wlan

If no problem exist, the output would be somehow like this:

random: Trying to read entropy from /dev/random
Configuration file: /etc/hostapd/hostapd.conf
nl80211: interface wlan0 in phy phy0
rfkill: initial event: idx=0 type=1 op=0 soft=0 hard=0
nl80211: Using driver-based off-channel TX
nl80211: Add own interface ifindex 4
nl80211: Set mode ifindex 4 iftype 3 (AP)
nl80211: Setup AP - device_ap_sme=0 use_monitor=1
nl80211: Create interface iftype 6 (MONITOR)
nl80211: New interface mon.wlan0 created: ifindex=7
nl80211: Add own interface ifindex 7
BSS count 1, BSSID mask 00:00:00:00:00:00 (0 bits)
nl80211: Regulatory information - country=CN
nl80211: 2402-2482 @ 40 MHz
nl80211: 5735-5835 @ 40 MHz
nl80211: Added 802.11b mode based on 802.11g information
Allowed channel: mode=1 chan=1 freq=2412 MHz max_tx_power=20 dBm
Allowed channel: mode=1 chan=2 freq=2417 MHz max_tx_power=20 dBm
Allowed channel: mode=1 chan=3 freq=2422 MHz max_tx_power=20 dBm
Allowed channel: mode=1 chan=4 freq=2427 MHz max_tx_power=20 dBm
Allowed channel: mode=1 chan=5 freq=2432 MHz max_tx_power=20 dBm
Allowed channel: mode=1 chan=6 freq=2437 MHz max_tx_power=20 dBm
Allowed channel: mode=1 chan=7 freq=2442 MHz max_tx_power=20 dBm
Allowed channel: mode=1 chan=8 freq=2447 MHz max_tx_power=20 dBm


....

nl80211: ifindex=4
nl80211: beacon_int=100
nl80211: dtim_period=2
nl80211: ssid - hexdump_ascii(len=8):
     59 6f 75 42 6f 74 41 50                           MyAccessPoint        
nl80211: hidden SSID not in use
nl80211: privacy=1
nl80211: auth_algs=0x1
nl80211: wpa_version=0x2
nl80211: key_mgmt_suites=0x2
nl80211: pairwise_ciphers=0x10
nl80211: group_cipher=0x10
wlan0: Event RX_MGMT (20) received
wlan0: Event TX_STATUS (18) received
wlan0: Event RX_MGMT (20) received
wlan0: Event RX_MGMT (20) received
wlan0: Event TX_STATUS (18) received
wlan0: Event RX_MGMT (20) received
wlan0: Event RX_MGMT (20) received
wlan0: Event TX_STATUS (18) received
wlan0: Event TX_STATUS (18) received
wlan0: Event RX_MGMT (20) received
wlan0: Event RX_MGMT (20) received
wlan0: Event RX_MGMT (20) received
wlan0: Event RX_MGMT (20) received
wlan0: Event RX_MGMT (20) received
wlan0: Event RX_MGMT (20) received

This lines

wlan0: Event TX_STATUS (18) received
wlan0: Event TX_STATUS (18) received
wlan0: Event RX_MGMT (20) received
wlan0: Event RX_MGMT (20) received

Will show up when another PC/client is probing or scanning our Access Point. This is a good sign. Now quit the test run by pressing Ctrl-C

The next step to configure the Ubuntu services so hostapd could start automatically upon booting. First, edit /etc/init.d/hostapd file, and make sure the variables are correct:

...
DAEMON_SBIN=/usr/local/bin/hostapd
DAEMON_CONF=/etc/hostapd/hostapd.conf
...

Second, edit /etc/default/hostapd

...
RUN_DAEMON="yes"
DAEMON_CONF="/etc/hostapd/hostapd.conf";
DAEMON_OPTS="-dd -t";
...

And now we can manage the hostapd through Ubuntu’s service, and it will run automatically upon booting.

sudo service hostapd restart

For more information about managing the service, this could be a good reading.

3. DHCP and DNS

For DHCP purpose we are going to use dnsmasq because of the simplicity of configuration. Please note that dnsmasq might be not suitable for big network.

But one thing worth noting is that Ubuntu 12.04 (Network-Manager) is using dnsmasq as DNS resolver. We have to disable it so we can use dnsmasq as our DHCP and “DNS” server. To do this, edit /etc/NetworkManager/NetworkManager.conf file and put a # (comment sign) in front of dns=dnsmasq so it will look like this:

...
#dns=dnsmasq
...

For more information about this, check this out.

Now we can configure dnsmasq to fit our need

sudo apt-get -y install dnsmasq

It will create default complete config file /etc/dnsmasq.conf, which is very useful for reference. For the sake of readability let’s just rename that file and make a new empty config file:

cd /etc/
sudo mv dnsmasq.conf dnsmasq.conf.orig
sudo touch dnsmasq.conf

Then edit the newly created file, and fill that with this basic configuration:

interface=wlan0
expand-hosts
domain=local
dhcp-range=10.0.0.10,10.0.0.20,24h
dhcp-option=3,10.0.0.1

Now we’re done. Restart the server/PC and make sure everything works. We can check the log at /var/log/syslog anytime to see our DHCP server in action.

Sometimes I got problem that dnsmasq is not running automatically upon booting, this could be because the runlevel of dnsmasq is called before the networking devices are up. The easiest hack is to put the service restart command in the /etc/rc.local:

#!/bin/sh -e
#
# rc.local

...

ifup wlan0

sleep 5
service dnsmasq restart

exit 0

Raspberry Pi Backup and Restore from Linux

0. Preparation

Before backing up the SD Card of Raspberry Pi, do clean up the system first to remove unneeded files such as package source codes and apt-get caches. You might be surprized by how much apt-get is keeping cache of downloaded packages. It was nearly 600MB for me. Cleaning this up would give you smaller backup image.

df -h
sudo apt-get clean
df -h

See how much space you free’d after cleaning apt-get’s cache.

I like to keep a piece of information, that tells me that the system is in the state of just being restored. I do that by either editing the MOTD (Message of The Day) or making an empty file on my home folder “THIS_IS_JUST_RESTORED”.

To back up the SD Card, first plug the SD Card into the SD Card reader of your laptop/PC that runs Linux. I use Ubuntu 12.04 Precise Pangolin. Then get any files that you need to copy, after that unmount the SD Card. Default Raspbian installation has 2 partitions made on the SD Card, so do not forget to unmount both. To check which folder is mounted to which device, use df -h and see the lines that start with /dev/mmcblk0p1 and /dev/mmcblk0p2. Then unmount the corresponding folders:

sudo umount /media/first_sd_partition
sudo umount /media/second_sd_partition

1. Backup

To back up the SD card, what we are about to do is making an image of the device, in this case both of the SD card partitions. For Linux, we have dd. I personally use dcfldd, an enhanced version of dd. It gives progress percentage, and also multiple on-the-fly hash calculation. To install dcfldd, in ubuntu simply:

sudo apt-get install dcfldd

If you want the backed up image to be as small as possible, you have to compress the image of the SD card. In Linux it is possible to compress an image which is currently being backed up (on-the-fly compression). With this you can save your hard disk space, because if you’re making an image without on-the-fly compression, you will require at least the same size as the SD card. If your have 8GB SD card, although only used partially, the resulting image from dd or dcfldd will be around 8GB in size.

To backup with on-the-fly compression:

sudo dcfldd bs=4M if=/dev/mmcblk0 hash=sha1 hashlog=./image.img.sha1sum | gzip > image.img.gz
sudo sync

And we’re done.

Everytime after you run dd or dcfldd, do not forget to call sudo sync to flush system buffers. I forgot to do this once and my system goes all crazy and weird.

If you want to do it the long way, you can do backup without compression:

sudo dcfldd bs=4M if=/dev/mmcblk0 of=./image.img hash=sha1 hashlog=./image.img.sha1sum
sudo sync

Then if you realize that it takes too much space, you can compress it anytime with gzip:

gzip image.img

Please note that it will take a while, since we’re dealing with gigabytes of data.

I also like to watch the image file grow in real time, so I do this:

watch ls -lh image.img*

2. Restore

If you have your image file already compressed, you can either uncompress and then restore, or uncompress while restore.

I find uncompressing and restoring in the same time (on-the-fly) is the most efficient way:

gunzip -c image.img.gz | sudo dcfldd bs=4M of=/dev/mmcblk0 hash=sha1 hashlog=./hash.log
sudo sync

Again, do not forget to flush the system buffer by calling sudo sync.

This hash thing, is for making sure that the backed up and restored image are consistent, not broken in any way which might happen during transfer/copying or upload. After the process finished, compare both of the hashes (image.img.sha1sum and hash.log) and make sure they are identical. You don’t need to read both files manually, just tell linux to do it:

diff -sq image.img.sha1sum hash.log

This will tell you either both files are identical or not.

If you are bored and have a lot of free space in your hard disk, you can do the restoring process in the long way by first uncompressing the image, then write it to the SD card:

gunzip image.img.gz
sudo dcfldd bs=4M if=./image.img of=/dev/mmcblk0 hash=sha1 hashlog=./hash.log
sudo sync

Raspberry Pi Rasbian + OpenCV

Sources:
http://opencv.willowgarage.com/wiki/InstallGuide%20%3A%20Debian
http://opencv.willowgarage.com/wiki/InstallGuide_Linux
http://mitchtech.net/raspberry-pi-opencv/
https://github.com/jayrambhia/Install-OpenCV/blob/master/Ubuntu/2.4/opencv2_4_3.sh
http://www.ozbotz.org/opencv-installation/

First of all, building OpenCV on Raspbian (Raspberry Pi) will take at least 4 hours. So consider doing this before you sleep so you can leave it compiling overnight.

And also if you’re doing all this through SSH, linux’s “screen” program will definitely very useful. It’s not installed by default, so do this:

sudo apt-get install screen

Click here for short and quick tutorial of how to use screen.

Now let’s cook!

  1. Prepare fresh installed Rasbian on Raspberry Pi.
  2. Run sudo apt-get update, then sudo apt-get upgrade, to make sure everything is updated.
  3. Copy and paste this into the terminal to install all the dependencies (NOTE: Some package names are altered, e.g. libavcodec52 is not available anymore, replaced by libavcodec53):

    sudo apt-get -y install build-essential
    sudo apt-get -y install cmake
    sudo apt-get -y install pkg-config
    sudo apt-get -y install libpng12-0 libpng12-dev libpng++-dev libpng3
    sudo apt-get -y install libpnglite-dev libpngwriter0-dev libpngwriter0c2
    sudo apt-get -y install zlib1g-dbg zlib1g zlib1g-dev
    sudo apt-get -y install libjasper-dev libjasper-runtime libjasper1
    sudo apt-get -y install pngtools libtiff4-dev libtiff4 libtiffxx0c2 libtiff-tools
    sudo apt-get -y install libjpeg8 libjpeg8-dev libjpeg8-dbg libjpeg-prog
    sudo apt-get -y install libavcodec53 libavcodec-dev libavformat53 libavformat-dev libavutil51 libavutil-dev libswscale2 libswscale-dev
    sudo apt-get -y install libgstreamer0.10-0-dbg libgstreamer0.10-0 libgstreamer0.10-dev
    sudo apt-get -y install libxine1-ffmpeg libxine-dev libxine1-bin
    sudo apt-get -y install libunicap2 libunicap2-dev
    sudo apt-get -y install libdc1394-22-dev libdc1394-22 libdc1394-utils
    sudo apt-get -y install swig
    sudo apt-get -y install python-numpy
    
    sudo apt-get -y install libpython2.6 python-dev python2.6-dev
    sudo apt-get -y install libjpeg-progs libjpeg-dev
    sudo apt-get -y install libgstreamer-plugins-base0.10-dev
    
    sudo apt-get -y install libqt4-dev libgtk2.0-dev
    
  4. We need to install other dependencies (x264, ffmpeg, and v4l) manually:
    sudo apt-get remove ffmpeg x264 x264-dev
    
    wget ftp://ftp.videolan.org/pub/videolan/x264/snapshots/x264-snapshot-20120528-2245-stable.tar.bz2
    tar -xvf x264-snapshot-20120528-2245-stable.tar.bz2
    cd x264-snapshot-20120528-2245-stable/
    ./configure --enable-shared --enable-pic
    make
    sudo make install
    cd ..
    
    wget http://ffmpeg.org/releases/ffmpeg-0.11.1.tar.bz2
    echo "Installing ffmpeg"
    tar -xvf ffmpeg-0.11.1.tar.bz2
    cd ffmpeg-0.11.1/
    ./configure --enable-gpl --enable-libfaac --enable-libmp3lame --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libtheora --enable-libvorbis --enable-libx264 --enable-libxvid --enable-nonfree --enable-postproc --enable-version3 --enable-x11grab --enable-shared --enable-pic
    make
    sudo make install
    cd ..
    
    wget http://www.linuxtv.org/downloads/v4l-utils/v4l-utils-0.8.8.tar.bz2
    tar -xvf v4l-utils-0.8.8.tar.bz2
    cd v4l-utils-0.8.8/
    make
    sudo make install
    cd ..
    
    
  5. Download desired version of OpenCV, in this example we’re using version 2.4.3. Unpack it anywhere you like.
    tar -xjvf  OpenCV-2.4.3.tar.bz2
    rm OpenCV-2.4.3.tar.bz2
    cd OpenCV-2.4.3/
    mkdir build
    cd build/
    
  6. Then to create standard configuration just follow this command:
    sudo cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local -D BUILD_NEW_PYTHON_SUPPORT=ON -D BUILD_EXAMPLES=ON .. | sudo tee ./CMAKE.log

    The part | sudo tee ./CMAKE.log is used for logging purpose. Normally I used redirection (>>) but it won’t work if you are trying to write inside a folder with no permission.

    You can use cmake-gui if it’s more comfortable for you, but it has to be run from a desktop environment (X Server is running). I did this over SSH so I don’t have the luxury of X.

  7. Then a configuration will be generated, make sure everything you need has no problem. For example see the first lines, it should be able to found the libraries needed, such as gtk+2.0, libavcodec, libavformat, etc.
    In my case cmake couldn’t find linux/videodev.h. According to this source, apparently there’s a change of structure for libv4l but OpenCV didn’t take that into account. In my installation I found the file libv4l1-videodev.h inside /usr/local/include, so we need to make a symlink to the location searched by OpenCV installation:

    sudo ln -s /usr/local/include/libv4l1-videodev.h /usr/include/linux/videodev.h
    

    TODO: there’s also one missing library, ffmpeg/avformat.h, but I’m not sure whether it’s necessary to fix or not.

  8. Now we’re ready to start the build. This process will take a long time to finish. So as said before, consider doing this before you sleep overnight. I do all this through SSH (I only have 1 keyboard and 1 mouse and I don’t want to back and forth plugging them between my laptop and the Raspberry Pi), so here’s where “screen” program is very useful. You can ignore this if you don’t use SSH:
    screen -S OpenCV_Installation

    Seems like nothing happened, but what actually happens is “screen” starts a new TTY/session, which you can build OpenCV, then you can “detach” it so it will run on background. After that you can quit the SSH session and turn off your laptop, without even bothering the building process.

    Now change user into root

    sudo su -

    then execute this as root

    make && make install
    

    or if you want some logging

    make | tee make.log && make install | tee make_install.log
    
  9. Now “detach” the compilation “screen” by pressing Ctrl+A then Ctrl+D consecutively. The building process will run in background. To check the process you have to get back to the “screen”, simply call in any session – either SSH or local
    screen -r

    If you use the logging with tee make.log and tee make_install.log as mentioned above, to check the status you can use tail

    tail -f make.log
    
  10. Sit back, watch some movie, or sleep. See you in 5 hours!

POST INSTALLATION SETUP

Now that you have energy from your sleep, let’s continue setting up the system to complete the installation.

  1. We have to tell the system that there are libraries available. Create a file named opencv.conf located in /etc/ld.so.conf.d/
    sudo touch /etc/ld.so.conf.d/opencv.conf
    

    Then using your favorite editor add this line into the file:

    /usr/local/lib
    

    After that:

    sudo ldconfig /etc/ld.so.conf.d
    
  2. Then we have to add this 2 lines into the file /etc/bash.bashrc
    PKG_CONFIG_PATH=$PKG_CONFIG_PATH:/usr/local/lib/pkgconfig
    export PKG_CONFIG_PATH
    

Testing

NOTE: Seems like my Raspberry Pi is unable to detect my cheap Logitech C170 yet. This is weird.

OpenCV comes with lots of pre-compiled sample programs, find it in build/bin folder. Some of them are drawing and kmeans. And if you have USB webcam you can check out lkdemo

./lkdemo

Press r then it will start tracking objects. Cool huh?

I also found this over here, to test camera capture using python.

import cv2

cv2.namedWindow("preview")
vc = cv2.VideoCapture(0)

if vc.isOpened(): # try to get the first frame
    rval, frame = vc.read()
else:
    rval = False

while rval:
    cv2.imshow("preview", frame)
    rval, frame = vc.read()
    key = cv2.waitKey(20)
    if key == 27: # exit on ESC
        break

Save it and run it with python:

python opencv_cam_test.py

For obvious reasons you can’t do this over SSH.

Making Raspberry Pi SD Card Backup in Linux

$ sudo dd if=/dev/mmcblk0 of=/path/to/image/file.img bs=4M

/dev/mmcblk0 argument depends on your system. In some system this argument could be /dev/sdX where X is the “device number” that points to the SD card. What is X could be known from:

$ sudo fdisk -l

Make sure you point dd to the device (e.g. /dev/mmcblk0, /dev/sdd), not the partition (e.g. /dev/mmcblk0p1, /dev/sdd1).

Making an image of 8GB SD card will take a long time, and dd won’t give any progress update whatsoever. It’s done, when it says it’s done (Walter White, Breaking Bad. LOL). It took 10 minutes (14.3MB/s) with my laptop. The only way to know the progress is by opening other terminal and check what is the size of the image file. The final size of the image file is same as the size of your SD card. OR you can use one front-end (?) of dd, namely dcfldd.

Before unplugging the SD card don’t forget to flush the buffer/cache:

$ sudo sync

Calculate the SHA1Sum of the image for future purposes. For huge file like this there’s a chance that it will get damaged when you do a lot of moving and transfer.

$ sha1sum file.img >> file.img.sha1sum

This will save the sha1sum into a file named file.img.sha1sum. After this you can compress it, transfer it, anything. Then, before restoring this image back into SD card, calculate the SHA1 once again and compare it to the original SHA1.

To compress the image use this:

$ cd /path/to/image
$ gzip file.img

This will “throw” the empty bits of the image and squeeze the file only with bits that actually contains data.

Restoring The Image

To restore the image first decompress the file

$ gunzip file.img.gz

then use dd

$ sudo dd if=/path/to/image/file.img of=/dev/mmcblk0 bs=4M

don’t forget to flush the cache by

$ sudo sync

TODO:
– sha1sum checking

Getting Started with Raspberry Pi

1. Get a SD Card, consult to compatibility page on http://elinux.org

2. Plug it in to linux machine.

3. sudo cfdisk /dev/mmcblk0

4. Delete every partition from there, don’t forget to select “write”.

5. Download Raspbian from here, check the sha1sum, then unzip. You’ll get a image file named something like 2012-12-16-wheezy-raspbian.img

6. Write it into your SD card, make sure you write it into the SD card device (e.g. /dev/mmcblk0, /dev/sdd), not the partition of the SD card (e.g. /dev/mmcblk0s1, /dev/sdd1).

$ sudo dd bs=4M if=./2012-12-16-wheezy-raspbian.img of=/dev/mmcblk0

Wait until it finishes. There will be no progress bar or indicator whatsoever, other than the SD card reader’s LED.

The Raspbian image is about 2GB in size. No matter how big your SD card, when you use it as it is after flashing it won’t be able to utilize the rest of the freespace. Then you need to expand/grow the partition. We do this later on below.

7. Flush the buffer (NOTE: at the first time I skipped this part, then random block reading error pops out everywhere. Segmentation fault, filesystem panic, etc. So make sure you do this.)

$ sudo sync

8. Remove the SD card, put it on the Raspberry Pi and fire it up!

9. First boot it will take some time, after then a blue screen (of life) will come up. It’s actually the “raspi-config” program.

10. Select the second option from the top to expand the free space of your SD card the next time Raspbian reboots. Configure other options as needed (other than expanding the partition, mostly not really necessary).

11. Select finish, then your Raspberry Pi will reboot.

12. Log in with username pi and default password raspberry (if you didn’t change it before in raspi-config). Check out the desktop environment by:

$ startx

Enjoy your Raspberry Pi.

 

How To Disable Ubuntu 12.04 Precise Pangolin Login Sound

One thing I hate from this release is that there is no easy way to turn off the annoying login sound. Hello ubuntu developer? Is it hard to make a tick box in the settings to enable/disable system sounds?

Anyway, while we’re waiting for the developers to fix this issue, we can work this thing out by renaming or removing the sound file of that login sound. Fire up Terminal, then:
$ cd /usr/share/sounds/ubuntu/stereo
$ sudo mv system-ready.ogg system-ready-OLD.ogg

With this, the system won’t be able to find the login sound file, hence it won’t play any login sound.

We can also use this trick to change the login sound with your own sound file, but first we have to convert our sound file into OGG format. The easiest way is using ffmpeg in terminal:
$ ffmpeg -i cool_sound.mp3 system-ready.ogg

Then copy the newly created system-ready.ogg into the directory /usr/share/sounds/ubuntu/stereo.

VLC’s Dynamic Range Compression Starter Settings

Sources:
Reddit
Lifehacker

Here’s the Dynamic Range Compression settings to make your movie more fluid, no sudden loud sound but still audible dialogs.

RMS/Peak 0
Attack 50 ms
Release 300 ms
Threshold -20 dB
Ratio 20.0 : 1
Knee Radius 1.0 dB
Makeup Gain 12.0 dB

We can’t change the settings with exact values, so just move the slider at least close to the values.

Slider can be precisely moved by pressing keyboard arrow up and down after clicking on  the slider. Thanks, Austin!

vlc_dynamic_range