[PYTHON] A memorandum when making a surveillance camera with Raspberry Pi

A memorandum when I made it because I needed a surveillance camera in an unmanned room. Motivation is not to use an external monitor and keyboard

What I used

I used the following.

Raspbian (OS) Insco

$ #Get the latest RASPBIAN
$wget https://downloads.raspberrypi.org/raspbian_latest
--2017-09-12 20:02:28--  https://downloads.raspberrypi.org/raspbian_latest
Resolving downloads.raspberrypi.org... 93.93.135.188, 93.93.128.211, 93.93.128.230, ...
Connecting to downloads.raspberrypi.org|93.93.135.188|:443... connected.
HTTP request sent, awaiting response... 302 Found
Location: https://downloads.raspberrypi.org/raspbian/images/raspbian-2017-09-08/2017-09-07-raspbian-stretch.zip [following]
--2017-09-12 20:02:31--  https://downloads.raspberrypi.org/raspbian/images/raspbian-2017-09-08/2017-09-07-raspbian-stretch.zip
Connecting to downloads.raspberrypi.org|93.93.135.188|:443... connected.
HTTP request sent, awaiting response... 302 Found
Location: http://director.downloads.raspberrypi.org/raspbian/images/raspbian-2017-09-08/2017-09-07-raspbian-stretch.zip [following]
--2017-09-12 20:02:32--  http://director.downloads.raspberrypi.org/raspbian/images/raspbian-2017-09-08/2017-09-07-raspbian-stretch.zip
Resolving director.downloads.raspberrypi.org... 93.93.130.214, 93.93.130.104, 93.93.128.133, ...
Connecting to director.downloads.raspberrypi.org|93.93.130.214|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 1757290390 (1.6G) [application/zip]
Saving to: 'raspbian_latest'

raspbian_latest                               100%[==============================================================================================>]   1.64G   271KB/s    in 2h 4m

2017-09-12 22:06:45 (230 KB/s) - 'raspbian_latest' saved [1757290390/1757290390]

wget https://downloads.raspberrypi.org/raspbian_latest  16.39s user 71.27s system 1% cpu 2:04:16.75 total

$ #Check files with SHA1
$openssl sha1 raspbian_latest
SHA1(raspbian_latest)= c35688583510fc93c5deac637976b7a5c9c55689
openssl sha1 raspbian_latest  3.70s user 0.46s system 92% cpu 4.478 total

$ #Defrost
$unzip raspbian_latest
Archive:  raspbian_latest
  inflating: 2017-09-07-raspbian-stretch.img
unzip raspbian_latest  32.40s user 4.09s system 87% cpu 41.859 total

$ #Check the file
$ ls -al 
total 13033808
drwxr-xr-x   4 os10  staff         136  9 12 22:38 .
drwxr-xr-x  12 os10  staff         408  9 12 20:02 ..
-rw-r--r--   1 os10  staff  4916019200  9  8 01:23 2017-09-07-raspbian-stretch.img
-rw-r--r--   1 os10  staff  1757290390  9  8 01:30 raspbian_latest

SD card format and copy of Raspbian

$ #* Mount the SD card first
$ diskutil list
...
/dev/disk2 (internal, physical):
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:     FDisk_partition_scheme                        *15.8 GB    disk2
   1:             Windows_FAT_32 NO NAME                 15.8 GB    disk2s1

$ #Format SD card
$ diskutil eraseDisk FAT32 RPI /dev/disk2
Started erase on disk2
Unmounting disk
Creating the partition map
Waiting for partitions to activate
Formatting disk2s2 as MS-DOS (FAT32) with name RPI
512 bytes per physical sector
/dev/rdisk2s2: 30487440 sectors in 1905465 FAT32 clusters (8192 bytes/cluster)
bps=512 spc=16 res=32 nft=2 mid=0xf8 spt=32 hds=255 hid=411648 drv=0x80 bsec=30517248 bspf=14887 rdcl=2 infs=1 bkbs=6
Mounting disk
Finished erase on disk2

$ #Unmount SD card
$ diskutil unmountDisk /dev/disk2
Unmount of all volumes on disk2 was successful

