Sound Control on Raspberry Pi

Introduction

Raspberry Pi has a build-in sound card, HDMI and phone jack output to play sound. If you connect to HDMI display or plug-in a headphone to it, you can play sound. The setup of sound feature is easy as described below.

raspberrypi-phone

Step 1. Install PiAUISuite sound software

$ sudo apt-get install git-core

$ git clone git://github.com/StevenHickson/PiAUISuite.git

$ ./InstallAUISite.sh

(be aware to answer pop-up question to continue installation)

Step 2. Setup Sound Device

$ modprobe snd_bcm2835

$ amixer controls
numid=3,iface=MIXER,name=’PCM Playback Route’
numid=2,iface=MIXER,name=’PCM Playback Switch’
numid=1,iface=MIXER,name=’PCM Playback Volume’

$ amixer cset numid=3 1

where 0 for auto-select, 1 for headphone, 2 for HDMI.

$ sudo amixer cset numid=1 60%

to set the volume between 0 – 100%, 0 for mute.

$ sudo amixer set PCM – 60%

Step 3. To Play Sound

$ sudo omxplayer voice.mp3

If omxplayer’s auto-detection of the correct audio output device fails, you can force output over hdmi with:

$ sudo omxplayer-o hdmivoice.mp3

or you can force output over the headphone jack with:

$ sudo omxplayer-o localvoice.mp3

Note: you should be able to play sound on VLC connection, too.

Reference Link:

Bonus:

You can install alsa to control sound. Make sure alsa-utils is installed and run alsamixer as below:

$ sudo apt-get install -y alsa-utils

$ alsamixer

Then use the F1-F6 keys and UI to push up the volume.

sound-control

Use the arrow keys to jack up the volume and quit.

To save what you changed in alsamixer as defaults, do:

sudo alsactl store 0

Pls consider to buy Headphone from Amazon as below link:

Build a Raspberry Pi Webcam Server for Motion Detection

Introduction

Raspberry Pi can be connected to a camera to capture picture and video in order to use it as a CCTV motion detection device, which I have described in my previous post. To further enhance the motion detection feature, we can build a Raspberry Pi Webcam Video Server for browsing from web. It is more effective to monitor environment from outside. In the following, I will describe the installation steps of a application call motionPie to build a web server.

The MotionPie Logo

1. Download & Format the SD Card

  1. Download the Motion Pie SD Card Image from the Motion Pie GitHub repository or my link <<HERE>>.
  2. You will need a formatting tool. Visit the SD Association’s website and download SD Formatter 4.0 for either Windows or Mac.
  3. Follow the instructions to install the formatting software.
  4. Insert your SD card into the computer or laptop’s SD card reader and check the drive letter allocated to it, e.g. I:/
  5. In SD Formatter, select the drive letter for your SD card (eg. I:/) and format

2. Install the Motion Pie Image onto the SD Card

  1. Download the Win32DiskImager.
  2. Now unzip the MotionPie ISO file so you can install it onto the Pi safely.
  3. Select the MotionPie ISO file and the drive letter your SD card is assigned (Eg. I:/)
  4. Confirm you have the correct details and click on Write.
  5. Once done you can safely remove your SD card from the computer.
win32diskimager-motionpie

Booting/Setting up MotionPie

Now we’re ready for boot up, so insert the SD Card, an Ethernet cord and the power cord. We will need to communicate to the Pi over the network rather than directly like I have done in most of the previous tutorials.

So now go ahead and boot the PI up and then we can move onto getting it setup correctly.

Setting up the Raspberry Pi Security Camera

Once the Pi has booted you will need to do the following:

  1. First we will need the IP or host name so we’re able to connect to the Pi.
    • If you’re using Windows simply go to network on the right hand side in the File Explorer.
    • You should see a computer names something like MP-xxxxxxx
    • Go to your browser and add this to your browser bar eg. http://MP-xxxxxxx
    • You should now have the Motion Pie interface up.
  2. Alternatively you can find out the IP of the Pi by going to your router. Since all routers are different I will not go into how this is done. Please refer to your manufactures manual.
  3. To login as the admin go to key symbol in the upper left corner. The username is admin and the password is blank, this can be changed later.
  4. You can access all the setting for the camera stream here. If you’re interested in altering these settings keep reading as I explain them as much as possible below.

picam_init

Now we should have a working security hub that we can configure! Require the security camera to be wireless? No problem! Require to alert you with an email? No problem! Read on more to find out what the settings do in Motion Pie.

How to setup multiple network Raspberry Pi security cameras.

If you want to run more than one Pi cameras it is pretty easy to set this up so you have all the streams under in one window. You can even add a stream that has been setup using the Raspberry Pi Webcam server tutorial.

  1. First click on the 3 lines with dots on them in the upper left hand corner.
  2. Now up in the upper left hand corner and click on the dropdown box and select add camera.
  3. In here you have four settings to set up.
  4. Device: This is allows you to select where the camera is located(network/local) and type. (Eg. motionEye, MJEPG camera)
  5. URL: This is the URL to the other network camera. Eg. http://othercamera:8080
  6. Username: This is the username to the camera device. (If no username/password required leave the fields blank)
  7. Password: This is the password for the username chosen above.
  8. Camera: Select the camera you wish to add.
motionpie-setup

Connecting to the surveillance outside your network

Now that you have your Raspberry Pi security cameras setup it might be worth considering allowing access to the central Pi so you can monitor your cameras elsewhere.

To do this simply head over to my guide on how to setup port forwarding and also how to setup dynamic DNS, you can find the guide at Raspberry Pi Dynamic DNS & Port Forwarding.

A few important bits of information you will need for the setting up the port forwarding.

  • The IP of your Raspberry Pi for example mine is 192.168.5.78
  • Internal port is 80.

Ensure you have also setup passwords on both the admin and the surveillance user to help avoid unwanted visitors.

Once setup should now be able to connect using your external IP address such as XX.XXX.XXX.XXX:80 (80 should be changed to something else, I would recommended changing it to avoid easy access for unwanted visitors)

Configuring the Settings in MotionPie

General Settings

In here you are able to set the administrator username and password. This account will have access to all the settings you’re seeing at the moment.

Surveillance username and password can also be set in here this can be used to just access the camera interface.

To view all the settings available to set turn the show advanced settings to on.

Wireless Network

Turn this on if you plan on connecting to the network via a wireless dongle. There are two things you will need to fill in here.

  1. Network Name – Enter the network name/SSID you wish to connect to in here.
  2. Network Key – Enter the network password/network key in here for the network you’re connecting to.

Once done you should be a able to disconnect the Ethernet cord and remain connected to the network.

Video Device

Under this menu you’re able to set certain settings regarding the Raspberry Pi camera device.

  1. Camera Name: Set this to whatever you would like the camera to be named. For example kitchen would work well for a camera in a kitchen.
  2. Camera Device: You’re unable to edit this one but this is the device name of the camera.
  3. Light Switch Detection: Enable this if you want sudden changes such as a light being switched on to not be treated as motion. (This will help prevent false positives)
  4. Automatic Brightness: This will enable software automatic brightness, this means the camera software will make adjustments for the brightness. You don’t need to activate this if your camera already handles this.
    • In here you change the brightness, contrast and saturation of the video of the camera.
  5. Video Resolution: Here you can set the video resolution of the camera. The higher the resolution the more room it will take up and the more bandwidth it will need to use in order to stream the footage. I set mine to 1280×800 and that seems to work perfectly fine.
  6. Video Rotation: You can rotate your video from the Raspberry Pi security if you’re finding that it is looking the wrong way.
  7. Frame Rate: This sets the amount of frames that will be sent be every second. The higher this is the smoother the video but again this will increase the storage used and bandwidth.

File Storage

Under this menu you can specify where you would like the files stored for the Raspberry Pi Security Camera. This can be a custom path on the Pi, the predetermined path or the network path.

Text Overlay

In here you can set the text overlay on the output of the camera. By default the left text reads the camera name and the right read the time stamp (Todays date and current time).

Video Streaming

This menu you’re able to set the video streaming options, this is the video you see in the browser.

  • Streaming Frame Rate: This is exactly the same as mentioned above under video device.
  • Streaming Quality: You can reduce the video streaming quality. This is good to reduce if you need to access the camera on a low bandwidth device often.
  • Streaming Image Resizing: Enable this if you want MotionPie to resize the images before being sent to a browser. (Not recommended on a Pi)
  • Streaming Port: This is the port that the device will listen to for connections looking to view the stream. Eg. http://motionpie:8081
  • Motion Optimization: This will reduce the frame rate whenever no motion is detected. This will save you bandwidth.

