Tag Archives: Raspberry Pi

Raspberry Pi – Tontec 3.5″ Screen Installation

Hello everyone,

today I want to show you how I set up my Tontec 3.5″ Screen on my Raspberry Pi B. I thought I should write about this in my blog since it took quite some research to get this screen up and running. Ok. Let´s start 🙂

Used Hardware:

  • Raspberry Pi B
  • Tontec 3.5″ Screen (I bought it from here.)

Used Software:

  • Raspbian Wheezy (You can download it from here.)

The first step is simple. Build the case and attach the screen to your Raspberry Pi. When you are done it should look like this:

tontec_raspberry_pi_screen
Now we will update the Raspbian Wheezy Operating System:

sudo apt-get update
sudo apt-get upgrade
sudo reboot

Now we will download and install a firmware update. To do this simply run the following commands and wait a few minutes:

sudo apt-get install rpi-update
REPO_URI=https://github.com/notro/rpi-firmware
sudo rpi-update
sudo reboot

The next step is to adjust the SPI and Overlay settings to our Tontec MZ61581 display:

sudo nano /boot/config.txt

Add the following code to the end of the file and hit save:

dtparam=spi=on
dtoverlay=mz61581
gpu_mem=128

Your config.txt file should now look like this:

# uncomment if you get no picture on HDMI for a default "safe" mode
#hdmi_safe=1

# uncomment this if your display has a black border of unused pixels visible
# and your display can output without overscan
#disable_overscan=1

# uncomment the following to adjust overscan. Use positive numbers if console
# goes off screen, and negative if there is too much border
#overscan_left=16
#overscan_right=16
#overscan_top=16
#overscan_bottom=16

# uncomment to force a console size. By default it will be display's size minus
# overscan.
#framebuffer_width=1280
#framebuffer_height=720

# uncomment if hdmi display is not detected and composite is being output
#hdmi_force_hotplug=1

# uncomment to force a specific HDMI mode (this will force VGA)
#hdmi_group=1
#hdmi_mode=1

# uncomment to force a HDMI mode rather than DVI. This can make audio work in
# DMT (computer monitor) modes
#hdmi_drive=2

# uncomment to increase signal to HDMI, if you have interference, blanking, or
# no display
#config_hdmi_boost=4

# uncomment for composite PAL
#sdtv_mode=2

#uncomment to overclock the arm. 700 MHz is the default.
#arm_freq=800

# for more options see http://elinux.org/RPi_config.txt
dtparam=spi=on
dtoverlay=mz61581
gpu_mem=128

Now we will install the necessary dependencies to set our Default Display to our Tontec Screen:

sudo apt-get install xserver-xorg-video-fbturbo

After you have successfully installed the dependencies you need to alter the following file:

sudo nano /usr/share/X11/xorg.conf.d/99-fbturbo.conf

All you need to do is to alter the following line:

Option "fbdev" "/dev/fb0"

To look like this:

Option "fbdev" "/dev/fb1"

This will switch the Default Display from HDMI to the Tontec Screen.

Here you can see how your 99-fbturbo.conf file should look like:

# This is a minimal sample config file, which can be copied to
# /etc/X11/xorg.conf in order to make the Xorg server pick up
# and load xf86-video-fbturbo driver installed in the system.
#
# When troubleshooting, check /var/log/Xorg.0.log for the debugging
# output and error messages.
#
# Run "man fbturbo" to get additional information about the extra
# configuration options for tuning the driver.

Section "Device"
Identifier "Allwinner A10/A13 FBDEV"
Driver "fbturbo"
Option "fbdev" "/dev/fb1"

Option "SwapbuffersWait" "true"
EndSection

The last step is to tell your Raspberry Pi to display the boot screen on your Tontec Screen. To do so edit the following file:

sudo nano /boot/cmdline.txt

Now add the below code before “rootwait“:

fbcon=map:10

Your cmdline.txt file should now look like this:

dwc_otg.lpm_enable=0 console=ttyAMA0,115200 kgdboc=ttyAMA0,115200 console=tty1 root=/dev/mmcblk0p2 rootfstype=ext4 elevator=deadline fbcon=map:10 rootwait

Now reboot your Raspberry Pi one last time:

sudo reboot

Now when your Raspberry Pi boots your screen should switch on and you should be able to see the boot screen on it.

tontec_raspberry_pi_screen_working

Well, that´s it. Your Tontec screen is now ready to use 🙂

If you want to have a look at my config files or the documentation of the screen I found online you can find them here.

I hope you liked my post and I hope to see you again next time 🙂

Sources:

https://www.raspberrypi.org/forums/viewtopic.php?f=63&t=45746&start=75

http://www.riess-group.de/2015/08/29/raspberry-pi-mit-35-zoll-touchscreen-auf-raspbian/ (german)

Advertisements
Tagged

Raspberry Pi – Send Mails

Hello everyone, today I want to show you how to setup your Raspberry Pi to send mails via Googles SMTP server (smtp.gmail.com). I struggled a bit with Googles security settings and wanted to let you know how to solve the problems I encountered easily.

Before we begin you should update your Raspberry Pi:

sudo apt-get update

Next install ssmtp and mailutils:

sudo apt-get install ssmtp
sudo apt-get install mailutils

Next we will save the current default ssmtp.conf Configuration file:

sudo mv /etc/ssmtp/ssmtp.conf /etc/ssmtp/ssmtp.conf.old

Now we will create a new ssmtp.conf Configuration file:

sudo nano /etc/ssmtp/ssmtp.conf

Now have a look at the Configuration below and replace username and password with your Account data:

root=username@gmail.com
mailhub=smtp.gmail.com:465
rewriteDomain=gmail.com
AuthUser=username@gmail.com
AuthPass=password
FromLineOverride=YES
UseTLS=YES

Important: If your password contains the character # your Configuration will not work since the character # is used to define comments in the Configuration file. (Source: http://ubuntuforums.org/showthread.php?t=1691878)

Now run the below command to send a mail via ssmtp:

ssmtp <RecipientMailAddress>
Subject: <YourSubject>
<YourMailText>

or you can use the below command to send a mail via mailutils:

echo "<YourMailText>" | mail -s "<YourSubject>" <RecipientMailAddress>

When you run the above ssmtp command to send your mail you will probably receive an error message like shown in the below screenshot:

send_mail_raspberry_authentication_failed

