Posts mit dem Label webcam monitoring werden angezeigt. Alle Posts anzeigen
Posts mit dem Label webcam monitoring werden angezeigt. Alle Posts anzeigen

Samstag, 17. Dezember 2016

surveillance cam : zoneminder and rasperry pi model b+

got a pi b+ model from straubson and installed: raspian jessy on it.

- add a file "ssh" in the /boot/ directory so you can access the pi without using a monitor, change the password afterwards.
Based on  https://bkjaya.wordpress.com/2016/11/23/how-to-install-zoneminder-1-29-0-on-raspberry-pi-3-with-raspbian-8-1-jessy-64-bit/  adapted it to work following these steps
-add zhe Jessie backports
sudo gedit  /etc/apt/sources.list
-add following line to the bottom of the file and save
deb http://http.debian.net/debian jessie-backports main
You will encounter signature errors, to
-fix those errors run following on the terminal

gpg --keyserver pgpkeys.mit.edu --recv-key  8B48AD6246925553
gpg -a --export 8B48AD6246925553 | sudo apt-key add -
gpg --keyserver pgpkeys.mit.edu --recv-key  7638D0442B90D010
gpg -a --export 7638D0442B90D010 | sudo apt-key add -

-Then run on the terminal
sudo apt-get update
-Install PHP, and MySQL server. You will be prompted to set a MySQL password
sudo apt-get install php5 mysql-server php-pear php5-mysql php5-gd
- Then install zoneminder using the software center of Raspbian
sudo apt-get install zoneminder

Create Zoneminder database in MySQL
There is a line missing from zm_create.sql that is packed with this version.
-If you search /usr/share/zoneminder/db/zm_create.sql (On Debian Wheezy, Your location may differ) for line:

CREATE TABLE `Logs` (

Simply add a line above this which reads:

DROP TABLE IF EXISTS `Logs`;

-Run following on the terminal

mysql -uroot -p < /usr/share/zoneminder/db/zm_create.sql
mysql -uroot -p -e "grant all on zm.*
to 'zmuser'@localhost identified by 'zmpass';"
mysqladmin -uroot -p reload
sudo chmod 740 /etc/zm/zm.conf
sudo chown root:www-data /etc/zm/zm.conf
sudo systemctl enable zoneminder.service
sudo adduser www-data video
sudo ln -s /etc/zm/apache.conf /etc/apache2/conf-enabled/zoneminder.conf
sudo a2enmod cgi
sudo a2enconf zoneminder
sudo a2enmod rewrite
sudo chown -R www-data:www-data /usr/share/zoneminder/
sudo systemctl enable zoneminder
sudo service zoneminder start

-Adding  timezone to PHP

sudo nano /etc/php5/apache2/php.ini

Edit 894 line to enter your time zone  and save the php.ini file
-then

sudo service apache2 reload

Open Zoneminder http://localhost/zm/

As USB Camera I used a 046d:08da Logitech, Inc. QuickCam Messanger (sic) according to lsusb

the resolution is bad, but, heck lets also account for annonymity

I set it up the following way

Monitor

If the USB camera on your pi tends to crash /stop working: set the resolution to 320 and 240


Zone Setting


Challenge: I want to count people using the biodegradbale bin . ( yep, nerdy...)

"The bin"



False events I get from

a) big cars/semis covering the bin



b) lights of cars passing by at night




Task

Set up zones

Zone 1 setting


zone 2 setting


zone 3



zone 4




and then I added as well a zone to overcome moving shadow induced by the trees/wind

  




Create a event video  every day

Since ffmpeg avconv etc and rasperry is not a love story, due to missing hardware accelerated video encoding of those packages use gstreamer - with that you use the very powerfull GPU, and it is actually converting the thousands of images to a vid faster than my WIN10 machine. Inspired , I managed to get the it run following this steps
sudo apt-get install gstreamer1.0-tools
sudo sh -c 'echo deb http://vontaene.de/raspbian-updates/ . main >> /etc/apt/sources.list'
add the missing key for this repo

gpg --recv-keys 0C667A3E
gpg -a --export 0C667A3E | sudo apt-key add -
 update your machine