You can also see three URLs that can be used to access different footage. These URLs are very important if you have multiple cameras per Pi as each camera will have a unique port that you listen to the stream on.

Still Images

Here you can set the Raspberry Pi security camera to take still images whenever motion is triggered, during specific intervals or all the time.

Motion Detection

In here you activate the Raspberry Pi security camera motion detection that is included in the software. You are able to make adjustments to the settings here so that you can get better motion detection.

Motion Movies

In you here you can set the Pi to record movies whenever motion is detected

Motion Notifications

You’re able to set up email notifications, web hook notifications or even run a command whenever motion is detected. This will allow you to be notified whenever activity is detected on the cameras, perfect if they are monitoring areas with low traffic.

Working Schedule

Here you can set the days and the hours of operation you would like the system to be monitoring (If you leave this off then it is 24/7). This option is perfect if you only need it running during specific hours.

Summary

The Raspberry Pi security camera system is a great way to have multiple cameras hooked up both locally and over a network. All the extra setting motion pie provides allows you to have a  strong functioning security hub for your home, office or wherever you’re setting this up.

Information Source:

http://pimylifeup.com/raspberry-pi-security-camera/

Note:

In past, we often used “Motion” package (“sudo apt-get install motion”) for webserver, but this method doesn’t work on the Raspberry Pi 2.

Install OpenCV 3.0 for both Python 2.7+ and Python 3+ on your Raspberry Pi 2

Information source: http://www.pyimagesearch.com/2015/07/27/installing-opencv-3-0-for-both-python-2-7-and-python-3-on-your-raspberry-pi-2/

So if you’re interested in building awesome computer vision based projects like this, then follow along with me and we’ll have OpenCV 3.0 with Python bindings installed on your Raspberry Pi 2 in no time.

UPDATE: The tutorial you are reading now covers how to install OpenCV 3 with Python 2.7 and Python 3 bindings on Raspbian Wheezy. This tutorial works perfectly, but if you are looking to install OpenCV 2.4 on Raspbian Wheezy or OpenCV 3 on Raspbian Jessie, please see these tutorials:

The rest of this blog post will detail how to install OpenCV 3.0 for both Python 2.7 and Python 3+ on your Raspberry Pi 2. These install instructions could also be used for the B+, but I highly recommend that you use the Pi 2 for running OpenCV applications — the added speed and memory makes the Pi 2 much more suitable for computer vision.

In order to keep this tutorial concise and organized, I have broken down the OpenCV 3.0 install process into four sections:

  • Section 1: Configuring your Raspberry Pi by installing the required packages and libraries. Regardless of whether you are using Python 2.7 or Python 3+, we need to take some steps in order to prepare our Raspberry Pi for OpenCV 3.0 — these steps are mainly calls to aptget  , followed by installing the required packages and libraries.
  • Section 2: Compiling OpenCV 3.0 with Python 2.7+ support. If you want to install OpenCV 3.0 with Python 2.7+ bindings on your Raspberry Pi, then this is the section that you’ll want to go to. After you complete this section,  skip Section 3 and head right to Section 4.
  • Section 3: Compiling OpenCV 3.0 with Python 3+ support. Similarly, if you want to install OpenCV 3.0 with Python 3+ bindings on your Pi 2, then complete Section 1 and skip right to Section 3.
  • Section 4: Verifying your OpenCV 3.0 install. After you have installed OpenCV 3.0 with Python support on your Raspberry Pi 2, you’ll want to confirm that is is indeed installed correctly and working as expected. This section will show you how to verify your OpenCV 3.0 install and ensure it’s working correctly.

Python 2.7+ or Python 3+?

Before we get started, take a second and consider which version of Python you are going to use. Are you going to compile OpenCV 3.0 with Python 2.7 bindings? Or are you going to compile OpenCV 3.0 Python 3 bindings?

There are pros and cons of each, but the choice is honestly up to you. If you use Python 3 regularly and are comfortable with it, then go ahead and compile with Python 3 bindings. However, if you do a lot of scientific Python development, you might want to stick with Python 2.7 (for the time being at least). While packages such as NumPy, Scipy, and scikit-learn are certainly increasing the Python 3+ adoption rate in the scientific community, there are still many scientific packages that still require Python 2.7 — because of this, you can easily pigeonhole yourself if you go with Python 3 and then realize that many of the packages you use on a daily basis only support Python 2.7.

When in doubt, I normally suggest that scientific developers use Python 2.7 since it ensures capability with a larger set of scientific packages and allows you to run experiments with legacy code. However, that is quickly changing — so proceed with whichever Python version you are most comfortable with!

Section 1: Configuring your Raspberry Pi by installing required packages and libraries

Let’s kick off this OpenCV 3.0 install tutorial by updating our Raspberry Pi:

Timing: 9m 5s

Now we can install developer tools required to build OpenCV from source:

Timing: 43s

As well as install packages used to load various image formats from disk:

Timings: 27s

Let’s install some video I/O packages:

Timings: 26s

Install GTK, which handles OpenCV’s GUI operations:

Timings: 2m 20s

We can also optimize various functions (such as matrix operations) inside OpenCV by installing these packages:

Timings: 46s

At this point we have all our prerequisites installed, so let’s pull down the OpenCV repository from GitHub and checkout the 3.0.0  version:

Timings: 8m 34s

Update (3 January 2016): You can replace the 3.0.0  version with whatever the current release is (as of right now, it’s 3.1.0 ). Be sure to check OpenCV.org for information on the latest release.

For the full, complete install of OpenCV 3.0, grab the opencv_contrib repo as well:

Timings: 1m 7s

Again, make sure that you checkout the same version for opencv_contrib  that you did for opencv  above, otherwise you could run into compilation errors.

Now we’re at at a crossroads, a sort of Choose Your Own (OpenCV) Adventure!

You can either follow Section 2 and compile OpenCV 3.0 with Python 2.7+ bindings. Or you can head to Section 3 and install OpenCV 3.0 with Python 3+ bindings. The choice is up to you — but choose wisely! Once you make the choice it will be non-trivial to change your mind later.

Note: It’s certainly possible to install OpenCV 3.0 for both versions of Python (it’s actually not too hard), but it’s outside the scope of this tutorial; I’ll be sure to cover this technique in a future post.

Section 2: Compiling OpenCV 3.0 with Python 2.7+ support

Install the Python 2.7 header files so we can compile the OpenCV 3.0 bindings:

Timings: 1m 20s

Install pip , a Python package manager that is compatible with Python 2.7:

Timings: 33s

Just as we did in the original tutorial on installing OpenCV 2.4.X on your Raspberry Pi, we are going to utilize virtualenv and virtualenvwrapper which allow us to create separate Python environments for each of our Python projects. Installing virtualenv  and virtualenvwrapper  is certainly not a requirement when installing OpenCV and Python bindings; however, it’s a standard Python development practiceone that I highly recommend, and the rest of this tutorial will assume you are using them!

Installing virtualenv  and virtualenvwrapper  is as simple as using the pip  command:

Timings: 17s

Next up, we need to update our ~/.profile  file by opening it up in your favorite editor and adding the following lines to the bottom of the file.

And if your ~/.profile  file does not exist, create it.

Now that your ~/.profile  file has been updated, you need to reload it so the changes take affect. To force a reload of the . profile , you can: logout and log back in; close your terminal and open up a new one; or the most simple solution is to use the source  command:

Time to create the cv3  virtual environment where we’ll do our computer vision work:

Timings: 19s

If you ever need to access the cv3  virtual environment (such as after you logout or reboot your Pi), just source  your ~/.profile  file (to ensure it has been loaded) and use the workon  command:

And your shell will be updated to only use packages in the cv3  virtual environment.

Moving on, the only Python dependency we need is NumPy, so ensure that you are in the cv3  virtual environment and install NumPy:

Timings 13m 47s

While unlikely, I have seen instances where the .cache  directory gives a “Permission denied” error since we used the sudo  command to install pip . If that happens to you, just remove the .cache/pip  directory and re-install NumPy:

Awesome, we’re making progress! You should now have NumPy installed on your Raspberry Pi in the cv3  virtual environment, as shown below:

Figure 1: NumPy has been successfully installed into our virtual environment for Python 2.7+.

Note: Performing all these steps can be time consuming, so it’s perfectly normal to logout/reboot and come back later to finish the install. However, if you have logged out or rebooted your Pi then you will need to drop back into your cv3  virtual environment prior to moving on with this guide. If you do not, OpenCV 3.0 will not compile and install correctly and you’ll likely run into import errors.