The error “ssmtp: Authorization failed (534 5.7.14 …” means that the security settings of your Google Mail Account do not allow ssmtp to send mails.

To solve this problem you need to alter the security settings of your Google Mail Account by turning on the “Access for less secure apps” setting.

You can find this setting here: https://www.google.com/settings/security/lesssecureapps

The settings page should now look like this:

send_mail_raspberry_access_less_secure_apps

Now try again to send a mail and it should work now without problems.
Well, that´s it. You should now be able to send mails from your Raspberry Pi.

I hope you liked my post and I hope to see you again next time 🙂

Sources:

http://www.raspberry-projects.com/pi/software_utilities/email/ssmtp-to-send-emails

http://ozzmaker.com/2012/12/03/send-email-from-the-raspberry-pi-or-linux-command-line-with-attachments/

http://ubuntuforums.org/showthread.php?t=1691878

https://support.google.com/accounts/answer/6010255?hl=en

https://www.google.com/settings/security/lesssecureapps

Tagged , ,

Raspberry Pi 2 – Windows 10 IOT Installation

Hello everyone, today I came across a great post on reddit which explains how to install Windows 10 IOT on your Raspberry Pi 2 in the most simple way I have seen so far. And I will show you how you can install the current Windows 10 IOT Build so you can lay your hands on this new topic as soon as possible 🙂

To download the new Windows 10 IOT you first need a Microsoft Account. Then click on this link to sign up on Microsoft Connect.

After you have successfully signed up for Microsoft Connect download the file “Windows_IoT_Core_RPI2_BUILD.zip“.

Now if you don´t have the Windows 10 Insider Preview Operating System installed on your computer or on a virtual machine, don´t worry: You don´t need it. The only thing yo need is a 7zip file called “DISM10074.7z” which you can download from here. (You can find the original post where this file comes from in this reddit thread here.)

Important: Don´t forget to unblock the “DISM10074.7z” file before you unzip it.

windows10iot_DISM10074_unblock

Next unzip the above zip files. In “Windows_IoT_Core_RPI2_BUILD” you will find the file “Flash.ffu“. Place this file into the “DISM10074” directory you extracted from the second zip file.

windows10iot_DISM10074

Next run PowerShell as Administrator and use the command “cd” to change into your “DISM10074” directory.

Now insert your Micro SD Card (at least 8GB) and start diskpart with the below command.

diskpart

Now find out the Disk number of your Micro SD card by using the below command:

list disk

Write down the Disk number of your Micro SD Card and exit diskpart.

exit

Now for the last step. Run the below command to write the Windows 10 IOT image to your Micro SD card:

Important: Replace the X of PhysicalDriveX with the number of your Disk before you run the below command.

.\dism.exe /Apply-Image /ImageFile:flash.ffu /ApplyDrive:\\.\PhysicalDriveX /SkipPlatformCheck

Wait for the command to complete. If it says “The operation completed successfully” everything went as expected.

Now you can close the PowerShell window and safely remove your Micro SD card and you are ready to use Windows 10 IOT.

Insert your Micro SD card into your Raspberry Pi 2 and plug in all necessary cables. Please keep in mind that the first boot will take some time so please be patient and don´t turn off your Raspberry Pi 2.

Well, that´s it. You can now start to explore Windows 10 IOT. Have fun!

I hope my post was interesting for you and I hope to see you again next time 🙂

Sources:

http://www.reddit.com/r/raspberry_pi/comments/34cad5/windows_10_iot_core_raspberry_pi_2_preview_live/

https://ms-iot.github.io/content/win10/SetupRPI.htm

https://www.raspberrypi.org/forums/viewtopic.php?f=56&t=98395

http://www.engadget.com/2015/04/30/windows-10-preview-raspberry-pi-2/

https://mariofraiss.wordpress.com/2015/05/02/setup-your-rasperry-pi-with-windows-10-iot-in-a-hyper-v-or-physical-environment/

Tagged ,

Raspberry Pi – Simple Garage Door Opener

Hello everyone. Today I want to show you how you can build your own Garage Door Opener which will allow you to open your Garage Door by simply pressing a button on a website. Pretty cool, huh? What we will basically do is setup a computer controlled push switch/button. A pretty good explanation can be found here.

Okay let´s do this. These are the things you will need:

  • A Raspberry Pi Model B (Plus power adapter, SD card and a LAN cable)
  • Raspbian wheezy as Operating System. You can download it from here.
  • A Raspberry Pi Relay (like this one here) or a transistor (It should work exactly the same but I did not try it out) – I recommend to use a relay since they are not very expensive and you can use them to work with higher currents and voltages. If you use a relay for this project you can reuse the same hardware to create an intelligent AC light switch without making any changes to the hardware. All you would need to do would be to change some fragments of the custom.html code from this post.

Hardware setup:

The hardware setup is pretty simple. Take you Raspberry Pi and connect it to you Raspberry Pi relay like this:

  • Connect one 5V Power Pin to the relay´s VCC Pin
  • Connect one Ground Pin to the relay´s GND Pin
  • Connect the GPIO 17 Pin (You can use any GPIO Pin you want but for this project I used GPIO Pin 17) to the relay´s IN1 Pin

RaspberryPi_Garage_Door_Pins

Now connect you relay to your Garage Door Control as if you would add a new push switch/button. Wire the relay like this:

  • Connect one wire from your Garage Door Control to the relay´s COM contact
  • Connect the other wire from your Garage Door Control to the relay´s NO contact

There are some great tutorials out there which explain how to set up electric Garage Door Openers (like this one here) so if you have trouble have a look at them. All Garage Door Openers work pretty much the same.

That´s it. You have finished the Hardware setup.

Software Setup:

Now the Software Setup. This will be easy too.

The first thing you need to do is to update your Raspberry Pi:

sudo apt-get update
sudo apt-get upgrade

Now you need to download WebIOPi:

wget https://webiopi.googlecode.com/files/WebIOPi-0.6.0.tar.gz

Unpack the archive file:

tar xvzf WebIOPi-0.6.0.tar.gz

Change into the newly created directory:

cd WebIOPi-0.6.0

And run the WebIOPi setup: (This will take some time)

sudo ./setup.sh

After the setup has finished you can run WebIOPi by running the following command:

sudo python -m webiopi

Now you should be able to access the WebIOPi web interface by entering the following URL into your Browser: (Default User: webiopi and Default Password: raspberry)

http://<IP-of-your-Raspberry-Pi>:8000/webiopi/

Now end the execution of WebIOPi by hitting Ctrl+C.

Since we want WebIOPi to be always available we need to run the below command to make sure that it will be started at boot:

sudo update-rc.d webiopi defaults

Now reboot your Raspberry Pi:

sudo reboot

If you can access WebIOPi´s web interface after the reboot everything is working correctly.

The next thing I did was to create a directory where I store my custom made code for my project:

sudo mkdir /usr/share/webiopi/htdocs/custom

And here is my code:


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content = "height = 300, width = 300, user-scalable = no, initial-scale = 1, maximum-scale = 1" />
<title>Garage Door Opener</title>
<script type="text/javascript" src="/webiopi.js"></script>
<script type="text/javascript">

webiopi().ready(function() {
content = $("#content");
});

function setGPIO17()
{
webiopi().setFunction(17,"OUT");
sleep(1000);
webiopi().setFunction(17,"IN");
}

function changeButtonPressed()
{
document.getElementById('PowerButton').src="power_on.jpg";
}

function changeButtonReleased()
{
document.getElementById('PowerButton').src="power_off.jpg";
}

function RunFunctions()
{
changeButtonPressed();
setGPIO17();
setTimeout(changeButtonReleased, 500);
}

function sleep(milliseconds)
{
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds)
{
break;
}
}
}

</script>
</head>
<body bgcolor="#191f2f">
<div id="content" align="center">
<font face="verdana" color="white">
<h1>Garage Door Opener</h1>
</font>
<input type="image" style="outline: 0" id="PowerButton" src="power_off.jpg" onclick="RunFunctions();">
</div>
</body>
</html>

So, how does the above code work? Well, it will set GPIO Pin 17 to OUT which will allow the electric current to power our relay. When the relay is powered it will short the contacts COM and NO closing the electric circuit resulting in our Garage Door to either open or close. Next the Javascript code will sleep for 1 second before setting the state of GPIO Pin 17 to IN again. This will result in our relay getting un-powered thus opening the electric circuit between COM and NO and closing the electric circuit between COM and NC.

To access the custom.html page simply enter the following URL into your Browser:

http://<IP-of-your-Raspberry-Pi>:8000/custom/custom.html

Well, that´s it. Now everything is ready to use. Pretty simple isn´t it?

Important:

Please make sure to secure the network you are using to access this control website and make sure to change the user and password of webiopi to make sure that only you can open your Garage Door and to prevent theft. Please take care not to damage your belongings when trying to set this up. I will not take responsibility for any damages or problems when you use these instructions to set this up for yourself. Do this on your own risk. And please try not to get hurt.

Of course you can have my source code as always. You can find it here.

I hope my post was useful for you and I hope to see you again next time 🙂

Sources:

http://www.themagpi.com/issue/issue-9/article/webiopi-raspberry-pi-rest-framework/

http://store.raspberrypi.com/projects/webiopi

http://mark-amos.blogspot.co.at/2013/02/web-connected-outlet-part-6.html

http://nayarweb.com/blog/2014/control-raspberry-pis-gpio-with-rest-qt-webiopi/

http://www.raspberrypi.org/forums/viewtopic.php?f=44&t=45965

https://code.google.com/p/webiopi/wiki/JAVASCRIPT#WebIOPi.setFunction(gpio,_func[,_callback])

http://www.phpied.com/sleep-in-javascript/

https://raspbeerypi.wordpress.com/2014/01/15/webiopi-smartphone-computer-verbindung/ (german)

