[PYTHON] Phone notification when surveillance camera motion is detected on Raspberry Pi

It's standard to run the Raspberry Pi as a surveillance camera, There was no phone notification to the number specified when the motion was detected, so I made one.

specification

As an application ...

A call is received by detecting the movement of the child returning to his home. ↓ "Oh? I got a call." Check your child's appearance on Slack ↓ Even if you post incoming call OFF to Slack and detect motion, it will not be received

environment

The camera uses LOGICOOL webcam HD image quality 1.2 megapixel C270 (Amazon) .

procedure

Asterisk settings

See below for Asterisk settings Building an IP phone system with Raspberry Pi and Asterisk (Part 1) Building an IP phone system with Raspberry Pi and Asterisk (Part 2)

motion settings

install motion

Terminal


apt-get install -y motion

Modify motion.conf

Terminal


vi /etc/motion/motion.conf

motion.conf


# Threshold for number of changed pixels in an image that
# triggers motion detection (default: 1500)
#threshold 1500
threshold 8000   #Raise the threshold that triggers taking a picture

:

# Target base directory for pictures and films
# Recommended to use absolute path. (Default: current working directory)
target_dir /tmp/motion #Set the save destination of the captured image

:

#Motion at the time of shooting.Run the py file. Of the parameters%f is the captured file PATH
on_picture_save python /home/hasuo/motion/motion.py %f

It is successful if motion is executed and the camera detects the motion and an image file is generated in / home / tmp /.

Terminal


motion -c /etc/motion/motion.conf

Slack settings

Issue an account on Slack .

Check the token and channel ID to post using Slack's API. https://api.slack.com/methods/channels.list/test

With Sign In, press [Test Mode] to get the token and channel ID.

URL


https://slack.com/api/channels.list?token=<token>&pretty=1 

channels.list execution result


