Page 1 of 2

Telegram Notification IF LAN IP CHANGED

Posted: Saturday 17 September 2016 22:53
by sincze
A, yes. And suddenly the WAN IP address of my remote Domoticz machine changed by the ISP.
Yes you can use dyndns like services, but I just wanted to know when it changed.
For some reason I ended op adding this script as a cronjob, or can be called from within Domoticz with os.execute.

It will send you a Telegram message (pre requirement is that you have telegrambot working) with the NEW IP message.
You will also need to add a user variable in Domoticz to store the WAN IP address.

I borrowed some code from the world wide internet to obtain the WAN IP and added the Domoticz parts using the great wiki pages.

Code: Select all

#!/bin/bash

DomoticzIP="192.*.*.*"				# Your Domoticz IP
DomoticzPort="8080"					# Your Domoticz PORT

								# Info for Telegrambot
TelegramUrl="https://api.telegram.org"
TelegramToken="bot*********:***********************************"
token="*********:***********************************""					# A yes, this still needs to be fixed.. 
													# it is the same as TelegramToken without 'bot' ...
													# Yes I know scripts can be cleaned up a bit, yes yes
TelegramChatId="*********"									# you get the picture what needs to be here

# Create a USER VARIABLE as STRING in DOMOTICZ and write down the number and name

WAN_IP_VAR=***											# Domoticz ID of Uservariable
WAN_IP_NAME="THE_NAME_IN_DOMOTICZ"						# Domoticz NAME of Uservariable

CURRENT_IP=$(curl -s http://whatismijnip.nl |cut -d " " -f 5)		# Get the current public IP

#Get the current KNOWN IP from DOMOTICZ

DOMOTICZ_WAN=$(curl -s 'http://'$DomoticzIP':'$DomoticzPort'/json.htm?type=command&param=getuservariable&idx='$WAN_IP_VAR'' | jq '.result[].Value' | cut -f1 -d" " | sed 's/\"//g')

#Check DOMOTICZ for currently KNOWN IP address
if [ $DOMOTICZ_WAN ]; then
KNOWN_IP=$DOMOTICZ_WAN
else
KNOWN_IP=
fi

#See if the IP has changed
if [ "$CURRENT_IP" != "$KNOWN_IP" ]; then

# UPDATE DOMOTICZ VARIABLE if the IP was different
curl -s 'http://'$DomoticzIP':'$DomoticzPort'/json.htm?type=command&param=updateuservariable&vname='$WAN_IP_NAME'&vtype=2&vvalue='$CURRENT_IP''

#Generating string to send via Telegram.
MESSAGE="text=Domoticz: Current IP Address Changed to: "
TOTAL=$MESSAGE$CURRENT_IP							# Concatenation of both messages MESSAGE + IP

curl --data chat_id=$TelegramChatId --data-urlencode "$TOTAL" ''$TelegramUrl'/bot'$token'/sendMessage'
fi
A well that is it the script is working however I think I need to throw away 'token' and change the last curl statement to:

Code: Select all

curl --data chat_id=$TelegramChatId --data-urlencode "$TOTAL" ''$TelegramUrl'/'$TelegramToken'/sendMessage'
Did not test that yet. :D

Re: Telegram Notification IF LAN IP CHANGED

Posted: Sunday 18 September 2016 8:58
by Egregius
You could also use a file to store the ip address so you don't need to bother Domoticz with this:

Code: Select all

#!/bin/bash
CURRENT_IP=$(curl -s http://whatismijnip.nl |cut -d " " -f 5)
PREV_IP=$(</var/tmp/wanip)
if [[ "$CURRENT_IP" != "$PREV_IP" ]]
then
	curl -s --connect-timeout 2 --max-time 5 --data-urlencode "text=WAN IP Changed, new ip = $CURRENT_IP" --data "silent=false" http://127.0.0.1/secure/telegram.php
	echo $CURRENT_IP > /var/tmp/wanip
fi
exit
All my telegram notifications are routed to that php page so I don't need to put the whole code in every script.

Re: Telegram Notification IF LAN IP CHANGED

Posted: Sunday 18 September 2016 10:04
by sincze
Haha, indeed you are totally right. :) I've seen similar "store the result in file" examples.
Maybe add a little code to check if the file with the currentip still exists??

Code: Select all

#Check file for previous IP address
if [ -f /var/tmp/wanip ]; then
KNOWN_IP=$(</var/tmp/wanip)
else
KNOWN_IP=
fi
Source: http://www.linuxtutorial.co.uk/bash-scr ... -to-email/

As this is the Domoticz forum ;) I changed it to use Domoticz :D :D and store my data in 1 place.

I'm very interested in your remark:

All my telegram notifications are routed to that php page so I don't need to put the whole code in every script.

Code: Select all

curl -s --connect-timeout 2 --max-time 5 --data-urlencode "text=WAN IP Changed, new ip = $CURRENT_IP" --data "silent=false" http://127.0.0.1/secure/telegram.php
That all messages are routed through this .php page. Any suggestions where I can reed some tips. To try for myself.
It will make life 100% easier and scripts a lot shorter.

I'll start reading here: https://www.domoticz.com/wiki/PHP:_Send_notifications

Thank you for your suggestion, really appreciated. Looking forward to your feedback

Tnx.

Re: Telegram Notification IF LAN IP CHANGED

Posted: Sunday 18 September 2016 10:31
by Egregius
sincze wrote: Maybe add a little code to check if the file with the currentip still exists??
As the file is stored in tempfs it doesn't exists after reboot.
But then the PREV_IP is not the same as CURRENT_IP and the file will be written and also sent a notification.
There should be more checks in it, like maybe last notification timestamp, check if 'watismijnip' is down,...


This is the code of the telegram.php page:

Code: Select all

#!/usr/bin/php
<?php error_reporting(E_ALL);ini_set("display_errors","on");
$silent=true;$type=NULL;$to=NULL;
if(isset($_REQUEST['silent']))$silent=$_REQUEST['silent'];
if(isset($_REQUEST['text'])){$type='text';$content=$_REQUEST['text'];}
if(isset($_REQUEST['photo'])){$type='photo';$content=$_REQUEST['photo'];}
if(isset($_REQUEST['video'])){$type='video';$content=$_REQUEST['video'];$silent=true;}
if(isset($_REQUEST['to']))$to=$_REQUEST['to'];
if($to=='Wife')$telegramchatid=12345678;
elseif($to=='channel')$telegramchatid=-1234567890123;
else $telegramchatid=87654321;
if(!empty($argv[1])&&!empty($argv[2])){$type=$argv[1];$content=$argv[2];}
if(!empty($argv[1])&&$argv[1]=="snapshot") {$type='photo';$content = "/run/pikrellcam/mjpeg.jpg";$silent=true;}
if(isset($type)&&isset($content)){
    $bot_url="https://api.telegram.org/bot123592115:A2EZ-xCRhO-RBf2qICiJs8q2A_2YIr1irxI/";
    if($type=="text"){$url=$bot_url."sendMessage?chat_id=".$telegramchatid;$post_fields=array('chat_id'=>$telegramchatid,'text'=>$content,'disable_notification'=>$silent);}
    elseif($type=="photo"){$url=$bot_url."sendPhoto?chat_id=".$telegramchatid;$post_fields=array('chat_id'=>$telegramchatid,'photo'=>new CURLFile(realpath($content)),'disable_notification'=>true);}
    elseif($type=="video"){$url=$bot_url."sendVideo?chat_id=".$telegramchatid;$post_fields=array('chat_id'=>$telegramchatid,'video'=>new CURLFile(realpath($content)),'disable_notification'=>true);}
    $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);
    for($x=1;$x<=100;$x++){
        $result=json_decode(curl_exec($ch),true);
        if($result['ok']===true)break;
        sleep($x*3);
    }
}
 
It's a 'one page fit all' structure that I can use on all my systems. It can sent text, photo, video with or without notification sound. There's a option to choose the receiver and maybe the most important: it checks the result from Telegram so the message is sent again if it fails. Telegram ignores messages that are sent to frequent, thanks to this retry every message is sent.

Re: Telegram Notification IF LAN IP CHANGED

Posted: Sunday 18 September 2016 10:36
by sincze
Egregius wrote:
sincze wrote: Maybe add a little code to check if the file with the currentip still exists??
As the file is stored in tempfs it doesn't exists after reboot.
But then the PREV_IP is not the same as CURRENT_IP and the file will be written and also sent a notification.
There should be more checks in it, like maybe last notification timestamp, check if 'watismijnip' is down,...

This is the code of the telegram.php page:

It's a 'one page fit all' structure that I can use on all my systems. It can sent text, photo, video with or without notification sound. There's a option to choose the receiver and maybe the most important: it checks the result from Telegram so the message is sent again if it fails. Telegram ignores messages that are sent to frequent, thanks to this retry every message is sent.
Nice one, maybe remove your current bot data from your code?? I don't think other people should know your bot.

Code: Select all

bot1235*****:****-*****-RBf2qICiJs8q2A_********I/";

Re: Telegram Notification IF LAN IP CHANGED

Posted: Sunday 18 September 2016 10:57
by sincze
Egregius wrote: This is the code of the telegram.php page:
Great work Egregius,
EXCELLENT.

I just sent myself my first Telegram message with your PHP :D script.
Now.... I've to work my way through all the besh scripts. I know what my day will look like now :o
Let's see what else your .php can do ;) and after that I need to modify the remote machines that have Domoticz running on a NAS.
The NAS already has PHP enabled.

Again thank you very much for contributing to my initial post.

Re: Telegram Notification IF LAN IP CHANGED

Posted: Sunday 18 September 2016 11:14
by Egregius
Search the forum for pass2php, that's my script that sents the lua arrays to a php script. From there I have everything automated in one php file.

Re: Telegram Notification IF LAN IP CHANGED

Posted: Saturday 17 December 2016 18:09
by sincze
Egregius wrote:Search the forum for pass2php, that's my script that sents the lua arrays to a php script. From there I have everything automated in one php file.
I would wonder if you could help me to figure out why.... I do receive a nice notification via your telegram.php.
However the photo is still a problem.

Code: Select all

//if(!empty($argv[1])&&$argv[1]=="snapshot") {$type='photo';$content = "/var/tmp/snapshot1.jpg";$silent=true;}
if(!empty($argv[1])&&$argv[1]=="snapshot") {$type='photo';$content = "snapshot1.jpg";$silent=true;}
I tried modifying the location of the snapshot1.jpg but I am unable to figure it out.
Normally snapshots are stored in /var/tmp for me however I read that maybe using php that directory is not accessible.
So I moved the snapshot to the same directory as telegram.php. Still I do not recieve the image.
Suggestions??

Re: Telegram Notification IF LAN IP CHANGED

Posted: Saturday 17 December 2016 19:32
by Egregius
Are there any errors shown?
Is that snapshot a regular jpg file?

To enable error reporting in php add this right after <?php

Code: Select all

error_reporting(E_ALL);ini_set("display_errors","on");
This is a script I use on pikrellcam:

Code: Select all

<?php error_reporting(E_ALL);ini_set("display_errors","on");
$disnot=false;$poort=0;$ctx=stream_context_create(array('http'=>array('timeout' => 2,)));
$domoticz=json_decode(file_get_contents('http://192.168.2.10:8084/json.htm?type=devices&used=true&plan=8',true,$ctx),true);
if($domoticz){
    if($domoticz['result'][0]['Status']=='Off'||$domoticz['result'][1]['Status']=='On')$disnot=true;
    $poort=strtotime($domoticz['result'][2]['LastUpdate']);
}
if($poort>time()-300){unlink($file);exit;}
if(isset($argv[1])){
    $file=$argv[1];
    $r=$argv[2];
    $mag=$argv[3];
    $count=$argv[4];
    $disnot=$argv[5];
    $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/bot12345678:AAEZ-xCRhO-RBabcdefghq9A_3YIr9irxI/sendPhoto?chat_id=1234567";
    $post_fields=array('chat_id'=>1234567,'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);
    }
    unlink($file);
}
The script is called from a python script:

Code: Select all

Popen('/usr/bin/php /home/pi/pikrellcam/www/telegram.php %s %s %s %s true' % (('/temp/snapshot-%s-%s.jpg' % (r,tnow)),str(r),str(mag),str(count),),shell=True)

Re: Telegram Notification IF LAN IP CHANGED

Posted: Saturday 17 December 2016 23:14
by sincze
Egregius wrote:Are there any errors shown?
Is that snapshot a regular jpg file?

To enable error reporting in php add this right after <?php

Code: Select all

error_reporting(E_ALL);ini_set("display_errors","on"); 
A well that shows me the following :D

Code: Select all

#!/usr/bin/php
REQUEST=Array
(
    [photo] => true
)
Type = photo
Content = true

Fatal error: Class 'CURLFile' not found in /var/www/php/telegram.php on line 32
And indeed a regular .jpg.

I can retrieve the image from domoticz for example by using:

Code: Select all

wget -O - "$DomoticzIP":"$DomoticzPort"/camsnapshot.jpg?idx=4 > $SnapFile1
I am using PHP 5.4.45-0+deb7u5 (cli) (built: Sep 18 2016 13:51:57)

The issue might be:
From what I can tell (http://php.net/manual/en/class.curlfile.php) the CurlFile class is only available for php 5.5.0 and above.

Distributor ID: Debian
Description: Debian GNU/Linux 7.11 (wheezy)
Release: 7.11
Codename: wheezy

Re: Telegram Notification IF LAN IP CHANGED

Posted: Sunday 18 December 2016 0:21
by Egregius
I would update to Jessie and then to PHP7. PHP7 is a lot faster than PHP5.x

Or at least PHP to 5.6.29...

Re: Telegram Notification IF LAN IP CHANGED

Posted: Sunday 18 December 2016 12:14
by sincze
Egregius wrote:I would update to Jessie and then to PHP7. PHP7 is a lot faster than PHP5.x

Or at least PHP to 5.6.29...

Code: Select all

   Static hostname: domoticz
         Icon name: computer
           Chassis: n/a
  Operating System: Debian GNU/Linux 8 (jessie)
            Kernel: Linux 3.4.109-sunxi
      Architecture: arm
Have to find out where to get php7 for arm infrastructure.
Currently php: HP 5.6.29-0+deb8u1 (cli) (built: Dec 14 2016 13:57:05) but ofcourse I want twice the speed of php7 :D

Re: Telegram Notification IF LAN IP CHANGED

Posted: Sunday 18 December 2016 12:28
by Egregius
On Syno it's available in a package.
I haven't searched yet for a Pi. On my Pi's php is only used for pikrellcam, don't even now if that is PHP7 compatible.

But if you have it running with 5.6.29 don't bother anymore. In the execution of something like this their will probably be less than 2 msec of php time. So do you need to search much for something like 25-50% of 2 msec gain?

Re: Telegram Notification IF LAN IP CHANGED

Posted: Sunday 18 December 2016 13:24
by sincze
Egregius wrote:But if you have it running with 5.6.29 don't bother anymore. In the execution of something like this their will probably be less than 2 msec of php time. So do you need to search much for something like 25-50% of 2 msec gain?
Good point, the reason why it is still not on my Synology is the physical location.
It won't cover the area with 433 mhz even with additional help of external antenna. We can always move it later ofcourse. :D

If I now execute telegramp.php

Code: Select all

http://192.168.2.10/php/telegram.php?snapshot=true
is gives me.

Code: Select all

#!/usr/bin/php
REQUEST=Array
(
    [snapshot] => 
)
However no snapshot

Code: Select all

if(!empty($argv[1])&&$argv[1]=="snapshot") {$type='photo';$content = "/var/tmp/snapshot1.jpg";$silent=true;}
i even tried

Code: Select all

if(!empty($argv[1])&&$argv[1]=="snapshot") {$type='photo';$content = "snapshot1.jpg";$silent=true;}
As snapshot 1 is also located in the same directory as telegram.php ;-)
sending text messages is no problem text=blalbabla.

We are nearly there :D
Offtopic: I did see a Github update with all external .php files now??.

Re: Telegram Notification IF LAN IP CHANGED

Posted: Sunday 18 December 2016 13:49
by Egregius
You might need to add some echo statements here and there to debug where it stops.

Github update about pass2php? Yes, see http://www.domoticz.com/forum/viewtopic ... 15#p109300

Re: Telegram Notification IF LAN IP CHANGED

Posted: Sunday 18 December 2016 14:05
by sincze
Egregius wrote:You might need to add some echo statements here and there to debug where it stops.
Well so if I execute with text=... it will pass through the whole thing
If I execute with 'snapshot' it will not go past this line. "if(isset($type)&&isset($content))"

Code: Select all

#!/usr/bin/php
<?php
error_reporting(E_ALL);ini_set("display_errors", "on");
$silent=false;$type='';
if(isset($_REQUEST['silent'])) $silent = $_REQUEST['silent'];
if(isset($_REQUEST['text'])) {$type='text';$content = $_REQUEST['text'];}
if(isset($_REQUEST['photo'])) {$type='photo';$content = $_REQUEST['photo'];}
if(isset($_REQUEST['video'])) {$type='video';$content = $_REQUEST['video'];$silent=true;}
if(!empty($argv[1])&&!empty($argv[2])) {$type=$argv[1];$content = $argv[2];}
if(!empty($argv[1])&&$argv[1]=="snapshot") {$type='photo';$content = "/var/tmp/snapshot1.jpg";$silent=true;}
echo '<pre>REQUEST=';print_r($_REQUEST);echo '</pre>';
echo '9. I am right here<br>';


if(isset($type)&&isset($content)) {
    echo '10. I am right here<br>';    

    echo 'Type = '.$type.'<br/>Content = '.$content.'<br/>';
 
An now.. If I execute..

Code: Select all

/php/telegram.php?photo=/var/tmp/snapshot1.jpg
pfffff..

Re: Telegram Notification IF LAN IP CHANGED

Posted: Sunday 18 December 2016 15:16
by Egregius
So long ago that I created that...
I think $argv is for passing variables from CLI. Like from a shell script:
/usr/bin/php /path/telegram.php photo /var/temp/snapshot.jpg

The $_REQUEST array is for use with ?photo=/var/temp/snapshot.jpg
And for that there is no snapshot option in the if lines.

Re: Telegram Notification IF LAN IP CHANGED

Posted: Sunday 18 December 2016 19:06
by sincze
Egregius wrote:So long ago that I created that...
I think $argv is for passing variables from CLI. Like from a shell script:
/usr/bin/php /path/telegram.php photo /var/temp/snapshot.jpg

The $_REQUEST array is for use with ?photo=/var/temp/snapshot.jpg
And for that there is no snapshot option in the if lines.
No worries.. Just did the following

Code: Select all

telegram('Deurbel',true,'Members');
file_get_contents('http://192.168.2.10/php/telegram.php?photo=/var/tmp/snapshots/snapshot1.jpg');
file_get_contents('http://192.168.2.10/php/telegram.php?photo=/var/tmp/snapshots/snapshot2.jpg'); 
With these kind of options you can clearly see the difference in (LUA os.execute() / BASH) vs PHP.
Now the image is on my kodi machines instantly :D And screenshot arrived on my phone as well, without waiting.

Let's configure the rest and look at your pass2php3.0 :)

Re: Telegram Notification IF LAN IP CHANGED

Posted: Sunday 18 December 2016 21:09
by Egregius
Nice :D

Re: Telegram Notification IF LAN IP CHANGED

Posted: Sunday 25 December 2016 23:34
by ropske
will it also work with:
PHP Version
5.5.22

?
i have this one installed in my nas and if i want to run the telegram.php
i'm getting this error:

HTTP 500-fout
Dat is vreemd... deze pagina kan niet worden weergegeven door de website