sudo apt-get update
sudo apt-get -y upgrade
Install all necessary OPENMAX plugins for gstreamer

sudo apt-get install libgstreamer1.0-0 liborc-0.4-0 gir1.2-gst-plugins-base-1.0 gir1.2-gstreamer-1.0 gstreamer1.0-alsa gstreamer1.0-omx gstreamer1.0-plugins-bad gstreamer1.0-plugins-base gstreamer1.0-plugins-base-apps gstreamer1.0-plugins-good gstreamer1.0-plugins-ugly gstreamer1.0-pulseaudio gstreamer1.0-tools gstreamer1.0-x libgstreamer-plugins-bad1.0-0 libgstreamer-plugins-base1.0-0
done

Create a bash script to create a movie out of daily images
and upload it to youtube based
install sudo apt-get python-pip 
based on on http://stackoverflow.com/questions/36962260/batch-upload-videos-to-youtube-via-command-line-python

#!/bin/bash
# Ugly script to generate AVI files for youtube  from zoneminder events
# Change the followingvariables to accomodate your install and where you want the videos exported, there are more links in the code to check

events_dir=/var/cache/zoneminder/events/
THEDATE=$(date --date="today" +%Y-%m-%d)
MYTITLE="KompostNutzer-Gaselstr-$THEDATE"

#cd $events_dir
# If you don't want the ENTIRE server's events and just want the latest week's worth
# then just add something like -mtime -7 before the "-print" part.  That's what I did later so I could have a weekly cron job.
find $events_dir -name "*-capture.jpg" -mtime -1 -print > /home/pi/temp/unsortedallevents.txt
sort -n /home/pi/temp/unsortedallevents.txt > /home/pi/temp/allevents.txt
filename='/home/pi/temp/allevents.txt'

echo Start copying files ....
cd temp/
aa=0
while read p; do
#    echo $p
cp $p `printf "%04d" $aa`.jpg; aa=$(($aa+1))
done < $filename

echo Start creating vid files .... grab a coffee
#gsttramer create movie
gst-launch-1.0 multifilesrc location=%04d.jpg index=1 caps="image/jpeg,framerate=24/1" ! jpegdec ! omxh264enc ! avimux ! filesink location=daily.avi

#upload
youtube-upload --title=$MYTITLE daily.avi

cd