{
    "ok": true,
    "channels": [
        {
            "id": "<Channel ID>",
            "name": "general",
            "is_channel": true,
              :

Image upload

Images are automatically posted to Slack when motion is detected using Slack's API. First, create a place to post to Slack.

motion.py


TOKEN      = '<token>'
CHANNEL    = '<Channel ID>'

# slack API : files.upload
#Reference: https://api.slack.com/methods/files.upload
####
def upload_file(file_path, channel):
    
    with open(file_path,'rb') as f:
        param = {'token':TOKEN, 'channels':CHANNEL,}
        r = requests.post("https://slack.com/api/files.upload", params=param,files={'file':f})
    

if __name__ == "__main__":
    
    arg     = sys.argv
    file_path = arg[1]
    
    upload_file(file_path, CHANNEL)
    

Give execute permission to the source file and check if you can post an image with an appropriate image file.

Terminal


chmod 755 motion.py
python motion.py <Image file PATH>

When I checked it on Slack, the image was posted safely.

無題.png

Phone notification

Make sure to create a file for auto-call so that Asterisk will auto-call.

motion.py


TOKEN                 = '<token>'
CHANNEL               = '<Channel ID>'
CALLFILE_DIR          = '<Auto call file directory>'
CALLFILE_NAME         = 'auto_call.call'    #Auto call file name
OUTGOING_DIR          = '/var/spool/asterisk/outgoing/'

#Automatic outgoing file generation-> outgoing
####
def outgoing_call():
    
    file_str = '''#
Channel: SIP/<Phone number you want to notify>@<Section name for external line transmission>
MaxRetries: 0               #Call count is 1
RetryTime: 60               #Waiting time to call again(Seconds)
WaitTime: 30                #Call for 30 seconds
Context: <extensions.Context settings along with conf>
Extension: <extensions.Exten settings along with conf>
Priority: 1'''
    
    file = open(CALLFILE_DIR +CALLFILE_NAME, "w")
    file.writelines(file_str);
    file.close()
    
    os.chmod(CALLFILE_DIR + CALLFILE_NAME, 0755)
    shutil.move(CALLFILE_DIR + CALLFILE_NAME, OUTGOING_DIR)

if __name__ == "__main__":
    
    outgoing_call()

Give execute permission to the source file and write permission to / var / spool / asterisk / outgoing / and check if the call is received by executing the file.

Terminal


chmod 755 motion.py
python motion.py

Phone notification ON / OFF

Use get_channel_info from Slack to get the latest posts when motion is detected.

The ON / OFF status of phone notifications is retained by creating a configuration file with ConfigParser.

I think there is a smarter way, but I couldn't think of it, so this time.

motion.py


# coding:utf-8

import sys
import os
import shutil
import pprint
import urllib
import urllib2
import json
import ConfigParser

TOKEN                 = '<token>'
CHANNEL               = '<Channel ID>'
CALL_NOTIFY_START_STR = 'call';       #Telephone notification ON judgment character string
CALL_NOTIFY_END_STR   = 'nocall';     #Telephone notification OFF judgment character string
INIFILE_PATH          = 'config.ini'  #setting file
SECTION               = 'motion notify'

# slack API : channels.info
#Reference: https://api.slack.com/methods/channels.info
####
def get_channel_info():

    url = "https://slack.com/api/channels.info"

    params = {'token'  : TOKEN,
              'channel': CHANNEL,
    }

    params = urllib.urlencode(params)

    req    = urllib2.Request(url)
    req.add_header('Content-Type', 'application/x-www-form-urlencoded')

    req.add_data(params)
    res     = urllib2.urlopen(req)
    body    = res.read()
    result  = json.loads(body)

    return result

#Phone notification ON/OFF setting
# slack_last_text :The text part of the latest post received from slack
####
def set_call_notify(slack_last_text):

    config = ConfigParser.SafeConfigParser()

    if not config.has_section(SECTION):
        config.add_section(SECTION)

    #Get the contents of the configuration file
    try :
        config.read(INIFILE_PATH)
        ini_set = config.get(SECTION,'enable')
    except Exception as e:
        ini_set = 'FALSE'

    if slack_last_text == CALL_NOTIFY_START_STR:
        config.set(SECTION, 'enable', 'TRUE')
        ini_set = 'TRUE'

    elif slack_last_text == CALL_NOTIFY_END_STR:
        config.set(SECTION, 'enable', 'FALSE')
        ini_set = 'FALSE'
    else:
        config.set(SECTION, 'enable', ini_set)

    config.write(open(INIFILE_PATH, 'w'))

    return ini_set

if __name__ == "__main__":

    channnels_info = get_channel_info()

    is_call = set_call_notify(channnels_info['channel']['latest']['text'])

    print is_call

After posting "call on" and "call off" in Slack, it is successful if the following setting file is generated when shooting.

config.ini


[motion notify]
enable = FALSE

Create a source file based on these.

When I actually operate it ...

無題2.png

Just move in front of the camera and it will be posted and you will receive a phone call. No longer annoying (laughs)

When I posted "no call", the photo was posted to Slack and the phone notification was stopped, so this is completed

See below for more information on motion and Slack I made a surveillance camera with my first Raspberry PI.

Impressions

If you use the voice synthesis engine Open JTalk and detect a moving object, it will be interesting to talk about something.

reference

I made a surveillance camera with my first Raspberry PI.

Recommended Posts

Phone notification when surveillance camera motion is detected on Raspberry Pi
A memorandum when making a surveillance camera with Raspberry Pi
"Honwaka Notification Lamp" on Raspberry Pi Part 2
"Honwaka Notification Lamp" on Raspberry Pi Part 1
"Honwaka Notification Lamp" on Raspberry Pi Part 3
Why detectMultiScale () is slow on Raspberry Pi B +
What is Raspberry Pi?
pigpio on Raspberry pi
Raspberry Pi video camera
Cython on Raspberry Pi
Create a web surveillance camera with Raspberry Pi and OpenCV
I made a surveillance camera with my first Raspberry PI.
Introduced pyenv on Raspberry Pi
Use NeoPixel on Raspberry Pi
Install OpenCV4 on Raspberry Pi 3
Install TensorFlow 1.15.0 on Raspberry Pi
Resolved an error when putting pygame in python3 on raspberry pi
Testing uart communication on Raspberry Pi
MQTT on Raspberry Pi and Mac
Install ghoto2 on Raspberry Pi (memo)
Try using ArUco on Raspberry Pi
OpenCV installation procedure on Raspberry Pi
Power on / off Raspberry pi on Arduino
Detect switch status on Raspberry Pi 3
Install OpenMedia Vault 5 on Raspberry Pi 4
L Chika on Raspberry Pi C #
Build wxPython on Ubuntu 20.04 on raspberry pi 4
IPv6 should be disabled when ssh of Raspberry Pi 4 is very slow
Initial settings for using GrovePi + starter kit and camera on Raspberry Pi