Remote Motion-Activated Web-Based Surveillance with Raspberry Pi

Introduction

Ever want to keep an eye on your house while your away? Maybe observe backyard wildlife close-up? Or my favorite for IT, keep an eye on your server room? Low-end wireless IP cameras start at $50-$75 USD. Higher-end units can run into the hundreds of dollars. Add motion detection and the price raises even further. How about a lower-cost solution? Using a Raspberry Pi with an inexpensive webcam, a wireless WiFi Module, and optional battery pack, you can a remote, motion-activated camera solution, at a fraction of the cost. Best of all, you won’t need to write a single line of code or hack any electronics to get started.

_MG_9526

There are many good articles on the Web that demonstrate how to build a RaspPi-based motion-activated video solution. One of the more popular software solutions is Motion. According to their website, ‘Motion is a program that monitors the video signal from one or more cameras and is able to detect if a significant part of the picture has changed; in other words, it can detect motion‘. Motion has all the capabilities to stream images from your webcam to a built-in web server, where you can reach them through your browser, with little or no configuration. Motion is easily configured to work with streaming video apps like FFmpeg, save images to a database like mySQL or PostgreSQL, and execute external scripts such as python or shell. We are going to use Motion’s most basic features in this post, motion detection and streaming.

Installing Motion

Before installing Motion, I recommend ensuring your Raspberry Pi is up-to-date with the latest software and firmware. Updating firmware is not necessary; however I had an experience while helping someone else with their RaspPi, where their camera would not work correctly. After finding a few folks online with similar problems, we updated the firmware on the RaspPi and fixed the problem. Installing firmware can sound a bit intimidating; however, Liam McLoughlin (hexxeh) has made the process easy with rpi-update. I have used it successfully on three RaspPi’s. Three commands to update your RaspPi.

To update your RaspPi’s software, execute the following command. Note if you don’t do this on a regular basis, as recommended, these steps could take up to 5 minutes or more. Watch for errors. If there are any, just run it again. Sometimes, the RaspPi cannot connect to all sources for updates.

sudo apt-get update && sudo apt-get upgrade

Once the updates are completed successfully, install Motion by issuing the following command:

sudo apt-get install motion

Enabling Motion
As the installation completes, you should see a warning in the command shell about Motion being disabled by default.

...
Adding user `motion' to group `video' ...
Adding user motion to group video
Done.
[warn] Not starting motion daemon, disabled via /etc/default/motion ... (warning).
Setting up ffmpeg (6:0.8.4-1) ...
pi@garyrasppi ~ $

To enable Motion (the motion daemon), we need to edit the /etc/default/motion file.

sudo nano /etc/default/motion

Change the ‘start_motion_daemon‘ parameter to ‘yes’.

Enable Daemon

Configuring Motion

Motion is easy to customize, with a plethora of parameters you can tweak based on your needs. Since Motion has no GUI, configuration is all done through Motion’s configuration file (/etc/motion/motion.conf).

Before editing the configuration file we need to change the permissions on it, so Motion can access it. While we’re at it, we will also change permissions on the folder where Motion stores images.

sudo chmod -R 777 /etc/motion/motion.conf
sudo chmod -R 777 /tmp/motion

Open the configuration file in Nano with the following command.

sudo nano /etc/motion/motion.conf

Motion’s configuration file is lengthy, but broken down into sections to make finding the setting you are looking for, easy. First, we need to change the ‘Live Webcam Server’ section of configuration. Below are the default settings:

############################################################
# 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 50

# 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 off

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

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

# 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

The first thing you will want to change is Motion’s default setting that restricts image streaming to ‘localhost‘, only. This means you can only view images in a web browser on the RaspPi, not remotely on your LAN. Change that line of code to read ‘webcam_localhost off‘.

The next setting I recommend changing for security purposes is the default port Motion uses to stream images, port 8081. Change this port to another random port, for example, 6789 (‘webcam_port 6789‘). This means if your RaspPi’s wireless IP address is 192.169.1.9, images from your webcam should be accessible at 192.169.1.9:6789. If you plan on making the webcam’s images available over the Internet, I definitely recommend changing the port. Security through obscurity is better than no security at all.

