Automatisch Domoticz herstarten

Automatisch Domoticz herstarten

8 december 2021 2 Door Björn Meijer

De Raspberry Pi is een zeer stabiele mini-computer wat draait op Linux. Tevens is het ideaal om Domoticz op te laten draaien. Toch wil het wel eens gebeuren dat Domoticz (om wat voor reden dan ook) vastloopt. Hierdoor is er kans op verlies van data of bepaalde commando’s worden niet uitgevoerd.

Om dit probleem te voorkomen kun je een bash-script op de achtergrond mee laten draaien welke controleert of Domoticz nog online is. Zodra dit script merkt dat Domoticz offline is zal deze worden gestopt en vervolgens opnieuw worden opgestart.

Wat heb je hiervoor nodig?

  • Raspberry Pi;
  • Domoticz;
  • jq.

We gaan er even vanuit dat Domoticz al is geïnstalleerd op de Raspberry Pi en dat alles prima draait.

Open Nano of een andere tekstbewerker op de Raspberry Pi en kopieer en plak hierin onderstaand script. Vul voor:

  1. domoticz_ip het (interne) ip-adres is van je Raspberry Pi.
  2. domoticz_port de poort in waarop jouw Domoticz draait.
  3. device_id de idx van een schakelaar in.
#!/bin/bash

domoticz_ip="127.0.0.1"
domoticz_port="8080"
device_id="1"

DOMOTICZ=`curl -s --connect-timeout 2 --max-time 5 "http://"$domoticz_ip":"$domoticz_port"/json.htm?type=devices&rid="$device_id`

STATUS=`echo $DOMOTICZ | jq -r '.status'`
if [ "$STATUS" = "OK" ] ; then
   exit
else
   sleep 5
   DOMOTICZ=`curl -s --connect-timeout 2 --max-time 5 "http://"$domoticz_ip":"$domoticz_port"/json.htm?type=devices&rid="$device_id`
   STATUS2=`echo $DOMOTICZ | jq -r '.status'`
   if [ "$STATUS2" = "OK" ] ; then
      exit
   else
      sleep 5
      DOMOTICZ=`curl -s --connect-timeout 2 --max-time 5 "http://"$domoticz_ip":"$domoticz_port"/json.htm?type=devices&rid="$device_id`
      STATUS3=`echo $DOMOTICZ | jq -r '.status'`
      if [ "$STATUS3" = "OK" ] ; then
         exit
      else
         echo "domoticz offline... rebooting..."
         sudo service domoticz.sh stop
                sleep 8
                sudo kill $(sudo netstat -anp | awk '/ LISTEN / {if($4 ~ ":"$domoticz_port"$") { gsub("/.*","",$7); print $7; exit } }')
                sleep 8
                echo "domoticz stopped, now starting up..."
                sudo service domoticz.sh start
      fi
   fi
fi

Sla het bash-script op als domoticz_state_checker.sh in de map ~/domoticz/scripts.

Installeer jq

Omdat we JSON data ophalen en deze willen filteren op de sleutel(s) STATUS, STATUS2 of STATUS3 en hier de waarde van willen controleren hebben we een JSON processor nodig.

De jq is een op de opdrachtregel gebaseerde JSON-processor die het mogelijk maakt om JSON-gegevens te transformeren, filteren, segmenteren, in kaart te brengen of andere bewerkingen uit te voeren.

Maak verbinding met je Raspberry Pi via SSH of vul rechtstreeks in de terminal de volgende commando’s:

sudo apt update
sudo apt install -y jq

Nadat de installatieprocedure is afgerond kunnen we een test uitvoeren of jq correct werkt.

echo '{"employees": {"employee": [{"id": "1","firstName": "Tom","lastName": "Cruise"},{"id": "2","firstName": "Maria","lastName": "Sharapova"},{"id": "3","firstName": "Robert","lastName": "Downey Jr."}]}}' > test.json

Het programma jq heeft verschillende filters om JSON data te manipuleren. Het meest eenvoudige filter is de punt .. Dit filter laat de invoer ongewijzigd en print de uitvoer in JSON opmaak.

Voer het volgende commando in en het .-filter retourneert de uitvoer in JSON opmaak.

jq '.' test.json
{
  "employees": {
    "employee": [
      {
        "id": "1",
        "firstName": "Tom",
        "lastName": "Cruise"
      },
      {
        "id": "2",
        "firstName": "Maria",
        "lastName": "Sharapova"
      },
      {
        "id": "3",
        "firstName": "Robert",
        "lastName": "Downey Jr."
      }
    ]
  }
}

Testen van het script

Ga naar de map ~/domoticz/scripts en type in de command line het volgende commando:

sh domoticz_state_checker.sh

Indien er geen meldingen in de command line worden weergegeven lijkt het erop dat het script correct werkt. Als we Domoticz nu tijdelijk stoppen en het script nogmaals uitvoeren zullen we de volgende meldingen ontvangen:

domoticz offline... rebooting...

Usage:
 kill [options] <pid> [...]

Options:
 <pid> [...]            send signal to every <pid> listed
 -<signal>, -s, --signal <signal>
                        specify the <signal> to be sent
 -l, --list=[<signal>]  list all signal names, or convert one to a name
 -L, --table            list all signal names in a nice table

 -h, --help     display this help and exit
 -V, --version  output version information and exit

For more details see kill(1).
domoticz stopped, now starting up...

Het script automatisch uitvoeren

We willen dit script automatisch periodiek uit laten voeren. Dit is mogelijk met behulp van een cronjob. Een Cron is een taakplanner binnen Unix systemen voor het uitvoeren van taken op een vaste datum of tijdstip. Om zo’n taak uit te voeren kunnen we deze taak invoeren in een cron table. Om de cron table te openen/bewerken voeren we het volgende commando in de command line:

crontab -e

Je ziet nu in je editor het volgende:

# Edit this file to introduce tasks to be run by cron.
#
# Each task to run has to be defined through a single line
# indicating with different fields when the task will be run
# and what command to run for the task
#
# To define the time you can provide concrete values for
# minute (m), hour (h), day of month (dom), month (mon),
# and day of week (dow) or use '*' in these fields (for 'any').
#
# Notice that tasks will be started based on the cron's system
# daemon's notion of time and timezones.
#
# Output of the crontab jobs (including errors) is sent through
# email to the user the crontab file belongs to (unless redirected).
#
# For example, you can run a backup of all your user accounts
# at 5 a.m every week with:
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
#
# For more information see the manual pages of crontab(5) and cron(8)
#
# m h  dom mon dow   command

Voeg de onderstaande regel helemaal onderaan toe en sla het bestand op.

*/1 * * * * /domoticz/scripts/domoticz_state_checker.sh

Nu zal elke minuut het script worden uitgevoerd.

De werking van het script

In bovenstaand script wordt de JSON response opgehaald van het gekozen device. Indien de sleutel STATUS, STATUS2 of STATUS3 de waarde “OK” retourneert is Domoticz online en wordt het script beëindigd.
Indien er niet aan de voorwaarde wordt voldaan, dan is Domoticz niet beschikbaar en zal Domoticz worden gestopt met het commando sudo service domoticz.sh stop.

Vervolgens wordt met het commando kill in combinatie met andere parameters het proces Domoticz beëindigd.

Aan het einde van het script wordt met het commando sudo service domoticz.sh start Domoticz weer opgestart.