So I’ll say this again, before you run any other command, you’ll want to ensure that you are in the cv3  virtual environment:

And once you are in cv3  virtual environment, you can use cmake  to setup the build:

Update (3 January 2016): In order to build OpenCV 3.1.0 , you need to set D INSTALL_C_EXAMPLES=OFF  (rather than ON ) in the cmake  command. There is a bug in the OpenCV v3.1.0 CMake build script that can cause errors if you leave this switch on. Once you set this switch to off, CMake should run without a problem.

CMake will run for about 30 seconds, and after it has completed (assuming there are no errors), you’ll want to inspect the output, especially the Python 2 section:

Figure 2: The output of CMake looks good -- OpenCV 3.0 will compile with Python 2.7 bindings using the Python interpreter and NumPy package associated with our virtual environment.

The key here is to ensure that CMake has picked up on the Python 2.7 interpreter and numpy  package associated with the cv3  virtual environment.

Secondly, be sure look at the packages path  configuration — this is the path to the directory where your OpenCV 3.0 bindings will be compiled and stored. From the output above, we can see that my OpenCV bindings will be stored in /usr/local/lib/python2.7/sitepackages

All that’s left now is to compile OpenCV 3.0:

Where the 4 corresponds to the 4 cores on our Raspberry Pi 2.

Timings: 65m 33s

Assuming OpenCV has compiled without an error, you can now install it on your Raspberry Pi:

At this point, OpenCV 3.0 has been installed on your Raspberry Pi 2 — there is just one more step to take.

Remember how I mentioned the packages path  above?

Take a second to investigate the contents of this directory, in my case /usr/local/lib/python2.7/sitepackages/ :

Figure 3: Our Python 2.7+ bindings for OpenCV 3.0 have been successfully installed on our system. The last step is to sym-link the cv2.so file into our virtual environment.

You should see a file named cv2.so , which is our actual Python bindings. The last step we need to take is sym-link the cv2.so  file into the sitepackages  directory of our cv3  environment:

And there you have it! You have just compiled and installed OpenCV 3.0 with Python 2.7 bindings on your Raspberry Pi! 

Proceed to Section 4 to verify that your OpenCV 3.0 install is working correctly.

Section 3: Compiling OpenCV 3.0 with Python 3+ support

First up: Install the Python 3 header files so we can compile the OpenCV 3.0 bindings:

Timings: 54s

Install pip , ensuring that it is compatible with Python 3 (note that I am executing python3  rather than just python ):

Timings: 28s

Just like in the original tutorial on installing OpenCV 2.4.X on your Raspberry Pi 2, we are going to make use of virtualenv and virtualenvwrapper. Again, this is not a requirement to get OpenCV 3.0 installed on your system, but I highly recommend that you use these packages to manage your Python environments. Furthermore, the rest of this tutorial will assume you are using virtualenv  and virtualenvwrapper .

Use the pip3  command to install virtualenv  and virtualenvwrapper :

Timings: 17s

Now that virtualenv  and virtualenvwrapper  are installed on our system, we need to update our ~/.profile  file that is loaded each time we launch a terminal. Open up your ~/.profile  file in your favorite text editor (if it doesn’t exist create it) and add in the following lines:

In order to make the changes to our ~/.profile  file take affect, you can either (1) logout and log back in, (2) close your current terminal and open up a new one, or (3) simply use the source  command:

Let’s create our cv  virtual environment where OpenCV will be compiled and accessed from:

Timings: 19s

Note: I gathered the Python 2.7+ and Python 3+ install instructions on the same Raspberry Pi so I could not use the same virtual environment name for each installation. In this case, the cv3  virtual environment refers to my Python 2.7 environment and the cv  virtual environment refers to my Python 3+ environment. You can name these environments whatever you wish, I simply wanted to offer a clarification and hopefully remove any confusion.

This command will create your cv  virtual environment which is entirely independent of the system Python install. If you ever need to access this virtual environment, just use the workon  command:

And you’ll be dropped down into your cv  virtual environment.

Anyway, the only Python dependency we need is NumPy, so ensure that you are in the cv  virtual environment and install NumPy:

Timings 13m 47s

If for some reason your .cache  directory is giving you a Permission denied error, just remove it and re-install NumPy, otherwise you can skip this step:

At this point you should have a nice clean install of NumPy, like this:

Figure 3: NumPy has been successfully installed for Python 2.7 in the cv virtual environment.

Alright, it’s taken awhile, but we are finally ready to compile OpenCV 3.0 with Python 3+ bindings on your Raspberry Pi.

It’s important to note that if you have logged out or rebooted, that you will need to drop back into your cv  virtual environment before compiling OpenCV 3.0. If you do not, OpenCV 3.0 will not compile and install correctly and you’ll be scratching your head in confusion when you try to import OpenCV and get the dreaded ImportError: No module named cv2  error.

So again, before you run any other command in this section, you’ll want to ensure that you are in the cv  virtual environment:

After you are in the cv  virtual environment, we can setup our build:

Update (3 January 2016): In order to build OpenCV 3.1.0 , you need to set D INSTALL_C_EXAMPLES=OFF  (rather than ON ) in the cmake  command. There is a bug in the OpenCV v3.1.0 CMake build script that can cause errors if you leave this switch on. Once you set this switch to off, CMake should run without a problem.

After CMake has run, take a second to inspect the output of the make configuration, paying close attention to the Python 3 section:

Figure 4: Definitely take the time to ensure that CMake has found the correct Python 3+ interpreter before continuing on to compile OpenCV 3.0.

Specifically, you’ll want to make sure that CMake has picked up your Python 3 interpreter!

Since we are compiling OpenCV 3.0 with Python 3 bindings, I’m going to examine the Python 3 section and ensure that my Interpreter  and numpy  paths point to my cv  virtual environment. And as you can see from above, they do.

Also, take special note of the packages path  configuration — this is the path to the directory where your OpenCV 3.0 bindings will be compiled and stored. After the running the make  command (detailed below), you’ll be checking in this directory for your OpenCV 3.0 bindings. In this case,  my packages path  is lib/python3.2/sitepackages , so I’ll be checking /usr/local/lib/python3.2/sitepackages  for my compiled output file.

All that’s left now is to compile OpenCV 3.0:

Where the 4 corresponds to the 4 cores on our Raspberry Pi 2. Using multiple cores will dramatically speedup the compile time and bring it down from 2.8 hours to just above 1 hour!

Timings: 65m 33s

Assuming OpenCV has compiled without an error, you can now install it on your Raspberry Pi:

Timings: 39s

At this point OpenCV 3.0 has been installed on our Raspberry Pi!

However, we’re not quite done yet.

Remember how I mentioned the packages path  above?

Well, let’s list the contents of that directory and see if our OpenCV bindings are in there:

Here we can see there is a file named cv2.cpython32mu.so , which is our actual Python bindings.

However, in order to use OpenCV 3.0 in our cv  virtual environment, we first need to sym-link the OpenCV binary into the sitepackages  directory of the cv  environment:

So now when you list the contents of the sitepackages  directory associated with our cv  virtual environment, you’ll see our OpenCV 3.0 bindings (the cv2.so  file):

Figure 5: A good validation step to take is to list the contents of the site-packages directory for the cv virtual environment. You should see your cv2.so file sym-linked into the directory.

And there you have it! OpenCV 3.0 with Python 3+ support is now successfully installed on your system!

Section 4: Verifying your OpenCV 3.0 install

Before we wrap this tutorial up, let’s ensure that our OpenCV bindings have installed correctly. Open up a terminal, enter the cv  virtual environment (or cv3 , if you followed the Python 2.7+ install steps), fire up your Python shell import OpenCV:

And sure enough, we can see OpenCV 3.0 with Python 3+ support has been installed on my Raspberry Pi:

Figure 6: Success! OpenCV 3.0 with Python bindings has been successfully installed on our Raspberry Pi 2!

Summary

In this blog post, I have detailed how to install OpenCV 3.0 with Python 2.7+ and Python 3+ bindings on your Raspberry Pi 2. Timings for each installation step were also provided so you could plan your install accordingly. Just keep in mind that if you ever logout or reboot your Pi after setting up virtualenv  and virtualenvwrapper  that you’ll need to execute the workon  command to re-access your computer vision virtual environment prior to continuing the steps I have detailed. If you do not, you could easily find yourself in a situation with the dreaded ImportError: No module named cv2  error.

