Kutluhan Aktar
Published © CC BY

WhatsApp Surveillance Video Camera with IR Proximity Sensor

Get notified via WhatsApp with a video (mp4) and a captured first-look thumbnail image as intrusion alert when the IR sensor detects motion.

ExpertFull instructions provided4 hours6,475
WhatsApp Surveillance Video Camera with IR Proximity Sensor

Things used in this project

Hardware components

Raspberry Pi 3 Model B+
Raspberry Pi 3 Model B+
×1
Camera Module
Raspberry Pi Camera Module
×1
Arduino Nano R3
Arduino Nano R3
×1
DigitSpace Sharp IR Proximity Sensor
×1
LDR, 5 Mohm
LDR, 5 Mohm
×1
5 mm LED: Red
5 mm LED: Red
×1
5 mm LED: Green
5 mm LED: Green
×1
Breadboard (generic)
Breadboard (generic)
×1
Resistor 1k ohm
Resistor 1k ohm
×1
Resistor 221 ohm
Resistor 221 ohm
×4
Male/Female Jumper Wires
Male/Female Jumper Wires
×1
Male/Male Jumper Wires
×1

Software apps and online services

Thonny Python IDE
Arduino IDE
Arduino IDE
Notepad++

Hand tools and fabrication machines

Hot glue gun (generic)
Hot glue gun (generic)

Story

Read more

Custom parts and enclosures

Fritzing

Schematics

Schematic

Code

file_pathway (webhook)

PHP
<?php
// Implement Twilio's API to send data to WhatsApp.
require_once $_SERVER['DOCUMENT_ROOT'].'/path/to/vendor/autoload.php'; 
 
use Twilio\Rest\Client; 

if(!empty($_FILES["rasp_video"]["name"]) && !empty($_FILES["rasp_capture"]["name"])){
	// Get the brightness value from Raspberry Pi.
	$brightness = (isset($_POST['brightness'])) ? $_POST['brightness'] : "Not Detected!";
	
	// Get properties of the uploaded files.
	// Video File:
	$video_properties = array(
	    "name" => $_FILES["rasp_video"]["name"],
	    "tmp_name" => $_FILES["rasp_video"]["tmp_name"],
		"size" => $_FILES["rasp_video"]["size"],
		"extension" => pathinfo($_FILES["rasp_video"]["name"], PATHINFO_EXTENSION)
	);
	// Image File:
	$capture_properties = array(
	    "name" => $_FILES["rasp_capture"]["name"],
	    "tmp_name" => $_FILES["rasp_capture"]["tmp_name"],
		"size" => $_FILES["rasp_capture"]["size"],
		"extension" => pathinfo($_FILES["rasp_capture"]["name"], PATHINFO_EXTENSION)
	);
	// Check whether the uploaded file extensions are in allowed formats.
	$allowed_formats = array('jpg', 'png', 'mp4');
	if(!in_array($video_properties["extension"], $allowed_formats) || !in_array($capture_properties["extension"], $allowed_formats)){
		echo 'SERVER RESPONSE:\r\nFILE => File Format Not Allowed!';
	}else{
		// Check whether the uploaded file sizes exceed the data limit - 5MB.
		if($video_properties["size"] > 5000000 || $capture_properties["size"] > 5000000){
			echo 'SERVER RESPONSE:\r\nFILE => File size cannot exceed 5MB.';
		}else{
		    $video_root = $video_properties["name"];
		    $capture_root = $capture_properties["name"];
			$media = "[_URL_]".$capture_properties["name"]; // e.g., https://www.theamplituhedron.com/dashboard/WhatsApp-Surveillance-Camera/
			$video = "[_URL_]".$video_properties["name"];   // e.g., https://www.theamplituhedron.com/dashboard/WhatsApp-Surveillance-Camera/
			
			// Upload files - video and capture image.
		    move_uploaded_file($video_properties["tmp_name"], $video_root);
		    move_uploaded_file($capture_properties["tmp_name"], $capture_root);
			
		    // Send the information of the uploaded files, including temp names, to Raspberry Pi as the response message.
		    echo "SERVER RESPONSE:\r\nFILE => Files Uploaded Successfully!\r\nTMP_VIDEO => ".$video_properties["tmp_name"]."\r\nVIDEO_SIZE => ".$video_properties["size"]."\r\nTMP_CAPTURE => ".$capture_properties["tmp_name"]."\r\nCAPTURE_SIZE => ".$capture_properties["size"]."\r\nDATA => Received: ".$brightness;
			
			// Send the recently uploaded files to WhatsApp - video and capture image.
			// Define the required properties by Twilio's API:
            // SID, AUTH_TOKEN, FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE BODY, and MEDIA FILE PATH(CAPTURE).
			// Note: Refrain from adding '+' at the beginning of the phone numbers when entering them as send_data_to_WhatsApp() function parameters.
			send_data_to_WhatsApp("[_SID_]", "[_AUTH_TOKEN_]", "[_FROM_PHONE_NUMBER_]", "[_TO_PHONE_NUMBER_]", "Intrusion Detected by Raspberry Pi  \n\nBrightness => ".$brightness."\n\nVideo =>\n".$video, $media);
			echo "\r\nAPI => Files Send to WhatsApp!";
		}
	}

}else{
	echo "SERVER RESPONSE:\r\nFILE => No File Detected!";
}

