Examples
-
The following provides some sample configuration options and examples for MotionPlus.
- Persistent v4l2 device name
- Sample extpipe commands
- Loopback device setup
- FFmpeg as input device
- Webcontrol pages
- Database setup
- Haar setup
- HOG setup
- DNN setup
- Haar Model Training
- Sound Frequency Sample
- Fail2Ban example
- PTZ command examples
Persistent v4l2 device name
-
Since the exact device number is set by the kernel upon boot, when there is more than one video device
it is possible that the particular cameras that were assigned to /dev/video0 and /dev/video1 may switch. In
order to set up Motion so that a particular camera is always assigned the same way, users can set up
a symbolic link using udev rules. To do this a unique attribute must be identified for each camera. The
camera attributes can be viewed by using the command
udevadm info -a -p $(udevadm info -q path -n /dev/video0)
while the camera is attached. Usually
a serial number can be used. ("Usually" because some cameras have been observed to have the same serial
number for different cameras)
Once a unique attribute has been identified for each camera, edit or create the file
/etc/udev/rules.d/99-local.rules
.
Assuming that the unique attribute for the camera was name and was
ATTR{name}=="Philips SPC 900NC webcam"
you would add the following line to the
99-local.rules file:
KERNEL=="video[0-9]*", ATTR{name}=="Philips\ SPC\ 900NC*", SYMLINK+="video-webcam0"
Once the change has been made and saved, reboot the computer and there should now be a "sticky" device called
/dev/video-webcam0
Sample extpipe commands
-
The following are some sample extpipe commands
movie_extpipe mencoder -demuxer rawvideo -rawvideo w=%w:h=%h:i420 -ovc x264 -x264encopts bframes=4:frameref=1:subq=1:scenecut=-1:nob_adapt:threads=1:keyint=1000:8x8dct:vbv_bufsize=4000:crf=24:partitions=i8x8,i4x4:vbv_maxrate=800:no-chroma-me -vf denoise3d=16:12:48:4,pp=lb -of avi -o %f.avi - -fps %{fps}
movie_extpipe x264 - --input-res %wx%h --fps %{fps} --bitrate 2000 --preset ultrafast --quiet -o %f.mp4
movie_extpipe mencoder -demuxer rawvideo -rawvideo w=%w:h=%h:fps=%{fps} -ovc x264 -x264encopts preset=ultrafast -of lavf -o %f.mp4 - -fps %{fps}
movie_extpipe ffmpeg -y -f rawvideo -pix_fmt yuv420p -video_size %wx%h -framerate %{fps} -i pipe:0 -vcodec libx264 -preset ultrafast -f mp4 %f.mp4
Loopback device setup
-
The video loopback device can be added installed via apt in many distributions. The package tested
with Motion is v4l2loopback-dkms. Once the package is installed, you just need to run
sudo modprobe v4l2loopback
. This will add a new video device that you
can use for the loopback. It is believed that there are additional options associated with the
v4l2loopback that allows for adding more than one device. See the documentation of the v4l2loopback
project for additional details.
To activate the vloopback device in Motion set the 'video_pipe' option in the motion.conf file to the
device name associated with the one created by v4l2loopback.
You can also view the special motion pictures where you see the changed pixels by setting the option 'video_pipe_motion' in motion.conf. When setting the video_pipe and/or video_pipe_motion options specify the input device as e.g. /dev/video1. De-activating should be done with this command
sudo modprobe -r v4l2loopback
Use ffmpeg as input device
-
Sometimes the particular device is not function for MotionPlus but does work with FFmpeg. In
this situation the device can be setup to be used in MotionPlus using FFMpeg as an intermediate
application. The process would be to set up a loopback device and then have FFmpeg feed the
video into that device and then Motion can read from it. The following are some examples. First set up
the loopback device and set it to /dev/video0. Then start ffmpeg using options such as the following.
ffmpeg -re -i mymovie.mp4 -f v4l2 /dev/video0
Then in a separate terminal, start MotionPlus
with it set to use the /dev/video0
device as input. This method can can also be used to
reformat the content to a different format. The following outputs the original movie into a gray pixel format.
ffmpeg -re -i mymovie.mp4 -f v4l2 -pix_fmt gray /dev/video0
Database Setup
-
If a database is specified in the MotionPlus configuration, upon start up, MotionPlus will check for a table in
the database called "motionplus" and if it is not found, it will create it. This MotionPlus specific table is
required so that movies can be displayed on the webcontrol page. It tracks the movies created by MotionPlus along
with the various metadata about the movies. The following is a brief overview of how to create a simple database
and specify it within the MotionPlus parameters so recordings can be downloaded from the webcontrol.
sqlite3
This database type is by far the easiest to set up since it is file based. Simply provide the parameters in the MotionPlus configuration parameters
database_type sqlite3
database_dbname /full/path/and/file/name.db
mariadb
The following describes the process to set up a Mariadb database. If your machine already has a Mariadb database, adjust as appropriate to the situation that exists on your computer. Those with more experience with MariaDb are invited to provide suggestions and corrections to these steps.
sudo apt install libmariadb-dev libmariadb3 mariadb-client mariadb-client-core mariadb-common mariadb-server
sudo mariadb
GRANT ALL ON *.* TO 'YourUserNameHere'@'localhost' IDENTIFIED BY 'YourPasswordHere' WITH GRANT OPTION;
FLUSH PRIVILEGES;
exit
mariadb -u YourUserNameHere -p
{enter YourPasswordHere}
create database motionplus;
use motionplus;
quit;
Once the database is set up, check the status of Mariadb via systemctl.
sudo systemctl status mariadb
database_type mariadb
database_dbname motionplus
database_host localhost
database_port 3306
database_user YourUserNameHere
database_password YourPasswordHere
postgresql
The following describes the process to set up a PostgreSQL database. If your machine already has a PostgreSQL database, adjust as appropriate to the situation that exists on your computer. Those with more experience with PostgreSQL are invited to provide suggestions and corrections to these steps.
sudo apt install postgresql postgresql-contrib
sudo -u postgres psql
CREATE ROLE 'your_username_here' LOGIN PASSWORD 'YourPasswordHere';
CREATE DATABASE motionplus WITH OWNER = your_username_here;
GRANT ALL PRIVILEGES ON DATABASE motionplus TO your_username_here;
\quit
Once the database is set up, check the status via systemctl.
sudo systemctl status postgresql
psql -h localhost -d motionplus -U your_username_here -p 5432
Specify the following in the MotionPlus configuration parameters.
database_type postgresql
database_dbname motionplus
database_host localhost
database_port 5432
database_user your_username_here
database_password YourPasswordHere
Webcontrol pages
{IP}:{port0}/
Home html page with streams for all cameras
The following JSON pages are available via the webcontrol.
{IP}:{port0}/0/config.json
JSON object with the configuration information for all cameras{IP}:{port0}/0/status.json
JSON object with information about status of all cameras{IP}:{port0}/0/movies.json
JSON object with information about all movies{IP}:{port0}/{camid}/mjpg
Primary stream for the camera updated as a mjpg{IP}:{port0}/{camid}/mjpg/substream
Substream for the camera updated as a mjpg{IP}:{port0}/{camid}/mjpg/motion
Stream of motion images for the camera as a mjpg{IP}:{port0}/{camid}/mjpg/source
Source image stream of the camera as a mjpg{IP}:{port0}/{camid}/mjpg/secondary
Image from secondary detection stream (if active) as a mjpg{IP}:{port0}/{camid}/mpegts
Primary stream for the camera updated as a mpeg transport stream{IP}:{port0}/{camid}/mpegts/substream
Substream for the camera updated as a mpeg transport stream{IP}:{port0}/{camid}/mpegts/motion
Stream of motion images for the camera as a mpeg transport stream{IP}:{port0}/{camid}/mpegts/source
Source image stream of the camera as a mpeg transport stream{IP}:{port0}/{camid}/mpegts/secondary
Image from secondary detection stream (if active) as a mpeg transport stream{IP}:{port0}/{camid}/static
Primary image for the camera{IP}:{port0}/{camid}/static/substream
Substream image for the camera{IP}:{port0}/{camid}/static/motion
Motion image for the camera{IP}:{port0}/{camid}/static/source
Source image of the camera{IP}:{port0}/{camid}/static/secondary
Image from secondary detection stream (if active)eventstart
Start an eventeventend
End an eventsnapshot
Invoke a snapshotpause
Pause motion detectionunpause
Unpause motion detectionrestart
Restart camerastop
Stop cameraconfig_write
Write out the configuration to file. User account running Motionplus must have write access to directorycamera_add
Add a cameracamera_delete
Delete cameraconfig
Set configuration itemaction_user
Execute the on_action_user command. Provide as needed the additional parameter of action_userpan_left
Execute the ptz_pan_left commandpan_right
Execute the ptz_pan_left commandtilt_up
Execute the ptz_tilt_uptilt_down
Execute the ptz_tilt_downzoom_in
Execute ptz_zoom_in commandzoom_out
Execute the ptz_zoom_out commandcurl -s -o -X POST {IP}:{port0} --data "camid={camid}" --data "command=eventstart" 1>/dev/null
curl -s -o -X POST {IP}:{port0} --data "camid={camid}" --data "command=config" --data "framerate=12" 1>/dev/null
HAAR setup
- Set the following Motionplus items within the secondardy_params
frame_interval
Default: 5 | The number of images between each secondary detectionimage_type
Default: full | Type of image to process through secondary detectionmodel_file
Default: None | Full path and file name for the haar modelrotate
Default: 0 | Degrees of rotation of the image when processing through secondary detectionthreshold
Default: 1.10 | weights of detected values- Set the following parameters to the OpenCV function
CascadeClassifier::detectMultScale
within the secondardy_params scalefactor
Default: 1.10 | Scale factor to apply to the imageflags
Default: 0 |maxsize
Default: 1024 |minsize
Default: 8 |minneighbors
Default: 8 |
HOG setup
- Set the following items within the secondardy_params
frame_interval
Default: 5 | The number of images between each secondary detectionimage_type
Default: full | Type of image to process through secondary detectionmodel_file
Default: None | Full path and file name for the haar modelrotate
Default: 0 | Degrees of rotation of the image when processing through secondary detectionthreshold
Default: 1.10 | Weights of detected values- Set the following parameters to the OpenCV function
HOGDescriptor::detectMultScale
within the secondardy_params threshold_model
Default: 2.00 |scalefactor
Default: 1.05 |padding
Default: 8 |winstride
Default: 8 |
DNN setup
- Set the following items within the secondardy_params
model_file
Default: None | Full path and file name for the haar modelframe_interval
Default: 5 | The number of images between each secondary detectionimage_type
Default: full | Type of image to process through secondary detectionrotate
Default: 0 | Degrees of rotation of the image when processing through secondary detectionthreshold
Default: 0.75 | Confidence thresholdscalefactor
Default: 1.05 |backend
Default: 0(DNN_BACKEND_DEFAULT) |target
Default: 0(DNN_TARGET_CPU) |width
Default: none | Width for the model (not the source image)height
Default: none | Height for the model (not the source image)scale
Default: none | Scale used in the modelconfig
Default: none |classes_file
Default: none | Full path and name for a file with the names of the classesframework
Default: none |
Haar Model Training
-
The OpenCV documentation is the definitive source for instructions on how to train
a Haar model. This brief introduction only provides a few scripts that may be
helpful in using MotionPlus to get positive and negative images to feed into the
training process.
Start with creating positive images movie as input file.
Run with picture_output_motion roi
Remove any pictures that are not desired.
Run the script to create the positive file list
Run while in the directory with the positive images.
opencv_createsamples -vec posfiles.vec -info poslist.txt -num 350 -h 96 -w 96
Next get a sample file that does not have desired positives.
Change to picture_output on and turn off motion roi
Change threshold to tiny number and run to create negatives
opencv_traincascade -data ./model -vec ./pos/posfiles.vec -bg neglist.txt -numPos 350 -numNeg 325
The following are the simple scripts to create positive and negative list files for training
!/bin/bash
FILES=./pos/*.jpg
for FULLNAME in $FILES
do
HW=$(identify -format '%w %h' $FULLNAME)
printf "$FULLNAME 1 0 0 $HW \n" >>poslist.txt
done
!/bin/bash
FILES=./neg/*.jpg
for FULLNAME in $FILES
do
printf "$FULLNAME \n" >>neglist.txt
done
Sound Frequency Sample
-
Since sound frequency processing is new to MotionPlus, the following provides an illustrative sample of setting
up the sound and the associated alerts processing. This example will use ALSA. For PulseAudio, MotionPlus uses
the default audio recording device. Although MotionPlus has parameters for the PulseAudio server and device,
the set up is not straight forward and it is just recommended to change the PulseAudio default.
Go to the command prompt and use
arecord -l
to get the
device name such as hw:1,0
Specify log_level 8 in MotionPlus.conf
Do not specify a log file so that it is console output.
Specify snd_device and snd_show in the sound configuration file such as
snd_device hw:1,0
snd_show on
Start MotionPlus and make a noise to test the output.
Once MotionPlus responds to sounds, press the test button on the device to be monitored.
Note that while the various devices being monitored may be the same, the detected frequency from each may be slightly different. Care should be taken to not be too precise in the setting of the alert range for MotionPlus. For example, the frequency may be reported as 3402.2456 and MotionPlus can be set up to look for that precise number but devices age and the frequency may change. Also, note that the frequency resolution of MotionPlus is limited by the sample rate and frames from the audio device. The maximum resolution is determined by the following formula. Sample Rate / (frames * 2). So with the default sample rate of 44100hz, and frames of 2048, the maximum resolution is appoximately 10.7666hz. This means that the frequencies detected around the range reported above would be 3413.0122, 3402.2456 or 3391.4790 and no values between.
Once the frequencies of all the devices have been logged, set up the alerts in the sound configuration file as well as the on_sound_alert and turn off the showing of frequencies. (The frequencies in this sample are random)
snd_alerts alert_id=01,volume_level=01,volume_count=10,freq_low=2976,freq_high=2977,alert_nm=smokedown1
snd_alerts alert_id=02,volume_level=01,volume_count=10,freq_low=3400,freq_high=3450,alert_nm=smokelr
snd_alerts alert_id=03,volume_level=01,volume_count=10,freq_low=3388,freq_high=3399,alert_nm=smokebr1
snd_alerts alert_id=11,volume_level=01,volume_count=10,freq_low=3378,freq_high=3379,alert_nm=furnace
snd_alerts alert_id=22,volume_level=01,volume_count=10,freq_low=3281,freq_high=3399,alert_nm=waterheater
snd_alerts alert_id=22,volume_level=01,volume_count=10,freq_low=3270,freq_high=3279,alert_nm=kitchBath
snd_show off
on_sound_alert %{trig_nbr} %{trig_nm} %{trig_freq}
Then you can set up a script to send email or text messages using the sendemail
application like below
#!/bin/bash
ALRTNBR=$1
ALRTNM=$2
FREQ=$3
ATCH=$4
MYSTR=""
MYSTR=$MYSTR" -f \"Friendly Name \" "
MYSTR=$MYSTR" -t \"DestinationEmailAddress@gwhatever.com\" "
MYSTR=$MYSTR" -u \"MotionPlus Notification\" "
MYSTR=$MYSTR" -s \"smtp.gwhatever.com:587\" "
MYSTR=$MYSTR" -xu \"SendingEmailAddress@gwhatever.com\" "
MYSTR=$MYSTR" -xp \"SendingEmailPassword\" "
BODY=""
if [[ "$ALRTNBR" -ge 1 && "$ALRTNBR" -le 9 ]]; then
BODY="So, hey. Sorry to bother you. But thought I'd just let"
BODY=$BODY" you know that your house is burning down. The neighbors"
BODY=$BODY" may get annoyed so you should think about doing something. "
BODY=$BODY" The "$ALRTNM" alert numbered "$ALRTNBR" was triggered with "
BODY=$BODY" frequency "$FREQ
elif [[ "$ALRTNBR" -ge 10 && "$ALRTNBR" -le 19 ]]; then
BODY="Hi. So I noticed that the natural gas leak alarm is going off."
BODY=$BODY" Nothing too urgent or anything but when you get home, you"
BODY=$BODY" may want to hold off making any sparks to avoid blowing yourself up."
BODY=$BODY" The "$ALRTNM" alert numbered "$ALRTNBR" was triggered with "
BODY=$BODY" frequency "$FREQ
elif [[ "$ALRTNBR" -ge 20 && "$ALRTNBR" -le 29 ]]; then
BODY="Ahoy! Your house is going to be next water park attraction in"
BODY=$BODY" the neighborhood!!! The water is filling it up and the"
BODY=$BODY" children will be splashing around in it soon."
BODY=$BODY" The "$ALRTNM" alert numbered "$ALRTNBR" was triggered with "
BODY=$BODY" frequency "$FREQ
fi
if [ "$BODY" != "" ]; then
MYSTR=$MYSTR" -m \""$BODY"\" "
if [ -f "$ATCH" ]; then
MYSTR=$MYSTR" -m \""$ATCH"\" "
fi
sendemail $MYSTR
fi
exit 0
Fail2Ban Example
-
The following are example files to use with the fail2ban application. This allows users to ban IPs that
may be attempting to get in. This example was created using Debian 11. Adjust as appropriate for other
distros and versions.
Install fail2ban and create the following files:
File 1:
# Fail2Ban configuration file: /etc/fail2ban/filter.d/motionplus.conf
# Author: Mr Dave
#
[INCLUDES]
# Read common prefixes. If any customizations available -- read them from common.local
before = common.conf
[Definition]
daemon = nsd
# Option: failregex
# Notes.:
# regex to match the log in failures messages in the logfile. The
# host must be matched by a group named "host". The tag "<HOST>" can
# be used for standard IP/hostname matching and is only an alias for
# (?:::f{4,6}:)?(?P[\w\-.^_]+)
# Sample: Jul 01 02:50:32 [EMG][STR][00:wc00] webu_failauth_check: Ignoring connection from: 192.168.1.10
# Values: TEXT
failregex = ^.*Ignoring connection from: <HOST>$
ignoreregex =
datepattern = {^LN-BEG}Epoch
{^LN-BEG}
File2:
#Fail2Ban Jail Configuration File: /etc/fail2ban/jail.d/motionplus-jail.conf
[motionplus]
enabled = true
filter = motionplus
logpath = /var/log/motionplus/motionplus.log
bantime = 23h
banaction = iptables-allports[blocktype="DROP"]
maxretry = 0
port = 0:65535
Make sure to adjust the log file location indicated in the jail file as well as how long to ban the IP address.
PTZ command examples
-
The following are some example sources and scripts to send PTZ (Pan Tilt Zoom) commands to cameras.
sofiactl is a Perl script that can control many imported inexpensive cameras.
Adjust script location, timing, cameraip, user, etc as appropriate.
#!/bin/bash
sofiactl.pl --user admin --host cameraip --port 34567 --command OPPTZControl --sd ZoomTile --s2 0.5
sofiactl.pl --user admin --host cameraip --port 34567 --command OPPTZControl --sd ZoomWide --s2 0.5
sofiactl.pl --user admin --host cameraip --port 34567 --command OPPTZControl --sd DirectionUp --s2 2.0
sofiactl.pl --user admin --host cameraip --port 34567 --command OPPTZControl --sd DirectionDown --s2 2.0
sofiactl.pl --user admin --host cameraip --port 34567 --command OPPTZControl --sd DirectionLeft --s2 2.0
sofiactl.pl --user admin --host cameraip --port 34567 --command OPPTZControl --sd DirectionRight --s2 2.0
exit
camxmctl is a c++ program with a sample HTML page that makes adjusting the parameters easier. It reuses some of the code from Motionplus and is based upon the JSON files and commands in the sofiactl script.
Adjust location, timing, cameraip, user, etc as appropriate.
#!/bin/bash
tbd. Review sample page to see post commands.
exit
curl scripts. Example 1
Adjust as appropriate.
#!/bin/bash
curl -X PUT -H "Content-Type: application/x-www-form-urlencoded" -d 'Param1=1' http://admin@cameraip:80/PTZ/1/TurnDown
sleep 2
curl -X PUT -H "Content-Type: application/x-www-form-urlencoded" -d 'Param1=0' http://admin@cameraip:80/PTZ/1/TurnDown
exit
#!/bin/bash
curl -X PUT -H "Content-Type: application/x-www-form-urlencoded" -d 'Param1=1' http://admin@cameraip:80/PTZ/1/TurnLeft
sleep 2
curl -X PUT -H "Content-Type: application/x-www-form-urlencoded" -d 'Param1=0' http://admin@cameraip:80/PTZ/1/TurnLeft
exit
#!/bin/bash
curl -X PUT -H "Content-Type: application/x-www-form-urlencoded" -d 'Param1=1' http://admin@cameraip:80/PTZ/1/TurnRight
sleep 2
curl -X PUT -H "Content-Type: application/x-www-form-urlencoded" -d 'Param1=0' http://admin@cameraip:80/PTZ/1/TurnRight
exit
#!/bin/bash
curl -X PUT -H "Content-Type: application/x-www-form-urlencoded" -d 'Param1=1' http://admin@cameraip:80/PTZ/1/TurnUp
sleep 2
curl -X PUT -H "Content-Type: application/x-www-form-urlencoded" -d 'Param1=0' http://admin@cameraip:80/PTZ/1/TurnUp
exit
curl scripts. Example 2
Adjust as appropriate.
#!/bin/bash
curl 'http://admin:admin@cameraip:80/web/cgi-bin/hi3510/ptzctrl.cgi?-step=0&-act=left&-speed=45'
sleep 1
curl 'http://admin:admin@cameraip:80/web/cgi-bin/hi3510/ptzctrl.cgi?-step=0&-act=stop&-speed=45'
exit
#!/bin/bash
curl 'http://admin:admin@cameraip:80/web/cgi-bin/hi3510/ptzctrl.cgi?-step=0&-act=right&-speed=45'
sleep 1
curl 'http://admin:admin@cameraip:80/web/cgi-bin/hi3510/ptzctrl.cgi?-step=0&-act=stop&-speed=45'
exit
#!/bin/bash
curl 'http://admin:admin@cameraip:80/web/cgi-bin/hi3510/ptzctrl.cgi?-step=0&-act=down&-speed=45'
sleep 1
curl 'http://admin:admin@cameraip:80/web/cgi-bin/hi3510/ptzctrl.cgi?-step=0&-act=stop&-speed=45'
exit
#!/bin/bash
curl 'http://admin:admin@cameraip:80/web/cgi-bin/hi3510/ptzctrl.cgi?-step=0&-act=up&-speed=45'
sleep 1
curl 'http://admin:admin@cameraip:80/web/cgi-bin/hi3510/ptzctrl.cgi?-step=0&-act=stop&-speed=45'
exit
#!/bin/bash
curl 'http://admin:admin@cameraip:80/web/cgi-bin/hi3510/ptzctrl.cgi?-step=0&-act=zoomin&-speed=45'
sleep 1
curl 'http://admin:admin@cameraip:80/web/cgi-bin/hi3510/ptzctrl.cgi?-step=0&-act=stop&-speed=45'
exit
#!/bin/bash
curl 'http://admin:admin@cameraip:80/web/cgi-bin/hi3510/ptzctrl.cgi?-step=0&-act=zoomout&-speed=45'
sleep 1
curl 'http://admin:admin@cameraip:80/web/cgi-bin/hi3510/ptzctrl.cgi?-step=0&-act=stop&-speed=45'
exit