The other two settings in this section you can play with are the webcam quality and maximum frame-rate. You will have to adjust this based on your network speed and the processing power of your RaspPi. The default settings are a good place to start. I changed my quality from the default of 50 to 80 (‘webcam_quality 80‘), and I changed my max frame-rate to 2 (‘webcam_maxrate 2‘).

Speaking of quality, the other two settings you may want to change are the width and height of the image being captured by motion. This is done in the ‘Capture device options’ section. As the file’s comments suggest, these settings are dependent on your camera. Check the camera’s available image sizes; you will need to use one of those size combinations. I have mine set to an average size of 352 x 288. This is a good size for those of us with a slower network, or when streaming video over the Internet to mobile web browser. Conversely, a larger image is better for viewing on your local LAN. Image size, like compression quality, and frame-rate are dependent on processing power of your RaspPi and its OS (Raspbian, Debian, Arch, etc.). You may need to play with these settings to get the desired results. I couldn’t stream images larger than 352 x 288 over the Internet, even though my webcam could go up to 640 x 480.

<pre># Image width (pixels). Valid range: Camera dependent, default: 352
width 352

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

It’s important to remember, each time you make changes to Motion’s configuration file, you must restart Motion, using the following command.

sudo /etc/init.d/motion restart

Viewing Your Webcam Remotely

To view your webcam’s output from another device on your LAN, point your web browser to the IP address of your RaspPi and the port you assigned in Motion’s configuration file. Motion may take up to 15-20 seconds to start responding in the browser. If it takes much longer, you probably have your image size, frame-rate, and compression settings to high for your RaspPi.

Viewing Your Webcam Over the Internet
Viewing your webcam’s output over the Internet can be relativity easy or totally impossible, depending on your router and your Internet provider. In my case, I configured port-forwarding on my Netgear Wireless Router. In the example below, I created port-forwarding rule, which allows all external HTTP requests to port ’3456′ to be forwarded to internal port ’6789′, which is the streaming port for Motion on my RaspPi.

For example, let’s say the internal address of my RaspPi on my LAN is 192.168.1.9, and my external Internet IP address if 113.45.67.88. I go down to the local coffee shop and decide to check if the mailman has delivered my new Raspberry pi to my front porch. I enter http://113.45.67.88:3456 in my phone’s web browser. My home router receives the request and forwards it to 192.168.1.9:6789, which returns a stream of still images to my phone at the coffee shop. Still no RaspPi, so sad…

So what is the external address of my network? I checked the Internet port’s IP address in the Netgear’s Router Status window. Since I do not pay my Internet-provider for a static IP address, the address I am assigned is dynamic. It can and will change, sometimes almost never, sometimes daily; it depends on your provider. To view your webcam’s images, you will have to know your current Internet port’s IP address. User this address, with the external port you used for port-forwarding.

Netgear Port Forwarding

Motion Examples
Here are some example from a Microsoft LifeCam VX-500 and Logitech Webcam C210 webcams. The highest quality I could consistently stream over the Internet, from my RaspPi 512Mb Model B, with both Soft-float Debian “wheezy” and Raspbian “wheezy”, was 352 x 288 at 80% compression and 2 fsp max. Locally, on my LAN I could achieve 640 x 480.

In this example, I’ve placed the RaspPi in a plastic container to protect it, and mounted the attached webcam in a flower box. Viewing the feed over our local network, we are able to watch the hummingbirds without spooking them.

Hummingbird Feeder Remote Camera

In these two images, I’ve turned on Motion’s ‘locate box’ option, which tracks the exact area within the image that is moving. As I come into view of the camera, Motion detects and outlines the area of the images that are changing.

Front Entrance

Capture2

In the next video, you see the view from a Google Nexus 7 tablet. My wife and I use the RaspPi surveillance system to monitor our pool area or backyard when the kids have friends over (the camera is no substitute for adult supervision when the kids are in the pool).

This last image is from my iPhone while shopping at the local grocery store. My wife was pretty impressed with my port-forwarding knowledge. OK, not really…

iPhone Scaled

Useful Links

Here are a few links to other useful articles on the use of Motion with the Raspberry Pi:

Setup a webcam security system with Ubuntu Linux and Motion

Guest blog #7: Bird table webcam by Francis Agius

Raspberry Pi webcam

motion(1) – Linux man page (good source for understand Motion config)

Linux UVC Supported Devices (a good starting point for buying a webcam)

About these ads