http://www.instructables.com/id/Raspberry-Pi-Garage-Door-Opener/step5/Wire-the-Circuit-to-the-Pi/

Tagged

Raspberry Pi – VPN for all devices

Hello everyone. Today I want to show you how you can use your Raspberry Pi to tunnel all your traffic over a VPN connection. (I for example use this solution to watch my favorite TV shows on hulu. (I´m not an American and hulu is blocked outside the USA as you may know)). Ok let´s go.

The first thing you need to do is go to the VPNGate website and search for a VPN server. (one in the United States of America if you want to watch videos on hulu if you are located outside of the United States of America). If you found a VPN server download the ovpn file (OpenVPN) and store it on your Raspberry Pi.

Before we start you need to setup your Raspberry Pi as a Wireless Router like I explained in this post. After this is done we continue with the following:

To prevent issues update your Raspberry Pi first:

sudo apt-get update
sudo apt-get upgrade

Next install OpenVPN:

sudo apt-get install openvpn

Now move the ovpn file you downloaded by running the following command:

sudo mv <ovpn file> /etc/openvpn/openvpn.conf

Next we need to create a text file containing the user and password credentials:

sudo nano /etc/openvpn/user.txt

For a VPNGate VPN server enter vpn as username and vpn as password. Save the data in user.txt:

vpn
vpn

Next adjust the permissions of your user.txt file by running:

sudo chmod 755 /etc/openvpn/user.txt

Next we need to edit the openvpn.conf file (the ovpn file we downloaded earlier):

sudo nano /etc/openvpn/openvpn.conf

Now search for the following line:

#auth-user-pass

And replace it with this line to tell OpenVPN to use the user credentials provided in the user.txt file:

auth-user-pass user.txt

Now adjust the permissions of the openvpn.conf file by running:

sudo chmod 755 /etc/openvpn/openvpn.conf

Next reboot the Raspberry Pi. (It is faster than restarting the necessary services manually.)

sudo reboot

If you now have a look at your interfaces after your Raspberry Pi is has finished rebooting by running:

ifconfig

VPN_tunnel_interface

You will notice that you have a new interface called tun0. This is your new VPN tunnel interface.

If you followed my instructions from this post we need to do some clean up. Run the below command to clean up the iptables configuration:

sudo rm /etc/iptables.ipv4.nat

Next run the below commands to redirect all your traffic through the VPN tunnel interface:

sudo iptables -t nat -A POSTROUTING -o tun0 -j MASQUERADE
sudo iptables -A FORWARD -i tun0 -o wlan0 -m state --state RELATED,ESTABLISHED -j ACCEPT
sudo iptables -A FORWARD -i wlan0 -o tun0 -j ACCEPT

Save the iptables configuration by running:

sudo sh -c "iptables-save > /etc/iptables.ipv4.nat"

Now reboot your Raspberry Pi one last time:

sudo reboot

If you now connect to your Raspberry Pi´s wireless network all your traffic will be redirected through the VPN tunnel interface. (You can check if it works by using this website.)

Here is a picture from hulu without using this solution: (outside of the USA of course)

hulu_blocked

And here is a picture of hulu while using this solution:

hulu_unblocked

That´s it. It´s as simple as that. I hope you liked my post and I hope to see you again next time 🙂

And as always you can download all relevant files I used from here.

Update: Please keep in mind that the VPN relays on VPNGate are run by volunteers and that this means that your experience and the quality may vary. Please keep also in mind that hulu tries to blacklist all kinds of VPNs to make solutions like this useless so this solution might not work anymore in the future.

Sources:

http://www.vpngate.net/en/

http://alphaloop.blogspot.co.at/2014/01/raspberry-pi-as-vpn-wireless-access.html

http://serverfault.com/questions/544285/connection-reset-by-peer-when-im-trying-to-connect-to-server

https://awangga.wordpress.com/2014/03/12/setting-openvpn-client-using-vpngate-on-raspberry-pi/

Tagged

Raspberry Pi – Say Goodbye to Ads with Pi-hole

Hello everyone. Today I stumbled over a great way to get rid of nasty advertisements: The Pi-hole. I thought you might like this too so I wanted to share it. Here is how it works:

The Pi-hole uses a simple technique to get rid of advertisements: First you install a webserver on your Raspberry Pi which will serve an empty web page. Next you download the domain names of the advertisement servers you want to block and create DNS entries for them in the DNS server you install on your Raspberry Pi. And these DNS entries all point to your webserver which will serve you an empty page instead of advertisements. Pretty simple right? It´s practically DNS Spoofing to be specific. Now that we know how this works let´s get going.

Before you start with the steps below please have a look at this post (The IP addresses and configuration files I used in my current post are based on that post) and set up your Raspberry Pi as a wireless router. This way all your clients will be configured correctly by simply connecting to your Raspberry Pi´s wireless network.

The first step is to update your Raspberry Pi to avoid issues:

sudo apt-get update
sudo apt-get upgrade

Now install the webserver which will serve the empty html page for us. To do so run:

sudo apt-get install lighttpd

Now set the necessary permissions for the webserver.

sudo chown www-data:www-data /var/www
sudo chmod 755 /var/www

Next create a new directory called pihole and create and empty html page called index.html in it:

sudo mkdir -p /var/www/pihole
sudo touch /var/www/pihole/index.html

Next edit the lighttpd webservers configuration file.

sudo nano /etc/lighttpd/lighttpd.conf

Add the following line to the end of the file:

$HTTP["host"] =~ ".*" {
url.rewrite = (".*" => "pihole/index.html")
}

Next install the dnsutils and dnsmasq:

sudo apt-get install dnsutils dnsmasq

Stop the dnsmasq service till we finish our configuration.

sudo service dnsmasq stop

Next rename the dnsmasq.conf file (Do not delete it just to be safe):

sudo mv /etc/dnsmasq.conf /etc/dnsmasq.conf.bak

Now create a new dnsmasq.conf file:

sudo nano /etc/dnsmasq.conf

Add the following code to the file:

domain-needed
interface=wlan0
min-port=4096
cache-size=10000
log-queries
bogus-priv

We use the wlan0 interface since this is the interface where our clients will connect to.

Next you need to edit the resolv.conf file:

sudo nano /etc/resolv.conf

Replace all contents of the file with the following code: (Besides our own DNS server we add Googles DNS servers to resolve domain names)

nameserver 127.0.0.1
nameserver 8.8.8.8
nameserver 8.8.4.4

Next create the script which will get the DNS domain names from the ad servers we want to block:

sudo nano /usr/local/bin/gravity.sh

Here is the script:

#!/bin/bash
adListURL="http://pgl.yoyo.org/adservers/serverlist.php?hostformat=dnsmasq&showintro=0&mimetype=plaintext"
# Address to send ads to (your Raspberry Pi's IP)
piholeIP="192.168.0.1"
adFile="/etc/dnsmasq.d/adList.conf"
eventHorizion="/etc/dnsmasq.d/adList.conf.tmp"
curl $adListURL | sed "s/127\.0\.0\.1/$piholeIP/" > $eventHorizion
if [ -f "$eventHorizion" ];then
mv -f $eventHorizion $adFile
else
echo "Error building the ad list, please try again."
exit 1
fi
service dnsmasq restart

Set the necessary permissions for the script by running:

sudo chmod 755 /usr/local/bin/gravity.sh

Now run the script to get the DNS domain entries of the ad servers into your DNS server:

sudo /usr/local/bin/gravity.sh

Next set up a cronjob to update your DNS entries to keep your network ad-free. To do so run:

sudo crontab -e

Now add the following line to the file to run the update cronjob weekly:

@weekly /usr/local/bin/gravity.sh

Now we need to update the dhcp.conf file to redirect all clients DNS queries to our DNS server on our Raspberry Pi. Edit the file by running:

sudo nano /etc/dhcp/dhcp.conf

Now edit “option domain-name-servers” and make sure to replace the IP addresses with the IP address of your Raspberry Pi (mine is 192.168.0.1):