$ sudo dd bs=16m if=2017-09-07-raspbian-stretch.img of=/dev/rdisk2
$ #Adding r to the device name is about 10 times faster. Progress is Ctrl+Check with t.
$ #Image capacity is 5GB and 6MB/Since it was a sec speed, it was about 10 minutes.
load: 2.00  cmd: dd 73563 uninterruptible 0.00u 0.04s
3+0 records in
2+0 records out
33554432 bytes transferred in 5.498053 secs (6102966 bytes/sec)
load: 2.00  cmd: dd 73563 uninterruptible 0.00u 0.07s
...
4916019200 bytes transferred in 461.069118 secs (10662217 bytes/sec)
sudo dd bs=16m if=2017-09-07-raspbian-stretch.img of=/dev/rdisk2  0.01s user 3.18s system 0% cpu 7:43.63 total

Enable SSH

Apparently it has been disabled in the initial state recently

$ cd /Volumes
Macintosh HD boot
$ ls -al 
total 12
drwxr-xr-x@  4 root  wheel   136  9 13 00:54 .
drwxr-xr-x  34 root  wheel  1224  8 13 16:54 ..
lrwxr-xr-x   1 root  wheel     1  8 12 21:44 Macintosh HD -> /
drwxrwxrwx@  1 os10  staff  2048  9 13 00:54 boot

$ touch ./boot/ssh
$ #It seems that you should create an empty file called ssh in the boot folder

$ diskutil unmountDisk /dev/disk2
Unmount of all volumes on disk2 was successful

Connect Raspberry Pi to Mac

Follow the steps below to set up Sharing for Mac Network

  1. Open System Preference> Sharing
  2. Activate the Internet Sharing (Service) checkbox
  3. Activate the Thunderbolt Ethernet (Ports) checkbox in To computers using
  4. Start Raspberry Pi and connect to Mac with LAN cable

Connect to Raspberry Pi with SSH

$ #Check network interface(bridge***Interface with Ethernet option)
$ ifconfig
...
bridge100: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500
        options=3<RXCSUM,TXCSUM>
        ether a6:5e:60:ab:ad:64
        inet 192.168.2.1 netmask 0xffffff00 broadcast 192.168.2.255
        inet6 fe80::a45e:60ff:feab:ad64%bridge100 prefixlen 64 scopeid 0x10
        Configuration:
                id 0:0:0:0:0:0 priority 0 hellotime 0 fwddelay 0
                maxage 0 holdcnt 0 proto stp maxaddr 100 timeout 1200
                root id 0:0:0:0:0:0 priority 0 ifcost 0 port 0
                ipfilter disabled flags 0x2
        member: en6 flags=3<LEARNING,DISCOVER>
                ifmaxaddr 0 port 15 priority 0 path cost 0
        nd6 options=201<PERFORMNUD,DAD>
        media: autoselect
        status: active
$ #Thunderbolt I because inet is IPv4/F becomes
$ # -IP address: 192.168.2.1
$ # -sub-net mask: 255.255.255.0(/24)
$ # -Broadcast address: 192.168.2.255
$ #So the target IP address is 19.168.2.2~In the range of 244