#sleep 10
rm /home/pi/temp/*.jpg
rm /home/pi/temp/*.avi
rm /home/pi/temp/allevents.txt
rm /home/pi/temp/unsortedallevents.txt
exit

run the script as cron every nite

Mail events to Googledrive spreadsheet

install mail agent: http://www.sbprojects.com/projects/raspberrypi/exim4.php I prefer  exim4 with my gmail account, set gmail account to accept unsecure (sic) apps
since zoneminder EMAIL send is PITA
use https://ifttt.com/channels/google_drive/actions/81-add-row-to-spreadsheet

install

apt-get install html-xml-utils 

and add run with cron or a script for daily entries with a date and number events of the last 24


wget http://192.168.1.100/zm/index.php?view=events&page=1&filter[terms][0][attr]=DateTime&filter[terms][0][op]=%3E%3D&filter[terms][0][val]=-1+day&filter[terms][1][cnj]=and&filter[terms][1][attr]=MonitorId&filter[terms][1][op]=%3D&filter[terms][1][val]=1

hxnormalize -x zr49zcf | hxselect -s '\n' -c "h2" > FILE
sed "s@Events@@g" FILE > EVENTS
THEDATE=$(date --date="today" +%Y-%m-%d)
mail -s "$THEDATE #ZM" trigger@applet.ifttt.com < EVENTS

and in case: the USB cam does suddenly stops working: unplug cam reboot device use a different port, etc see
https://www.raspberrypi.org/forums/viewtopic.php?t=17212

I have script which checks if the conenction zoneminder usb cam is broken, and reboots the pi, which usually brings the cam back on
#/bin/bash
echo Checking if USB Cam is still running.....
cd /home/pi/temp/

#extracting last 10min of syslog
sed -n "/^$(date --date='10 minutes ago' '+%b %_d %H:%M')/,\$p" /var/log/syslog
> last10min.txt

#if usb cam is not working..simply reboot.
if grep -q "Failed to start capture stream: Broken pipe" last10min.txt ; ##note
the space after the string you are searching for
then
echo "Cam not working" ; echo "restarted zoneminder due to broken pipe of USBCAM
" | mail -s "zm restarted" david.oesch@gmail.com ; sleep 10m ; rm last10min.txt
; /sbin/reboot
else
echo "Cam working"
fi

#if usb cam is not working..simply reboot.
if grep -q "Failed to set video format: Device or resource busy" last10min.txt ;
 ##note the space after the string you are searching for
then
echo "Cam not working" ; echo "restarted zoneminder due to Device busy" | mail -
s "zm restarted" david.oesch@gmail.com ; sleep 10m ; rm last10min.txt ; /sbin/re
boot
else
echo "Cam working"; rm last10min.txt
fi


exit


To omit zoneminder running at night I halt via sunwait command on bootup:

install
wget http://www.risacher.org/sunwait/sunwait-20041208.tar.gz
tar xvzf sunwait-20041208.tar.gz
cd sunwait-20041208/
ls
make
sudo cp sunwait /usr/local/bin


then launch it on boot



i) Create a script called mystartup.sh in /etc/init.d/ directory(login as root)

# vi /etc/init.d/mystartup.sh

ii) Add commands to this script one by one:

#!/bin/bash
/usr/local/bin/sunwait civ down -1:00:00 46.90860N 7.41549E; /usr/sbin/service zoneminder stop

iii) Setup executable permission on script:
# chmod +x /etc/init.d/mystartup.sh
iv)Make sure this script get executed every time Debian Linux system boot up/comes up:

# update-rc.d mystartup.sh defaults 100


Where,

mystartup.sh: Your startup script name

defaults : The argument ‘defaults’ refers to the default runlevels, which are 2 through 5.

100 : Number 100 means script will get executed before any script containing number 101. Just run the command ls –l /etc/rc3.d/ and you will see all script soft linked to /etc/init.d with numbers.

Next time you reboot the system, you custom command or script will get executed via mystartup.sh. You can add more commands to this file or even call other shell/perl scripts from this file too.

And of course I have at sixish in the morning a cron which starts up zoneminder

Upload Event Images

Download gdrive-linux-rpi and install it according to this guide 

Analogue above, create a script called zm_alatm which scans messages for alarmstates and add it to run update-rc.d


#!/bin/bash
tail -f /var/log/messages | grep --line-buffered 'Gone into alarm state' | while read line; do cp -p "`find /var/cache/zoneminder/events/1/$(date +"%y/%m/%d/") -name "*aptur*" -printf "%p\n" | sort -rn | head -n 1`" /home/pi/eventimages/$(date +"%Y%m%d%H%M").jpg;  done




the Result? Here


UPDATE: 2018

with "stretch" if followed this https://wiki.zoneminder.com/Raspbian
- just install php (not php5)
- for raspberry pi camera modul follow http://marcel.duketown.com/?p=651

Samstag, 26. Januar 2008

A big brother is watching you webcam server

Zoneminder recommended, folllow the instructions here

To make your box squeak when there is an alarm event:
sudo apt-get install mpg321 alsamixer

Adjust volume: alsamixer


To trigger the alarm on the very moment of the event based on this how to

Install perl

Create perl script to monitor DB (alarm_loop.pl)

#!/usr/bin/perl -w

use strict;

use ZoneMinder;

$| = 1;

zmDbgInit( "myscript", level=>0, to_log=>0, to_syslog=>0, to_term=>1 );

my $dbh = DBI->connect( "DBI:mysql:database=".ZM_DB_NAME.";host=".ZM_DB_HOST, ZM_DB_USER, ZM_DB_PASS );

my $sql = "select M.*, max(E.Id) as LastEventId from Monitors as M left join Events as E on M.Id = E.MonitorId where M.Function != 'None' group by (M.Id)";
my $sth = $dbh->prepare_cached( $sql ) or die( "Can't prepare '$sql': ".$dbh->errstr() );

my $res = $sth->execute() or die( "Can't execute '$sql': ".$sth->errstr() );
my @monitors;
while ( my $monitor = $sth->fetchrow_hashref() )
{
push( @monitors, $monitor );
}

$sql = "select * from Events where Id = ?";
$sth = $dbh->prepare_cached( $sql ) or die( "Can't prepare '$sql': ".$dbh->errstr() );

while( 1 )
{
foreach my $monitor ( @monitors )
{
next if ( !zmShmVerify( $monitor ) );

if ( my $last_event_id = zmHasAlarmed( $monitor, $monitor->{LastEventId} ) )
{
$monitor->{LastEventId} = $last_event_id;
# print( "Monitor ".$monitor->{Name}." has alarmed\n" );
$res = $sth->execute( $last_event_id ) or die( "Can't execute '$sql': ".$sth->errstr() );
my $
event = $sth->fetchrow_hashref();

if ( $
event->{Id} ) {
# print( "EventID= ".$
event->{Id} );

my $command = "./alarm1.sh"
# ." --monitor=" .$monitor->{Id}
." --
event=" .$event->{Id}
." --starttime=\"" .$
event->{StartTime} ."\"";
my $output = qx( $command );
my $status = $? >> 8;

# print ("Output(" .$status ."):" .$output);


# Print output if required
# Check status if required
#
# Do your stuff here
#
}
}
}
sleep( 1 );
}

Create bash script with link to alrm file (alarm1.sh)

#!/bin/bash

echo "1=$1 2=$2 3=$3 4=$4"

mpg123 /home/boxuser/www/wav/alarm.mp3

Run perl script:

sudo ./alarm_loop.pl\

Activate 640×480 streaming

You should be able to use a similar procedure with other distributions to modify the shared memory pool without kernel recompilations though in some cases this may be necessary. Note, this error also sometimes occurs if you have an old shared memory segment lying around from a previous run that is too small. Use the ipcs and ipcrm system commands to check and remove it if necessary.'"

You can often find out how much shared memory is available by typing the following :-

cat /proc/sys/kernel/shmall

and the most you can allocate in one go :-

cat /proc/sys/kernel/shmmax

To change these values type (for example) :-

echo 134217728 >/proc/sys/kernel/shmall
echo 134217728 >/proc/sys/kernel/shmmax

Be sure to restart ZoneMinder after this.However be aware that sometimes you will only need to change the shmmax value as shmall is often large enough. Also changing these values in this way is only effective until your machine is rebooted.

To change them permanently you will need to edit /etc/sysctl.conf and add the following lines (for example) :-

kernel.shmall = 134217728
kernel.shmmax = 134217728

To load these settings in the sysctl.conf file type:

sysctl -p

To check your shared memory settings type:

ipcs -l

These changes will now also be set the next time your machine is restarted.


To send an email on event

- install the exim4 according to https://help.ubuntu.com/community/Exim4

- my /etc/exim4/update-exim4.conf.conf looks like this (using the normal smtp server of my provider)

dc_eximconfig_configtype='smarthost'
dc_other_hostnames='nerd.alert'
dc_local_interfaces='127.0.0.1'
dc_readhost=''
dc_relay_domains=''
dc_minimaldns='true'
dc_relay_nets=''
dc_smarthost='mail.bluewin.ch::25'
CFILEMODE='644'
dc_use_split_config='false'
dc_hide_mailname='false'
dc_mailname_in_oh='true'
dc_localdelivery='mail_spool'
restart the system.

sudo update-exim4.conf
sudo /etc/init.d/exim4 restart

test if you can mail:

echo test | mail -s test_mail yourmail@yourprovider.com


To send an email on event with video included

chnage in the options sections of ZM

ZM_OPT_MPEG to ffmpeg

ZM_PATH_FFMPEG to /usr/bin/ffmpeg

add the %EV% in the e-mail text: will attach the movie as mail

Check in zmvideo.pl and change ">& ffmpeg.log" to "&> /tmp/ffmpeg.log"



To do:

  • place a script in the /etc/init.d folder (may differ in your distribution) to start it on boot up