Domoticz Bluetooth Presence Detection

Update script being used as presence detection. Previously would take arguments for -s and -b (switch and bluetooth) and only check 1 device. Required multiple cron entries, 1 for each device. This could lead to polling issues if more devices are added. This new script “Should” only poll once for all devices. There’s a pause when it’s searching for the first device but consecutive devices fly through so I think it’s working.

Python Script saved in /home/domoticz/domoticz/bluetooth/bluescan.py

#!/usr/bin/python

import bluetooth
import time
import argparse
import urllib
import urllib2
import json

parser = argparse.ArgumentParser(description='SwitchID BluetoothID')
parser.add_argument('-l', '--link', action='append', help='BluetoothMac-SwitchID', required=True)
parser.add_argument('-d', '--debug', help='Debug Output', required=False, action='store_true')
parser.add_argument('-u', '--updatefound', help='Always update Found Devices', required=False, action='store_true')
args = parser.parse_args()

def update_switch(args, switchid, status):
URL="http://127.0.0.1/json.htm?username=YWRtaW4=&password=ZG9tb3RpY3o=&type=command&param=switchlight&idx={0}&switchcmd={1}".format( switchid, status )
if args.debug:
print URL
request = urllib2.Request(URL)
response = urllib2.urlopen(request)
return response.read()

if args.debug:
print "Checking " + time.strftime("%a, %d %b %Y %H:%M:%S", time.gmtime())

for value in args.link:
s = value.split("-")
blueid, switchid = s[0], s[1]
if args.debug:
print ("Switch ID: %s" %switchid )
print ("Bluetooth ID: %s" %blueid )

#Get the current status
URL="http://127.0.0.1/json.htm?username=YWRtaW4=&password=ZG9tb3RpY3o=&type=devices&rid={0}".format( switchid )
if args.debug:
print URL
response = urllib2.urlopen(URL)
json_data = json.load(response)
current_status = json_data['result'][0]['Status']
if args.debug:
print ("Current Status: %s" %current_status )

result = bluetooth.lookup_name(blueid, timeout=10)

if (result != None):
if args.debug:
print "Found"
# status = 1
status = "On"
else:
if args.debug:
print "NOT Found"
# status = 0
status = "Off"

if current_status == status:
if args.debug:
print "Status UnChanged"
if status=="On" and args.updatefound:
update = update_switch( args, switchid, status )
if args.debug:
print update
else:
update = update_switch( args, switchid, status )
if args.debug:
print update

Cronjob as user domoticz

* * *   *       *       /home/domoticz/domoticz/bluetooth/bluescan.py -u -l C0:EE:FB:00:00:00-7 -l A0:82:1F:00:00:00-23

Had to us – as separator. : in mac address would be confusing, tried ; but conflicts with bash, was going to use a space but would need to account for that in the argument parser and – was just easier.

Leave a Reply

Your email address will not be published. Required fields are marked *