Synology-Forum.nl
Packages => 3rd party Packages => Overige 3rd party packages => Topic gestart door: GuidoG op 16 februari 2015, 19:53:45
-
Ik wil graag presence detection instellen op Domoticz. Ik heb versie v2.258 draaien op mijn NAS.
http://www.domoticz.com/wiki/Presence_detection
Ik heb het script aangepast (mijn IP adres en mijn gebruiker en wachtwoord) en dit met WinSCP geplaatst in /volume1/homes/admin/check_device_online.py
Python geinstalleerd op de NAS
de Cronjob editor geinstalleerd, om aan te geven naar welk IP adres het python script elke 10 seconden moet pingen, maar ik krijg in cronjob deze fout:
Feb 16 19:52:58 crond: crond (busybox 1.16.1) started, log level 8
Wat doe ik fout?
-
maar ik krijg in cronjob deze fout:
Feb 16 19:52:58 crond: crond (busybox 1.16.1) started, log level 8
Dat is geen fout maar een normale melding.
Maar goed, het probleem is natuurlijk dat "het" niet werkt.
Wat staat er in /etc/crontab ?
-
Hee dat is de plek van het echte crontab bestand! Dank je.
Mijn iphone zit op 192.168.2.31, mijn dummy knop zit op 32, dus dat klopt allemaal. Ik kan nu alleen niet zien of merken dat crontab nu telkens pingt naar mijn iphone
[attachimg=1]
-
Hee dat is de plek van het echte crontab bestand
Yep, dat klopt ;)
Ik kan nu alleen niet zien of merken dat crontab nu telkens pingt naar mijn iphone
Kun je niet gewoon een logfile laten maken door check_device_online.py naar b.v. /volume1/<pinglog>/<ping.log of zoiets ?
-
Dat heb ik nog nooit gedaan, hoe doe ik dat?
-
Nou, ik beheers Python niet en dacht jij wel :S
-
Dan zie ik er blijkbaar slimmer uit dan ik ben, ik heb alleen maar de stappen in deze beschrijving gevolgd;
http://www.domoticz.com/wiki/Presence_detection
Ik ga wel even op onderzoek uit.
-
Eigenlijk is de vraag meer: hoe krijg ik presence detection werkend op een Synology NAS (iemand?)
Ik overweeg nu (kan geen Python programmeren) om een RPI als slave te gebruiken en daar het presence script op draaien (ofwel speciaal voor presence detection een raspberry pi inzetten)
-
Hmmmm, zou gewoon moeten kunnen werken via een cronjob...
Wat mij opvalt is dat je het onder het admin account laat lopen (is root wellicht een optie?) en dat het .py script niet in domoticz/scripts staat maar in je home folder.
Is het script wel uitvoerbaar geflagged? (zie domoticz wiki 'make executable')
Wat gebeurt er als je het script met de hand in een terminalvenster start. Krijg je dan wel gegevens binnen?
Succes!
Wizjos
EDIT: Volgens mij ontbreekt ook de aanroep naar python zelf (kan het nu niet zelf nakijken, maar iets als /usr/bin/python /padnaarscript/script.py)
-
Heb het bewuste Python script eens in de scripts directory van m'n 214Play geplaatst en de nodige parameters ingevuld.
Vervolgens het geheel maar eens gestart ( /usr/bin/python /volume1/@appstore/domoticz/scripts/presence.py) en gemerkt dat 'ie eeuwig blijft doorlopen... :o
Niet zo gek bij nadere beschouwing: Er zit een loop in 't script (while 1==1:) die er voor zorgt dat het script maar blijft draaien. Tikje vreemd dan dat je het met een cronjob moet schedulen...
In principe zou het allemaal redelijk simpel moeten kunnen met een shell-scriptje. Iets als:
#!/bin/ash
# Settings
PRESENCE_IP="192.168.131.88" # IP Address of Device to be checked
DOMO_IP="192.168.131.21" # Domoticz IP Address
DOMO_PORT="8084" # Domoticz Port
PRESENCE_IDX="65" # DEVICE Switch IDX
WAIT_TIME="10" # Time to wait before retry
LOOPCOUNTER=3 # Number of retries
# DO NOT MODIFY BELOW HERE
# Check if DEVICE in online
echo $(date) "Device presence check starting" >> /var/log/cron.log
# Function check: pings te specified device
check()
{
PINGTIME=`ping -c1 -q $PRESENCE_IP | awk -F"/" '{print $5}' | xargs`
echo "Pingtime:" $PINGTIME
if expr "$PINGTIME" '>' 0
then
curl -s "http://$DOMO_IP:$DOMO_PORT/json.htm?type=devices&rid=$PRESENCE_IDX" | grep "Status" | grep "On" > /dev/null
if [ $? -eq 0 ] ; then
echo "DEVICE is ON"
else
curl -s -i -H "Accept: application/json" "http://$DOMO_IP:$DOMO_PORT/json.htm?type=command¶m=switchlight&idx=$PRESENCE_IDX&switchcmd=On"
echo "DEVICE switched ON"
fi
echo $(date) "Device presence check finished" >> /var/log/cron.log
exit
else
if expr "$LOOPCOUNTER" '=' 0
then
curl -s "http://$DOMO_IP:$DOMO_PORT/json.htm?type=devices&rid=$PRESENCE_IDX" | grep "Status" | grep "Off" > /dev/null
if [ $? -eq 0 ] ; then
echo "DEVICE is OFF"
echo $(date) "Device presence check finished" >> /var/log/cron.log
exit
else
echo "DEVICE OFF"
# Send data
curl -s -i -H "Accept: application/json" "http://$DOMO_IP:$DOMO_PORT/json.htm?type=command¶m=switchlight&idx=$PRESENCE_IDX&switchcmd=Off"
echo $(date) "Device presence check finished" >> /var/log/cron.log
exit
fi
fi
fi
}
# Main loop
while [ $LOOPCOUNTER -gt 0 ]; do
echo "Retries left: " $LOOPCOUNTER
LOOPCOUNTER=$((LOOPCOUNTER - 1))
check
echo "...waiting..."
sleep $WAIT_TIME
done
Als je nu dit script in een cronjob giet zou e.e.a. moeten gaan werken.
Let op:
- script moet executable geflagged worden
- script moet Unix regeleinden bevatten (Niet via een Windows editor (Kladblok) maken)
- correcte aanroep van script in cronjob: /volume1/@appstore/domoticz/scripts/Presence.sh
Ik hoop dat je er wat mee kunt...
Wizjos
-
Heb je de laatste versie van het script gebruikt ? Deze is aangepast om te gebruiken
op een synology.
Link naar laatste versie >>> https://www.chopperrob.nl/domoticz/5-report-devices-online-status-to-domoticz
Het script 'check_device_online.py' wordt geplaatst in /var/packages/domoticz/target/scripts
Bij mij werkt het probleemloos bij dit script , en krijg meldingen op mijn smartphone wanneer iemand zichtbaar is of niet.
Wel in domoticz via blokly scripting (lua) ingesteld dat ik hiervoor melding wil ontvangen. ;)
-
Hey Capman,
Ik heb ook zitten prutsen met het script van chopperrob, krijg het alleen niet voor elkander. Zou je willen uitleggen welke stappen je precies hebt gevolgd? Ik probeer het ook op een synology te draaien, maar simpel plak en knip werk is het niet :(
Alvast bedankt! Je bent een held.
Gr
Sander
-
Oud bericht maar ben net bezig met afwezigheids detectie en kwam deze posting tegen.
Het het script van Rob gebruikt en het loopt op mijn DS214PLAY.
Nu me verdiepen in Cronjob om het op te starten.
Heb blockly gemaakt en krijg nu berichten als ik binnen/buiten bereik kom.
Bedankt.
-
De site van Chopperrob lijkt al een tijdje offline te zijn, heeft iemand het schript nog beschikbaar?
-
Hier is de code. Was volgens mij de meest recente versie van het script.
Heb het zelf wel aan de praat gehad echter stopte het op mijn NAS. Verder niet meer ingedoken.
Succes.
#!/usr/bin/python
# Title: check_device_online.py
# Author: Chopper_Rob
# Date: 25-02-2015
# Info: Checks the presence of the given device on the network and reports back to domoticz
# URL : https://www.chopperrob.nl/domoticz/5-report-devices-online-status-to-domoticz
# Version : 1.6.2
import sys
import datetime
import time
import os
import subprocess
import urllib2
import json
import base64
# Settings for the domoticz server
domoticzserver="IP:PORT"
domoticzusername = "****"
domoticzpassword = "******"
# 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 = False
# The script supports two types to check if another instance of the script is running.
# One will use the ps command, but this does not work on all machine (Synology has problems)
# The other option is to create a pid file named _.pid. The script will update the timestamp
# every interval. If a new instance of the script spawns it will check the age of the pid file.
# If the file doesn't exist or it is older then 3 * Interval it will keep running, otherwise is stops.
# Please chose the option you want to use "ps" or "pid", if this option is kept empty it will not check and just run.
check_for_instances = "pid"
# DO NOT CHANGE BEYOND THIS LINE
if len(sys.argv) != 5 :
print ("Not enough parameters. Needs %Host %Switchid %Interval %Cooldownperiod.")
sys.exit(0)
device=sys.argv[1]
switchid=sys.argv[2]
interval=sys.argv[3]
cooldownperiod=sys.argv[4]
previousstate=-1
lastsuccess=datetime.datetime.now()
lastreported=-1
base64string = base64.encodestring('%s:%s' % (domoticzusername, domoticzpassword)).replace('\n', '')
domoticzurl = 'http://'+domoticzserver+'/json.htm?type=devices&filter=all&used=true&order=Name'
if check_for_instances.lower() == "pid":
pidfile = sys.argv[0] + '_' + sys.argv[1] + '.pid'
if os.path.isfile( pidfile ):
print datetime.datetime.now().strftime("%H:%M:%S") + "- pid file exists"
if (time.time() - os.path.getmtime(pidfile)) < (float(interval) * 3):
print datetime.datetime.now().strftime("%H:%M:%S") + "- script seems to be still running, exiting"
print datetime.datetime.now().strftime("%H:%M:%S") + "- If this is not correct, please delete file " + pidfile
sys.exit(0)
else:
print datetime.datetime.now().strftime("%H:%M:%S") + "- Seems to be an old file, ignoring."
else:
open(pidfile, 'w').close()
if check_for_instances.lower() == "ps":
if int(subprocess.check_output('ps x | grep \'' + sys.argv[0] + ' ' + sys.argv[1] + '\' | grep -cv grep', shell=True)) > 2 :
print (datetime.datetime.now().strftime("%H:%M:%S") + "- script already running. exiting.")
sys.exit(0)
def log(message):
print message
if log_to_file == True:
logfile = open(sys.argv[0] + '_' + sys.argv[1] + '.log', "a")
logfile.write(message + "\n")
logfile.close()
def domoticzstatus ():
json_object = json.loads(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 and "Lighting" in json_object["result"][i]["Type"] :
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.datetime.now().strftime("%H:%M:%S") + "- Error. Could not find switch idx in Domoticz response. Defaulting to switch off.")
return status
def domoticzrequest (url):
request = urllib2.Request(url)
request.add_header("Authorization", "Basic %s" % base64string)
response = urllib2.urlopen(request)
return response.read()
log (datetime.datetime.now().strftime("%H:%M:%S") + "- script started.")
lastreported = domoticzstatus()
if lastreported == 1 :
log (datetime.datetime.now().strftime("%H:%M:%S") + "- according to domoticz, " + device + " is online")
if lastreported == 0 :
log (datetime.datetime.now().strftime("%H:%M:%S") + "- according to domoticz, " + device + " is offline")
while 1==1:
currentstate = subprocess.call('ping -q -c1 -W 1 '+ device + ' > /dev/null', shell=True)
if currentstate == 0 : lastsuccess=datetime.datetime.now()
if currentstate == 0 and currentstate != previousstate and lastreported == 1 :
log (datetime.datetime.now().strftime("%H:%M:%S") + "- " + device + " online, no need to tell domoticz")
if currentstate == 0 and currentstate != previousstate and lastreported != 1 :
if domoticzstatus() == 0 :
log (datetime.datetime.now().strftime("%H:%M:%S") + "- " + device + " online, tell domoticz it's back")
domoticzrequest("http://" + domoticzserver + "/json.htm?type=command¶m=switchlight&idx=" + switchid + "&switchcmd=On&level=0")
else:
log (datetime.datetime.now().strftime("%H:%M:%S") + "- " + device + " online, but domoticz already knew")
lastreported=1
if currentstate == 1 and currentstate != previousstate :
log (datetime.datetime.now().strftime("%H:%M:%S") + "- " + device + " offline, waiting for it to come back")
if currentstate == 1 and (datetime.datetime.now()-lastsuccess).total_seconds() > float(cooldownperiod) and lastreported != 0 :
if domoticzstatus() == 1 :
log (datetime.datetime.now().strftime("%H:%M:%S") + "- " + device + " offline, tell domoticz it's gone")
domoticzrequest("http://" + domoticzserver + "/json.htm?type=command¶m=switchlight&idx=" + switchid + "&switchcmd=Off&level=0")
else:
log (datetime.datetime.now().strftime("%H:%M:%S") + "- " + device + " offline, but domoticz already knew")
lastreported=0
time.sleep (float(interval))
previousstate=currentstate
if check_for_instances.lower() == "pid": open(pidfile, 'w').close()
-
Tnx, ik ga er mee aan de slag :)
-
En? Heb je een oplossing gevonden om deze script 'live' te houden?
-
In principe zou het allemaal redelijk simpel moeten kunnen met een shell-scriptje. Iets als:
#!/bin/ash
# Settings
PRESENCE_IP="192.168.131.88" # IP Address of Device to be checked
DOMO_IP="192.168.131.21" # Domoticz IP Address
DOMO_PORT="8084" # Domoticz Port
PRESENCE_IDX="65" # DEVICE Switch IDX
WAIT_TIME="10" # Time to wait before retry
LOOPCOUNTER=3 # Number of retries
# DO NOT MODIFY BELOW HERE
# Check if DEVICE in online
echo $(date) "Device presence check starting" >> /var/log/cron.log
# Function check: pings te specified device
check()
{
PINGTIME=`ping -c1 -q $PRESENCE_IP | awk -F"/" '{print $5}' | xargs`
echo "Pingtime:" $PINGTIME
if expr "$PINGTIME" '>' 0
then
curl -s "http://$DOMO_IP:$DOMO_PORT/json.htm?type=devices&rid=$PRESENCE_IDX" | grep "Status" | grep "On" > /dev/null
if [ $? -eq 0 ] ; then
echo "DEVICE is ON"
else
curl -s -i -H "Accept: application/json" "http://$DOMO_IP:$DOMO_PORT/json.htm?type=command¶m=switchlight&idx=$PRESENCE_IDX&switchcmd=On"
echo "DEVICE switched ON"
fi
echo $(date) "Device presence check finished" >> /var/log/cron.log
exit
else
if expr "$LOOPCOUNTER" '=' 0
then
curl -s "http://$DOMO_IP:$DOMO_PORT/json.htm?type=devices&rid=$PRESENCE_IDX" | grep "Status" | grep "Off" > /dev/null
if [ $? -eq 0 ] ; then
echo "DEVICE is OFF"
echo $(date) "Device presence check finished" >> /var/log/cron.log
exit
else
echo "DEVICE OFF"
# Send data
curl -s -i -H "Accept: application/json" "http://$DOMO_IP:$DOMO_PORT/json.htm?type=command¶m=switchlight&idx=$PRESENCE_IDX&switchcmd=Off"
echo $(date) "Device presence check finished" >> /var/log/cron.log
exit
fi
fi
fi
}
# Main loop
while [ $LOOPCOUNTER -gt 0 ]; do
echo "Retries left: " $LOOPCOUNTER
LOOPCOUNTER=$((LOOPCOUNTER - 1))
check
echo "...waiting..."
sleep $WAIT_TIME
done
Als je nu dit script in een cronjob giet zou e.e.a. moeten gaan werken.
Let op:
- script moet executable geflagged worden
- script moet Unix regeleinden bevatten (Niet via een Windows editor (Kladblok) maken)
- correcte aanroep van script in cronjob: /volume1/@appstore/domoticz/scripts/Presence.sh
Ik hoop dat je er wat mee kunt...
Wizjos
Heel oude post, maar na van alles te hebben uitgeprobeerd, lijkt dit tenminste te werken. In ieder geval in een test-situatie.
Bedankt