Hager Domovea Custom Reporting

De Hager Domovea TJA450 server biedt geen mogelijkheid om data automatisch te exporteren naar een database. Via de servermanager kan je de historische data van meetwaarden wel downloaden naar een csv of xml bestand maar daar houdt het dus ook op.

Persoonlijk vind ik het interessant om bv bij te houden hoeveel keer een bepaald event zich voorgedaan heeft. bv: het openen van de achterdeur of garagepoort.

De domovea server is wel in staat om emails te sturen. Dus de idee ontstond al snel om elke week een rapportje naar mezelf te mailen met een overzichtje van wat er allemaal gebeurd is.

BV: Magneetcontact achterdeur gaat open

–> busevent komt bij de domovea server

domoveastats1

domoveastats2

–> de domovea server doet de variabele achterdeurOpen + 1

domoveastats3

–> zondagnacht verstuurt de domoveaserver een rapportje en reset alle variabelen.

domoveastats4

domoveastats5

 

Zo een wekelijks rapportje ziet er als volgt uit

————————————————————–
START DOMOVEA REPORT
————————————————————–

Weekly Facts:

– Aantal keer garage geopend: 34
– Aantal keer schuifraam geopend: 27
– Aantal keer achterdeur geopend: 164
– Aantal keer voordeur geopend: 7
– Aantal keer alarm ingeschakeld: 6
– Buitenalarm afgegaan: 0
– Binnenkomst als alarm nog actief was (Lichten pinken): 1
– Aantal keer op de deurbel geduwd: 4
– Aantal keer de filmmodus ingeschakeld: 0
– Aantal keer nachtmodus aangezet: 7

————————————————————–
Variabelen Check:

Status Filmmodus: Vals (0)
Status AlarmNetAan: Vals (0)
Status DeurbelVerlichting: Vals (0)

————————————————————–
END DOMOVEA REPORT
————————————————————–

 

Het zou interessant zijn mocht er een mogelijkheid bestaan om zelf een logfile aan te maken of de waarden vanuit domovea rechtstreeks te kunnen wegschrijven in een database. Maar tot op heden is dit dus niet het geval.

Als workaround heb ik een python scriptje geschreven die deze mailtjes uitleest uit mijn gmail account en wegschrijft in een MySQL tabel.

import os
import sys
import datetime
from gmail import Gmail

## Important notes
# give stijn_domovea file permissions for writing files to NAS!
#
# UPDATE mysql.user SET File_priv = 'Y' WHERE user='stijn_domovea' AND host='localhost';
# 1 rij bijgewerkt.
# FLUSH PRIVILEGES;
# MySQL gaf een lege resultatenset terug (0 rijen).

# Vars
mysqlbin="/usr/bin/mysql"
mysqlhost="localhost"
mysqlport="3306"
#mysqluser="xxx"
mysqluser="xxx"
mysqldb="xxx"
#mysqlpass="xxx"
mysqlpass="xxx"

MySQLOutFile = "/tmp/tmpWRdata.txt"
LogOutFile = "/volume2/data/scripts/DomoveaStats/log/processedDomoveaStats.log"

# Classes
class Report:
def __init__(self, date, garage, schuifraam, achterdeur, voordeur, alarm_aan, alarm_actief, alarm_stil, deurbel, filmmodus, nachtmodus):
self.date = date
self.garage = garage
self.schuifraam = schuifraam
self.achterdeur = achterdeur
self.voordeur = voordeur
self.alarm_aan = alarm_aan
self.alarm_actief = alarm_actief
self.alarm_stil = alarm_stil
self.deurbel = deurbel
self.filmmodus = filmmodus
self.nachtmodus = nachtmodus

def toString(self):
datest = str(self.date)
st = "reportdate %s - garage %d - schuifraam %d - achterdeur %d - voordeur %d - alarm_aan %d - alarm_actief %d - alarm_stil %d - deurbel %d - filmmodus %d - nachtmodus %d" % (datest, self.garage, self.schuifraam, self.achterdeur, self.voordeur, self.alarm_aan, self.alarm_actief, self.alarm_stil, self.deurbel, self.filmmodus, self.nachtmodus)
return st

