Skip to content

Streaming as a Linux Service

Gábor Vecsei edited this page Sep 23, 2018 · 1 revision

Maybe you would like to skip the docker 🐳 part, so I'll show how can you setup your simple "security system" without docker.

The best way to do this is to create a linux service. Actually it's pretty easy to do this.

Expectations:

  • Start streaming when:
    • Video device is attached (webcamera 📷 )
    • There is internet connection 🔌
  • Restart service:
    • When something unexpected happens (e.g webcam gets disconnected)
  • Stop streaming & do not restart:
    • When we manually stop it

Creating the service

Create symlink to video devices

This is a crucial step, so we can set up a rule in our service file which says:

Wait until a video device is connected

Inside the /lib/udev/rules.d/99-systemd.rules file we need to add one more line:

KERNEL=="video0", SYMLINK="video0", TAG+="systemd"

After this, we need to update our rules, and we can do this without rebooting the device:

udevadm control --reload-rules && udevadm trigger

The service file

In this file we can define all the expected behavior of our service

We should create a new file like: /etc/systemd/system/youtube_stream.service

The name of the file defines the name of the service which is now: youtube_stream

Add these lines to the file with your favorite text editor:

[Unit]
Description=Yoututbe Streaming Service
Wants=network-online.target
BindsTo=dev-video0.device
After=network-online.target dev-video0.device

[Service]
ExecStart=/bin/bash simple_youtube_stream.sh
WorkingDirectory=<PATH_TO_THE_BASE_FOLDER>/youtube_stream_image/code
StandardOutput=inherit
StandardError=inherit
Restart=on-failure
RestartSec=5
User=<YOUR_USER>

[Install]
WantedBy=multi-user.target

Of course you need to fill out the <PATH_TO_THE_BASE_FOLDER> and <YOUR_USER> parts in the script

That's it! 👏

Now you can enable & start the service:

sudo systemctl start youtube_stream
sudo systemctl enable youtube_stream

Logs

You can see the logs of the service with:

sudo journalctl -e -f -b -u youtube_stream

Troubleshooting

If there are any troubles please check this list:

  • You user is in the video group (this is needed in order to access the video devices without sudo)
  • Your device (e.g. raspberry pi) can see the video device
    • ls /dev | grep video* ➡️ This should show the available devices
  • Does your device has internet connection

If none of these helped you can check the logs and you can figure out what went wrong! 😈