Make a systemd Service Unit start, stop and restart while starting, stopping or restarting openHAB

Make a systemd Service Unit start, stop and restart while starting, stopping or restarting openHAB

Wouldn’t it be practical if I write a program especially for openHAB that only works during the runtime of openHAB and I don’t have to restart it separately when I restart openHAB?

For me, HABApp is a good example. It would also be conceivable that a database is only executed during the runtime of openHAB. Most databases, however, run permanently directly after system start. An independently written Python or Java program could of course make just as much sense here instead of my HABApp example. Which is also why I want to present it as a general solution rather than a HABApp solution.

Things to be done

You need to write, download or configure and prepare a program accordingly. After that you have to create a service file.

Please make sure that you enabled openhab

sudo systemctl enable openhab

And please make sure that you enable your service after you have create it:

sudo systemctl enable <your_service>.service

So in my case sudo systemctl enable habapp.

Example service file

Here my example service file:

[Unit]
Description=HABApp
Documentation=https://habapp.readthedocs.io
Requires=openhab.service
After=openhab.service
BindsTo=openhab.service
PartOf=openhab.service

[Service]
Type=simple
User=openhab
Group=openhab
UMask=002
ExecStart=/bin/bash -c 'source /etc/environment; /usr/bin/python3 /opt/habapp/bin/habapp -c /etc/openhab/habapp'
Restart=on-failure
RestartSec=30s

[Install]
WantedBy=openhab.service

Please notice that BindsTo, PartOf should have the openhab.service. WantedBy is also need and should contain openhab.service. If not only restarting openhab would work but not stop and start which could be needed if you want to clear the cache.

I used also Restart=on-failure and RestartSec=30s. That was my experience. HABApp itself of course wants to access openHAB even before it is started so far. So after a restart or start the service would stop HABApp in this case and say that it can not be started. So HABApp restarts several times until openHAB also works so far that HABApp could be started without error message.

Outlook

For what can this be useful? Well, applications like databases or Grafana that you like to connect usually don’t need this. I myself have an application running that stores the openHAB logs in a database. This only works as long as openHAB is running. With this application I do process mining.

If you have an application that uses the REST API or a MQTT connection to openHAB, this little tip might be necessary. Many applications continue to run and simply wait until openHAB is working again.

I have also distributed several openHAB instances running. For this I also use services that restart the other instances. This way the whole system is restarted.