I want to keep my media server on for as little time as possible while at the same time I don't want to manually turn it on every time I want to use it. Turning it on right before I reach home after work is no big deal most of the time, I can also easily turn it on with a wakeonlan call from my phone, turning it off however was more of a problem as I don't know how late I'm going to stay up to watch a film or TV series. I stream all the media from the server over DLNA to both my TV, my PC and my phone.
The result was that I needed a script that could detect if media was streaming over the network, and if no streams were detected for about 20 minutes, suspend the server. I already have a bash script in place that suspends the server at certain times and also wakes it up, this is working ok but I wanted it to be a little more intelligent. This is still a work in prograss but this is what I got so far.
The problematic part here was that tcpdump just sits there if it doesn't get any packages so I needed to add something that kills it if there is no traffic. This is the result as of now:
#!/bin/bash # Check if any unit is streaming video, need to be root LASTTIMEOFSTREAM='date -d$(/usr/sbin/tcpdump -i eth0 -c 1 -q src 192.168.1.66 and port 8895 2> /dev/null | cut -d. -f1) +%s &' eval $LASTTIMEOFSTREAM && PID=$! sleep 2 if [ -d /proc/$PID ] then kill -15 $PID 2> /dev/null fi
This script is small an can be called with
RESULT=$(sudo check_if_streaming); if [ -z $RESULT ]; then echo "1"; else echo "0";fi
to get a 1 or a 0 depending on if there is any traffic going out on port 8895, it's asomewhat workaroundish way to get a proper retval from the script :). So now I can check from the suspend script if it's OK to suspend or if anyone is streaming from the server. This is the suspend script by the way:
There is one more thing though, after waking up the server it won't automatically connect to the VPN tunnel so I did this:
#!/bin/bash /bin/ping -w 1 220.127.116.11 > /dev/null RETVAL_PING=$? if [[ $RETVAL_PING -eq 0 ]] then echo "Fine!" else echo "No connection, start VPN" nmcli con down id "VPN" sleep 3 nmcli con up id "VPN" fi