$ #Get a list of hosts that exist on the network
$ nmap -n -sP 192.168.2.1/24
Starting Nmap 6.47 ( http://nmap.org ) at 2017-09-13 02:37 PHT
Strange error from connect (65):No route to host
Nmap scan report for 192.168.2.1
Host is up (0.0058s latency).
Nmap scan report for 192.168.2.3
Host is up (0.0052s latency).
Nmap done: 256 IP addresses (2 hosts up) scanned in 0.03 seconds
$ #This IP address(192.168.2.3)Is like that

$ #SSH connection
$ ssh [email protected]  # [email protected] is OK
[email protected]'s password: #PW is raspberry
$ # NOTE:For REMOTE HOST IDENTIFICATION HAS CHANGED, delete the fingerprint with the following command
$ # ssh-keygen -R 192.168.2.3

Use VNC

The reason for using VNC is to check the captured image

--Settings on the Raspberry side

```shell-session
$ #Put VNC on raspberry
$ sudo apt-get update
$ sudo apt-get install tightvncserver
$ tightvncserver #Start VNC server
#PW settings
```

--Mac settings --Launch Finder

Wifi settings

--Stab Buffalo's wireless LAN slave unit into Raspberry Pi --Set up Wifi with GUI --You can do it from CUI with wpa-supplicant.conf --Do not use Thunderbolt Ethernet adapter after setting Wifi

Camera settings

$ #Connect the USB camera to the Raspberry Pi
$ lsusb
Bus 001 Device 004: ID 0411:01a2 BUFFALO INC. (formerly MelCo., Inc.) WLI-UC-GNM Wireless LAN Adapter [Ralink RT8070]
Bus 001 Device 005: ID 046d:0826 Logitech, Inc. HD Webcam C525
Bus 001 Device 003: ID 0424:ec00 Standard Microsystems Corp. SMSC9512/9514 Fast Ethernet Adapter
Bus 001 Device 002: ID 0424:9514 Standard Microsystems Corp. SMC9514 Hub
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
$ #Logitech Webcam is recognized

$ #Insco capture software
$ sudo apt install fswebcam
...
Unpacking fswebcam (20140113-1) ...
Setting up fswebcam (20140113-1) ...
Processing triggers for man-db (2.7.6.1-2) ...

$ #Shooting test
$ pwd
/home/pi
$ fswebcam -r 640x480 -F 1 -S 100 ./test.jpg # -F is the frame, -S is exposure
--- Opening /dev/video0...
Trying source module v4l2...
/dev/video0 opened.
No input was specified, using the first.
Adjusting resolution from 384x288 to 352x288.
--- Capturing frame...
Captured frame in 0.00 seconds.
--- Processing captured image...
Fontconfig warning: ignoring UTF-8: not a valid region tag
Writing JPEG image to 'test.jpg'.
$ # /home/pi/test.The image is saved in jpg, so check it with VNC.

$ #Camera parameter adjustment software
$ sudo apt install guvcview
$ # Menu > Sound & Video >Launch guvcview

Motion sensor settings

$ sudo apt-get install -y motion

$ #Shooting test
$ sudo motion -c /etc/motion/motion.conf
$ # /var/lib/motion/It is saved in. Check with GUI

$ #Configuration file update(As follows)
$ sudo vi /etc/motion/motion.conf
#Run Motion as a service
daemon on
#Video function OFF
ffmpeg_output_movies off
#Photo size
width 640
height 480
#Motion detection threshold
threshold 3000 
gap 100
#About images
locate_motion_mode on #Let's scratch the motion detection point
text_double on #Text big

$ sudo vi /etc/default/motion
#Run as a daemon at startup
start_motion_daemon=yes 

Notify with Slack

Do the following in advance

--Slack registration --Create Slack App --Enable the following two points  1. Add features and functionality(Bot)
2. Install your app to your workspace (Target Team) --Invite the bot to the target channel

Python Dependent Module Insco

$ sudo pip install slacker
pi@raspberrypi:~/slack $ sudo pip install slacker

Collecting slacker
  Downloading slacker-0.9.60.tar.gz
Requirement already satisfied: requests>=2.2.1 in /usr/lib/python2.7/dist-packages (from slacker)
Building wheels for collected packages: slacker
  Running setup.py bdist_wheel for slacker ... done
  Stored in directory: /root/.cache/pip/wheels/57/61/2c/99406ad2141fdf3ede576acedad209a3b63b9674af56bbfa19
Successfully built slacker
Installing collected packages: slacker
Successfully installed slacker-0.9.60

Message posting test

$ python
Python 2.7.9 (default, Mar  8 2015, 00:52:26)
[GCC 4.9.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from slacker import Slacker
>>> token = "HOGEHOGE" # OAuth Tokens for Your Team >  Bot User OAuth Access Token
>>> slk = Slacker(token)
>>> cn = "C71DQB3MG" #The channel name is encoded. You can see it by looking at the URL of slack
>>> msg = 'It's an API' 
>>> slk.chat.post_message(cn, msg)
<slacker.Response object at 0xb64aca50>

Image upload test

$ python
Python 2.7.9 (default, Mar  8 2015, 00:52:26)
[GCC 4.9.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from slacker import Slacker
>>> token = "HOGEHOGE" # OAuth Tokens for Your Team >  Bot User OAuth Access Token
>>> slk = Slacker(token)
>>> cn = "C71DQB3MG"
>>> fn = '/home/pi/hoge.jpg'
>>> comment = "test"
>>> slk.files.upload(fn, channels=[cn], initial_comment=comment) #Post image
 <slacker.Response object at 0xb64aca50>

Automatic image posting with Motion

Hook the script every time you save the image in the Motion settings

$ sudo vi /etc/motion/motion.conf
#You can hook scripts from conf when saving
on_picture_save python /home/pi/slack/bot.py %f # %f=Image file name

$ cd /home/pi
$ mkdir slack
$ cd slack
$ vi bot.py #Script creation described later
$ chmod a+x /home/pi/slack/bot.py #Grant execution authority
$ python ./bot.py /home/pi/test.jpg #test

bot.py


# -*- coding: utf-8 -*-
import sys
from slacker import Slacker
from datetime import datetime

class Slack(object):

    __slacker = None

    def __init__(self, token):
        self.__slacker = Slacker(token)

    def post_to_file(self, file_path, encoded_ch_name):
        now = datetime.now()
        comment = "Uploaded At: " + now.strftime('%Y-%m-%d %H:%M:%S') + '(UTC)'
        print("Sending a picture")
        self.__slacker.files.upload(file_path, channels=[encoded_ch_name], initial_comment=comment)
        print("Done")

if __name__ == "__main__":

    param = sys.argv
    file_path = param[1]

    token = "" # Bot User OAuth Access Token
    slack = Slack(token)
    encoded_ch_name = "C71DQB3MG"
    slack.post_to_file(file_path, encoded_ch_name)

Make Motion a daemon

$ #Activated as a service
$ sudo systemctl enable motion
$ sudo systemctl list-unit-files -t service #Check the settings of the service list
$ sudo systemctl is-enabled motion #Check motion settings
motion.service is not a native service, redirecting to systemd-sysv-install.
Executing: /lib/systemd/systemd-sysv-install is-enabled motion
enabled
$ #OK because it is enabled

$ #Runlevel change
$ sudo systemctl set-default multi-user.target #Change default target to multi-user mode(Motion is enabled when the power is turned on)
$ sudo systemctl get-default
multi-user.target

$ #Start and check the service status
$ sudo systemctl start motion
$ sudo service motion status
● motion.service - LSB: Start Motion detection
   Loaded: loaded (/etc/init.d/motion; generated; vendor preset: enabled)
   Active: active (exited) since Wed 2017-09-13 01:19:37 UTC; 5h 51min ago
     Docs: man:systemd-sysv-generator(8)
  Process: 5219 ExecStop=/etc/init.d/motion stop (code=exited, status=0/SUCCESS)
  Process: 5268 ExecStart=/etc/init.d/motion start (code=exited, status=0/SUCCESS)
   CGroup: /system.slice/motion.service

Sep 13 01:19:37 raspberrypi systemd[1]: Starting LSB: Start Motion detection...
Sep 13 01:19:37 raspberrypi motion[5268]: Starting motion detection daemon: motion.
Sep 13 01:19:37 raspberrypi systemd[1]: Started LSB: Start Motion detection.
Sep 13 01:19:38 raspberrypi motion[5274]: [0:motion] [NTC] [ALL] conf_load: Processing thread 0 - config file /etc/motion/motion.conf
Sep 13 01:19:38 raspberrypi motion[5274]: [0:motion] [NTC] [ALL] motion_startup: Motion 4.0 Started
Sep 13 01:19:38 raspberrypi motion[5274]: [0:motion] [ERR] [ALL] myfopen: Error opening file /var/log/motion/motion.log with mode a: Permission denied
Sep 13 01:19:38 raspberrypi motion[5274]: [0:motion] [EMG] [ALL] motion_startup: Exit motion, cannot create log file /var/log/motion/motion.log: Permission denied

$ #It seems that there is no permission for the motion user, so change it
$ sudo chown motion:motion /var/run/motion
$ sudo chown motion:motion /var/log/motion/motion.log

$ #reconfirmation
$ sudo systemctl start motion
$ sudo systemctl status motion
...
Sep 13 07:17:01 raspberrypi systemd[1]: Starting LSB: Start Motion detection...
Sep 13 07:17:02 raspberrypi motion[5860]: Starting motion detection daemon: motion.
Sep 13 07:17:02 raspberrypi systemd[1]: Started LSB: Start Motion detection.
Sep 13 07:17:03 raspberrypi motion[5866]: [0:motion] [NTC] [ALL] conf_load: Processing thread 0 - config file /etc/motion/motion.conf
Sep 13 07:17:03 raspberrypi motion[5866]: [0:motion] [NTC] [ALL] motion_startup: Motion 4.0 Started
$ #This time OK

$ #If you want to see the entire service log
$ sudo journalctl -b | less #Check all logs
$ sudo journalctl -u motion | less #Motion log check

$ #Other
$ sudo systemctl stop motion
$ sudo systemctl disable motion

References

http://qiita.com/toshihirock/items/8e7f0887b565defe7989 https://medium.com/@tzhenghao/how-to-ssh-into-your-raspberry-pi-with-a-mac-and-ethernet-cable-636a197d055 http://qiita.com/wf9a5m75/items/6712181de189169eb444 http://www.pawprint.net/designresources/netmask-converter.php https://vivibit.net/raspbian-enable-ssh/ https://www.raspberrypi.org/forums/viewtopic.php?t=191252 http://daisukekmr.hatenablog.com/entry/2015/01/22/201919 http://qiita.com/kinpira/items/bf1df2c1983ba79ba455 http://a244.hateblo.jp/entry/2016/10/14/053000 http://qiita.com/Go-zen-chu/items/63f65156c748b34e1678 http://safe-linux.homeip.net/web/motion/motion-03.html https://github.com/yusukeyamatani/slackbot/blob/master/slack_bot.py https://github.com/os/slacker https://github.com/Motion-Project/motion/issues/309 https://raspberrypi.stackexchange.com/questions/41342/how-to-start-motion-in-daemon-mode-on-rpi-running-raspbian-jessie https://raspberrypi.stackexchange.com/questions/43740/how-do-i-change-runlevel-on-model-3

Recommended Posts

A memorandum when making a surveillance camera with Raspberry Pi
Create a web surveillance camera with Raspberry Pi and OpenCV
I made a surveillance camera with my first Raspberry PI.
Using a webcam with Raspberry Pi
Build a Tensorflow environment with Raspberry Pi [2020]
I tried to make a motion detection surveillance camera with OpenCV using a WEB camera with Raspberry Pi
Make a wash-drying timer with a Raspberry Pi
Phone notification when surveillance camera motion is detected on Raspberry Pi
Operate an oscilloscope with a Raspberry Pi
Create a car meter with raspberry pi
GPGPU with Raspberry Pi
Raspberry Pi video camera
DigitalSignage with Raspberry Pi
Display images taken with the Raspberry Pi camera module
Gently explain the process of making a simple serverless surveillance camera using Raspberry Pi, Gmail API and Line API
Face detection from images taken with Raspberry Pi camera
A memorandum when an error occurs with pip install
Display USB camera video with Python OpenCV with Raspberry Pi
Play with the Raspberry Pi Zero WH camera module Part 1
Python beginner opens and closes interlocking camera with Raspberry Pi
I made a resource monitor for Raspberry Pi with a spreadsheet
getrpimodel: Recognize Raspberry Pi model (A, B, B +, B2, B3, etc) with python
Creating a temperature / humidity monitor with Raspberry Pi (pigpio version)
[Raspberry Pi] Stepping motor control with Raspberry Pi
A memorandum when using beautiful soup
Control the motor with a motor driver using python on Raspberry Pi 3!
Use vl53l0x with Raspberry Pi (python)
Servo motor control with Raspberry Pi
How to upload a file to Cloud Storage using Python [Make a fixed point camera with Raspberry PI # 1]
A memorandum when I tried to get it automatically with selenium
Let's make a cycle computer with Raspberry Pi Zero (W, WH)
Serial communication with Raspberry Pi + PySerial
How to make a surveillance camera (Security Camera) with Opencv and Python
Christmas classic (?) Lighting a Christmas tree with Raspberry Pi and Philips Hue
OS setup with Raspberry Pi Imager
Make a thermometer with Raspberry Pi and make it viewable with a browser Part 4
Try L Chika with raspberry pi
A memo when connecting bluetooth from a smartphone / PC to Raspberry Pi 4
VPN server construction with Raspberry Pi
Try moving 3 servos with Raspberry Pi
[Note] Using 16x2-digit character LCD (1602A) from Python with Raspberry Pi
I made a pet camera that is always connected with WebRTC (Nuxt.js + Python + Firebase + SkyWay + Raspberry Pi)
A memo to simply use the illuminance sensor TSL2561 with Raspberry Pi 2
Detect analog signals with A / D converter using python on Raspberry Pi 3!
[Electronic work] I made a Suica touch sound detector with Raspberry Pi
Make a wireless LAN Ethernet converter and simple router with Raspberry Pi
[Python + PHP] Make a temperature / humidity / barometric pressure monitor with Raspberry Pi
I tried to make a traffic light-like with Raspberry Pi 4 (Python edition)
The story of making a sound camera with Touch Designer and ReSpeaker
Measure SIM signal strength with Raspberry Pi
Pet monitoring with Rekognition and Raspberry pi
Knowledge when making a bot using discord.py
[Raspberry Pi] Add a thermometer and a hygrometer
Raspberry Pi Security Infrared Camera (Python Edition)
Hello World with Raspberry Pi + Minecraft Pi Edition
Programming normally with Node-RED programming on Raspberry Pi 3
Improved motion sensor made with Raspberry Pi
Try Object detection with Raspberry Pi 4 + Coral
A workaround when installing pyAudio with pip.
Power SG-90 servo motor with raspberry pi
Memorandum of Understanding when migrating with GORM