PiKrellCam

Moderator: leecollings

Post Reply
MarnixO
Posts: 18
Joined: Sunday 24 September 2017 12:02
Target OS: Raspberry Pi / ODroid
Domoticz version: V4.10199
Location: Destelbergen Belgium
Contact:

PiKrellCam

Post by MarnixO »

Anyone uses a script in PikrellCam to make an action in Domoticz on starting motion capture
Or sending email with pictures ?
User avatar
Egregius
Posts: 2592
Joined: Thursday 09 April 2015 12:19
Target OS: Linux
Domoticz version: v2024.7
Location: Beitem, BE
Contact:

Re: PiKrellCam

Post by Egregius »

I do. :D
Will try to post something this evening.
User avatar
Egregius
Posts: 2592
Joined: Thursday 09 April 2015 12:19
Target OS: Linux
Domoticz version: v2024.7
Location: Beitem, BE
Contact:

Re: PiKrellCam

Post by Egregius »

I have this in pikrellcam.

In .pikrellcam/pikrellcam.conf:

Code: Select all

on_motion_begin /home/pi/region.py
on_motion_end /home/pi/on_motion_end.sh
/home/pi/region.py:

Code: Select all

#!/usr/bin/env python
import os,sys,socket,time
from subprocess import Popen
from shutil import copyfile
hold = 5000
holdoff = 180000
filename = '/run/pikrellcam/motion-events'
file = open('/run/pikrellcam/motion-events','r')
state = 'wait'
tsent0 = open('/temp/tsent0').read()
tsent1 = open('/temp/tsent1').read()
tsent2 = open('/temp/tsent2').read()

while 1:
	where = file.tell()
	line = file.readline()
	if not line:
		time.sleep(0.01)
		file.seek(where)
		continue
	line = line.strip('\n')
	if (line.find('<motion') == 0):
		state = 'motion'
	elif (line.find('</motion>') == 0):
		state = 'wait'
	elif (line.find('<end>') == 0):
		sys.exit(1)
	elif (state == 'motion'):
		if (line.startswith(str(2))):
			tnow = int(round(time.time() * 1000))
			if (tnow >= int(tsent2) + holdoff and tnow > int(tsent1) + hold and tnow > int(tsent0) + hold):
				r, x, y, dx, dy, mag, count = line.split()
				if (int(mag) >= 2 and int(mag) <= 40 and int(count) >= 110 and int(count) <= 3000):
					copyfile('/run/pikrellcam/mjpeg.jpg', ('/temp/snapshot-%s-%s.jpg' % (r,tnow)))
					tsent2 = tnow
					with open('/temp/tsent2', 'w') as myFile:
						myFile.write('{}'.format(tsent2))
					Popen('/usr/bin/php /home/pi/pikrellcam/www/telegram.php %s %s %s %s' % (('/temp/snapshot-%s-%s.jpg' % (r,tnow)),str(r),str(mag),str(count),),shell=True)
		elif (line.startswith(str(3))):
			tnow = int(round(time.time() * 1000))
			if (tnow >= int(tsent0) + holdoff and tnow > int(tsent1) + hold and tnow > int(tsent2) + hold):
				r, x, y, dx, dy, mag, count = line.split()
				if (int(mag) >= 2 and int(mag) <= 40 and int(count) >= 130 and int(count) <= 3000):
					copyfile('/run/pikrellcam/mjpeg.jpg', ('/temp/snapshot-%s-%s.jpg' % (r,tnow)))
					tsent0 = tnow
					with open('/temp/tsent2', 'w') as myFile:
						myFile.write('{}'.format(tsent2))
					Popen('/usr/bin/php /home/pi/pikrellcam/www/telegram.php %s %s %s %s' % (('/temp/snapshot-%s-%s.jpg' % (r,tnow)),str(r),str(mag),str(count),),shell=True)
I have multiple motion zones set. I only want zone 2 and 3 to sent me a telegram with the picture.
The rest is handled in a php script, but this should get you starting.
Let me know if you need anything else. Been using pikrellcam for several years now, I'm pretty happy with it.
MarnixO
Posts: 18
Joined: Sunday 24 September 2017 12:02
Target OS: Raspberry Pi / ODroid
Domoticz version: V4.10199
Location: Destelbergen Belgium
Contact:

Re: PiKrellCam

Post by MarnixO »

I only want to switch a virtual switch by movement in 1 zone
Sending a snapshot can be done by sending a notification
Many thanks for the fast response
User avatar
Egregius
Posts: 2592
Joined: Thursday 09 April 2015 12:19
Target OS: Linux
Domoticz version: v2024.7
Location: Beitem, BE
Contact:

Re: PiKrellCam

Post by Egregius »

What do you want to achive by setting a switch on movement?
In my case that’s handled by the php script wich first checks several switches like home/away, gate open etc.
MarnixO
Posts: 18
Joined: Sunday 24 September 2017 12:02
Target OS: Raspberry Pi / ODroid
Domoticz version: V4.10199
Location: Destelbergen Belgium
Contact:

Re: PiKrellCam

Post by MarnixO »

can i have a copy of that script ?
User avatar
Egregius
Posts: 2592
Joined: Thursday 09 April 2015 12:19
Target OS: Linux
Domoticz version: v2024.7
Location: Beitem, BE
Contact:

Re: PiKrellCam

Post by Egregius »

I'll try, but it seems to be a mess :lol:

So the python script launches this script if movement is detected:

Code: Select all

<?php
error_reporting(E_ALL);ini_set("display_errors","on");
$disnot=false;

$time=time();
$data=file_get_contents('http://192.168.2.2/camera.php');
if($data)$d=unserialize($data);
else {
	$d=array();
	$d['Weg']='On';
	$d['meldingen']='On';
	$d['poortrf']='Off';
}
if(isset($_REQUEST['silent'])){
	$disnot=$_REQUEST['silent'];
}
if($d['Weg']==1||$d['meldingen']=='Off')$disnot=true;
if(isset($_REQUEST['snapshot'])||isset($_REQUEST['deurbel'])){
	shell_exec('cp /run/pikrellcam/mjpeg.jpg /temp/snapshot.jpg');
	$file='/temp/snapshot.jpg';
	if($d['poortrf']=='On'||$d['meldingen']=='Off'){unlink($file);exit;}
	$jpg_image=imagecreatefromjpeg($file);
	$white=imagecolorallocate($jpg_image,0,0,0);
	$font='/home/pi/pikrellcam/www/arial.ttf';
	if(isset($_REQUEST['deurbel']))imagettftext($jpg_image,48,0,15,60,0,$font,'DEURBEL');
	imagejpeg($jpg_image,$file);
	imagedestroy($jpg_image);
	usleep(20000);
	$url="https://api.telegram.org/bot111TELEGRAMBOTID111/sendPhoto?chat_id=CHATID1";
	$post_fields=array('chat_id'=>CHATID1,'photo'=>new CURLFile(realpath($file)),'disable_notification'=>$disnot);
	for($x=1;$x<=100;$x++){
		$ch=curl_init();
		curl_setopt($ch,CURLOPT_HTTPHEADER,array("Content-Type:multipart/form-data"));
		curl_setopt($ch,CURLOPT_URL,$url);
		curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
		curl_setopt($ch,CURLOPT_POSTFIELDS,$post_fields);
		$result=json_decode(curl_exec($ch),true);
		if($result['ok']===true){echo 'OK';break;}
		sleep($x*3);
	}
	$url="https://api.telegram.org/bot111TELEGRAMBOTID111/sendPhoto?chat_id=CHATID2";
	$post_fields=array('chat_id'=>CHATID2,'photo'=>new CURLFile(realpath($file)),'disable_notification'=>$disnot);
	for($x=1;$x<=100;$x++){
		$ch=curl_init();
		curl_setopt($ch,CURLOPT_HTTPHEADER,array("Content-Type:multipart/form-data"));
		curl_setopt($ch,CURLOPT_URL,$url);
		curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
		curl_setopt($ch,CURLOPT_POSTFIELDS,$post_fields);
		$result=json_decode(curl_exec($ch),true);
		if($result['ok']===true){echo 'OK';break;}
		sleep($x*3);
	}
	$folder='/temp/stills/'.strftime("%Y/%m/%d",$time);
	if(!file_exists($folder))mkdir($folder, 0777, true);
	rename($file , $folder.'/'.str_replace('temp','',str_replace('.jpg','',$file)).'-'.strftime("%Y%m%d-%H%M%S",$time).'.jpg');
}elseif(isset($argv[1])){
	$file=$argv[1];
	if($d['poortrf']=='On'||$d['meldingen']=='Off'){unlink($file);exit;}
	$r=$argv[2];
	$mag=$argv[3];
	$count=$argv[4];
	$jpg_image=imagecreatefromjpeg($file);
	$white=imagecolorallocate($jpg_image,0,0,0);
	$font='/home/pi/pikrellcam/www/arial.ttf';
	imagettftext($jpg_image,24,0,10,30,0,$font,"count=$count");
	imagettftext($jpg_image,24,0,10,60,0,$font,"mag=$mag");
	imagettftext($jpg_image,24,0,10,90,0,$font,"r=$r");
	imagejpeg($jpg_image,$file);
	imagedestroy($jpg_image);
	usleep(20000);
	$url="https://api.telegram.org/bot111TELEGRAMBOTID111/sendPhoto?chat_id=CHATID1";
	$post_fields=array('chat_id'=>CHATID1,'photo'=>new CURLFile(realpath($file)),'disable_notification'=>$disnot);
	for($x=1;$x<=100;$x++){
		$ch=curl_init();
		curl_setopt($ch,CURLOPT_HTTPHEADER,array("Content-Type:multipart/form-data"));
		curl_setopt($ch,CURLOPT_URL,$url);
		curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
		curl_setopt($ch,CURLOPT_POSTFIELDS,$post_fields);
		$result=json_decode(curl_exec($ch),true);
		if($result['ok']===true){break;}
		sleep($x*3);
	}
	$url="https://api.telegram.org/bot111TELEGRAMBOTID111/sendPhoto?chat_id=CHATID2";
	$post_fields=array('chat_id'=>CHATID2,'photo'=>new CURLFile(realpath($file)),'disable_notification'=>$disnot);
	for($x=1;$x<=100;$x++){
		$ch=curl_init();
		curl_setopt($ch,CURLOPT_HTTPHEADER,array("Content-Type:multipart/form-data"));
		curl_setopt($ch,CURLOPT_URL,$url);
		curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
		curl_setopt($ch,CURLOPT_POSTFIELDS,$post_fields);
		$result=json_decode(curl_exec($ch),true);
		if($result['ok']===true){break;}
		sleep($x*3);
	}
	$timestamp=substr($file,-17);$timestamp=str_replace('.jpg','',$timestamp);$timestamp=$timestamp/1000;
	$folder='/temp/stills/'.strftime("%Y/%m",$time);
	if(!file_exists($folder))mkdir($folder, 0777, true);
	rename($file , $folder.'/PiCam3-'.strftime("%Y-%m-%d_%H-%M-%S",$timestamp).'-'.$r.'.jpg');
}
?>
On my domoticz server I have camera.php wich gives the status of some devices. For instance I don't want to receive images if my garage port is open. And when I'm a sleep the notification must be delivered silent.

Code: Select all

<?php
/**
 * Pass2PHP
 * php version 7.3.4-2
 *
 * @category Home_Automation
 * @package  Pass2PHP
 * @author   Guy Verschuere <[email protected]>
 * @license  GNU GPLv3
 * @link     https://egregius.be
 **/
require '/var/www/config.php';
$mysqli=new mysqli('localhost', $dbuser, $dbpass, $dbname);
$result = $mysqli->query("select n,i,s,UNIX_TIMESTAMP(t) as t,m from devices;") or trigger_error($mysqli->error." [$sql]");
while ($row = $result->fetch_array()) {
    $d[$row['n']]['i'] = $row['i'];
    $d[$row['n']]['s'] = $row['s'];
    $d[$row['n']]['t'] = $row['t'];
    $d[$row['n']]['m'] = $row['m'];
}

$data=array();
$data['Weg']=$d['Weg']['s'];
$data['meldingen']=$d['auto']['s'];
$data['poortrf']=$d['poortrf']['s'];
echo serialize($data);
shell_exec('curl -s "http://127.0.0.1/beep.php" > /dev/null 2>/dev/null &');
That script in turn triggers the beep.php script wich plays a sound on a Xiaomi gateway.

Code: Select all

<?php
/**
 * Pass2PHP
 * php version 7.3.4-2
 *
 * @category Home_Automation
 * @package  Pass2PHP
 * @author   Guy Verschuere <[email protected]>
 * @license  GNU GPLv3
 * @link     https://egregius.be
 **/
require 'secure/functions.php';
$d=fetchdata();
if ($d['Weg']['s']>0) {
    die('Slapen of niet thuis');
}
if (past('Xlight')<60) {
    die('To soon');
}
if (past('belknop')<60) {
    die('To soon');
}
if ($d['poortrf']['s']=='On') {
    die('Poort on');
}
if ($d['auto']['s']=='Off') {
    die('Meldingen uitgeschakeld');
}
if ($d['lgtv']['s']=='On') {
    shell_exec('python3 secure/lgtv.py -c send-message -a "Beweging oprit" 192.168.2.27');
}
if ($d['Xvol']['s']!=5) {
    sl('Xvol', 5, basename(__FILE__).':'.__LINE__);
}
sl('Xbel', 20, basename(__FILE__).':'.__LINE__);
MarnixO
Posts: 18
Joined: Sunday 24 September 2017 12:02
Target OS: Raspberry Pi / ODroid
Domoticz version: V4.10199
Location: Destelbergen Belgium
Contact:

Re: PiKrellCam

Post by MarnixO »

I think my programming knowledge is a bit inadequate for this
User avatar
Egregius
Posts: 2592
Joined: Thursday 09 April 2015 12:19
Target OS: Linux
Domoticz version: v2024.7
Location: Beitem, BE
Contact:

Re: PiKrellCam

Post by Egregius »

What do you want to achive with it?
User avatar
Egregius
Posts: 2592
Joined: Thursday 09 April 2015 12:19
Target OS: Linux
Domoticz version: v2024.7
Location: Beitem, BE
Contact:

Re: PiKrellCam

Post by Egregius »

Out of my head, in other words: not tested...
Maybe this will do for your case:

Set a switch to on when there's motion, set it to off when motion stops.
Keep in mind that this will trigger the on status on every new movement detected. If you don't want that you'll have to look at my tsent0 stuff in my first python script in this topic.

Code: Select all

#!/usr/bin/env python
import os,sys,socket,time,urllib2

filename = '/run/pikrellcam/motion-events'
file = open('/run/pikrellcam/motion-events','r')
state = 'wait'

while 1:
	where = file.tell()
	line = file.readline()
	if not line:
		time.sleep(0.01)
		file.seek(where)
		continue
	line = line.strip('\n')
	if (line.find('<motion') == 0):
		state = 'motion'
	elif (line.find('</motion>') == 0):
		state = 'wait'
	elif (line.find('<end>') == 0):
		urllib2.urlopen("http://192.168.2.2:8080/json.htm?type=command&param=switchlight&idx=1383&switchcmd=Off")
		sys.exit(1)
	elif (state == 'motion'):
		urllib2.urlopen("http://192.168.2.2:8080/json.htm?type=command&param=switchlight&idx=1383&switchcmd=On")
MarnixO
Posts: 18
Joined: Sunday 24 September 2017 12:02
Target OS: Raspberry Pi / ODroid
Domoticz version: V4.10199
Location: Destelbergen Belgium
Contact:

Re: PiKrellCam

Post by MarnixO »

Wonderful, I will only be able to try this weekend because the pikrellcam is in a remote location
MarnixO
Posts: 18
Joined: Sunday 24 September 2017 12:02
Target OS: Raspberry Pi / ODroid
Domoticz version: V4.10199
Location: Destelbergen Belgium
Contact:

Re: PiKrellCam

Post by MarnixO »

I noticed that there was no subdirectory scripts in the pikrell directory and I created them
then I placed the script with the extension .py in this directory and made it executable
I also noticed that there is an asterisk in front of script.py, does this have any influence on the script ?
In the log window I do not see any message or reference to the script
User avatar
Egregius
Posts: 2592
Joined: Thursday 09 April 2015 12:19
Target OS: Linux
Domoticz version: v2024.7
Location: Beitem, BE
Contact:

Re: PiKrellCam

Post by Egregius »

Where is that asterisk?
And has never been a mention about a scripts folder. The config on_motion_begin holds a absolute path to avoid issues with that.
MarnixO
Posts: 18
Joined: Sunday 24 September 2017 12:02
Target OS: Raspberry Pi / ODroid
Domoticz version: V4.10199
Location: Destelbergen Belgium
Contact:

Re: PiKrellCam

Post by MarnixO »

The asterix appears in the directory list in Midnight Comander
If I understand correctly I have to uncomment the on_motion_begin section
and put the script afterwards in the pikrellcam.conf
User avatar
Egregius
Posts: 2592
Joined: Thursday 09 April 2015 12:19
Target OS: Linux
Domoticz version: v2024.7
Location: Beitem, BE
Contact:

Re: PiKrellCam

Post by Egregius »

Don’t know what that asterisk means, never heard of mc before. Will check that tomorrow.

Yes, add the complete path to the python script in pikrellcam.conf as mentioned in one of my first replies.
MarnixO
Posts: 18
Joined: Sunday 24 September 2017 12:02
Target OS: Raspberry Pi / ODroid
Domoticz version: V4.10199
Location: Destelbergen Belgium
Contact:

Re: PiKrellCam

Post by MarnixO »

Thank you very much for your help
Once you know it, it's easy, but you have to know where to start
I am starting to get more and more interested in the script language, thanks to you
Post Reply

Who is online

Users browsing this forum: No registered users and 1 guest