Each Internet of Things (IOT) device in my Do It Yourself Home Automation System (Diyhas) has three elements.
- Headless Raspberry Pi server with Wi-FI and Bluetooth (Pi Zero W for example)
- Build and production Python directory structure with my device or subsystem Python modules and a variety of Open Source modules.
- Boot configuration using systemctl
The systemctl process is used to manage the IOT application.
Configuring a Basic systemctl Service Configuration File
I’m going to use my basic DiyhasClock.py application as an example. My basic file structure requires to three directories: ../fonts, ../logs and ../systemd. The DiyhasClock service requires a configuration file called DiyhasClock.service. This file has three sections:
- [Unit] — contains options not dependent on the type of the service. It contains directives like description, service behavior and dependencies with other services.
- [Service] — categorizes services by their process and daemonizing behavior
- [Install] — optional and defines the behavior if the service is enabled or disabled
The first step is to create a service configuration file in development directory.
The first section of the configuration file contains a [Unit] with a simple Description and the After directive which states that it requires multi-user run level.
The [Service] section has two directives. The Type specifies that the service runs after the boot sequence is complete, i.e., idle. The ExecStart is the full command and path to execute. In my case I use Python, the directory of the Python code and a log file.
ExecStart=/usr/bin/python /home/pi/systemd/DiyhasClock.py > /home/pi/logs/DiyhasClock.log 2>&1
The remaining section is used to add DiyhasClock.service to the multi-user run level when the Raspberry Pi server is booted.
The next step is to move the completed DiyhasClock.service to the systemctl directory.
Adding the DiyhasClock Service to the Boot Sequence
The next steps are relatively simple. Move the DiyhasClock.service to the systemctl directory and enabling the service.
sudo cp DiyhasClock.service /lib/systemd/system/DiyhasClock.service
sudo chmod 644 /lib/systemd/system/DiyhasClock.service
sudo systemctl daemon-reload
sudo systemctl enable DiyhasClock.service
Reboot and test the installation. For convenience I always create an aliases file to manage my IOT applications.
The file contains the following systemctl specific aliases.
alias stop='sudo systemctl stop DiyhasClock.service'
alias status='sudo systemctl -l status DiyhasClock.service'
alias start='sudo systemctl start DiyhasClock.service'
alias restart='sudo systemctl restart DiyhasClock.service'
alias catlog='cat /home/pi/logs/DiyhasClock.log'
alias taillog='tail -f /home/pi/logs/DiyhasClock.log'
That’s all I need to manage an IOT production device.