As the Raspberry Pi and the Raspbian/NOOBS operating system evolves, so will our installation instructions. If you run across any edge cases, please feel free to let me know so I can keep these install instructions updated.

And of course, in future blog posts we’ll be doing some really amazing projects using OpenCV 3.0 and the Raspberry Pi, so consider entering your email address in the form below to be notified when these posts go live!

Python Motion Detection Program on Raspberry Pi

Introduction

Raspberry Pi can connect to a camera to capture picture and video. As an advance feature, it can be used as a CCTV to monitor the environment. For example, from official Raspberry Pi web site “https://www.raspberrypi.org/forums/viewtopic.php?t=45235”, there shows a simple and efficient motion detection script in Python using PIL.

While watching for motion it pipes a thumbnail image from raspistill at around 1fps to analyse (it keeps everything in memory to avoid wearing out the SD card). Once motion is detected it calls raspistill again to write a high-res jpeg to disk. It also checks free disk space and if under a set limit it starts to delete the oldest images to make sure there is always enough free space for new images. While running on my rev1 B it consumes around 12% CPU / 4% ram and manages to capture a full size image once ever 2-3 secs.

picamera

picamera

In the following, I will show you the step of of installation of this motion detection python script.

Step 1. Install PIL by running “sudo aptitude install python-imaging-tk”

Step 2. Create a python script with file name “picam.py” as below:

#!/usr/bin/python

# original script by brainflakes, improved by pageauc, peewee2 and Kesthal
# www.raspberrypi.org/phpBB3/viewtopic.php?f=43&t=45235

# You need to install PIL to run this script
# type “sudo apt-get install python-imaging-tk” in an terminal window to do this

import StringIO
import subprocess
import os
import time
from datetime import datetime
from PIL import Image

# Motion detection settings:
# Threshold          – how much a pixel has to change by to be marked as “changed”
# Sensitivity        – how many changed pixels before capturing an image, needs to be higher if noisy view
# ForceCapture       – whether to force an image to be captured every forceCaptureTime seconds, values True or False
# filepath           – location of folder to save photos
# filenamePrefix     – string that prefixes the file name for easier identification of files.
# diskSpaceToReserve – Delete oldest images to avoid filling disk. How much byte to keep free on disk.
# cameraSettings     – “” = no extra settings; “-hf” = Set horizontal flip of image; “-vf” = Set vertical flip; “-hf -vf” = both horizontal and vertical flip
threshold = 10
sensitivity = 20
forceCapture = True
forceCaptureTime = 60 * 60 # Once an hour
filepath = “/home/pi/picam”
filenamePrefix = “capture”
diskSpaceToReserve = 40 * 1024 * 1024 # Keep 40 mb free on disk
cameraSettings = “”

# settings of the photos to save
saveWidth   = 1296
saveHeight  = 972
saveQuality = 15 # Set jpeg quality (0 to 100)

# Test-Image settings
testWidth = 100
testHeight = 75

# this is the default setting, if the whole image should be scanned for changed pixel
testAreaCount = 1
testBorders = [ [[1,testWidth],[1,testHeight]] ]  # [ [[start pixel on left side,end pixel on right side],[start pixel on top side,stop pixel on bottom side]] ]
# testBorders are NOT zero-based, the first pixel is 1 and the last pixel is testWith or testHeight

# with “testBorders”, you can define areas, where the script should scan for changed pixel
# for example, if your picture looks like this:
#
#     ….XXXX
#     ……..
#     ……..
#
# “.” is a street or a house, “X” are trees which move arround like crazy when the wind is blowing
# because of the wind in the trees, there will be taken photos all the time. to prevent this, your setting might look like this:

# testAreaCount = 2
# testBorders = [ [[1,50],[1,75]], [[51,100],[26,75]] ] # area y=1 to 25 not scanned in x=51 to 100

# even more complex example
# testAreaCount = 4
# testBorders = [ [[1,39],[1,75]], [[40,67],[43,75]], [[68,85],[48,75]], [[86,100],[41,75]] ]

# in debug mode, a file debug.bmp is written to disk with marked changed pixel an with marked border of scan-area
# debug mode should only be turned on while testing the parameters above
debugMode = False # False or True

# Capture a small test image (for motion detection)
def captureTestImage(settings, width, height):
    command = “raspistill %s -w %s -h %s -t 200 -e bmp -n -o -” % (settings, width, height)
    imageData = StringIO.StringIO()
    imageData.write(subprocess.check_output(command, shell=True))
    imageData.seek(0)
    im = Image.open(imageData)
    buffer = im.load()
    imageData.close()
    return im, buffer

# Save a full size image to disk
def saveImage(settings, width, height, quality, diskSpaceToReserve):
    keepDiskSpaceFree(diskSpaceToReserve)
    time = datetime.now()
    filename = filepath + “/” + filenamePrefix + “-%04d%02d%02d-%02d%02d%02d.jpg” % (time.year, time.month, time.day, time.hour, time.minute, time.second)
    subprocess.call(“raspistill %s -w %s -h %s -t 200 -e jpg -q %s -n -o %s” % (settings, width, height, quality, filename), shell=True)
    print “Captured %s” % filename

# Keep free space above given level
def keepDiskSpaceFree(bytesToReserve):
    if (getFreeSpace() < bytesToReserve):
        for filename in sorted(os.listdir(filepath + “/”)):
            if filename.startswith(filenamePrefix) and filename.endswith(“.jpg”):
                os.remove(filepath + “/” + filename)
                print “Deleted %s/%s to avoid filling disk” % (filepath,filename)
                if (getFreeSpace() > bytesToReserve):
                    return

# Get available disk space
def getFreeSpace():
    st = os.statvfs(filepath + “/”)
    du = st.f_bavail * st.f_frsize
    return du

# Get first image
image1, buffer1 = captureTestImage(cameraSettings, testWidth, testHeight)

# Reset last capture time
lastCapture = time.time()

while (True):

    # Get comparison image
    image2, buffer2 = captureTestImage(cameraSettings, testWidth, testHeight)

    # Count changed pixels
    changedPixels = 0
    takePicture = False

    if (debugMode): # in debug mode, save a bitmap-file with marked changed pixels and with visible testarea-borders
        debugimage = Image.new(“RGB”,(testWidth, testHeight))
        debugim = debugimage.load()

    for z in xrange(0, testAreaCount): # = xrange(0,1) with default-values = z will only have the value of 0 = only one scan-area = whole picture
        for x in xrange(testBorders[z][0][0]-1, testBorders[z][0][1]): # = xrange(0,100) with default-values
            for y in xrange(testBorders[z][1][0]-1, testBorders[z][1][1]):   # = xrange(0,75) with default-values; testBorders are NOT zero-based, buffer1[x,y] are zero-based (0,0 is top left of image, testWidth-1,testHeight-1 is botton right)
                if (debugMode):
                    debugim[x,y] = buffer2[x,y]
                    if ((x == testBorders[z][0][0]-1) or (x == testBorders[z][0][1]-1) or (y == testBorders[z][1][0]-1) or (y == testBorders[z][1][1]-1)):
                        # print “Border %s %s” % (x,y)
                        debugim[x,y] = (0, 0, 255) # in debug mode, mark all border pixel to blue
                # Just check green channel as it’s the highest quality channel
                pixdiff = abs(buffer1[x,y][1] – buffer2[x,y][1])
                if pixdiff > threshold:
                    changedPixels += 1
                    if (debugMode):
                        debugim[x,y] = (0, 255, 0) # in debug mode, mark all changed pixel to green
                # Save an image if pixels changed
                if (changedPixels > sensitivity):
                    takePicture = True # will shoot the photo later
                if ((debugMode == False) and (changedPixels > sensitivity)):
                    break  # break the y loop
            if ((debugMode == False) and (changedPixels > sensitivity)):
                break  # break the x loop
        if ((debugMode == False) and (changedPixels > sensitivity)):
            break  # break the z loop

    if (debugMode):
        debugimage.save(filepath + “/debug.bmp”) # save debug image as bmp
        print “debug.bmp saved, %s changed pixel” % changedPixels
    # else:
    #     print “%s changed pixel” % changedPixels

    # Check force capture
    if forceCapture:
        if time.time() – lastCapture > forceCaptureTime:
            takePicture = True

    if takePicture:
        lastCapture = time.time()
        saveImage(cameraSettings, saveWidth, saveHeight, saveQuality, diskSpaceToReserve)

    # Swap comparison buffers
    image1 = image2
    buffer1 = buffer2