function send_data_to_WhatsApp($sid, $token, $from, $to, $body, $media){
	$twilio = new Client($sid, $token);
    $message = $twilio->messages->create("whatsapp:+".$to, array("from" => "whatsapp:+".$from, "body" => $body, "mediaUrl" => array($media)));
}

?>

whatsapp_surveillance.py

Python
# WhatsApp Surveillance Video Camera with Infrared Proximity Sensor
#
# Raspberry Pi 3 Model B+
#
# By Kutluhan Aktar
#
# Get notified via WhatsApp with a video and a captured first-look thumbnail as intrusion alert
# when the proximity sensor detects motion.
#
# For more information and explanation, visit the link below:
# https://www.theamplituhedron.com/projects/WhatsApp-Surveillance-Video-Camera-with-Infrared-Proximity-Sensor/
#
# If you need a host server for this project or a web application by which you can manage the uploaded files easily,
# check out this application on TheAmplituhedron:
# https://www.theamplituhedron.com/dashboard/WhatsApp-Surveillance-Camera/

from picamera import PiCamera
from time import sleep
import datetime
from subprocess import call 
import requests
import RPi.GPIO as GPIO

# Set up BCM GPIO numbering
GPIO.setmode(GPIO.BCM)
# Set up input pins
IR_INPUT = 22
PR_INPUT = 23
GPIO.setup(IR_INPUT, GPIO.IN)
GPIO.setup(PR_INPUT, GPIO.IN)

# Define functions:

# Initiate the camera module with pre-defined setttings.
camera = PiCamera()
camera.resolution = (640, 480)
camera.framerate = 15

def record_trespassing(file_h264, file_mp4, file_capture, text):
    # Add date as timestamp on the generated files.
    camera.annotate_text = text
    # Capture an image as the thumbnail.
    sleep(2)
    camera.capture(file_capture)
    print("\r\nImage Captured! \r\n")
    # Record a 15 seconds video.
    camera.start_recording(file_h264)
    sleep(20)
    camera.stop_recording()
    print("Rasp_Pi => Video Recorded! \r\n")
    # Convert the h224 format to the mp4 format.
    command = "MP4Box -add " + file_h264 + " " + file_mp4
    call([command], shell=True)
    print("\r\nRasp_Pi => Video Converted! \r\n")
    