def sql(sqlcmd):
os.system(mysqlbin + " -h" + mysqlhost + " -P" + mysqlport + " -u" + mysqluser + " -p" + mysqlpass + " -e " + sqlcmd)

# Body
# Retrieve mails
g = Gmail()
g.login("xxx@gmail.com", "onetimeapplicationpassword")
mails = g.label("DeLinde/WeeklyStats").mail(prefetch=True)

# Build array with reports
allReports = []
x = 0
totalmails = len(mails)

# Quit when gmail label is empty !
if totalmails == 0:
print "no reports found --> exiting script!"
exit(0)

while x < totalmails:
r = Report(0,0,0,0,0,0,0,0,0,0,0)
r.date = mails[x].sent_at
bl = mails[x].body.split('\n')

r.garage = int(filter(str.isdigit, bl[7]))
r.schuifraam = int(filter(str.isdigit, bl[8]))
r.achterdeur = int(filter(str.isdigit, bl[9]))
r.voordeur = int(filter(str.isdigit, bl[10]))
r.alarm_aan = int(filter(str.isdigit, bl[11]))
r.alarm_actief = int(filter(str.isdigit, bl[12]))
r.alarm_stil = int(filter(str.isdigit, bl[13]))
r.deurbel = int(filter(str.isdigit, bl[14]))
r.filmmodus = int(filter(str.isdigit, bl[15]))
r.nachtmodus = int(filter(str.isdigit, bl[16]))
allReports.append(r)

x = x + 1
print "Done! building report objects"

# Build MySQL connection & update stijn_domovea database
try:
file = open(LogOutFile, "ab")
# get all added dates, on this base we will filter reports already added to DB. In this way we will never add duplicate files
# sql("'use stijn_domovea; select date from WeeklyReports INTO OUTFILE \"/volume2/data/scripts/DomoveaStats/tmpWRdata.txt\";'")
sql("'use stijn_domovea; select date from WeeklyReports INTO OUTFILE \"/tmp/tmpWRdata.txt\";'")

for ar in allReports:
#check date already in DB
date = str(ar.date)
if date in open(MySQLOutFile).read():
print "found %s already in db." % date
else:
sqlstr = "'use stijn_domovea; INSERT INTO WeeklyReports (date,garage,schuifraam,achterdeur,voordeur,alarm_aan,alarm_actief,alarm_stil,deurbel,filmmodus,nachtmodus) VALUES (\"%s\",%d,%d,%d,%d,%d,%d,%d,%d,%d,%d);'" % (str(ar.date), ar.garage, ar.schuifraam, ar.achterdeur, ar.voordeur, ar.alarm_aan, ar.alarm_actief, ar.alarm_stil, ar.deurbel, ar.filmmodus, ar.nachtmodus)
sql(sqlstr)
#print "%s --> Totaal aantal keer garagepoort geopend: %d" % (str(ar.date), ar.garage)
#print sqlstr
print "added %s to db." % date
# append entry to log
logline = "date added: " + datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + " --> " + ar.toString() + "\n"
#with open(LogOutFile, "a") as myfile:
# myfile.write(logline)
file.write(logline)
file.write(u"\r\n")

# Remove temporary file
os.remove(MySQLOutFile)

file.close()

except mdb.Error, e:
# truncate temporary file
os.remove(MySQLOutFile)
# open(MySQLOutFile, 'w').close()

print "Error %d: %s" % (e.args[0],e.args[1])
sys.exit(1)

finally:

sys.exit(0)

 

Uitlezen Hager TE360 met KNXD

Inleiding

Dit script zal de totale verbruikte energie (in Watt) van een Hager TE360 ophalen en toevoegen aan een MySQL database.

Het groepsadres dat gebruikt wordt is 4/6/9
TE360 – 9 – TE360 – totale actieve energie tarief 1 + 2 (Wh)

Dependencies

MySQL client om data weg te schrijven naar de MySQL database

apt-get install mysql-client

Basic Calculator (BC)

apt-get install bc

 

Actieve KNXD logfile (niet meer van toepassing)

crontab -e
@reboot knxtool log local:/run/knx

knxd tools

knxtool groupreadresponse

 