Step 3: Change execute mode of picam.py by running the command “sudo chmod 755 picam.py

Step 4: Make a directory by running the command “mkdir /home/pi/picam” which is a hard code path in the picam.py script.

Step 5: Run the picam.py script by execute the command “sudo python picam.py

Step 6: You will see that a series of picture files will be created under the /home/pi/picam directory.

Step 7: If you want to auto-start this program at boot-up, you should create the following script by download a file to directory “/etc/init.d/picam_init” as below link –> https://infotechmanagefactory.com/wp-content/uploads/2016/01/picam_init.zip.

Step 8. change its mode as: sudo chmod 755 /etc/init.d/picam_init

Step 9: make the boot system aware of this script as “sudo update-rc.d picam_init defaults

Step 10: This script will now start and shutdown along with the Raspberry Pi. You can also manually control it like any other daemon. Running “/etc/init.d/picam_init stop" will stop the script and “/etc/init.d/picam_init start" will start it.

Reference Doc Link : https://www.maketecheasier.com/raspberry-pi-as-surveillance-camera/

Installation of Riak Cluster on Raspberry Pi

Introduction

Actually Raspberry Pi is a low performance computer board, however, we can use cluster technology to build of a powerful Raspberry Pi computer by combining several pi. It is very scalable. We can use “Riak” software to build the cluster function on Raspberry Pi. It can improve the data process power to speed-up the data upload and download process. I will introduce the installation of Riak in the following.

RPiImage3

Step 1 Prerequisite Requirement – Installation of mysql & esl-erlang

1.0 Install mysql by running the following command:

$ sudo apt-get install mysql-server mysql-clietn php5-mysql

$ sudo apt-get install phpmyadmin

$ sudo nano /etc/apache2/apache2.conf

add the following line to the end:

 Include /etc/phpmyadmin/apache.conf

1.1 Add the following line to your /etc/apt/sources.list:

deb http://binaries.erlang-solutions.com/debian wheezy contrib

(you may remove all other lines in the file)

1.2 Add erlang Key:

$ cd ~$ sudo wget –o – http://binaries.erlang_solutions.com/debian/erlang_solutions.asc | sudo apt-key add –

1.3 Installation of esl-erlang

$ sudo apt-get update

$ sudo apt-get install esl-erlang

$ sudo reboot

Tips: If you have problem to install esl-erlang, you can try to install erlang-mini.

Step 2: Download the riak-1.2.1 version from the web site

http://s3.amazonaws.com/downloads.basho.com/riak/1.2/1,2.1/riak-1.2.1.tar.gz

$ tar zxvf riak-1.2.1.tar.gz$ mv riak-1.2.1 ~

$ cd ~/riak-1.2.1

Tips: I tried the latest version, but could not succeed to install; so I referred to use version 1.2.1)

Step 3: Installation of Riak

$ sudo make

$ sudo make rel

Tips: If you meet error message “Unable to generate spec: read file info /usr/lib/erlang/man/man3/cerfcl.3.gzfailed make: *** [generate] Error 1”, you can remove those cert* files to solve the problem as below, and then re-run “sudo make rel” command :

$ sudo mv /usr/lib/erlang/man/man3/cerfcl.3.gz ~

$ sudo mv /usr/lib/erlang/man/man3/cerfl.3.gz ~

$ sudo mv /usr/lib/erlang/man/man3/cerff.3.gz ~

$ sudo mv /usr/lib/erlang/man/man3/cerfcf.3.gz ~

Step 4: Test Riak

4.1. start Riak process

$ cd ./rel/riak$ sudo ./bin/riak start

4.2 Test Riak process

4.2.1 First Test:

pi@gopi1:~/riak-1.2.1/rel/riak/bin $ curl http://192.168.5.78:8098/ping
OKpi@gopi1:~/riak-1.2.1/rel/riak/bin $

You will see OK display after run curl command as red highlight above.

4.2.2 Second Test on Speed:

pi@gopi1:~/riak-1.2.1/rel/riak/bin $ curl http://192.168.5.78:8098/riak/druple?keys=true | json_pp
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 436 100 436 0 0 1153 0 –:–:– –:–:– –:–:– 1159
{
“keys” : [],
“props” : {
“young_vclock” : 20,
“postcommit” : [],
“dw” : “quorum”,
“basic_quorum” : false,
“allow_mult” : false,
“w” : “quorum”,
“linkfun” : {
“mod” : “riak_kv_wm_link_walker”,
“fun” : “mapreduce_linkfun”
},
“name” : “druplets”,
“notfound_ok” : true,
“chash_keyfun” : {
“fun” : “chash_std_keyfun”,
“mod” : “riak_core_util”
},
“pr” : 0,
“old_vclock” : 86400,
“last_write_wins” : false,
“big_vclock” : 50,
“rw” : “quorum”,
“pw” : 0,
“precommit” : [],
“small_vclock” : 50,
“r” : “quorum”,
“n_val” : 3
}
}

Step 5: Setup Cluster on Two Raspberry Pi

5.1. Ensure a static ip address was setup in /etc/network/interfaces

5.2. edit ~/riak-1.2.1/rel/riak/etc/vm.args file by changing the following line to assign ip as:

-name riak@127.0.0.1 –> -name riak@192.168.5.78

5.3. edit ~/riak-1.2.1/rel/riak/etc/app.config file by changing the following lines to assign ip as:

{pb_ip, “127.0.0.1” }, –> {pb_ip, “192.168.5.78” },

{http, [ {“127.0.0.1”, 8098 } ]}, –> {http, [ {“192.168.5.78”, 8098 } ]},

%{https, [{ “127.0.0.1”, 8098 }]}, –> %{https, [{ “192.168.5.78”, 8098 }]},

Do the 5.1, 5.2, and 5.3 for other Raspberry Pi, for example, setup another pi with ip 192.168.5.88.

5.4. Start the Riak in all Raspberry Pi by the following command: ~/riak-1.2.1/rel/riak/bin $ sudo ./riak start

5.5 Setup Cluster Process by adding salve to master, by running the command in master raspberry pi:

~/riak-1.2.1/rel/riak/bin $ sudo ./riak-admin cluster join riak@192.168.5.88

5.6 Test Cluster Process

pi@gopi1:~/riak-1.2.1/rel/riak/bin $ sudo ./riak-admin member-status
================================= Membership ==================================
Status Ring Pending Node
——————————————————————————-
joining 0.0% — ‘riak@192.168.5.88’
valid 100.0% — ‘riak@192.168.5.78’
——————————————————————————-
Valid:1 / Leaving:0 / Exiting:0 / Joining:1 / Down:0

Will Change to below after success:

——————————————————————————-
valid 50.0% — ‘riak@192.168.5.78’
valid 50.0% — ‘riak@192.168.5.88’
——————————————————————————-
Valid:2 / Leaving:0 / Exiting:0 / Joining:0 / Down:0

5.7 Check the Process Speed:

pi@gopi1:~/riak-1.2.1/rel/riak/bin $ curl http://192.168.5.78:8098/riak/druplets?keys=true | json_pp
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 436 100 436 0 0 5119 0 –:–:– –:–:– –:–:– 5190
{
“keys” : [],
“props” : {
“name” : “druplets”,
“chash_keyfun” : {
“mod” : “riak_core_util”,
“fun” : “chash_std_keyfun”
},
“postcommit” : [],
“big_vclock” : 50,
“small_vclock” : 50,
“allow_mult” : false,
“linkfun” : {
“mod” : “riak_kv_wm_link_walker”,
“fun” : “mapreduce_linkfun”
},
“last_write_wins” : false,
“old_vclock” : 86400,
“precommit” : [],
“r” : “quorum”,
“w” : “quorum”,
“basic_quorum” : false,
“pr” : 0,
“pw” : 0,
“rw” : “quorum”,
“young_vclock” : 20,
“n_val” : 3,
“notfound_ok” : true,
“dw” : “quorum”
}
}

Bonus:

You can install “Siege” Software to test the web speed performance, and its installation procedure is as below:

sudo apt-get install siege

(If cannot auto-install, try the following manual-install)

Download from https://www.joedog.org/2015/11/siege-3.1.3/

tar xvf siege-3.1.3.tar.gz

cd siege-3.1.3

sudo ./configure

sudo make

sudo make install

sudo make uninstall

(Testing as below command)

siege –c200 –d1 –r1 –v http://localhost/index.html

Installation Edimax Dongle for Wifi Receiver & Access Point on Raspberry Pi

Introduction