subnet 192.168.0.0 netmask 255.255.255.0 {
range 192.168.0.10 192.168.0.250;
option broadcast-address 192.168.0.255;
option routers 192.168.0.1;
default-lease-time 600;
max-lease-time 7200;
option domain-name "local-network";
option domain-name-servers 192.168.0.1;
}

That´s it. Now reboot your Raspberry Pi to apply the changes.

sudo reboot

Ok. Your Raspberry Pi Pi-hole is now ready to use.

Here is a picture of a website (http://winfuture.de/) with advertisements without the use of Pi-hole:

winfuture_not_ad_free

And here is a picture of the same website without advertisements by using Pi-hole:

winfuture_ad_free

And all that´s necessary is that you are connected to the wireless network of your Raspberry Pi to surf advertisement free. Pretty cool right?

I hope you liked my post and I hope to see you again next time 🙂

Sources:

http://jacobsalmela.com/raspberry-pi-block-ads-adtrap/

Tagged

Raspberry Pi – Use Proxy for “Caging” people

Hello everyone. Today I have something fun for you: You can use your Raspberry Pi Wireless Router (I showed you how to create one in my last post) to replace all pictures from the net with pictures of Nicolas Cage for people who are connected to your wireless network. (Believe me: “Caging” people is pretty funny. I used this prank on my brothers and it was hilarious 🙂 )

For this prank we will use a transparent proxy which replaces all pictures coming from the internet with a picture of Nicolas Cage using a perl script. Here are the steps to do this:

The first step is to update your Pi to avoid issues.

sudo apt-get update
sudo apt-get upgrade

Now install the Proxy software squid. It will help us to do the trick.

sudo apt-get install squid3

The next step is to edit the squid.conf file.

sudo nano /etc/squid3/squid.conf

Press Ctrl + W to search for “acl manager” and write the following line into the configuration file:

acl localnet src 192.168.0.0/24

The above line will define our wireless network (I called it “localnet”). Now search for “cachemgr” and add the following line to your configuration file:

http_access allow localnet

The above line will allow access to our proxy from our wireless network. Next search for “url_rewrite_program” and add the following line:

url_rewrite_program /var/www/scripts/images.pl

The above line will define the path to the script we will use to replace the pictures coming from the internet. (Don´t worry we will create the script soon.)

Next search for “http_port 3128” and add “transparent” to the line. This will turn our squid proxy into a transparent proxy (This way we will not need to configure proxy settings on the clients).

http_port 3128 transparent

Save the changes. And we are ready for the next step. (You can have a look at the full configuration file here.)

Next we need to install apache webserver to host our picture of Nicolas Cage.

sudo apt-get install apache2

Next create the following directories and place your picture into the content directory.

sudo mkdir /var/www/scripts
sudo mkdir /var/www/content

Now go to the scripts directory and create a perl script called images.pl.

cd /var/www/scripts
sudo nano images.pl

Have a look at the script below and modify it according to your environment if necessary: (I got the script from here)


#!/usr/bin/perl
########################################################################
# replaceImages.pl --- Squid Script (Replace every image) #
# g0tmi1k 2011-03-25 #
########################################################################
use IO::Handle;
use POSIX strftime;

$debug = 0; # Debug mode - create log file
$imageURL = "http://192.168.0.1/nicolas-cage.jpg";

$|=1;
$pid = $$;

if ($debug == 1) { open (DEBUG, '>>/tmp/replaceImages_debug.log'); }
autoflush DEBUG 1;

print DEBUG "########################################################################\n";
print DEBUG strftime ("%d%b%Y-%H:%M:%S\n",localtime(time()));
print DEBUG "########################################################################\n";
while (<>) {
chomp $_;
if ($debug == 1) { print DEBUG "Input: $_\n"; }
if ($_ =~ m/.*$imageURL/) {
print "$imageURL\n";
}
elsif ($_ =~ /(.*\.(gif|png|bmp|tiff|ico|jpg|jpeg|swf))/i) { # Image format(s)
print "$imageURL\n";
if ($debug == 1) { print DEBUG "Image Replaced: $_ \n"; }
}
else {
print "$_\n";
if ($debug == 1) { print DEBUG "Output: $_\n"; }
}
}

close (DEBUG);

After you saved the script you need to give it the execution right by running:

sudo chmod +x images.pl

Next you need to edit the default file of your apache webserver:

sudo nano /etc/apache2/sites-available/default

Have a look at the below script and modify the file according to your environment:


<VirtualHost *:80>
ServerAdmin webmaster@localhost
DirectoryIndex nicolas-cage.jpg

DocumentRoot /var/www/content
<Directory />
Options FollowSymLinks
AllowOverride None
</Directory>
<Directory /var/www/content>
Options Indexes FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from all
</Directory>

ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
<Directory "/usr/lib/cgi-bin">
AllowOverride None
Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
Order allow,deny
Allow from all
</Directory>

ErrorLog ${APACHE_LOG_DIR}/error.log

# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
LogLevel warn

CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

To redirect all http traffic to our transparent squid proxy we need to setup a new iptables rule. Create the rule by running:

sudo iptables -t nat -A PREROUTING -i wlan0 -p tcp --dport 80 -j REDIRECT --to-ports 3128

To save the above rule permanently run:

sudo sh -c "iptables-save > /etc/iptables.ipv4.nat"

The last step is to run the below command to start our squid proxy at boot:

sudo update-rc.d squid3 enable

That´s it. Reboot your Pi and you are ready to go.

Now if someone connects to your network and opens a website in his/her browser the result will look like this:

raspberry_pi_caging

As you can see it works as expected 🙂

I hope you liked my today´s post and I hope to see you again.

As always you can download all scripts I used in my post from here.

Sources:

http://wiki.ubuntuusers.de/Squid

http://xmodulo.com/squid-transparent-web-proxy-centos-rhel.html

http://failverse.com/creating-the-kittynet/

Tagged

Raspberry Pi – Turn your Pi into a Wireless Router

Hello everyone. Today I want to show you how you can turn your Raspberry Pi into a Wireless Router. I know there are many posts of this kind out there in the net but I wanted to show you the easiest solution I found on the net so far since it can be quite troublesome to find a matching Wireless adapter and to set up hostapd.

What do you need?

  • A Raspberry Pi Model B (plus power adapter, SD card and a LAN cable. And I recommend to set up SSH)
  • A Wireless adapter. I used the EDIMAX EW-7811UN Wireless USB Adapter I bought from Amazon (Link here) since it is quite cheap and it worked for me pretty well.
  • Raspbian wheezy as Operating System. You can download it from here.
  • A (wireless) router to download the necessary software packages.

Hardware Setup

Install the Raspbian wheezy Operating System on your SD card and put it into your Raspberry Pi. Next plug your LAN cable into your Raspberry Pi and connect the other end to your (wireless) router you use to access the internet. As mentioned above I would recommend to enable SSH on your Raspberry Pi so you can configure it without having a monitor, keyboard, etc. ready.

Turn your Pi into a wireless router

Now to the most interesting steps.

The first thing you need to do is to update your Raspberry Pi by running the following commands: (It´s always a good idea to update first to prevent issues with outdated versions, etc.)

sudo apt-get update
sudo apt-get upgrade

Next install the software packages for the DHCP server. (Ignore error messages if you receive some. They are normal since you haven´t configured the DHCP server yet.)

sudo apt-get install isc-dhcp-server

The next step is to install hostapd. Since our wireless adapter (EDIMAX EW-7811UN Wireless USB Adapter) needs a driver not supported by hostapd we need to download a custom version of hostapd (Thanks to this guy (http://jenssegers.be/) we have this simple solution. Please give him some credit for his work.). Simply run the following commands to install this custom version:

wget https://github.com/jenssegers/RTL8188-hostapd/archive/v1.1.tar.gz
tar -zxvf v1.1.tar.gz
cd RTL8188-hostapd-1.1/hostapd
sudo make
sudo make install

The above commands will take some time so please be patient.

Next we need to configure our DHCP server.

sudo nano /etc/dhcp/dhcpd.conf

Find the following lines and place a hashtag (#) in front of them to remove them from the configuration file:

option domain-name "example.org";
option domain-name-servers ns1.example.org, ns2.example.org;

Now search for the following line and remove the hashtag in front of it:

#authoritative;

Now go to the end of the file and add the following configuration:

subnet 192.168.0.0 netmask 255.255.255.0 {
range 192.168.0.10 192.168.0.250;
option broadcast-address 192.168.0.255;
option routers 192.168.0.1;
default-lease-time 600;
max-lease-time 7200;
option domain-name "local-network";
option domain-name-servers 8.8.8.8, 8.8.4.4;
}

You can alter the above configuration to fit your needs. The above configuration will set up your DHCP server to hand out IP addresses from 192.168.0.10 to 192.168.0.250 and will set the DNS server to Googles DNS servers 8.8.8.8 and 8.8.4.4.

Don´t forget to save the changes.

Next we need to configure on which Interface our DHCP server will hand out IP addresses. To do so run this command:

sudo nano /etc/default/isc-dhcp-server

Now search for:

INTERFACES=""

And add the name of your WLAN Interface to it like this: (My WLAN Interface is called “wlan0”)

INTERFACES="wlan0"

Next we need to assign a static IP address to out WLAN Interface. To do so run the following command:

sudo nano /etc/network/interfaces

Now assign the IP address you chose as “option routers” in the dhcpd.conf file (in our example: 192.168.0.1) to your WLAN Interface. Your file should now look like this:


auto lo

iface lo inet loopback
iface eth0 inet dhcp

#allow-hotplug wlan0
#iface wlan0 inet manual
#wpa-roam /etc/wpa_supplicant/wpa_supplicant.conf
#iface default inet dhcp

allow-hotplug wlan0

iface wlan0 inet static
address 192.168.0.1
netmask 255.255.255.0

Ok. Now we have finished setting up our DHCP server.

For the next step we need to setup hostapd. To do so run the following command:

sudo nano /etc/hostapd/hostapd.conf

Now search for ssid and wpa_passphrase and enter an SSID Name (for example: MyPi) and Password (for example: Password1) for your future wireless network. That´s it. We finished configuring hostapd.

Next we need to enable NAT. First we need to make sure that our Raspberry Pi will forward packages. To do so we run:

sudo nano /etc/sysctl.conf

And search for:

#net.ipv4.ip_forward=1

Remove the hashtag in front of the line and save your changes.

Run the following command to enable the forwarding immediately:

sudo sh -c "echo 1 > /proc/sys/net/ipv4/ip_forward"

Next we need to configure rules to forward all traffic from our WLAN Interface (wlan0) to our cable bound network (eth0) to make sure that Clients connected to our WLAN network can access the internet. To do so run the following commands:

sudo iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
sudo iptables -A FORWARD -i eth0 -o wlan0 -m state --state RELATED,ESTABLISHED -j ACCEPT
sudo iptables -A FORWARD -i wlan0 -o eth0 -j ACCEPT

Now run the following command to save the rules otherwise they will be lost when you turn off your Raspberry Pi:

sudo sh -c "iptables-save > /etc/iptables.ipv4.nat"

Ok. We finished configuring NAT. The last step is to make sure that all services and configurations we made above will be set up at start so that we do not need to run them every time we start our Raspberry Pi.

To automatically start our DHCP server at start run the following command:

sudo update-rc.d isc-dhcp-server enable

To automatically start hostapd at start run the following command:

sudo update-rc.d hostapd enable

Unfortunately I received the following error:

update-rc.d: using dependency based boot sequencing
update-rc.d: error: no runlevel symlinks to modify, aborting!

If you receive the same error run the following commands:

sudo ln -s /etc/init.d/hostapd /etc/rc2.d/S02hostapd
sudo update-rc.d hostapd enable

After I did that it worked for me. (Thanks to this thread I was able to solve this problem: http://www.raspberrypi.org/forums/viewtopic.php?f=63&t=37898)

Now we need to make sure that the traffic forwarding rules will also get loaded at start. To do so open the interfaces file by running:

sudo nano /etc/network/interfaces

Add the following line to the end of the file:

up iptables-restore < /etc/iptables.ipv4.nat

Ok. We are almost there. Now reboot your Raspberry Pi by running:

sudo reboot

Wait till your Raspberry Pi has rebooted. You should now find a new SSID with the name you chose (for example: MyPi). If everything worked you should be able to connect to it by entering your Password (for example: Password1) and you should be able to access the internet.

Well, that´s it. Your Raspberry Pi is now a wireless router. I hope you liked my post and I hope to see you again next time 🙂

By the way my configuration files are stored here if you want to have a look at them. And please have a look at the sources if you want to know more about this topic.

Sources:

http://raspberrypihq.com/how-to-turn-a-raspberry-pi-into-a-wifi-router/

http://www.raspberrypi.org/forums/viewtopic.php?f=63&t=37898

http://www.maketecheasier.com/set-up-raspberry-pi-as-wireless-access-point

http://www.daveconroy.com/turn-your-raspberry-pi-into-a-wifi-hotspot-with-edimax-nano-usb-ew-7811un-rtl8188cus-chipset/

http://elinux.org/RPI-Wireless-Hotspot

http://jacobsalmela.com/raspberry-pi-and-routing-turning-a-pi-into-a-router/

Tagged

Raspberry Pi – Automatic Number/License Plate Recognition (ANPR/ALPR)

Hello everyone. Today I want to show you how you can use your Raspberry Pi and Javaanpr to automatically extract a license plate number from a picture. You can use this technology to open your garage door for example.

To make this work run the following commands to update your Raspberry Pi and to install Java on it: (Oracle Java 7 JDK did the best job in my tests)

sudo apt-get update
sudo apt-get install oracle-java7-jdk

After the update and installation have finished you need to download Javaanpr.

Now use a test picture of a license plate and run the following command:

time java -jar javaanpr.jar -recognize -i test.jpg

Here is a screenshot of my test: (I used the Raspberry Pi B Model and I did not overclock it.)

raspberry_pi_javaanpr

It took about 10 seconds for Javaanpr to get the license plate number. Pretty fast in my opinion.

Well, that´s it. You can now use this knowledge for you projects. For example an automatic garage door opener. I hope you liked my post and I hope to see you next time 🙂

Update: I forgot to mention the following: To use Javaanpr all you need to do is to place the jar you downloaded from here into some directory on your Raspberry Pi and run the command

java -jar javaanpr.jar -recognize -i test.jpg

 to execute it. That´s all.

Sources:

http://object-network.blogspot.co.at/2014/02/seven-uses-of-raspberry-pi-camera.html

http://www.raspberrypi.org/forums/viewtopic.php?f=37&t=58257

http://javaanpr.sourceforge.net/

http://www.raspberrypi.org/forums/viewtopic.php?t=44080&p=374054

http://scruss.com/blog/2013/09/26/faster-java-on-raspberry-pi/

Tagged ,

Raspberry Pi – Turn your Raspberry Pi into a Webcam Server

Hello everyone. Today I will show you how you can turn your Raspberry Pi into a webcam server by using your Raspberry Pi and the Raspi cam.

Install your Raspi Cam:

Make sure that you place the cable correctly into its socket and start your Raspberry Pi.

Raspberry_Pi_camera

Important:

I used wheezy as Operating System. So the following commands might be a bit different on other Operating Systems.

Update your Pi:

The first step is to update your Pi. Do this by executing the following commands:

sudo apt-get update
sudo apt-get upgrade

Enable your camera:

This step is very important. You need to enable your camera first otherwise you will receive “Operation not permitted” errors later. To enable your camera do the following:

sudo raspi-config

Search for Enable Camera and choose Enable. If you are asked to reboot choose Yes.

Raspberry_Pi_enable_camera

Install video driver for Raspi cam:

Now we need to install a video driver so we can use our Raspi cam with motion. But before we can do that we need to add a new source into sources.list to get the video driver.

Open up sources.list:

sudo nano /etc/apt/sources.list

And add the following line:

deb http://www.linux-projects.org/listing/uv4l_repo/raspbian/ wheezy main

Now you must add the key so you can use your newly added source. Do this by running the following command:

wget http://www.linux-projects.org/listing/uv4l_repo/lrkey.asc && sudo apt-key add ./lrkey.asc

Next run an Update to make sure you get the newest driver version.

sudo apt-get update

Now run the below command to install the video driver:

sudo apt-get install uv4l uv4l-raspicam

To load the driver at boot you need to install the following extras:

sudo apt-get install uv4l-raspicam-extras

Now reboot.

sudo reboot

Install motion:

Next you need to install motion. Do this by running:

sudo apt-get install motion

Next we need to create a custom motion.conf file in our home directory:

nano motion.conf

Copy the following code into your motion.conf file: (You can download the file from here)

# Rename this distribution example file to motion.conf
#
# This config file was generated by motion 3.2.12

############################################################
# Daemon
############################################################

# Start in daemon (background) mode and release terminal (default: off)
daemon off

# File to store the process ID, also called pid file. (default: not defined)
process_id_file /var/run/motion/motion.pid 

############################################################
# Basic Setup Mode
############################################################

# Start in Setup-Mode, daemon disabled. (default: off)
setup_mode off

###########################################################
# Capture device options
############################################################

# Videodevice to be used for capturing  (default /dev/video0)
# for FreeBSD default is /dev/bktr0
videodevice /dev/video0

# v4l2_palette allows to choose preferable palette to be use by motion
# to capture from those supported by your videodevice. (default: 8)
# E.g. if your videodevice supports both V4L2_PIX_FMT_SBGGR8 and
# V4L2_PIX_FMT_MJPEG then motion will by default use V4L2_PIX_FMT_MJPEG.
# Setting v4l2_palette to 1 forces motion to use V4L2_PIX_FMT_SBGGR8
# instead.
#
# Values :
# V4L2_PIX_FMT_SN9C10X : 0  'S910'
# V4L2_PIX_FMT_SBGGR8  : 1  'BA81'
# V4L2_PIX_FMT_MJPEG   : 2  'MJPEG'
# V4L2_PIX_FMT_JPEG    : 3  'JPEG'
# V4L2_PIX_FMT_RGB24   : 4  'RGB3'
# V4L2_PIX_FMT_UYVY    : 5  'UYVY'
# V4L2_PIX_FMT_YUYV    : 6  'YUYV'
# V4L2_PIX_FMT_YUV422P : 7  '422P'
# V4L2_PIX_FMT_YUV420  : 8  'YU12'

# For the UV4L raspicam driver valid values are 2 and 8 (8 for higher fps)
v4l2_palette 8

# Tuner device to be used for capturing using tuner as source (default /dev/tuner0)
# This is ONLY used for FreeBSD. Leave it commented out for Linux
; tunerdevice /dev/tuner0

# The video input to be used (default: 8)
# Should normally be set to 0 or 1 for video/TV cards, and 8 for USB cameras
#input 8
input 8

# The video norm to use (only for video capture and TV tuner cards)
# Values: 0 (PAL), 1 (NTSC), 2 (SECAM), 3 (PAL NC no colour). Default: 0 (PAL)
norm 0

# The frequency to set the tuner to (kHz) (only for TV tuner cards) (default: 0)
frequency 0

# Rotate image this number of degrees. The rotation affects all saved images as
# well as mpeg movies. Valid values: 0 (default = no rotation), 90, 180 and 270.
rotate 0

# Image width (pixels). Valid range: Camera dependent, default: 352
width 640

# Image height (pixels). Valid range: Camera dependent, default: 288
height 480

# Maximum number of frames to be captured per second.
# Valid range: 2-100. Default: 100 (almost no limit).
framerate 100

# Minimum time in seconds between capturing picture frames from the camera.
# Default: 0 = disabled - the capture rate is given by the camera framerate.
# This option is used when you want to capture images at a rate lower than 2 per second.
minimum_frame_time 0

# URL to use if you are using a network camera, size will be autodetected (incl http:// ftp:// or file:///)
# Must be a URL that returns single jpeg pictures or a raw mjpeg stream. Default: Not defined
; netcam_url value

# Username and password for network camera (only if required). Default: not defined
# Syntax is user:password
; netcam_userpass value

# The setting for keep-alive of network socket, should improve performance on compatible net cameras.
# 1.0:         The historical implementation using HTTP/1.0, closing the socket after each http request.
# keep_alive:  Use HTTP/1.0 requests with keep alive header to reuse the same connection.
# 1.1:         Use HTTP/1.1 requests that support keep alive as default.
# Default: 1.0
; netcam_http 1.0

# URL to use for a netcam proxy server, if required, e.g. "http://myproxy".
# If a port number other than 80 is needed, use "http://myproxy:1234".
# Default: not defined
; netcam_proxy value 

# Set less strict jpeg checks for network cameras with a poor/buggy firmware.
# Default: off
netcam_tolerant_check off

# Let motion regulate the brightness of a video device (default: off).
# The auto_brightness feature uses the brightness option as its target value.
# If brightness is zero auto_brightness will adjust to average brightness value 128.
# Only recommended for cameras without auto brightness
auto_brightness off

# Set the initial brightness of a video device.
# If auto_brightness is enabled, this value defines the average brightness level
# which Motion will try and adjust to.
# Valid range 0-255, default 0 = disabled
brightness 0

# Set the contrast of a video device.
# Valid range 0-255, default 0 = disabled
contrast 0

# Set the saturation of a video device.
# Valid range 0-255, default 0 = disabled
saturation 0

# Set the hue of a video device (NTSC feature).
# Valid range 0-255, default 0 = disabled
hue 0

############################################################
# Round Robin (multiple inputs on same video device name)
############################################################

# Number of frames to capture in each roundrobin step (default: 1)
roundrobin_frames 1

# Number of frames to skip before each roundrobin step (default: 1)
roundrobin_skip 1

# Try to filter out noise generated by roundrobin (default: off)
switchfilter off

############################################################
# Motion Detection Settings:
############################################################

# Threshold for number of changed pixels in an image that
# triggers motion detection (default: 1500)
threshold 1500

# Automatically tune the threshold down if possible (default: off)
threshold_tune off

# Noise threshold for the motion detection (default: 32)
noise_level 32

# Automatically tune the noise threshold (default: on)
noise_tune on

# Despeckle motion image using (e)rode or (d)ilate or (l)abel (Default: not defined)
# Recommended value is EedDl. Any combination (and number of) of E, e, d, and D is valid.
# (l)abeling must only be used once and the 'l' must be the last letter.
# Comment out to disable
despeckle EedDl

# Detect motion in predefined areas (1 - 9). Areas are numbered like that:  1 2 3
# A script (on_area_detected) is started immediately when motion is         4 5 6
# detected in one of the given areas, but only once during an event.        7 8 9
# One or more areas can be specified with this option. (Default: not defined)
; area_detect value

# PGM file to use as a sensitivity mask.
# Full path name to. (Default: not defined)
; mask_file value

# Dynamically create a mask file during operation (default: 0)
# Adjust speed of mask changes from 0 (off) to 10 (fast)
smart_mask_speed 0

# Ignore sudden massive light intensity changes given as a percentage of the picture
# area that changed intensity. Valid range: 0 - 100 , default: 0 = disabled
lightswitch 0

# Picture frames must contain motion at least the specified number of frames
# in a row before they are detected as true motion. At the default of 1, all
# motion is detected. Valid range: 1 to thousands, recommended 1-5
minimum_motion_frames 1

# Specifies the number of pre-captured (buffered) pictures from before motion
# was detected that will be output at motion detection.
# Recommended range: 0 to 5 (default: 0)
# Do not use large values! Large values will cause Motion to skip video frames and
# cause unsmooth mpegs. To smooth mpegs use larger values of post_capture instead.
pre_capture 0

# Number of frames to capture after motion is no longer detected (default: 0)
post_capture 0

# Gap is the seconds of no motion detection that triggers the end of an event
# An event is defined as a series of motion images taken within a short timeframe.
# Recommended value is 60 seconds (Default). The value 0 is allowed and disables
# events causing all Motion to be written to one single mpeg file and no pre_capture.
gap 60

# Maximum length in seconds of an mpeg movie
# When value is exceeded a new mpeg file is created. (Default: 0 = infinite)
max_mpeg_time 0

# Always save images even if there was no motion (default: off)
output_all off

############################################################
# Image File Output
############################################################

# Output 'normal' pictures when motion is detected (default: on)
# Valid values: on, off, first, best, center
# When set to 'first', only the first picture of an event is saved.
# Picture with most motion of an event is saved when set to 'best'.
# Picture with motion nearest center of picture is saved when set to 'center'.
# Can be used as preview shot for the corresponding movie.
output_normal off

# Output pictures with only the pixels moving object (ghost images) (default: off)
output_motion off

# The quality (in percent) to be used by the jpeg compression (default: 75)
quality 75

# Output ppm images instead of jpeg (default: off)
ppm off

############################################################
# FFMPEG related options
# Film (mpeg) file output, and deinterlacing of the video input
# The options movie_filename and timelapse_filename are also used
# by the ffmpeg feature
############################################################

# Use ffmpeg to encode mpeg movies in realtime (default: off)
ffmpeg_cap_new off

# Use ffmpeg to make movies with only the pixels moving
# object (ghost images) (default: off)
ffmpeg_cap_motion off

# Use ffmpeg to encode a timelapse movie
# Default value 0 = off - else save frame every Nth second
ffmpeg_timelapse 0

# The file rollover mode of the timelapse video
# Valid values: hourly, daily (default), weekly-sunday, weekly-monday, monthly, manual
ffmpeg_timelapse_mode daily

# Bitrate to be used by the ffmpeg encoder (default: 400000)
# This option is ignored if ffmpeg_variable_bitrate is not 0 (disabled)
ffmpeg_bps 500000

# Enables and defines variable bitrate for the ffmpeg encoder.
# ffmpeg_bps is ignored if variable bitrate is enabled.
# Valid values: 0 (default) = fixed bitrate defined by ffmpeg_bps,
# or the range 2 - 31 where 2 means best quality and 31 is worst.
ffmpeg_variable_bitrate 0

# Codec to used by ffmpeg for the video compression.
# Timelapse mpegs are always made in mpeg1 format independent from this option.
# Supported formats are: mpeg1 (ffmpeg-0.4.8 only), mpeg4 (default), and msmpeg4.
# mpeg1 - gives you files with extension .mpg
# mpeg4 or msmpeg4 - gives you files with extension .avi
# msmpeg4 is recommended for use with Windows Media Player because
# it requires no installation of codec on the Windows client.
# swf - gives you a flash film with extension .swf
# flv - gives you a flash video with extension .flv
# ffv1 - FF video codec 1 for Lossless Encoding ( experimental )
# mov - QuickTime ( testing )
ffmpeg_video_codec swf

# Use ffmpeg to deinterlace video. Necessary if you use an analog camera
# and see horizontal combing on moving objects in video or pictures.
# (default: off)
ffmpeg_deinterlace off

############################################################
# Snapshots (Traditional Periodic Webcam File Output)
############################################################

# Make automated snapshot every N seconds (default: 0 = disabled)
snapshot_interval 0

############################################################
# Text Display
# %Y = year, %m = month, %d = date,
# %H = hour, %M = minute, %S = second, %T = HH:MM:SS,
# %v = event, %q = frame number, %t = thread (camera) number,
# %D = changed pixels, %N = noise level, \n = new line,
# %i and %J = width and height of motion area,
# %K and %L = X and Y coordinates of motion center
# %C = value defined by text_event - do not use with text_event!
# You can put quotation marks around the text to allow
# leading spaces
############################################################

# Locate and draw a box around the moving object.
# Valid values: on, off and preview (default: off)
# Set to 'preview' will only draw a box in preview_shot pictures.
locate off

# Draws the timestamp using same options as C function strftime(3)
# Default: %Y-%m-%d\n%T = date in ISO format and time in 24 hour clock
# Text is placed in lower right corner
text_right %Y-%m-%d\n%T-%q

# Draw a user defined text on the images using same options as C function strftime(3)
# Default: Not defined = no text
# Text is placed in lower left corner
; text_left CAMERA %t

# Draw the number of changed pixed on the images (default: off)
# Will normally be set to off except when you setup and adjust the motion settings
# Text is placed in upper right corner
text_changes off

# This option defines the value of the special event conversion specifier %C
# You can use any conversion specifier in this option except %C. Date and time
# values are from the timestamp of the first image in the current event.
# Default: %Y%m%d%H%M%S
# The idea is that %C can be used filenames and text_left/right for creating
# a unique identifier for each event.
text_event %Y%m%d%H%M%S

# Draw characters at twice normal size on images. (default: off)
text_double off

############################################################
# Target Directories and filenames For Images And Films
# For the options snapshot_, jpeg_, mpeg_ and timelapse_filename
# you can use conversion specifiers
# %Y = year, %m = month, %d = date,
# %H = hour, %M = minute, %S = second,
# %v = event, %q = frame number, %t = thread (camera) number,
# %D = changed pixels, %N = noise level,
# %i and %J = width and height of motion area,
# %K and %L = X and Y coordinates of motion center
# %C = value defined by text_event
# Quotation marks round string are allowed.
############################################################

# Target base directory for pictures and films
# Recommended to use absolute path. (Default: current working directory)
target_dir /home/pi

# File path for snapshots (jpeg or ppm) relative to target_dir
# Default: %v-%Y%m%d%H%M%S-snapshot
# Default value is equivalent to legacy oldlayout option
# For Motion 3.0 compatible mode choose: %Y/%m/%d/%H/%M/%S-snapshot
# File extension .jpg or .ppm is automatically added so do not include this.
# Note: A symbolic link called lastsnap.jpg created in the target_dir will always
# point to the latest snapshot, unless snapshot_filename is exactly 'lastsnap'
snapshot_filename %v-%Y%m%d%H%M%S-snapshot

# File path for motion triggered images (jpeg or ppm) relative to target_dir
# Default: %v-%Y%m%d%H%M%S-%q
# Default value is equivalent to legacy oldlayout option
# For Motion 3.0 compatible mode choose: %Y/%m/%d/%H/%M/%S-%q
# File extension .jpg or .ppm is automatically added so do not include this
# Set to 'preview' together with best-preview feature enables special naming
# convention for preview shots. See motion guide for details
jpeg_filename %v-%Y%m%d%H%M%S-%q

# File path for motion triggered ffmpeg films (mpeg) relative to target_dir
# Default: %v-%Y%m%d%H%M%S
# Default value is equivalent to legacy oldlayout option
# For Motion 3.0 compatible mode choose: %Y/%m/%d/%H%M%S
# File extension .mpg or .avi is automatically added so do not include this
# This option was previously called ffmpeg_filename
movie_filename %v-%Y%m%d%H%M%S

# File path for timelapse mpegs relative to target_dir
# Default: %Y%m%d-timelapse
# Default value is near equivalent to legacy oldlayout option
# For Motion 3.0 compatible mode choose: %Y/%m/%d-timelapse
# File extension .mpg is automatically added so do not include this
timelapse_filename %Y%m%d-timelapse

############################################################
# Live Webcam Server
############################################################

# The mini-http server listens to this port for requests (default: 0 = disabled)
webcam_port 8081

# Quality of the jpeg (in percent) images produced (default: 50)
webcam_quality 100

# Output frames at 1 fps when no motion is detected and increase to the
# rate given by webcam_maxrate when motion is detected (default: off)
webcam_motion on

# Maximum framerate for webcam streams (default: 1)
webcam_maxrate 30

# Restrict webcam connections to localhost only (default: on)
webcam_localhost off

# Limits the number of images per connection (default: 0 = unlimited)
# Number can be defined by multiplying actual webcam rate by desired number of seconds
# Actual webcam rate is the smallest of the numbers framerate and webcam_maxrate
webcam_limit 0

############################################################
# HTTP Based Control
############################################################

# TCP/IP port for the http server to listen on (default: 0 = disabled)
control_port 8080

# Restrict control connections to localhost only (default: on)
control_localhost off

# Output for http server, select off to choose raw text plain (default: on)
control_html_output on

# Authentication for the http based control. Syntax username:password
# Default: not defined (Disabled)
; control_authentication username:password

############################################################
# Tracking (Pan/Tilt)
############################################################

# Type of tracker (0=none (default), 1=stepper, 2=iomojo, 3=pwc, 4=generic, 5=uvcvideo)
# The generic type enables the definition of motion center and motion size to
# be used with the conversion specifiers for options like on_motion_detected
track_type 0

# Enable auto tracking (default: off)
track_auto off

# Serial port of motor (default: none)
; track_port value

# Motor number for x-axis (default: 0)
track_motorx 0

# Motor number for y-axis (default: 0)
track_motory 0

# Maximum value on x-axis (default: 0)
track_maxx 0

# Maximum value on y-axis (default: 0)
track_maxy 0

# ID of an iomojo camera if used (default: 0)
track_iomojo_id 0

# Angle in degrees the camera moves per step on the X-axis
# with auto-track (default: 10)
# Currently only used with pwc type cameras
track_step_angle_x 10

# Angle in degrees the camera moves per step on the Y-axis
# with auto-track (default: 10)
# Currently only used with pwc type cameras
track_step_angle_y 10

# Delay to wait for after tracking movement as number
# of picture frames (default: 10)
track_move_wait 10

# Speed to set the motor to (stepper motor option) (default: 255)
track_speed 255

# Number of steps to make (stepper motor option) (default: 40)
track_stepsize 40

############################################################
# External Commands, Warnings and Logging:
# You can use conversion specifiers for the on_xxxx commands
# %Y = year, %m = month, %d = date,
# %H = hour, %M = minute, %S = second,
# %v = event, %q = frame number, %t = thread (camera) number,
# %D = changed pixels, %N = noise level,
# %i and %J = width and height of motion area,
# %K and %L = X and Y coordinates of motion center
# %C = value defined by text_event
# %f = filename with full path
# %n = number indicating filetype
# Both %f and %n are only defined for on_picture_save,
# on_movie_start and on_movie_end
# Quotation marks round string are allowed.
############################################################

# Do not sound beeps when detecting motion (default: on)
# Note: Motion never beeps when running in daemon mode.
quiet on

# Command to be executed when an event starts. (default: none)
# An event starts at first motion detected after a period of no motion defined by gap
; on_event_start value

# Command to be executed when an event ends after a period of no motion
# (default: none). The period of no motion is defined by option gap.
; on_event_end value

# Command to be executed when a picture (.ppm|.jpg) is saved (default: none)
# To give the filename as an argument to a command append it with %f
; on_picture_save value

# Command to be executed when a motion frame is detected (default: none)
; on_motion_detected value

# Command to be executed when motion in a predefined area is detected
# Check option 'area_detect'.   (default: none)
; on_area_detected value

# Command to be executed when a movie file (.mpg|.avi) is created. (default: none)
# To give the filename as an argument to a command append it with %f
; on_movie_start value

# Command to be executed when a movie file (.mpg|.avi) is closed. (default: none)
# To give the filename as an argument to a command append it with %f
; on_movie_end value

# Command to be executed when a camera can't be opened or if it is lost
# NOTE: There is situations when motion doesn't detect a lost camera!
# It depends on the driver, some drivers don't detect a lost camera at all
# Some hang the motion thread. Some even hang the PC! (default: none)
; on_camera_lost value

############################################################
# Common Options For MySQL and PostgreSQL database features.
# Options require the MySQL/PostgreSQL options to be active also.
############################################################

# Log to the database when creating motion triggered image file  (default: on)
sql_log_image on

# Log to the database when creating a snapshot image file (default: on)
sql_log_snapshot on

# Log to the database when creating motion triggered mpeg file (default: off)
sql_log_mpeg off

# Log to the database when creating timelapse mpeg file (default: off)
sql_log_timelapse off

# SQL query string that is sent to the database
# Use same conversion specifiers has for text features
# Additional special conversion specifiers are
# %n = the number representing the file_type
# %f = filename with full path
# Default value:
# insert into security(camera, filename, frame, file_type, time_stamp, text_event) values('%t', '%f', '%q', '%n', '%Y-%m-%d %T', '%C')
sql_query insert into security(camera, filename, frame, file_type, time_stamp, event_time_stamp) values('%t', '%f', '%q', '%n', '%Y-%m-%d %T', '%C')

############################################################
# Database Options For MySQL
############################################################

# Mysql database to log to (default: not defined)
; mysql_db value

# The host on which the database is located (default: localhost)
; mysql_host value

# User account name for MySQL database (default: not defined)
; mysql_user value

# User password for MySQL database (default: not defined)
; mysql_password value

############################################################
# Database Options For PostgreSQL
############################################################

# PostgreSQL database to log to (default: not defined)
; pgsql_db value

# The host on which the database is located (default: localhost)
; pgsql_host value

# User account name for PostgreSQL database (default: not defined)
; pgsql_user value

# User password for PostgreSQL database (default: not defined)
; pgsql_password value

# Port on which the PostgreSQL database is located (default: 5432)
; pgsql_port 5432

############################################################
# Video Loopback Device (vloopback project)
############################################################

# Output images to a video4linux loopback device
# The value '-' means next available (default: not defined)
; video_pipe value

# Output motion images to a video4linux loopback device
# The value '-' means next available (default: not defined)
; motion_video_pipe value

##############################################################
# Thread config files - One for each camera.
# Except if only one camera - You only need this config file.
# If you have more than one camera you MUST define one thread
# config file for each camera in addition to this config file.
##############################################################

# Remember: If you have more than one camera you must have one
# thread file for each camera. E.g. 2 cameras requires 3 files:
# This motion.conf file AND thread1.conf and thread2.conf.
# Only put the options that are unique to each camera in the
# thread config files.
; thread /usr/local/etc/thread1.conf
; thread /usr/local/etc/thread2.conf
; thread /usr/local/etc/thread3.conf
; thread /usr/local/etc/thread4.conf

Next adjust the permissions of your motion.conf file:

sudo chmod 777 motion.conf

Run motion at Boot:

To automatically start motion when you reboot your Pi you need to create a custom script. I called mine “start_motion.sh”. Do the following:

Create a new file called “start_motion.sh” in your home directory:

nano start_motion.sh

Add the following code to your “start_motion.sh” file:

#!/bin/bash
unset LD_PRELOAD
export LD_PRELOAD=/usr/lib/uv4l/uv4lext/armv6l/libuv4lext.so
exec motion -c ./motion.conf

And adjust the permissions of your script:

sudo chmod 777 start_motion.sh

Next you need to use crontab to run your script at boot. Run the following command:

crontab -e

And add the following line at the end of the file:

@reboot /home/pi/start_motion.sh

Next you need to enable crontab by running the following command:

sudo update-rc.d cron defaults

Now reboot your Raspberry Pi once more:

sudo reboot

When your Pi has rebooted successfully you will notice that the LED of your Raspi cam has turned on. Your webcam server is now ready to use.

To access your Pi´s video stream open up your Browser (I used Firefox. It did not work on Chrome and Internet Explorer for me.) and enter the following:

http://<IP address of your Raspberry Pi>:8081

You will now see what your Raspi cam sees. You can tune the video stream by altering the motion.conf file we created earlier.

That´s it. You now have a simple webcam server you can use to monitor your flat, etc.

I hope my post was interesting for you and I hope to see you next time.

And as always you can download the scripts I used in this post from here.

Sources:

http://www.karesyk.de/raspicam-webcam-server/ (german)

http://www.linux-projects.org/modules/sections/index.php?op=viewarticle&artid=14

http://www.linux-projects.org/modules/sections/index.php?op=viewarticle&artid=16

https://bbs.archlinux.org/viewtopic.php?id=81295

http://www.cyberciti.biz/faq/linux-execute-cron-job-after-system-reboot/

http://stackoverflow.com/questions/17131249/how-to-solve-bad-interpreter-no-such-file-or-directory

http://programmaticponderings.wordpress.com/2013/01/01/remote-motion-activated-web-based-video-surveillance-with-raspberry-pi/

Tagged ,