Script die Hager TE360 bevraagt en resultaat in textbestand wegschrijft:

log=/root/logs/getTotalConsumption.log
knxresult=/root/scripts/getTotalConsumption.knxresult
data=/root/scripts/getTotalConsumption.data

echo "$(date "+%Y%m%d %T") ## start ophalen totaal verbruik van Hager TE360 ##" >> $log

echo "$(date "+%Y%m%d %T") uitlezen TE360 met knxtool groupreadresponse" >> $log
#knxtool groupreadresponse local:/run/knx 4/6/9 > $knxresult
knxtool groupreadresponse ip:localhost 4/6/9 > $knxresult

hexdata=$(cat $knxresult | grep -m 1 "from 1.1.9:" | cut -d ":" -f 2)
echo "$(date "+%Y%m%d %T") hexadecimale energiewaarde extraheren: $hexdata" >> $log

# controle opgehaalde hexadecimale waarde
if [ -z "$hexdata" ]; then
echo "$(date "+%Y%m%d %T") fout met uitlezen hexadecimale waarde" >> $log
echo "$(date "+%Y%m%d %T") hexadecimale waarde is leeg" >> $log
echo "$(date "+%Y%m%d %T") script wordt gestopt!" >> $log
exit
fi
if ! [[ $hexdata =~ [!0-9A-Fa-f] ]]; then
echo "$(date "+%Y%m%d %T") fout met uitlezen hexadecimale waarde" >> $log
echo "$(date "+%Y%m%d %T") hexadecimale niet correct: $hexdata" >> $log
echo "$(date "+%Y%m%d %T") script wordt gestopt!" >> $log
exit
fi

# verwijderen spaties
hexdata="$(echo -e "${hexdata}" | tr -d '[[:space:]]')"

