Post by Jason on Dec 20, 2022 8:56:29 GMT -8
This is a simple Python script combined with two systemd services to signal when a Raspberry Pi has started up, shut down, halted, or rebooted. It is composed of four files: configuration file, Python script, and two systemd service definition files.
Install dependencies:
Quick note on pendulum: it can be particular about which version is required due to some stagnation in the library maintenance. For the Raspberry Pi 3B+ running Python 3.7.3, I had to install pendulum==2.1.0.
Configuration file:
Quick note on configuration file: The Python script expects the configuration file to be in the same folder as the script and titled config.json.
Python file:
Startup service:
Shutdown service:
You can see the folder structure. In order to link to systemd, I perform the following based on my folder structure:
If you ever want to remove the services, execute the following statements:
I'm using this in Node-RED to send me notifications through IFTTT when my SkyWeather2 Raspberry Pi 3B+ host system powers down or powers up due to power loss through my SolarMAX2 system. I can do a video on how I accomplish that if folks are interested.
Holler if you have any questions.
Thanks,
Jason
Install dependencies:
pip3 install paho.mqtt pendulum
Quick note on pendulum: it can be particular about which version is required due to some stagnation in the library maintenance. For the Raspberry Pi 3B+ running Python 3.7.3, I had to install pendulum==2.1.0.
Configuration file:
{
"mqtt": {
"address": "localhost",
"port": 1883,
"topic_prefix": "RPiDeviceInfo"
}
}
Quick note on configuration file: The Python script expects the configuration file to be in the same folder as the script and titled config.json.
Python file:
from paho.mqtt import publish
from pendulum import now
from socket import gethostname
import argparse
import json
def mqtt_publish_single(topic, message):
try:
publish.single(
topic=topic,
payload=json.dumps(message),
hostname=config['mqtt']['address'],
port=config['mqtt']['port']
)
except ConnectionError as e:
print(e)
except OSError as oe:
print(oe)
def signal(direction):
# current timestamp in milliseconds
now_ts = now(tz='UTC').int_timestamp * 1000
hostname = gethostname()
hostname = hostname.split('.')[0]
topic = '{0}/{1}/status'.format(config['mqtt']['topic_prefix'], hostname)
message = {
'timestamp': now_ts,
'signal': direction
}
mqtt_publish_single(topic, message)
if __name__ == '__main__':
# load configuration
with open('config.json', 'r') as config_file:
config = json.load(config_file)
# load command line switches
parser = argparse.ArgumentParser()
parser.add_argument('--direction')
args = parser.parse_args()
direction = args.direction
signal(direction)
Startup service:
[Unit]
Description=Sends MQTT message when host has started.
After=network.target
[Service]
Type=simple
User=pi
Group=pi
WorkingDirectory=/var/pyapps/RPiDeviceInfo
StandardOutput=append:/var/log/messages
StandardError=append:/var/log/errors
ExecStart=/bin/true
ExecStop=python3 /var/pyapps/RPiDeviceInfo/piupdownsignal.py --direction up
RemainAfterExit=yes
[Install]
WantedBy=multi-user.target
Shutdown service:
[Unit]
Description=Sends MQTT message when host halts, shutdowns, or reboots.
Before=shutdown.target
[Service]
Type=simple
User=pi
Group=pi
WorkingDirectory=/var/pyapps/RPiDeviceInfo
StandardOutput=append:/var/log/messages
StandardError=append:/var/log/errors
ExecStart=/bin/true
ExecStop=python3 /var/pyapps/RPiDeviceInfo/piupdownsignal.py --direction down
RemainAfterExit=yes
You can see the folder structure. In order to link to systemd, I perform the following based on my folder structure:
sudo ln -sf /var/pyapps/RPiDeviceInfo/startup.service /etc/systemd/system/startup.service
sudo ln -sf /var/pyapps/RPiDeviceInfo/shutdown.service /etc/systemd/system/shutdown.service
sudo systemctl daemon-reload
sudo systemctl enable startup
sudo systemctl enable shutdown
sudo systemctl start startup
sudo systemctl start shutdown
If you ever want to remove the services, execute the following statements:
sudo systemctl disable startup
sudo systemctl disable shutdown
I'm using this in Node-RED to send me notifications through IFTTT when my SkyWeather2 Raspberry Pi 3B+ host system powers down or powers up due to power loss through my SolarMAX2 system. I can do a video on how I accomplish that if folks are interested.
Holler if you have any questions.
Thanks,
Jason