Presence detection on an OpenWRT router

Python and python framework

Moderator: leecollings

Post Reply
piedro
Posts: 6
Joined: Wednesday 07 November 2018 11:09
Target OS: Linux
Domoticz version:
Contact:

Presence detection on an OpenWRT router

Post by piedro »

Just finished my presence detection based on querying an OpenWRT router through ssh, inspired by Chopper_Rob (arping based).

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




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
# Customise 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 = "edgar"
domoticzpassword = "Passie"
domoticzpasscode = "Passcode"



# MAC of clients to look for
mac1="20:EE:DA:38:FF:75"
mac2="00:BB:0A:58:AA:A0"

# 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&param=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&param=switchlight&idx="+switchid+"&switchcmd=On&level=0" + "&passcode=" + domoticzpasscode)



myCmd = os.popen('ssh [email protected]  "iwinfo wlan0 assoclist"').read()
myCmd2 = os.popen('ssh [email protected]  "iwinfo wlan1 assoclist"').read()


responsstat=myCmd+myCmd2


#print (responsstat)


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=t
rue&order=Name'

check('2', "E",currentstatemob2)
check('3', "F", currentstatemob1)
Guest7493264

Re: Presence detection on an OpenWRT router

Post by Guest7493264 »

Hi,

I've put up a script on GitHub which uses one openwrt master ap which can passively listen for events of any number of slave devices and resync in case events got lost e.g. during reboot. It emits connection, disconnection, present and away state for configured device mac's via flat file and fifos.

Link: https://forum.openwrt.org/t/script-how- ... -aps/52962

Put it to production and attached a fifo reader script on the master which toggles a virtual switch for every person's presence in domoticz via http json api - just works great.

It has a cooldown time built-in, so going into the garden will not immediately emit an away event. Moving to another ap will also not emit present-away-present but preserve the present status.

Have fun.
Post Reply

Who is online

Users browsing this forum: No registered users and 1 guest