# omzetten naar decimale waarde
echo "$(date "+%Y%m%d %T") omzetten hexadecimale waarde naar decimale waarde en wegschrijven naar $data" >> $log
echo $((16#$hexdata)) > $data

echo "$(date "+%Y%m%d %T") ## einde ophalen totaal verbruik van Hager TE360 ##" >> $log

 

Script die elke 5 minuten de database met meetwaarden update:

#!/bin/bash

# Uitlezen energiewaarde Hager TE360 via knxd
# Nadien het totaal verbruik van de afgelopen 5 minuten berekenen
# en wegschrijven naar de SQL database.

log="/root/logs/electricityToMySQL.log"
mysql_host=xx
mysql_user=xx
mysql_pass=xx
mysql_db=xx

# db connectie testen
# indien niet mogelijk script direct stoppen zodat later de correcte waarde in de db kan worden toegevoegd.
if ! mysql -h $mysql_host -u $mysql_user -p$mysql_pass -e "use $mysql_db"; then
echo "$(date "+%Y%m%d %T") db connection error -> script wordt gestopt" >> $log
exit
fi

echo "$(date "+%Y%m%d %T") ## start ophalen elektriciteit ##" >> $log

# ophalen huidig verbruik
echo "$(date "+%Y%m%d %T") uitlezen TE360 met knxtool groupreadresponse" >> $log
/root/scripts/getTotalConsumption.sh
currdata=$(</root/scripts/getTotalConsumption.data)

# ophalen totaalverbruik MySQL database
consumptionTotal=$(mysql -h $mysql_host $mysql_db -u $mysql_user -p$mysql_pass -e "SELECT consumptionTotal FROM Electricity ORDER BY id DESC LIMIT 1;")
consumptionTotal=$(echo $consumptionTotal | cut -d " " -f2)
echo "$(date "+%Y%m%d %T") Vorig totaal verbuik: $consumptionTotal watt" >> $log

# ophalen waarde van 5 minuten geleden
lastdata=$(</root/scripts/electricityToMySQL.lastdata)

# berekenen verbruik laatste 5 minuten
consumption=$(expr $currdata - $lastdata)
echo "$(date "+%Y%m%d %T") Energieverbruik laatste 5 minuten: $consumption watt" >> $log

consumptionTotal=$(($consumptionTotal + $consumption))

# ophalen prijs piek- en daluren
q=$(mysql -h $mysql_host $mysql_db -u $mysql_user -p$mysql_pass -e "SELECT priceHigh,priceLow FROM ElectricityPrice ORDER BY id DESC LIMIT 1;")
priceHigh=$(echo $q | cut -d " " -f3)
priceLow=$(echo $q | cut -d " " -f4)
echo "$(date "+%Y%m%d %T") kostprijs piek: $priceHigh, kostprijs dal: $priceLow" >> $log

# berekenen kostprijs verbruikte energie
# huidige uur
h=$(date +%H)
#dag van de week 1=maandag, 7=zondag
dow=$(date +%u)
# huidig tarief
ct="dal"
if [[ $dow -gt 5 ]] ; then
#echo "$h -> dal -> weekend"
conPrice=$(echo $consumption*$priceLow/1000 | bc -l)
elif (( 7 <= 10#$h && 10#$h < 22 )) ; then
#echo "$h -> piek"
conPrice=$(echo $consumption*$priceHigh/1000 | bc -l)
ct="piek"
else
#echo "$h -> dal"
conPrice=$(echo $consumption*$priceLow/1000 | bc -l)
fi

# toevoegen waarde is MySQL database
date=$(date +"%Y-%m-%d")
time=$(date +"%T")
echo "$(date "+%Y%m%d %T") toevoegen data aan MySQL -> tarief: $ct - verbruik: $consumption - kostprijs: $conPrice --> stijn_domovea -> Electricity" >> $log

mysql -h $mysql_host $mysql_db -u $mysql_user -p$mysql_pass -e "insert into Electricity (date,time,consumption,consumptionTotal,price) values ('$date','$time','$consumption','$consumptionTotal','$conPrice')"

# wegschrijven van nieuwe lastdata
echo "$(date "+%Y%m%d %T") wegschrijven totaal verbruik naar tekstfile -> totaalverbruik: $currdata" >> $log
echo $currdata > /root/scripts/electricityToMySQL.lastdata

echo "$(date "+%Y%m%d %T") ## einde ophalen elektriciteit ##" >> $log

Toevoegen aan crontab

*/5 * * * * /root/scripts/electricityToMySQL.sh

 

Checks, Monitoring & Backup

Hieronder een overzicht van alle controles die geïmplementeerd zijn.

Het komt er op neer dat er thuis 2 toestellen continue draaien

  • RPI3
  • Synology

Beide toestellen controleren elkaar en sturen indien nodig email alerts uit.

De RPI3 heeft ook een M/Monit webinterface waar alles visueel en met historiek kan nagekeken worden.

mmonit

Het is belangrijk dat er een werkende internetverbinding aanwezig is zodat er ten alle tijde emails kunnen verstuurd worden. Ik gebruik hiervoor de mailserver van telenet (uit.telenet.be) en heb op beide toestellen een secondary dns server geconfigureerd zodat de mailserver altijd resolveable zal zijn.

Beide toestellen inclusief internetverbinding (modem / router)  hangen aan een backup-UPS 650. Zo zal bij kort stroomverlies geen uitval zijn. (< 1u)

Monitoring & Checks

RPI3

  • Monit Agent
  • M/Monit visualisatie

Email alerting via uit.telenet.be

Synology

Controle meetwaarden elektriciteit
Python script dat elke 5 minuten controleert indien er nieuwe meetwaarden in de database binnenkomen.

Kort samengevat kunnen we met dit script het volgende vaststellen

  1. De RPI3 staat aan
  2. KNXD service draait
  3. De RPI3 kan de Hager TE360 uitlezen –> de Energiemeter functioneert goed
  4. De DB van de synology draait en is up to date
import os
import sys
import datetime

# Import smtplib for the actual sending function
import smtplib

# Import the email modules we'll need
from email.mime.text import MIMEText

# Vars
mysqlbin="/usr/bin/mysql"
mysqlhost="localhost"
mysqlport="3306"
mysqluser="xxx"
mysqldb="xxx"
mysqlpass="xxx"

# File Vars
MySQLOutFile = "/tmp/tmpWRdata.txt"
LogOutFile = "/volume2/data/scripts/log/checkElectricity.log"
DateLastMailFile = "/volume2/data/scripts/log/checkElectricity.lastmail"

# Email Vars
smtphost = "uit.telenet.be"
me = "synology@domovea.com"
you = "skitex@gmail.com"

def sql(sqlcmd):
os.system(mysqlbin + " -h" + mysqlhost + " -P" + mysqlport + " -u" + mysqluser + " -p" + mysqlpass + " -e " + sqlcmd)

# Body
# Build MySQL connection & update database
try:
file = open(LogOutFile, "ab")
# get all added dates, on this base we will filter reports already added to DB. In this way we will never add duplicate files
# sql("'use stijn_domovea; select date from DailyStats INTO OUTFILE \"/volume2/data/scripts/DomoveaStats/tmpWRdata.txt\";'")
sql("'use stijn_domovea; SELECT * FROM Electricity ORDER BY id DESC LIMIT 1 INTO OUTFILE \"/tmp/tmpWRdata.txt\";'")

file2 = open(MySQLOutFile, "r")
lastDBEntry = file2.read()
file2.close()

# Remove temporary file
os.remove(MySQLOutFile)

#Array maken van SQL record
#0: ID
#1: DATE
#2: TIME
#3: CONSUMPTION
#4: CONSUMPTIONTOTAL
lastDBEntry = lastDBEntry.split('\t')

#ophalen tijd waarop laatste email verstuurd is
file3 = open(DateLastMailFile, "r")
timelastsend = file3.read()
file3.close()
form = '%Y-%m-%d %H:%M:%S.%f'
timels = datetime.datetime.strptime(timelastsend,form)
timedelta3hours = datetime.timedelta(hours=3)
timenow = datetime.datetime.today()

#Controle op CONSUMPTION = 0
#Dit wordt weggeschreven indien de KNXD tool geen correcte waarde kan uitlezen van de BYS
if lastDBEntry[3] == '0':
print "Fout: vermogen is 0"
#print unicode(timels)
#print unicode(timenow)
#print unicode(timedelta3hours)
if timels >= timenow - timedelta3hours:
print "tijd is niet ouder dan 3 uur"
print "stuur geen email"
else:
print "tijd is ouder dan 3 uur"
print "stuur email en update tijd"

#stuur email
body = "laatste entry: \nid: %s \ndatum: %s \ntijd: %s \nverbruik: %s watt \ntotaal: %s watt" % (lastDBEntry[0],lastDBEntry[1],lastDBEntry[2],lastDBEntry[3],lastDBEntry[4].rstrip('\n'))
# Create a text/plain message
msg = MIMEText(body)
msg['Subject'] = 'Elektriciteit: Foutieve waarde in DB'
msg['From'] = me
msg['To'] = you

# Send the message via our own SMTP server.
s = smtplib.SMTP(smtphost)
s.sendmail(me, [you], msg.as_string())
s.quit()

#update tijd
file3 = open(DateLastMailFile, "w+")
file3.write(unicode(timenow))
file3.close()

#Sluit logfile en stop script
file.close()
sys.exit(0)

#Controle op Datum en Tijd niet ouder dan 5 minuten!
sqldate = "%s %s" % (lastDBEntry[1],lastDBEntry[2])
form = '%Y-%m-%d %H:%M:%S'
timeindb = datetime.datetime.strptime(sqldate, form)
timedelta = datetime.timedelta(seconds=305)

#de tijd in de database moet altijd groter zijn als de huidige tijd - 5 min
if timeindb >= timenow - timedelta:
print "tijd is niet ouder als 5 min"
print timeindb
print timenow
logline = "OK: " + datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + " --> " + sqldate + " --> " + lastDBEntry[3]
file.write(logline)
file.write(u"\r\n")
else:
logline = "Probleem met laatste elektriciteitswaarde in DB: " + datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + " --> " + sqldate + " --> " + lastDBEntry[3]
file.write(logline)
file.write(u"\r\n")
print "stuur email met oude data indien er de laatste 3 uur geen email gestuurd is."

if timels >= timenow - timedelta3hours:
print "tijd is niet ouder dan 3 uur"
print "stuur geen email"
else:
print "tijd is ouder dan 3 uur"
print "stuur email en update tijd"

#stuur email
body = "laatste entry: \nid: %s \ndatum: %s \ntijd: %s \nverbruik: %s watt \ntotaal: %s watt" % (lastDBEntry[0],lastDBEntry[1],lastDBEntry[2],lastDBEntry[3],lastDBEntry[4].rstrip('\n'))
# Create a text/plain message
msg = MIMEText(body)
msg['Subject'] = 'Elektriciteit: Er komen geen meetwaarden meer binnen in de DB'
msg['From'] = me
msg['To'] = you

# Send the message via our own SMTP server.
s = smtplib.SMTP(smtphost)
s.sendmail(me, [you], msg.as_string())
s.quit()

#update tijd
file3 = open(DateLastMailFile, "w+")
file3.write(unicode(timenow))
file3.close()

file.close()

except mdb.Error, e:
# truncate temporary file
os.remove(MySQLOutFile)
# open(MySQLOutFile, 'w').close()

print "Error %d: %s" % (e.args[0],e.args[1])
sys.exit(1)

finally:
sys.exit(0)

Email alerting elke 3 uur via uit.telenet.be

Backup

Synology

SQL Database
Backup location /volume2/data/Domotica/Database
Backup script /volume2/data/scripts/Backup/domotica.sh

#!/bin/ash
find /volume2/data/Domotica/Database -type f -mtime +365 -exec rm {} \;
DBNAME=xxx
DATE=`date +"%Y%m%d"`
SQLFILE=$DBNAME-${DATE}.sql
mysqldump --opt --user=stijn_domovea --password=xxx $DBNAME > $SQLFILE
gzip $SQLFILE
SQLFILE=$SQLFILE.gz
mv $SQLFILE "/volume2/data/Domotica/Database/"$SQLFILE

Script houdt de laatste de backups bij van de laatste 7 dagen. De PC-living houdt via syncbackfree alle historische backups bij.

PC-living
Kritische NAS data naar interne schijf
Via SyncBackFree

  • \\fietology.zilverlinde.home\data\Domotica
  • \\fietology.zilverlinde.home\data\Film
  • \\fietology.zilverlinde.home\data\Fotos
  • \\fietology.zilverlinde.home\mobofietje
  • \\fietology.zilverlinde.home\stufjes\Music
  • \\fietology.zilverlinde.home\data scripts
  • \\fietology.zilverlinde.home\web

Schema: Elke zondag tussen 9u ’s morgens en 18u ’s avonds. Indien gemist zo snel mogelijk uitvoeren na opstart PC.

RPI3

Weekly backup naar fietology (via NFS mounts)

NASLOCATION=/mnt/nasdata/Domotica/SennePi/backup
find $NASLOCATION -type f -mtime +365 -exec rm {} \;
DATE=`date +"%Y%m%d"`
FILE="/tmp/BACKUPSennePi-${DATE}.tar.gz"
tar -hzcvf $FILE /root
mv $FILE $NASLOCATION

Edit: added tar -h option to follow symlinks. In /root heb ik enkele symlinks aangemaakt met config files die ik graag meeneem in de backup. door de parameter -h mee te geven zal mijn tar archief niet de snelkoppeling maar het volledige bestand opnemen in de backup.

 root@SennePi:~ # ln -s /etc/monit/monitrc monitrc
root@SennePi:~ # ln -s /var/spool/cron/crontabs/root crontab
root@SennePi:~ # ln -s /etc/knxd.conf knxd

Google Drive
Meerdere lokale syncs

DNS .local domein adressen onder linux

Als intern dns domain gebruikte ik tot op heden zilverlinde.local. Dit heeft altijd goed gewerkt tot op het moment dat ik van op een linux client enkele adressen probeerde te pingen.

root@SennePi:/home/pi# ping htpc.zilverlinde.local
ping: unknown host htpc.zilverlinde.local

Na wat troubleshooting en installatie van dnsutils bleek dat dit adres wel resolveable was.

apt-get install dnsutils

root@SennePi:/home/pi# nslookup htpc.zilverlinde.local
Server: 192.168.10.5
Address: 192.168.10.5#53

Name: htpc.zilverlinde.local
Address: 192.168.10.42

Na wat rondneuzen op google kwam ik tot de vaststelling dat .local onder linux zou gebruikt worden als root voor multicast adressen. Vandaar dat bovenstaande een foutmelding geeft.

Ik kan nu 2 dingen doen.

  • Beginnen prutsen in linux en ervoor zorgen dat ipv mutlicast toch unicast gebruikt wordt voor zilverlinde.local. Maar dan zal ik in de toekomst bij eventueel andere linux clients ook in de problemen komen.
  • Aangezien ik nog maar een beperkt aantal interne dns-records heb. mijn interne dns domain aanpassen naar alles behalve .local.

 

Ik heb voor de 2de optie gekozen en alles gemigreerd naar zilverlinde.home. Het pingen en het resolven werkt nu zonder problemen.

root@SennePi:/home/pi# ping onkyo.zilverlinde.home
PING onkyo.zilverlinde.home (192.168.10.41) 56(84) bytes of data.
64 bytes from 192.168.10.41: icmp_seq=1 ttl=64 time=0.558 ms

Monit

Er is dringend nood aan monitoring van alle interne apparaten. Het is dan ook zeer belangrijk dat ik onmiddellijk een email kan krijgen wanneer de RPI niet beschikbaar meer zou zijn. Het belangrijkste is dat de RPI een zo klein mogelijke downtime kent omdat deze instaat voor periodieke metingen. Hoe minder downtime hoe meer meetwaarden dus.

Mijn ogen vielen op de opensource tool Monit. Deze tool is compatibel met ARM processoren zoals de RPI en kan via apt-get eenvoudig geïnstalleerd worden.

https://mmonit.com/monit/

Installatie agent

apt-get install monit

Controle onboot

Controleer dat START=yes voorkomt in

vim /etc/default/monit

 

Installatie Monitoring Server (M/Monit)


cd /opt
wget https://mmonit.com/dist/mmonit-3.5.1-linux-arm.tar.gz
tar -xvf mmonit-3.5.1-linux-arm.tar.gz

Autostart M/Monit via Monit Agent

vim /etc/monit/monitrc
check process mmonit with pidfile /opt/mmonit-3.5.1/logs/mmonit.pid
start program = "/opt/mmonit-3.5.1/bin/mmonit"
stop program = "/opt/mmonit-3.5.1/bin/mmonit stop"

Autostart M/Monit via systemctl

cd /lib/systemd/system
vim mmonit.service

[Unit]
Description = Easy, proactive monitoring of Unix systems, network and cloud services
After = network.target

[Service]
Type=forking
ExecStart = /opt/mmonit-3.5.1/bin/mmonit start
ExecStop = /opt/mmonit-3.5.1/bin/mmonit stop
PIDFile = /opt/mmonit-3.5.1/logs/mmonit.pid

[Install]
WantedBy = multi-user.target

systemctl enable mmonit
systemctl start mmonit
systemctl status mmonit

 

Monit Agent koppelen

vim /etc/monit/monitrc

 

set mmonit http://monit:password@192.168.10.15:8080/collector

set httpd port 2812
allow localhost
allow 192.168.10.15
allow monit:password

 

Extra service toevoegen

check device root with path /dev/root
 if SPACE usage > 80% then alert

check process sshd with pidfile /var/run/sshd.pid
start program "/etc/init.d/ssh start"
stop program "/etc/init.d/ssh stop"
if failed port 22 protocol ssh then restart

check process knxd
matching "knxd";
start program = "/etc/init.d/knxd start"
stop program = "/etc/init.d/knxd stop"
# not working: if failed unixsocket /run/knx then alert

check host fietology.zilverlinde.local with address 192.168.10.5
if failed ping then alert
if failed port 3306 protocol mysql with timeout 15 seconds then alert
if failed port 80 protocol http
and request /domotics/assets/monitcheck with content = "MMonit OK"
then alert

check host cam-voordeur.zilverlinde.local with address 192.168.10.81
if failed ping then alert

check host cam-garage.zilverlinde.local with address 192.168.10.80
if failed ping then alert

check host onkyo.zilverlinde.local with address 192.168.10.41
if failed ping then alert

root@raspberrypi:/etc/monit # monit reload
Reinitializing monit daemon