def send_video_to_server(file_mp4, file_capture, brightness):
    # Define the file path to send the currently recorded video to the server.  
    url = 'https://www.theamplituhedron.com/dashboard/WhatsApp-Surveillance-Camera/file_pathway.php'
    files = {'rasp_video': open(file_mp4, 'rb'), 'rasp_capture': open(file_capture, 'rb')}
    data = {'brightness': brightness}
    # Make an HTTP Post Request to the server.
    request = requests.post(url, files=files, data=data)
    # Print the response from the server.
    print ("Rasp_Pi => Files Transferred! \r\n")
    print(request.text + "\r\n")

# Initiate the loop.
while True:
    print("Waiting...")
    
    if GPIO.input(IR_INPUT):
        brightness = "LOW" if GPIO.input(PR_INPUT) else "OPTIMUM"
        # Get the current date as the timestamp to generate unique file names.
        date = datetime.datetime.now().strftime('%m-%d-%Y_%H.%M.%S')
        capture_img = '/home/pi/Surveillance/intrusion_' + date + '.jpg'
        video_h264 = '/home/pi/Surveillance/intrusion_' + date + '.h264'
        video_mp4 = '/home/pi/Surveillance/intrusion_' + date + '.mp4'
        # Create and send files:
        record_trespassing(video_h264, video_mp4, capture_img, date)
        send_video_to_server(video_mp4, capture_img, brightness)
        
    sleep(1)

WhatsApp Surveillance Video Camera.ino

Arduino
         ////////////////////////////////////////////////////  
        //      WhatsApp Surveillance Video Camera        //
       //        with Infrared Proximity Sensor          //
      //           -------------------------            //
     //                 Arduino Nano                   //           
    //               by Kutluhan Aktar                // 
   //                                                //
  ////////////////////////////////////////////////////

// Get notified via WhatsApp with a video and a captured first-look thumbnail as intrusion alert when the proximity sensor detects motion.
//
// This code is only for reading analog inputs in order to pass the values to Raspberry Pi.
//
// For more information, visit the project page:
// https://www.theamplituhedron.com/projects/WhatsApp-Surveillance-Video-Camera-with-Infrared-Proximity-Sensor/
//
// If you need a host server for this project or a web application by which you can manage the uploaded files easily, check out this application on TheAmplituhedron:
// https://www.theamplituhedron.com/dashboard/WhatsApp-Surveillance-Camera/
//
// Connections
// Arduino Nano :           
//                                Sharp-GP2Y0A02YK0F IR Sensor
// GND --------------------------- GND
// 5V  --------------------------- +
// A0  --------------------------- Signal
//
//                                Photoresistor
// A1  --------------------------- 
//                                IR_OUTPUT_LED
// D3  --------------------------- 
//                                PR_OUTPUT_LED
// D4  --------------------------- 


// Define sensor pins.
#define IR_PIN A0
#define PR_PIN A1
#define IR_OUTPUT 3
#define PR_OUTPUT 4

// Define data holders.
int distance, brightness;

void setup() {
  Serial.begin(9600);

  pinMode(IR_OUTPUT, OUTPUT);
  pinMode(PR_OUTPUT, OUTPUT);
  
}

void loop() {
  // Get brightness.
  brightness = map(analogRead(PR_PIN), 0, 1023, 0, 100);
  
  // Get distance from Sharp-GP2Y0A02YK0F IR Sensor.
  float volts = analogRead(IR_PIN) * 0.0048828125; // Sensor Value: (5 / 1024)
  distance = 13 * pow(volts, -1); //from datasheet graph
  delay(100);

  Serial.println("Brightness: " + String(brightness) + "%\n\n");
  Serial.println("Distance: " + String(distance) + "cm");

  // Send signal to Raspberry Pi.
  if(distance < 9){ digitalWrite(IR_OUTPUT, HIGH); }else{ digitalWrite(IR_OUTPUT, LOW); }

  if(brightness < 10){digitalWrite(PR_OUTPUT, HIGH); }else{ digitalWrite(PR_OUTPUT, LOW); }
}

Credits

Kutluhan Aktar

Kutluhan Aktar

30 projects • 66 followers
Self-Taught Full Stack Developer | Programmer | Maker | Physics Enthusiast

Comments