Recently, I bought an Edimax Wifi Dongle and used it on my Raspberry Pi. It selected Edimax because it is 100% compatible with Raspberry Pi, and can works out of the box. Moreover, it is cheap, and it can be used as a WiFi Receiver and an Access Point to share out WiFi. The features of Edimax are as below:

  • It supports 150 MBPS speed at an 802.11n wireless data rate, which is the latest wireless standard. It provides the fastest range and widest coverage area.
  • The Raspberry Pi Wifi dongle also supports Wifi Multimedia (WMM)  standard, which allows better streaming of real-time data.
  • It has a multi-language EZmax setup wizard
  • Nano size design helps you to connect it with any USB port without  blocking other USB ports
  • Supports Windows 10
  • Ideal wifi adapter for Raspberry P

In the following, I will talk about how to set it up as a WiFi receiver and Access Point.

EdimaxDongle

Setup Edimax as WiFi Receiver

Step 1. Connect the Edimax to USB port

Step 2. Edit the /etc/network/interfaces files as below:

# Please note that this file is written to be used with dhcpcd
# For static IP, consult /etc/dhcpcd.conf and ‘man dhcpcd.conf’

# Include files from /etc/network/interfaces.d:
source-directory /etc/network/interfaces.d

auto lo
iface lo inet loopback

iface eth0 inet dhcp

allow-hotplug wlan0
auto wlan0
iface wlan0 inet manual
    wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf

allow-hotplug wlan1
iface wlan1 inet manual
    wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf

Step 2. Edit the /etc/wpa_supplicant/wpa_supplicant.conf files to add the SSID and its passphrase as below:

ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1

network={
        ssid=”SSID Name”
        psk=”SSID Passphrase”
}

Bonus:

If you do not familiar with editor to edit wpa_supplicant.conf file, you can setup SSID via “wpa-cli” command as below:

Setup SSID command:

$ ifup -force wlan0
$ wpa_cli
> scan
> scan_result
> add_network
0
> set_network 0 ssid “SSID Name”
> set_network 0 psk “SSID Passphrase”
> enable_network 0
> save_config
> quit
$ sudo /etc/init.d/networking restart

Monitor command:

$ lsusb
$ lsmod
$ ifconfig
$iwconfig

Setup Edimax WiFi as Access Point

Now, we share our network card internet and share the internet via Edimax WiFi dongle with bridge mode as below:

Step 1. Install the following packages.

sudo apt-get install bridge-utils hostapd

Step 2. Download the installed binary version of hostapd with the following commands:

wget https://infotechmanagefactory.com/wp-content/uploads/2016/01/hostapd.zip

unzip hostapd.zip

sudo mv /usr/sbin/hostapd /usr/sbin/hostapd.bak

sudo mv hostapd /usr/sbin/hostapd.edimax

sudo ln -sf /usr/sbin/hostapd.edimax /usr/sbin/hostapd

sudo chown root.root /usr/sbin/hostapd

sudo chmod 755 /usr/sbin/hostapd

Step 3. Bridge the Network Connection – to edit interfaces file as below:

$ sudo nano /etc/network/interfaces

# interfaces(5) file used by ifup(8) and ifdown(8)

# Please note that this file is written to be used with dhcpcd
# For static IP, consult /etc/dhcpcd.conf and ‘man dhcpcd.conf’

# Include files from /etc/network/interfaces.d:
source-directory /etc/network/interfaces.d

auto lo
iface lo inet loopback

allow-hotplug eth0

auto eth0
iface eth0 inet dhcp

#bridge
auto br0
iface br0 inet dhcp
bridge_ports eth0 wlan0

Step 4. Configure Hostapd by creating the hostapd.conf file as below:

sudo nano /etc/hostapd/hostapd.conf

interface=wlan0
driver=rtl871xdrv
bridge=br0
ssid=YourSsidHere
channel=1
wmm_enabled=0
wpa=1
wpa_passphrase=YourPassPhraseHere
wpa_key_mgmt=WPA-PSK
wpa_pairwise=TKIP
rsn_pairwise=CCMP
auth_algs=1
macaddr_acl=0

Step 5. Test the Hostapd

$ sudo reboot

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

Now, you should be able to search its SSID via another WiFi device, and test to connect it. Good Luck !

Pls consider to buy Edimax WiFi Adaptor from Amazon as below link:

Setup Honeyport on Raspberry Pi

Introduction

glastopf-logoA honey pot is a computer system on the Internet that is expressly set up to attract and “trap” people who attempt to penetrate other people’s computer systems. To set up a honey pot on Paspberry Pi, I recommend to use Glastopf. Glastopf is a web application honeypot project lead by Lukas Rist a.k.a glaslos of the Honeynet Project. The Glastopf project started in the year 2009. It is a simple and minimalistic web server written in Python that records information of web-based application attacks like Structured Query Language Injection (SQLI), Remote Code Execution (RCE), Local File Inclusion (LFI), Remote File Inclusion (RFI), and many more, because it emulates web application vulnerabilities tricking attackers or scanners that it is a vulnerable web server.

Step 1. Installation the dependencies of Glastopf

Prerequisite:  Your system should install apache, mysql, python.

For example, let show of mysql Installation by running below commend:

1.0 $sudo  apt-get install mysql-server mysql-client php5-mysql

      $sudo apt-get install phpmyadmin

      $sudo vi /etc/apache2/apache2.conf to include below line:

             Include /etc/phpmyadmin/apache.conf

SSH into your console then install the dependencies for the web honeypot.

1.1. Add the backports repository to your sources list file, which can be found under the /etc/apt directory:

sudo echo “deb http://backports.debian.org/debian-backports squeeze-backports main” >> /etc/apt/sources.list

1.2. Now let’s install the dependencies:

sudo apt-get update
sudo apt-get install python python-openssl python-gevent libevent-dev python-dev build-essential make

sudo apt-get install python-argparse python-chardet python-requests python-sqlalchemy python-lxml   ( Error for python-argparse, so run the following)

sudo apt-get install python-argparse python-chardet python-requests python-sqlalchemy python-lxml

sudo apt-get install python-beautifulsoup python-pip python-dev python-numpy python-setuptools
sudo apt-get install python-numpy-dev python-scipy libatlas-dev g++ git php5 php5-dev liblapack-dev gfortran

sudo apt-get install libxml2-dev libxslt-dev

sudo pip install –upgrade distribute   (Error to upgrade)

Step 2. Install and configure the PHP sandbox

The next thing that we should do is to configure the PHP sandbox.

2.1. First, we download BFR (Better Function Replacer) by using git:

$ sudo apt-get install git-core
$ cd /opt
$ sudo git clone git://github.com/glastopf/BFR.git
$ cd BFR
$ sudo phpize
$ sudo ./configure –enable-bfr
$ sudo make && make install

It should have this following message after the make install:

Build complete.
Don’t forget to run ‘make test’.
Installing shared extensions: /usr/lib/php5/20100525/

2.2. Copy or append the search path to bfr.so and add it to php.ini file:

$ sudo echo “zend_extension = /usr/lib/php5/20100525/bfr.so” >> /etc/php5/cli/php.ini

2.3. You should see the extension on the output by using the php –version command in the terminal:

$ php –version
PHP 5.6.14-0+deb8u1 (cli) (built: Oct 28 2015 00:02:05)
Copyright (c) 1997-2015 The PHP Group
Zend Engine v2.6.0, Copyright (c) 1998-2015 Zend Technologies
    with Zend OPcache v7.0.6-dev, Copyright (c) 1999-2015, by Zend Technologies

2.4. Install the latest stable release of Glastopf from pip:

$ sudo pip install glastopf

Step 3. Configuration and Preparation for the Glastopf environment

3.1. Prepare the environment:

$ cd /opt
$ sudo mkdir glastopf

3.2. Stop the apache service so that the web application honeypot could listen to port 80:

$ sudo service apache2 stop

3.3. Now, run the web application honeypot:

$ sudo glastopf-runner

2016-01-02 00:58:34,570 (glastopf.glastopf) Initializing Glastopf 3.1.2 using “/home/pi” as work directory.
2016-01-02 00:58:34,587 (glastopf.glastopf) Connecting to main database with: sqlite:///db/glastopf.db
2016-01-02 00:58:34,738 (glastopf.modules.handlers.emulators.dork_list.dork_page_generator) Bootstrapping dork database.
2016-01-02 00:58:34,790 (urllib3.connectionpool) Starting new HTTPS connection (1): mnemosyne.honeycloud.net
2016-01-02 00:58:39,378 (glastopf.modules.handlers.emulators.dork_list.mnem_service) Error while communication with mnemosyne: (‘Connection aborted.’, error(113, ‘No route to host’))
2016-01-02 00:59:15,225 (glastopf.glastopf) Generating initial dork pages – this can take a while.

