Presence detection on TPlink router (http access)
Posted: Wednesday 07 November 2018 11:24
Just finished my presence detection, inspired by Chopper_Rob (arping based) en code Home Assistant (tplink queries).
11:21:06- script started.
11:21:06- according to domoticz, E is online
11:21:06- E offline, tell domoticz
11:21:06- according to domoticz, F is offline
11:22:06- script started.
11:22:06- according to domoticz, E is offline
11:22:06- according to domoticz, F is offline
Might be helpful:
11:21:06- script started.
11:21:06- according to domoticz, E is online
11:21:06- E offline, tell domoticz
11:21:06- according to domoticz, F is offline
11:22:06- script started.
11:22:06- according to domoticz, E is offline
11:22:06- according to domoticz, F is offline
Might be helpful:
Code: Select all
#author: Piedro Genius
#inspired by Chopper_Rob (arping based) en code Home Assistant (tplink queries)
# Date: 25-02-2015 en 7-11-2018
# Info: Checks the presence of a given MAC thru router and reports changes back to domoticz
# Add to crontab for recurrent check
# how to determine encrypted password TPlink, see https://www.home-assistant.io/components/device_tracker.tplink/
# Python 3.6
# Customize check(switchid_in_domoticz, "Optional human name for log",presence_status_according_to_router)
# and all credentials and IP addresses
import requests
import sys
import time
import os
import json
from datetime import datetime
import re
from aiohttp.hdrs import (
ACCEPT, COOKIE, PRAGMA, REFERER, CONNECTION, KEEP_ALIVE, USER_AGENT,
CONTENT_TYPE, CACHE_CONTROL, ACCEPT_ENCODING, ACCEPT_LANGUAGE)
#HTTP_HEADER_NO_CACHE = 'no-cache'
# Settings for the domoticz server
domoticzserver="192.168.1.2:8080"
domoticzusername = "piedro"
domoticzpassword = "Password"
domoticzpasscode = "Passcode"
# Settings for TPLink
url = 'http://192.168.0.1/cgi-bin/luci/;stok=/login?form=login'
urlbegin='http://192.168.0.1/cgi-bin/luci/;stok='
urlstateind='/admin/wireless?form=statistics'
urlloeind='/admin/system?form=logout'
referer = 'http://192.168.0.1/webpages/login.html'
#credentials TP link
admin='admin'
#encrypted password see https://www.home-assistant.io/components/device_tracker.tplink/
pwd='5476765c33aaaaaf0deed1740a1e6f14ab9c67350a037c7478dfffff2f18f0ed45412fd5ed1c24bfeeba5c5f15dbbbbb58896b0f0bb1dd111f325533e831ac63bec2e5a914772e4e82698b651729970d2b644f269e38e35b223eaebbbaf0ac385354f9132d6b30b9ec9224459da99ba8988869f4fea86b4f45332298'
# MAC of clients to look for
mac1="00-AA-BB-CC-DD-01"
macw="00-AA-BB-CC-DD-02"
# If enabled. The script will log to the file _.log
# Logging to file only happens after the check for other instances, before that it only prints to screen.
log_to_file = True
def domoticzstatus (switchid):
# json_object = json.loads(domoticzrequest(domoticzurl))
json_object = domoticzrequest(domoticzurl)
status = 0
switchfound = False
if json_object["status"] == "OK":
for i, v in enumerate(json_object["result"]):
if json_object["result"][i]["idx"] == switchid:
switchfound = True
if json_object["result"][i]["Status"] == "On":
status = 1
if json_object["result"][i]["Status"] == "Off":
status = 0
if switchfound == False: print (datetime.now().strftime("%H:%M:%S") + "- Error. Could not find switch idx in Domoticz response. Defaulting to switch off.")
return status
def domoticzrequest (url):
response = requests.get(url, auth=('domoticzusername', 'domoticzpassword'))
# print (response.status_code)
return response.json()
def log (message):
# print (message)
if log_to_file == True:
logfile = open(sys.argv[0]+'.log','a')
logfile.write(message + "\n")
logfile.close()
def check(switchid, who, currentstate):
lastreported = domoticzstatus(switchid)
if lastreported == 1 :
log (datetime.now().strftime("%H:%M:%S") + "- according to domoticz, " + who + " is online")
if currentstate == 0 :
log (datetime.now().strftime("%H:%M:%S") + "- "+ who + " offline, tell domoticz")
domoticzrequest("http://" + domoticzserver + "/json.htm?type=command¶m=switchlight&idx="+switchid+"&switchcmd=Off&level=0" + "&passcode=" + domoticzpasscode)
if lastreported == 0 :
log (datetime.now().strftime("%H:%M:%S") + "- according to domoticz, " + who + " is offline")
if currentstate == 1:
log (datetime.now().strftime("%H:%M:%S") + "- "+ who + " online, tell domoticz")
domoticzrequest("http://" + domoticzserver + "/json.htm?type=command¶m=switchlight&idx="+switchid+"&switchcmd=On&level=0" + "&passcode=" + domoticzpasscode)
#retrieve auth tokens TPlink
stok=''
sysauth=''
# If possible implement RSA encryption of password here.
response = requests.post(url, params={'operation': 'login',
'username': admin,'password': pwd},
headers={REFERER: referer}, timeout=4)
try:
stok = response.json().get('data').get('stok')
# print(stok)
regex_result = re.search(
'sysauth=(.*);', response.headers['set-cookie'])
sysauth = regex_result.group(1)
# print(sysauth)
urlstat=urlbegin + stok + urlstateind
response = requests.post(
urlstat, params={'operation': 'load'}, headers={REFERER: referer},
cookies={'sysauth': sysauth}, timeout=5)
try:
responsstat=response.text
# print(responsstat)
goon=1;
urllo = urlbegin + stok + urlloeind
response = requests.post(
urllo, params={'operation': 'write'}, headers={REFERER: referer},
cookies={'sysauth': sysauth}, timeout=5)
try:
# print(response.text)
goon=1
except:
print("Couldn't logout")
except:
print("Couldn't retrieve stat")
goon=0
except (ValueError, KeyError) as _:
print("Couldn't fetch auth tokens! Response was: %s",
response.text)
goon=0;
if goon == 0:
print("quit")
quit()
if mac1 in responsstat:
currentstatemob1=1
else:
currentstatemob1=0
if mac2 in responsstat:
currentstatemob2=1
else:
currentstatemob2=0
log (datetime.now().strftime("%H:%M:%S") + "- script started.")
domoticzurl = 'http://'+domoticzserver+'/json.htm?type=devices&filter=all&used=true&order=Name'
check('2', "E",currentstatemob2)
check('3', "F", currentstatemob1)