, , , , , , , , , , , , , , ,

  1. #1 by raspibit on January 2, 2013 - 6:52 pm

    Hello Gary,

    I’ve been trying setting up motion properly, but when I try turning up the resolution to 640×480 I get terrible green lines in all my screen and it’s impossible to fix it because only works at the default motion resolution. I’m using a Creative LiveCam Sync HD, UVC and 720p HD resolution.

    Any idea about what I could do?

    Thanks a lot.

    • #2 by Gary A. Stafford on January 2, 2013 - 9:17 pm

      I’ve tried (2) Logitech cameras and (1) Microsoft camera on (2) RaspPi’s and (2) Operating Systems. I have not been able to get an image bigger than 358 x 288 pixels, not matter how much compression I use. It works perfect at a smaller size, but at 640 x 480 pixels, I get similar results to you or no results at all. The cameras are all capable of it.

      Troubleshooting this a little further, I think narrowed it down to the pre_capture buffer. I ran ‘motion’ and looked at the output:
      [1] Resizing pre_capture buffer to 1 items
      [0] Thread 1 – Watchdog timeout, trying to do a graceful restart

      I change to 352×288, and this succeeds:
      [1] Resizing pre_capture buffer to 1 items
      [1] Started stream webcam server in port 2929

      I haven’t found an answer, but this series of posts, discuss some possible solutions. Sounds very common: http://www.raspberrypi.org/phpBB3/viewtopic.php?f=38&t=17308

      I also noticed some permissions problems I had with the ‘motion.conf’ file and the ‘/tmp/motion’ directory, which I fixed and need to add to my post (see output below).

      pi@garyrasppi ~ $ motion
      [0] Processing thread 0 – config file /etc/motion/motion.conf
      [0] Motion 3.2.12 Started
      [0] ffmpeg LIBAVCODEC_BUILD 3482368 LIBAVFORMAT_BUILD 3478784
      [0] Thread 1 is from /etc/motion/motion.conf
      [0] motion-httpd/3.2.12 running, accepting connections
      [0] motion-httpd: waiting for data on port TCP 8080
      [1] Thread 1 started
      [1] cap.driver: “uvcvideo”
      [1] cap.card: “Microsoft LifeCam”
      [1] cap.bus_info: “usb-bcm2708_usb-1.2″
      [1] cap.capabilities=0×04000001
      [1] – VIDEO_CAPTURE
      [1] – STREAMING
      [1] Test palette YUYV (640×480)

      [1] Resizing pre_capture buffer to 1 items
      [0] Thread 1 – Watchdog timeout, trying to do a graceful restart
      [0] httpd – Finishing
      [0] httpd Closing
      [0] httpd thread exit

      Changed to 352 x 288
      pi@garyrasppi ~ $ motion

      [0] Processing thread 0 – config file /etc/motion/motion.conf
      [0] Motion 3.2.12 Started
      [0] ffmpeg LIBAVCODEC_BUILD 3482368 LIBAVFORMAT_BUILD 3478784
      [0] Thread 1 is from /etc/motion/motion.conf
      [0] motion-httpd/3.2.12 running, accepting connections
      [0] motion-httpd: waiting for data on port TCP 8080
      [1] Thread 1 started
      [1] cap.driver: “uvcvideo”
      [1] cap.card: “Microsoft LifeCam”
      [1] cap.bus_info: “usb-bcm2708_usb-1.2″
      [1] cap.capabilities=0×04000001
      [1] – VIDEO_CAPTURE
      [1] – STREAMING

      [1] Resizing pre_capture buffer to 1 items
      [1] Started stream webcam server in port 2929
      [1] File of type 1 saved to: /tmp/motion/01-20130102204736-00.jpg

      • #3 by raspibit on January 3, 2013 - 3:16 pm

        This is my problem too:

        [1] Resizing pre_capture buffer to 1 items
        [0] Thread 1 – Watchdog timeout, trying to do a graceful restart
        [0] httpd – Finishing
        [0] httpd Closing
        [0] httpd thread exit

  2. #4 by Chris on March 13, 2013 - 5:51 am

    I got the same problem:
    [1] Resizing pre_capture buffer to 1 items

    > Did one of you guys already solve that?

    THX!

  3. #5 by Dan Lake on April 6, 2013 - 2:46 am

    I set this up following your directions on my Raspberry Pi and my Logitech camera. It works great on Chrome over the web from a PC, but on iPhone or other Apple devices it doesn’t refresh. You show your MJPEG stream on your iphone. Do the photos update when you view it on the iphone? My Safari only shows the first image when I enter the URL and then never updates. If I stop the page and reload, I get 1 more image. If I install “CCTV Lite” or another MJPEG stream viewing app, then I can connect to my motion server but not directly from the web browser on the phone like I can on the PC. Any ideas?

  4. #6 by Dan Lake on April 6, 2013 - 10:24 pm

    So I got it working on Safari by making a webpage on my apache server and the only think on the page is an tag with the url to the motion server as the source. Now it works on both Chrome with PC and Safari with iPhone. Still no love from IE on Windows or Chrome for iPhone. I’d be interested in a good cross platform solution that doesn’t require special plugins. There must be a javascript or HTML5 solution.

    • #7 by Gary A. Stafford on April 15, 2013 - 9:20 pm

      Thanks for the feedback. I haven’t had a lot of luck getting enough performance out of the Raspberry Pi with motion to be really useful.

      • #8 by Dan Lake on April 15, 2013 - 10:46 pm

        The resolution definitely needs to be very low. If it goes much about 352 x 288 then it doesn’t display at all and I need to keep the frame rate at 1 or 2 per second. Saving videos has not worked for me at all so I just use it as an IP webcam that I can view online to check in things. Thanks for the nice instructions to get me started with the Pi and Motion.

  5. #9 by Syed on April 27, 2013 - 8:06 pm

    Hi Gary,

    Are you able to drive two webcam from a single Raspberry pi ? For some reason it works fine with single webcam but not with 2 webcams.

    • #10 by Gary A. Stafford on April 27, 2013 - 8:46 pm

      I have not tried. I had such slow results with one webcam, I would be surprised if the RPi could handle both.

      • #11 by Syed on May 22, 2013 - 6:02 pm

        Just an update. I have tried motion with two cameras by connecting through ethernet port for internet connectivity instead of wifi dongle and it works great.

        Syed

  6. #12 by Ayaz Ali Qureshi (@ayazaliqureshi) on May 16, 2013 - 4:11 pm

    Hello Gary,

    I have followed all the installation instructions. Now I want to execute a python program which sends the snapshot to my remote database and save it as a blob. I have written the python script although when user ‘motion’ executes as a daemon some permission issues dont let the python script open the file. But if I manually run the motion software from root user. It works fine. I am looking for a way to automate this, the permissions are the only issue in this.

    Any help is much appreciated.

  7. #13 by AISamurai on May 24, 2013 - 10:24 pm

    Hi, and thanks for the tutorial, could you please explain or write out how to config. multiple cams? I have enabled the additional threads, and the thread.conf files correctly and know all 3 cameras are live and can output. I think the problem is that I cannot get Motion to run more than 1 thread. How do I get the Pi to run all 4 motion threads (3 cameras+motion.conf).Can you help please?

  8. #14 by buminda on June 22, 2013 - 8:38 pm

    Thanks for sharing this. I had the same problem when resizing the image.But still managed to work with 640*480. Great tutorial.

  9. #16 by swabedor on July 9, 2013 - 2:20 pm

    has anyone tried using the area_detect option it doesn’t seem to work for me.

    area_detect 456789

  10. #17 by Ed on August 4, 2013 - 10:13 am

    Very nice. Will this setup work with the Raspberry Pi camera board?

  11. #18 by Leif on August 7, 2013 - 11:05 am

    You may want to use a dyndns account to get rid of the problem not to know your dynamic IP address. All in all a good desciption that halped my a lot. Thank you!

  12. #20 by Julien on August 25, 2013 - 5:02 am

    hello Gary,
    I have a problem. Being a total French beginer, and do not understanding every english Word, my Raspi displays:
    chmod: cannot access ‘ /tmp/motion’ : No such file or directory

    It will be kind of you to help me.
    thanks

  13. #21 by john on October 25, 2013 - 6:10 am

    Hi Gary. Amazing article, thanks for this.

    I’m wondering though.. When I view my cam – it seems to be constantly streaming new JPEGs (I see the timer changing every second on the camera feed), even when no motion is detected. Is this normal?

    • #22 by Gary A. Stafford on October 26, 2013 - 7:23 am

      I believe that is right, but only the motion images (frames) are saved to disk. Look at the Live Webcam Server section of the configuration.

  14. #23 by Arvin on October 25, 2013 - 7:49 am

    Hi Gary,

    Where does the images saved once they are captured? is it on the Memory card itself? If so is there a way to have them saved on a USB Drive or a NAS Drive please?

  15. #25 by Bogdan Craciun on November 17, 2013 - 2:16 pm

    Would it be possible to have the RPi in an “idle” state and turn back “on” when it detects motion by a PIR motion detector, then start capturing some frames and upload them to a database? in this way you could run it out of batteries for months

    • #26 by Gary A. Stafford on November 17, 2013 - 11:38 pm

      Good question. I don’t think so. The camera needs Motion running to detect. Motion needs the OS running. The camera needs power all the time, which it gets from the RPi. Imaging is pretty processor intensive.

      • #27 by Bogdan Craciun on November 17, 2013 - 11:55 pm

        what I was thinking about is having a Passive Infrared Motion detector attached to the RPi, triggering the video recording, instead of using the Motion software. But I guess your right, this would involve being possible to configure different power states for the RPi. Btw, I couldn’t found anything on this (idle, sleep, hibernate mode) for the RPi. I am looking to build a device similar to this: http://www.cambridgeconsultants.com/news/pr/release/140/en, but instead of using satellite communication I am thinking of a 3G dongle, SLA batteries, RPi and video cameras. If I want to make it fully or almoust fully automous (a couple of months on a single charge), I guess I would definetely need to digg into the power management

      • #28 by Gary A. Stafford on November 18, 2013 - 12:03 am

        Funny I was thinking the same thing – a PIR sensor, but figured it would also require power from the pi. If you could find a sensor with its own source of power supply Maybe?

      • #29 by Bogdan Craciun on November 18, 2013 - 12:25 am

        ok, my bad. I thought that by “motion running to detect” you mean that the motion software and ofcourse the video camera needs to be running in order to detect motion :). which I understand, is exactly like in your tutorial. (congrats on the detailed tutorial)
        however a PIR sensor with its own power supply would be a good idea for a battery operated solution, if the wake time of the Pi would be short enough to (video) capture the moving target.

  16. #30 by Winko on November 24, 2013 - 6:14 am

    Hi Gary,

    I loved your article!

    You asked: So what is the external address of my network?

    I configured xmail on my Raspberry Pi and used a script named ipaddrcheck.sh which runs every hour. It sends me an email whenever the ip-address changed.

    Regards,

    Winko

    ipaddrcheck.sh:

    !/bin/bash

    curl -o ~/newip ifconfig.me

    cmp ~/newip ~/oldip >/dev/null || {
    mv ~/newip ~/oldip
    mailx -s “I – SqueezePlug IP changed” winko@x.x < ~/oldip
    }

  17. #32 by Lukas on January 27, 2014 - 3:55 am

    I can’t view livestream,dosen’t work on port 8080 and 8081 :-(
    Any sugesion, why ?

  18. #34 by William Norris on February 13, 2014 - 9:08 pm

    Hey Gary, I have been trying to set up motion with a mysql database running on the raspberry pi with no luck. Any guides I have seen online make reference to the configure file which I cannot find. I have added the mysql database details to the motion.conf file but it has not made any difference. I was wondering if you have managed to get this working?

  19. #35 by Gerardo on March 20, 2014 - 2:12 am

    Hi Gary!,
    I’m working in a webcam surveillance with the Raspberry Pi and I’ve had some problems running the webcam on the internet. I can see the webcam on the internet but only for a couple of seconds and then I lost image.
    What would you recommend me?
    Thank you.

  1. Remote Motion-Activated Web-Based Surveillance with Raspberry Pi | Arduino, Netduino, Rasperry Pi! | Scoop.it
  2. Object Tracking on the Raspberry Pi with C++, OpenCV, and cvBlob « ProgrammaticPonderings
  3. Playing with raspberries
  4. Using the Raspberry Pi for something other than XBMC?
  5. Remote Motion-Activated Web-Based Surveillance with Raspberry Pi | buminda
  6. Raspberry Pi-Powered Dashboard Video Camera Using Motion and FFmpeg | ProgrammaticPonderings
  7. Remote Motion-Activated Web-Based Surveillance ...

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 398 other followers

%d bloggers like this: