22
33. /usr/share/common
44
5- ENABLED=false
6- INTERVAL=60
75RTSP_URL=
" rtsp://thingino:[email protected] /ch0" 6+ PID_FILE=" /run/rtsp_watchdog.pid" # PID file to store the background process ID
7+
8+ # Interval to check the stream
9+ INTERVAL=60
810
911# Number of retries before declaring the stream down
1012RETRY_COUNT=3
@@ -18,28 +20,71 @@ RESTART_LIMIT=3
1820# Delay in seconds between restarts
1921RESTART_DELAY=10
2022
23+ # Seconds to wait for probe command
24+ CHECK_TIMEOUT=10
25+
26+ RTSP_HOST=" "
27+ RTSP_PORT=" "
28+ PID=" "
2129RESTART_COUNT=0
22- PID_FILE=" /run/rtsp_watchdog.pid" # PID file to store the background process ID
30+
31+ parse_rtsp_endpoint () {
32+ local url=" ${RTSP_URL# rtsp:// } "
33+ local creds_trim=" ${url##*@ } "
34+ local host_port=" ${creds_trim%%/* } "
35+ if [ -z " $host_port " ]; then
36+ return 1
37+ fi
38+ if echo " $host_port " | grep -q ' :' ; then
39+ RTSP_HOST=" ${host_port%%:* } "
40+ RTSP_PORT=" ${host_port##*: } "
41+ else
42+ RTSP_HOST=" $host_port "
43+ RTSP_PORT=554
44+ fi
45+ [ -n " $RTSP_HOST " ] && [ -n " $RTSP_PORT " ]
46+ }
47+
48+ check_with_curl () {
49+ curl -s --max-time " $CHECK_TIMEOUT " --fail -X OPTIONS " $RTSP_URL " > /dev/null 2>&1
50+ }
51+
52+ check_with_nc () {
53+ [ -n " $RTSP_HOST " ] || parse_rtsp_endpoint || return 1
54+ local payload
55+ payload=$( printf ' OPTIONS %s RTSP/1.0\r\nCSeq: 1\r\nUser-Agent: stream-watchdog\r\n\r\n' " $RTSP_URL " )
56+ printf ' %s' " $payload " | timeout " $CHECK_TIMEOUT " nc -w " $CHECK_TIMEOUT " " $RTSP_HOST " " $RTSP_PORT " 2> /dev/null | grep -q " RTSP/1.0 200"
57+ }
58+
59+ check_rtsp_stream () {
60+ if check_with_curl; then
61+ return 0
62+ fi
63+
64+ if check_with_nc; then
65+ return 0
66+ fi
67+
68+ return 1
69+ }
2370
2471# Handle signals
2572trap ' echo "Stream Watchdog: Stopping watchdog..."; cleanup; exit 0' INT TERM
2673
2774cleanup () {
2875 # Kill any background processes and cleanup resources
29- [ -n " $PID " ] && kill $PID
76+ if [ -f " $PID_FILE " ]; then
77+ PID=$( cat " $PID_FILE " )
78+ [ -n " $PID " ] && kill " $PID " 2> /dev/null || true
79+ fi
3080}
3181
3282watch () {
3383 while true ; do
3484 SUCCESS=false
3585
3686 for i in $( seq 1 $RETRY_COUNT ) ; do
37- openRTSP -v -V -d 5 -t " $RTSP_URL " > /dev/null 2>&1 &
38- PID=$!
39-
40- wait $PID
41- if [ $? -eq 0 ]; then
42- echo_info " Stream stream is active."
87+ if check_rtsp_stream; then
4388 SUCCESS=true
4489 RESTART_COUNT=0 # Reset the restart count after a successful check
4590 break
@@ -79,8 +124,11 @@ start() {
79124 exit 1
80125 fi
81126
127+ parse_rtsp_endpoint || true
128+
82129 watch &
83- echo $! > " $PID_FILE " # Store the PID of the background process
130+ PID=$!
131+ echo " $PID " > " $PID_FILE " # Store the PID of the background process
84132}
85133
86134stop () {
0 commit comments