Systemd

systemd is used to configure how and when to run the Python scripts. The GrowBuddies use Systemd to run in the background - when you want it to. I run mine pretty much all the time. Another nice feature is the availability of the logging info.

Useful Learning Resources on Systemd

I found the following info useful to figure out how to get systemd to do what I want:

Setting Up A Python Script to run as a Systemd service

Write the Script

  1. The first thing to do is write the .service file. Here are the snifferbuddy_storereadings.servicefile I used for thesnifferbuddy_storereadings.py` code.

  1. From the directory where the service file is located, set permissions so systemd can execute the script: sudo chmod +x {python script}. For example, sudo chmod +x snifferbuddy_storereadings.py.

  2. Copy the systemd service file to /lib/systemd/system. sudo privileges are needed. For example, sudo cp snifferbuddy_storereadings.service /lib/systemd/system/.

  3. Enable the service with sudo systemctl enable snifferbuddy_storereadings.service.

  4. Check to make sure the service has been enabled with systemctl is-enabled snifferbuddy_storereadings.service.

  5. Start the service with sudo systemctl start snifferbuddy_storereadings.service.

  6. Check to make sure the service has been started with systemctl is-active snifferbuddy_storereadings.service. In this example, starting the service failed. To find out why, try journalctl -u snifferbuddy_storereadings.service. Here are log lines from one of the services I ran:

Nov 27 15:23:00 gus systemd[1]: Started Store SnifferBuddyReadings service..
Nov 27 15:23:00 gus systemd[24566]: snifferbuddy_storereadings.service: Failed to execute command: No such file or directory
Nov 27 15:23:00 gus systemd[24566]: snifferbuddy_storereadings.service: Failed at step EXEC spawning /home/pi/growbuddy/py_env/bin/python: No such f
Nov 27 15:23:00 gus systemd[1]: snifferbuddy_storereadings.service: Main process exited, code=exited, status=203/EXEC
Nov 27 15:23:00 gus systemd[1]: snifferbuddy_storereadings.service: Failed with result 'exit-code'.
Nov 27 15:23:00 gus systemd[1]: snifferbuddy_storereadings.service: Service RestartSec=100ms expired, scheduling restart.
Nov 27 15:23:00 gus systemd[1]: snifferbuddy_storereadings.service: Scheduled restart job, restart counter is at 1.
Nov 27 15:23:00 gus systemd[1]: Stopped Store SnifferBuddyReadings service..
Nov 27 15:23:00 gus systemd[1]: Started Store SnifferBuddyReadings service..

The highlighted line shows the service failed to start up /home/py/growbuddy/py_env… .

Oh, right! our directory is growbuddies. I changed this back in the service file.

The reason for the above example is to give a little detail on the approach I take when I can’t get the service to start. I hope it is helpful.