3.4. A new default /usr/bin/glastopf.cfg will be created in the glastopfpi directory, which can be customized to your liking just like what port you want the application to listen on. (In my case, I choose port 80 and that’s why I stopped the Apache service).

3.5. You should see the following output from your terminal as shown by my screenshot result below:

glastopf-browser

Learn More Raspberry Pi from Amazon as below link:

 

Bonus: Error Fixing Case

If you cannot run “sudo” command and get an error message of

“/usr/bin/sudo must be owned by uid 0 and have the setuid bit set”, you can execute the following command to solve:

$ chown root:root /usr/bin/sudo && chmod 4755 /usr/bin/sudo

VPN Server Setup for Raspberry Pi

Introduction

Pi-VPN-TunnelRaspberry Pi can be used as a VPN server to allow users to setup a secure tunnel from a remote client to the local network. Once a VPN tunnel is established between the Raspberry Pi and the client device, such as laptop, mobile device, ipad, itab, etc; if the port forward of router and access right is setup probably, then, the device can be accessed from local network or vice verse. I can successfully use pttpd software to setup VPN feature, and I will explain the setup step in the following.

Step 1. To make the latest update of the System:

$ sudo apt-get update

$ sudo apt-get upgrade

Step 2. Install the pttpd program:

$ sudo apt-get install pptpd

Step 3. Configure the pptpd:

3.1 Edit the pptpd.conf file by removing the “#” and place there the IP-address of the Raspberry Pi, for example 192.168.178.28 (which you should use your device’s ip address in your case):

$ sudo nano /etc/pptpd.conf

#localip 192.168.0.1 change to localip 192.168.178.28

3.2 Edit the pptpd-options file:

$ sudo nano /etc/ppp/pptpd-options

Add following at the end of the file (DNS-servers):

ms-dns 8.8.8.8

noipx

mtu 1490

mru 1490

Instead of 8.8.8.8 also 208.67.222.222 or 213.73.91.35 should work.

3.3 Configure internet traffic forwarding in your Pi to get access to your local network:

$ sudo nano /etc/sysctl.conf

Remove the “#”:

#net.ipv4.ip_forward=1     change to     net.ipv4.ip_forward=1

3.4 Change the firewall entry:

$ sudo iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE

3.5 Make it permanent in case of a reboot:

$ sudo crontab –e

Add following line at the lower end:

@reboot sudo iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE

3.6 add a user and password in “chap-secrets”. Both have to be the same as later on used in the smartphone client configuration. It is recommended to use a password longer than 13 characters:

sudo nano /etc/ppp/chap-secrets

Username[TAB]*[TAB]password[TAB]*

Example:

loginname     *       password   *

3.7 Restart the VPN server:

$ sudo service pptpd restart

Client Connection Setup on Android Device

  1. Select ‘Settings’ -> ‘More Network’ -> VPN -> + (to Add VPN Configuration)
  2. Input VPN Name, Login Account, Password, and Select Type -> ‘PPTP’ Type
  3. Press ‘Connect’

Note: One port-forwarding in the router is still necessary. Enter your router menu and configure port-forwarding for your VPN-server IP address with port 1723 to port 1723,

Reference Information for pptpd VPN Setup

Bonus Information (OpenVPN Server Setup)

Many people use another VPN server software called OpenVPN to install on Raspberry Pi device. It is more secure than pttpd because it can use ssl for VPN connection, however, its setup is a little bit more difficult than pttpd. If you are interested in the OpenVPN setup on Raspberry Pi, I suggest you to take a look on the following web page: https://www.raspberrypi.org/forums/viewtopic.php?t=81657

Learn More Raspberry Pi from Amazon as below link:

Secure Hardening a Raspberry Pi Server

Introduction

raspberrypi-logoRaspberry Pi is a low cost, high power and small size Linux Server or Computer. I foresee that it will become very popular in future, especially using in automatic controller aspect which is the next generation of computer world. An important topic for setup a raspberry pi server is about server hardening, which we have better setup a security server before explore it to www. I will introduce you the step by step security setup of Raspberry Pi which is installed with NOOBS O/S in the following.

raspberrypi-ssh

1. Initialize Setup Right After Installed NOOBS

Run the following command when first time successfully install and startup the NOOBS O/S:

raspi-config

Then, navigate the menu with the arrow keys, select things by pressing the enter key. Do the following:

  1. Change the Pi password
    We’ll be deleting the default “pi” user account later (for security) but right now, if you were connected to the internet your Pi would be susceptible to someone SSHing into it – because every Pi has the same default password. Better to change it now, before you’re connected, just in case.
  2. Disable “Boot to Desktop”
    Currently that means entering the “Enable boot to desktop” menu item and then selecting “no”. We won’t be using the desktop (we’re going to run headless), and disabling the boot to desktop option will free up some system resources so the Pi performs better.
  3. Update your Locale settings
    If you’re in the UK then it’s already set to use UK English in UTF8 – if not, pick the best choice for your location and if you can, a UTF-8 version of your locale. Also set your timezone (for me that’s Europe > London).
  4. Set your Hostname (Advanced > Hostname).
    Your ‘hostname’ is simply the name of the Pi itself, you can choose anything but don’t use special characters or spaces. So, for example, ‘webserver1′ might be good for you.
  5. Set the Memory Split (Advanced > Memory Split).
    The Pi’s GPU and CPU both share the same RAM modules (512Mb of it in current Pi models). As we won’t be running a desktop we don’t need the GPU to have much memory, so we can set it to 16 – leaving the rest of the RAM free for the system to use.
  6. Ensure SSH is enabled (Advanced > SSH).
    SSH is the protocol we will be using to access and control the Pi from another computer. It must be enabled for us to do that.
  7. Commit the changes and reboot
    Select ‘Finish’ – if it asks, yes you want to reboot. If it doesn’t ask to reboot then force a reboot so the new hostname and other changes take effect; type:

$ sudo reboot

Once it’s rebooted you’ll be prompted for the username/password. Use ‘pi’ and the password you just set up.

2. Security of User/Group Setup

Step 1. Creating a new user

To get rid of the default ‘pi’ user to make it harder for anyone. Firstly, we need to create a new user by typing the command with replacing your own username as USERNAME in the following:

$ sudo useradd -m -G adm,dialout,cdrom,sudo,audio,video,plugdev,games,users,netdev,input USERNAME

Next we set a password for the new user:

$ sudo passwd USERNAME

Complete the prompts as they appear. Now shutdown the Pi:

$ sudo shutdown -h now

The Pi will turn itself off. Un-plug the power, plug in the network cable, then plug the power back in. The Pi will boot up and leave you in a Bash shell asking for a login name: Log-in with your newly created user’s details (i.e., don’t log in as ‘pi’).

Step 2. Deleting the default ‘pi’ user (optional: as long as you are comfortable with the newly created user above)

Type:

$ sudo deluser –remove-all-files pi

This will take a little while and spit out a lot of lines of text – eventually it will say ‘Done’. The ‘pi’ user and it’s associated files are now removed from the system.

3. Updating the operating system and software

Connect to internet and update the system:

$ sudo apt-get update

Wait for this to complete; it’s just got a list of all the potential updates and new bits of software you could install. To upgrade all of the currently installed software type:

$ sudo apt-get upgrade

Wait for that to complete, answer any prompts with ‘y’ + Enter. Your system is now up-to-date.

4. Fixing your machine’s internal IP address

The default network ip address is using DHCP. If you are familiar with network address setup, you can change and setup from DHCP to STATIC type; otherwise, I advise you not change it, however, I suggest you bind the MAC address of Raspberry Pi to the router in order to get a fix ip address from the router all the time

  1. Find the MAC address of the Pi
  2. Set the router to always assign the same IP to any device with that MAC address.

Note: A MAC address is a unique identifier – any and all devices attached to your network have their own unique MAC address – think of it like a serial number; no other Pi (or other device) shares the same MAC address as yours. To find your Pi’s MAC address in detail, type the following command:

$ ifconfig

5. Securing Pi Connection with SSH

Using SSH key-pair authentication is more secure than typing a password to authenticate your user (i.e., to log-in to your Pi).

From Client Side, you can download puTTY and use it to connect to Pi via SSH, or type the following SSH command:

> ssh USERNAME@IPADDRESS

6. Securing Pi with Fail2Ban

This application helps to prevent hacking attempts by detecting log-in attempts that use a dictionary attack and banning the offending IP address for a short while. NOTE: If you’re using SSH Key Pairs and have disabled SSH Password Authentication then you may not want to bother with this as no-one can hack their way in via a dictionary attack anyway.

$ sudo apt-get install fail2ban

Wait for this to complete; it should be fine running the default set up so you can stop there, or learn more about customising fail2ban.

7. SSL Setup on Apache

7.1 Create a 3 years life (1095 days) SSL certification file under directory /etc/apache2/ssl with following command:

$ sudo mkdir /etc/apache2/ssl

$ sudo openssl req -x509 -nodes -days 1095 -newkey rsa:2048 -out /etc/apache2/ssl/server.crt -keyout /etc/apache2/ssl/server.key

You need to answer some question as below example:

pi@raspberrypi:~ $ sudo openssl req -x509 -nodes -days 1095 -newkey rsa:2048 -out /etc/apache2/ssl/server.crt -keyout /etc/apache2/ssl/server.key
Generating a 2048 bit RSA private key
……………………………………………………………………………………….+++
……………………………………+++
writing new private key to ‘/etc/apache2/ssl/server.key’
—–
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter ‘.’, the field will be left blank.
—–
Country Name (2 letter code) [AU]:HK
State or Province Name (full name) [Some-State]:HK
Locality Name (eg, city) []:HK
Organization Name (eg, company) [Internet Widgits Pty Ltd]:Gold
Organizational Unit Name (eg, section) []:IT
Common Name (e.g. server FQDN or YOUR name) []:YourDomainName.com
Email Address []:youremail@hotmail.com

Remark: It is important to setup the Common Name, which should match your internet domain name FQDN.

7.2 Install the SSL mod for apache with command sudo a2enmod ssl as below example:

pi@raspberrypi:~ $ sudo a2enmod ssl
Considering dependency setenvif for ssl:
Module setenvif already enabled
Considering dependency mime for ssl:
Module mime already enabled
Considering dependency socache_shmcb for ssl:
Module socache_shmcb already enabled
Module ssl already enabled

7.3 Check the default-ssl.conf configure file under /etc/apache2/sites-enabled directory as below:

pi@raspberrypi: /etc/apache2/sites-enabled $ ls -l
total 0
lrwxrwxrwx 1 root root 35 Dec 18 22:21 000-default.conf -> ../sites-available/000-default.conf
lrwxrwxrwx 1 root root 35 Dec 18 23:11 default-ssl.conf -> ../sites-available/default-ssl.conf

If you cannot find the default-ssl.conf file in this directory, you need to run the following command to create link:

$ sudo ln -s /etc/apache2/sites-available/default-ssl.conf /etc/apache2/sites-enabled/default-ssl.conf

7.4 Edit the default-ssl.conf file and change two lines as below:

$ sudo nano /etc/apache2/sites-enabled/default-ssl.conf

SSLCertificateFile         /etc/apache2/ssl/server.crt

SSLCertificateKeyFile   /etc/apache2/ssl/server.key

7.5 Restart the apache server as below example:

pi@raspberrypi:/etc/apache2/sites-enabled $ sudo /etc/init.d/apache2 restart
[ ok ] Restarting apache2 (via systemctl): apache2.service.

7.6 Now, you can browse the web site with web link as https://yourdomainname.com, but you need to accept the security exceptional message to browse the site. As a result, it forces the SSL encryption on each page that require authentication, and it is more safety for data transfer in internet.

Remark: If you connect to the https://yourdomainname.com through your router, you need to open the port 443 on the router in order to allow data transfer through it.

Bonus Information:

  • For WordPress SSL setup, you need to edit wp-config.php file to define the following two lines:

define(‘FORCE_SSL_LOGIN’, true);

define(‘FORCE_SSL_ADMIN’, true);

  • For phpmyadmin SSL setup, you need to edit its config_inc.php file to define the following line:

$cfg[‘ForceSSL’] = ‘true’;

Reference Link / Doc:

  • https://mattwilcox.net/web-development/setting-up-a-secure-home-web-server-with-raspberry-pi
  • https://hallard.me/enable-ssl-for-apache-server-in-5-minutes/

Learn More Raspberry Pi from Amazon as below link:

Installation of Raspberry Pi Camera

Introduction

Raspberry pi computer can be connected to a camera to take picture and video. We can use it as a CCTV to monitor facility and environment. In the following, we will talk about how to setup a camera in raspberry pi step by step.

picamera

picamera

Step 1: Connect the Camera to Raspberry Pi as above picture, and enable the camera via raspi-config

Step 2: Capture Picture Command

$ raspistill -o image.jpg

Step 3: Capture Video Command

$ raspivid -o 5sec-video.h264

$ raspivid -o 10sec-video.h264 -t 10000

Note:  You can’t view anything over VNC, and obviously you can’t do it via a ssh terminal. You need to be viewing the Pi directly over hdmi.

Step 4.      Record raw video, convert to mp4, play:

The h264 video the camera records is “raw”.  To make it easily viewable by the Pi or Mac (or other PC’s) it needs to be converted as below steps. First, you need to install gpac on the Pi, then run MP4Box (part of that install) to do the convert using below commands:

$ sudo apt-get update

$ sudo apt-get install -y gpac

$ MP4Box -fps 30 -add myvid.h264 myvid.mp4

To play video on the Pi, you need omxviewer.  I think it may come installed iwth NOOBS now(?), but if not:

$ sudo apt-get install omxplayer

Then play in a window (again, this doesn’t work over VNC, need to be on a monitor connected to the Pi) or to the HDMI port:

$ omxplayer myvid.mp4

$ omxplayer -p -o hdmi myvid.mp4

Step 5.      Broadcast video to the Internet:

Using VLC

Install VLC if no, with below command:

$ sudo apt-get install vlc

Sometimes, I need to go to the official web site to download as link <<here>>, installed the App that way, and it started working!

Port Forward the Router:

I accessed my routers web page 192.168.x.x and via the “virtual servers” option, opened up port 8554 for outside listening.  I’m sure this process can vary widely per router.

Stream from the Pi:

After ssh’ing into the Pi, I executed this to start the video stream (note I knocked down the resolution from the default 1080p):

$ raspivid -w 640 -h 480 -o – -t 9999999 |cvlc -vvv stream:///dev/stdin –sout ‘#standard{access=http,mux=ts,dst=:8554}’ :demux=h264

View via VLC:

I accessed “What’s My Ip” to find the external IP of my router.

Launching VLC, I accessed “File -> Open Network…”, and entered:

http://<ip of my router>:8554

And hit “open” :  Next popped up a (delayed by about 5 seconds) stream from my Pi’s cam.  Awesome.

Using MJPG-Streamer

There is a tutorial shows how to broadcast video straight to a web page via MJPG-Streamer. It’s really easy to setup referring to “Raspberry Pi camera board video streaming”.

We firstly made two shell scripts, start_stream.sh & stop_stream.sh that handle all the heavy lifting of starting and stopping all the services, then make a copy of them to your home dir for easy execution.

Note, we changed them to up the resolution, jpg quality, and add a password to the site. We only made one change:  Since we previously port-forwarded port 8554, we also changed their code to use that port, rather than 9000.

To add your own password, edit start_stream.sh and change the line including the block of code below to include the “-c” stuff shown here, changing myUserName:myPassword appropriately.  Note, the -c argument must be inside the quotes, after the www, or things won’t work so well.

-o “output_http.so -p 8554 -w /opt/mjpg-streamer/www -c myUserName:myPassword”

Then browse to:

http://<ip of your router>:8554/stream_simple.html

To login and start watching from the auto-generated web page!  Looks like I’m getting around 1fps.

raspistill Image Formats

–encoding <format>

The default is jpg, but you can change it, where <format> is jpg, bmp, gif, & png.  From the docs: “Note that unaccelerated image types (gif, png, bmp) will take much longer to save than JPG which is hardware accelerated.”

If using jpg, you can set the quality via:

–quality #

Where # is a value from 1 -> 100.  They say that 75 is a good number.

Reference Info:

Here on PyPi.  Official documentation here.  Source on Github here.  Forum discussion here.

Easy to install with pip:

$ sudo pip install picamera

We can run the quickstarts via Adafruit WebIDE successfully (while having the Pi hooked up over HDMI to preview the results).

 Order a RaspBerry Pi Camera from Amazon as below link: