Unofficial Whatsapp - Notification System - Doorbell example

From Domoticz
Revision as of 12:56, 25 November 2016 by Ariekanarie (talk | contribs) (Added info for sending to whatsapp groups)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Introduction

Whatsapp is similar to Telegram, however is not officially supported by an external API. In the past there have been several "API's" that did or dit not work all the time. Recently I stumbled upon a nice tutorial on how to setup Whatsapp and see if I could make it communicate with Domoticz.

I recommend you to use this tutorial in combination with a PRE-PAID simcard. (In case you get banned by Whatsapp should you start spamming their network.)

Getting your Whatsapp password

Basically follow the instructions to the letter on the Instructables website: [1]

Store your password and the mobile phone number you registered with in a safe place. You will need it later in the config file.

Setup Domoticz so it can send messages via Whatsapp

Once you have obtained your password and had successfully send several 2 way messages using yowsup-cli it is now time to use your knowledge with Domoticz.

Create a file in the following directory: /home/pi/domoticz/scripts/ and call it "whatsapp.notify.sh"

#!/bin/bash
DomoticzIP="192.168.**.**"
DomoticzPort="8080"
TempFileDir="/var/tmp/"
WhatsappPath="/home/pi/domoticz/Whatsapp/"			# your Whatsapp install directory
WhatsappHomePath=$WhatsappPath"yowsup/"				# your yowsub directory
WhatsappConfigFile=$WhatsappHomePath"yowsup/config"
WhatsappRecipient1=316********					# your Whatsapp recipients
WhatsappRecipient2=316********

yowsup-cli demos -c $WhatsappConfigFile -s $WhatsappRecipient1 "Doorbell Pressed"
yowsup-cli demos -c $WhatsappConfigFile -s $WhatsappRecipient2 "Doorbell Pressed"


In essence when called this script will send a Whatsapp message to your Whatsapp recipient. (we will add a picture later) Please don't forget to "sudo chmod +x whatsapp.notify.sh" after saving.

I've also created a LUA DEVICE script (Doorbell) that will trigger the whatsapp.notify.sh script if the doorbell is pressed. under Setup -> More Options -> Events. And additionally I created a user variable 'LastDeurbel'. Using this variable I was able to ignore the 433 'chime' bursts.

---------------------------------------------------------------------------------------------------------
-- Script parameters
----------------------------------------------------------------------------------------------------------
Debug 	   = "YES"                    -- Turn debugging on ("YES") or off ("NO")

----------------------------------------------------------------------------------------------------------
-- Script functions
----------------------------------------------------------------------------------------------------------
function datetimedifferencenow(s)
   year = string.sub(s, 1, 4)
   month = string.sub(s, 6, 7)
   day = string.sub(s, 9, 10)
   hour = string.sub(s, 12, 13)
   minutes = string.sub(s, 15, 16)
   seconds = string.sub(s, 18, 19)
   t1 = os.time()
   t2 = os.time{year=year, month=month, day=day, hour=hour, min=minutes, sec=seconds}
   difference = os.difftime (t1, t2)
   return difference
end

----------------------------------------------------------------------------------------------------------
-- Command Array functions
----------------------------------------------------------------------------------------------------------


----------------------------------------------------------------------------------------------------------
-- Command Tools & Examples
----------------------------------------------------------------------------------------------------------
notify_whatsapp ="/home/pi/domoticz/scripts/whatsapp.notify.sh"

----------------------------------------------------------------------------------------------------------
-- Declare & Fill variables
----------------------------------------------------------------------------------------------------------

commandArray = {}

if (devicechanged['Deurbel'] == 'Chime') 
then
	if (datetimedifferencenow(uservariables_lastupdate['LastDeurbel']) > 2)
	then	
		print('<font color="red">### DeurBel ingedrukt -> ok.</font>')
		os.execute (notify_whatsapp)
		commandArray['Variable:LastDeurbel']=tostring(os.time())
	else 
		print("### DeurBel pressed within 2 seconds, or multiple RF commands received!.")
	end
end

return commandArray

Once you doorbell is pressed you should now receive a whatsapp 'text' notification to 1 or more recipients.

Sending to Whatsapp Groups

You can send your notifications to Whatsapp groups by replacing the recepient number by the GroupID.

This GroupID can be found with the following steps:

- First make sure your Domoticz whatsapp number is added to a group.

- On your raspberry cd tot your YOWSUP installation folder. (eg /home/pi/domoticz/yowsup/)

cd ~/domoticz/yowsup/

- Start yowsup

sudo yowsup-cli demos --yowsup --config config

- Login:

/L

- Show a list of al groups the number is assigned to

/groups list

- Result:

[connected]:Iq:
ID: 30
Type: result
from: g.us
Groups:
ID: 316xxxxxxxx-1480070591, Subject: Domoticz, Creation: 1480070591, Creator: [email protected], Subject Owner: [email protected], Subject Time: 1480070633
Participants: [email protected], [email protected]

GroupID is composed by the number of the creator-Timestamp, so in this example 316xxxxxxxx-1480070591 is the GroupID. (316xxxxxxxx is my own number, 316zzzzzzzz is my Domoticz number)

It is my excperience that when using group messages, you can't use multiple (single) recipients in the config, so the whatsapp.notify.sh is gonna look like this:

 
#!/bin/bash
DomoticzIP="192.168.**.**"
DomoticzPort="8080"
TempFileDir="/var/tmp/"
WhatsappPath="/home/pi/domoticz/Whatsapp/"			# your Whatsapp install directory
WhatsappHomePath=$WhatsappPath"yowsup/"				# your yowsub directory
WhatsappConfigFile=$WhatsappHomePath"yowsup/config"
WhatsappRecipient1=316xxxxxxxx-1480070591			# your Whatsapp recipients

 
yowsup-cli demos -c $WhatsappConfigFile -s $WhatsappRecipient1 "Doorbell Pressed"


Snapping the image from your camera

#!/bin/sh

DomoticzIP="192.168.**.**"
DomoticzPort="8080"
TempFileDir="/var/tmp/"

##########################################################
IP=192.168.**.**                       # IP address Camera
##########################################################
SnapFile=$TempFileDir"snapshot.jpg"

if ping -c 1 $IP > /dev/null ; then # if IPCAM is online then:
   wget -O - "$DomoticzIP":"$DomoticzPort"/camsnapshot.jpg?idx=** > $SnapFile       # IDX of your IP Camera in Domoticz
else
   print "IP-cam niet beschikbaar."
fi

Ofcourse this bash code can be merged in your: whatsapp.notify.sh. However as I use Telegram, Pushover and Whatsapp it is in a separate file for me. If you are unable to figure it out, just let me know in [2].

A well why not... this updated: "whatsapp.notify.sh" script should also do the trick.

#!/bin/bash
DomoticzIP="192.168.**.**"
DomoticzPort="8080"
IP=192.168.**.**                       				# IP address Camera
TempFileDir="/var/tmp/"
WhatsappPath="/home/pi/domoticz/Whatsapp/"			# your Whatsapp install directory
WhatsappHomePath=$WhatsappPath"yowsup/"				# your yowsub directory
WhatsappConfigFile=$WhatsappHomePath"yowsup/config"
WhatsappRecipient1=316********					# your Whatsapp recipients
WhatsappRecipient2=316********


SnapFile=$TempFileDir"snapshot.jpg"
 
if ping -c 1 $IP > /dev/null ; then # if IPCAM is online then:
   wget -O - "$DomoticzIP":"$DomoticzPort"/camsnapshot.jpg?idx=** > $SnapFile       # IDX of your IP Camera in Domoticz
else
   print "IP-cam niet beschikbaar."
fi

yowsup-cli demos -c $WhatsappConfigFile -s $WhatsappRecipient1 "Doorbell Pressed"
python $WhatsappPath"image.py" > /dev/null
yowsup-cli demos -c $WhatsappConfigFile -s $WhatsappRecipient2 "Doorbell Pressed"
python $WhatsappPath"image.py" > /dev/null

Adding Pictures

To add images we can use documentation that has been provided here: [3]. It could be that you still need to install the python pillow library as well
I created image.py based upon this post: [4] that will add the photo to a whatsapp message.

from wamedia import *

import logging
logging.basicConfig(level=logging.ERROR)


def credential():
    return "PHONE NUMBER YOU REGISTRED WHATSAPP WITH","WHATSAPP PASSWORD=" # Put your credentials here!

def sendphoto1():
    try:
        stack = SendMediaStack(credential(), [(["PHONE_NUMBER_RECIPIENT1", "/var/tmp/snapshot.jpg"])])
        stack.start()
    except ImageSent as e:
        if ("ERROR" in e.value): print("Could not send the image!")


def sendphoto2():
    try:
        stack = SendMediaStack(credential(), [(["PHONE_NUMBER_RECIPIENT2", "/var/tmp/snapshot.jpg"])])
        stack.start()
    except ImageSent as e:
        if ("ERROR" in e.value): print("Could not send the image!")


# Main program
sendphoto2()
sendphoto1()

Ofcourse now your "whatsapp.notify.sh" needs to be adjusted as well a bit.

Replace:

yowsup-cli demos -c $WhatsappConfigFile -s $WhatsappRecipient1 "Doorbell Pressed"
yowsup-cli demos -c $WhatsappConfigFile -s $WhatsappRecipient2 "Doorbell Pressed"

With:

yowsup-cli demos -c $WhatsappConfigFile -s $WhatsappRecipient1 "Doorbell Pressed"
python $WhatsappPath"image.py" > /dev/null
yowsup-cli demos -c $WhatsappConfigFile -s $WhatsappRecipient2 "Doorbell Pressed"
python $WhatsappPath"image.py" > /dev/null


Ofcourse an updated image of whoever is at the front door (/var/tmp/snapshot.jpg) has to be available as well.