Command to switch running service

If you have a Raspberry Pi and a project in a box that has buttons and perhaps a screen displaying something that runs from a system daemon , you might benefit from being able to switch the output of the display from one desired output to another.

For example – I have a music player setup and it runs the fantastic mpd_oled which has a spectrum analyzer output and track display details, time etc. This is a compiled c program. I also have some stats I want to see that are in a python3 script.

A simple way to have these switchable at the press of a button (I use the fantastic Pimoroni Keybow) is to run these programs as services and use a bash script, which you trigger from a button.

My mpd_oled service is created in the compile and install process of mpd_oled itself, it looks like this and this runs at boot :

[Unit]
Description=MPD OLED Display

[Service]
ExecStart=/usr/local/bin/mpd_oled -o 6 -b 10 -g 1 -f 15

[Install]
WantedBy=multi-user.target

My python script has a service which isn’t enabled at boot (otherwise you would be trying to run two things on the display at once). The service file (stats.service in /etc/systemd/system) looks like this :

[Unit]
Description=stats3
After=network.target

[Service]
ExecStart=/usr/bin/python -u temp.py
WorkingDirectory=/home/pi/Scripts
StandardOutput=inherit
StandardError=inherit
Restart=always
User=pi

[Install]
WantedBy=multi-user.target

Now, in order to create a switcher in shellscript, I simply write code which sees if mpd_oled is running as a service, and if so, stops it and starts the other service and vice versa – every time the bash script is run (i.e. when you press the button on Keybow assigned to that command).

Fire up nano and create this command in /usr/bin as su :

sudo nano /usr/bin/toggle_disp

#!/bin/sh
service=mpd_oled

case  "$(pidof $service | wc -w)" in
0) sudo systemctl stop stats
sudo systemctl start mpd_oled
;;
1) sudo systemctl stop mpd_oled
sudo systemctl start stats
;;
*) echo "multiple instances running"
;;
esac

After saving this in nano , make it executable :

sudo chmod a+x /usr/bin/toggle_disp

You now have a command you can run in the terminal that will switch the running service by simply typing “toggle_disp“.

Do what you wish with this, but its certainly a good building block to make use of multiple display programs as an example from a triggered button or keypress.

Posted in Raspberry Pi and tagged , , , , .

Leave a Reply

Your email address will not be published. Required fields are marked *