Ahojte, pripajam nieo co som stihol dorobit este pred odidenim maliny do vecnych lovist. Monitor je upraveny pre moje potreby a prostredie od peter54 ale len ako sh script,
Kód: Vybrat vše
#!/bin/bash
# =========================================================================
# Raspberry Pi & Oscam Monitor
# =========================================================================
# Zoznam Oscam portov na monitorovanie
OSCAM_PORTS=(8888 9999)
# Funkcia na ziskanie vsetkych dat z Oscam
get_oscam_info() {
local port=$1
local oscam_output=$(curl -m 1 -s "http://localhost:$port")
if [ -z "$oscam_output" ]; then
echo "offline|-|-"
return
fi
local runtime=$(echo "$oscam_output" | grep 'OSCam Run Time:' | perl -pe 's/.*id="runtime"> //;s/<.*>//;s/:\d\d$//')
local clients=$(echo "$oscam_output" | grep -oP 'TITLE="Edit User: \K[^"]*' | tr '\n' ',' | sed 's/,$//')
local version=$(echo "$oscam_output" | grep -oP '(?<=<B>Build:</B> )[r0-9]+' | head -n 1)
# PRIDANE: Príkaz na extrakciu kompilátora
local compiler=$(echo "$oscam_output" | grep -oP '(?<=<B>Compiler:</B> )[^<]+' | head -n 1)
if [ -z "$runtime" ]; then runtime="offline"; fi
if [ -z "$clients" ]; then clients="No clients"; fi
if [ -z "$version" ]; then version="N/A"; fi
if [ -z "$compiler" ]; then compiler="N/A"; fi
echo "$runtime|$clients|$version|$compiler"
}
# Funkcia na ziskanie systémovych dat
get_system_info() {
uptime_output=$(uptime)
linux_uptime=$(echo "$uptime_output" | sed 's/.*up \([^,]*\),.*/\1/' | sed 's/ days /d /;s/ day /d /;s/:/,/g')
load_average=$(echo "$uptime_output" | sed 's/.*load average: //')
teplota_file="/sys/class/thermal/thermal_zone0/temp"
if [ ! -f "$teplota_file" ]; then
teplota_file="/sys/class/thermal/thermal_zone1/temp"
fi
if [ -f "$teplota_file" ]; then
teplota=$(cat "$teplota_file")
teplota_C=$(echo "scale=1; $teplota / 1000" | bc)
else
teplota_C="N/A"
fi
siet=$(ethtool eth0 | awk '/Speed/ {print $2}')
# Získanie informácií o pamäti
ram_total=$(free -h | grep 'Mem:' | awk '{print $2}')
ram_used=$(free -h | grep 'Mem:' | awk '{print $3}')
ram_free=$(free -h | grep 'Mem:' | awk '{print $4}')
# Získanie informácií o disku
disk_used=$(df -h --output=used / | tail -n 1 | xargs)
disk_avail=$(df -h --output=avail / | tail -n 1 | xargs)
disk_total=$(df -h --output=size / | tail -n 1 | xargs)
echo "$linux_uptime|$load_average|$teplota_C°C|$siet|$ram_total|$ram_used|$ram_free|$disk_total|$disk_used|$disk_avail"
}
# =========================================================================
# === Enigma2 STB Monitor ===
# =========================================================================
declare -A receivers
receivers[obyvacka]="192.168.1.155"
receivers[spalna]="192.168.1.190"
receivers[detska1]="192.168.1.187"
receivers[detska2]="192.168.1.199"
to_sat () {
local ref=$1
local sat=" "
if echo "$ref" | grep -q '16E:A00000'; then sat="16.0E"; fi
if echo "$ref" | grep -q '3:EB0000'; then sat="23.5E"; fi
if echo "$ref" | grep -q '2:11A0000'; then sat="28.2E"; fi
if echo "$ref" | grep -q '1:C00000'; then sat="19.2E"; fi
echo "$sat"
}
# =========================================================================
# === HLAVNY VYPIS ===
# =========================================================================
echo "=========================================================================================="
echo " Monitor Raspberry Pi & STB: $(date +"%d.%m.%Y %T") "
echo "=========================================================================================="
echo "System: $(uname -a)"
echo ""
# -- VYPIS PRE RASPBERRY PI SYSTEMOVE INFO --
echo "--- Systemove metriky ---"
IFS='|' read -r uptime_info load_info temp_info siet_info ram_total_info ram_used_info ram_free_info disk_total_info disk_used_info disk_avail_info <<< $(get_system_info)
printf " Uptime Linux: %s\n" "$uptime_info"
printf " Load Average: %s\n" "$load_info"
printf " Teplota CPU: %s\n" "$temp_info"
printf " Siet (eth0): %s\n" "$siet_info"
echo ""
printf " Pamäť RAM: Celkom: %s, Použité: %s, Voľné: %s\n" "$ram_total_info" "$ram_used_info" "$ram_free_info"
printf " Miesto Disk: Celkom: %s, Použité: %s, Voľné: %s\n" "$disk_total_info" "$disk_used_info" "$disk_avail_info"
echo ""
# -- VYPIS PRE OSCAM INSTANCIE --
echo "--- Oscam instancie ---"
IFS='|' read -r runtime_8888 clients_8888 version_8888 compiler_8888 <<< $(get_oscam_info 8888)
printf " Oscam 8888:\n"
printf " - Runtime: %s\n" "$runtime_8888"
printf " - Users: %s\n" "$clients_8888"
printf " - Version: %s\n" "$version_8888"
# PRIDANE: Vypis kompilátora
printf " - Compiler: %s\n" "$compiler_8888"
echo ""
IFS='|' read -r runtime_9999 clients_9999 version_9999 compiler_9999 <<< $(get_oscam_info 9999)
printf " Oscam 9999:\n"
printf " - Runtime: %s\n" "$runtime_9999"
printf " - Users: %s\n" "$clients_9999"
printf " - Version: %s\n" "$version_9999"
# PRIDANE: Vypis kompilátora
printf " - Compiler: %s\n" "$compiler_9999"
echo ""
# -- VYPIS PRE SATELITNE PRIJIMACE (STB) --
echo "--- Enigma2 Receivers Status ---"
printf "%-12s| %-16s| %-20s| %-10s| %-44s| %-11s| %-8s| %-10s| %-10s| %-10s\n" "STB" "Hostname" "IP Adresa" "Time" "Stanica & Program" "Rozlisenie" "Sat" "Signal" "Kvalita" "Stav"
echo "------------|-----------------|---------------------|-----------|---------------------------------------------|------------|---------|-----------|-----------|----------"
for name in "${!receivers[@]}"; do
ip_port="${receivers[$name]}"
about_data=$(curl -m 3 -s "http://$ip_port/web/about")
if [ -z "$about_data" ]; then
printf "%-12s| %-16s| %-20s| %-10s| %-44s| %-11s| %-8s| %-10s| %-10s| %-10s\n" "$name" "-" "-" "Offline" "-" "-" "-" "-" "-" "-"
continue
fi
time=$(curl -m 3 -s "http://$ip_port/web/currenttime" | grep -oP '(?<=<e2currenttime>)[0-9]{2}:[0-9]{2}(?=</e2currenttime>)' | tr -d '\n\r ')
current_data=$(curl -m 3 -s "http://$ip_port/web/getcurrent")
service_name=$(echo "$current_data" | grep -oP '(?<=<e2servicename>)[^<]*(?=</e2servicename>)' | tr -d '\n\r' | sed 's/N\/A//;s/^[[:space:]]*//;s/[[:space:]]*$//')
event_name=$(echo "$current_data" | grep -oP '(?<=<e2eventname>)[^<]*(?=</e2eventname>)' | tr -d '\n\r' | sed 's/N\/A//;s/^[[:space:]]*//;s/[[:space:]]*$//')
if [ -z "$event_name" ]; then
stanica_program="$service_name"
else
stanica_program="$service_name: $event_name"
fi
stanica_program_short=$(echo "$stanica_program" | cut -c 1-45)
video_size=$(echo "$about_data" | grep -oP '(?<=<e2servicevideosize>)[^<]*(?=</e2servicevideosize>)' | tr -d '\n\r ')
sat_ref=$(curl -m 3 -s "http://$ip_port/web/subservices" | grep -oP '(?<=<e2servicereference>)[^<]*(?=</e2servicereference>)' | tr -d '\n\r ')
sat_pos=$(to_sat "$sat_ref")
signal_data=$(curl -m 3 -s "http://$ip_port/web/signal")
signal_strength=$(echo "$signal_data" | grep -oP '(?<=<e2snrdb>)[^<]*(?=</e2snrdb>)' | tr -d '\n\r ')
signal_quality=$(echo "$signal_data" | grep -oP '(?<=<e2snr>)[^<]*(?=</e2snr>)' | tr -d '\n\r ')
standby_status=$(echo "$about_data" | grep -oP '(?<=<e2isstandby>)[^<]*(?=</e2isstandby>)')
if [ "$standby_status" == "true" ]; then
power_status="Standby"
else
power_status="Zapnutý"
fi
hostname=$(echo "$about_data" | grep -oP '(?<=<e2hostname>)[^<]*(?=</e2hostname>)')
image_version=$(echo "$about_data" | grep -oP '(?<=<e2imageversion>)[^<]*(?=</e2imageversion>)')
if [ -z "$hostname" ]; then
hostname="-"
fi
printf "%-12s| %-16s| %-20s| %-10s| %-45s| %-11s| %-8s| %-10s| %-10s| %-10s\n" "$name" "$hostname" "$ip_port" "$time" "$stanica_program_short" "$video_size" "$sat_pos" "$signal_strength" "$signal_quality%" "$power_status"
done
echo "========================================================================================================================================================================"
na aktualizaciu som mal toto a spustal som to crontab:
Kód: Vybrat vše
#!/bin/sh
# --- NOVÉ: Synchronizácia s oscam_dynamic_monitor.sh ---
LOCK_FILE="/tmp/oscam_emm_refresh.lock"
MONITOR_LOG="/var/log/oscam_dynamic_monitor.log" # Logovací súbor monitorovacieho skriptu
# Vytvoríme lock file, aby ostatné skripty vedeli, že tento beží
touch "$LOCK_FILE"
echo "$(date '+%Y-%m-%d %H:%M:%S'): oscam_emm_refresh.sh started. Lock file created: $LOCK_FILE" >> "$MONITOR_LOG"
# --- KONIEC NOVÉHO KÓDU ---
#### 1) assign the execution attributes to the script file:
#### chmod a+x /usr/script/oscam_emm_refresh.sh
####
#### 2) to start the script between 06:00 and 23:00, every 10 minutes, add the following line into the CRON configuration file:
#### */10 6-23 * * * sh /usr/script/oscam_emm_refresh.sh
#### For a testing purpose:
#### wget -q -O /tmp/test-oscam-api.xml $WEBIF_OSCAM/oscamapi.html?part=status
#### cat /tmp/test-oscam-api.xml | sed -rn '/name="'$READER_LABEL'"/,/times/p'
#### cat /tmp/test-oscam-api.xml | sed -rn '/name="'$READER_LABEL'"/,/times/ {s/.*idle="([0-9]+)".*/\1/p}'
#### USER CONFIGURATION:
WEBIF_ENIGMA="http://192.168.1.155:80"
WEBIF_OSCAM="http://192.168.1.155:8888"
EMM_AWAITING="5m" # awaiting to EMM arrival (1m = meaning 1 min. waiting time, 30s = meaning 30 secs, ... etc.)
SRC_MARKIZA="1:0:19:3731:C8E:3:EB0000:0:0:0:"
SRC_NOVAACTION="1:0:1:3394:C9D:3:EB0000:0:0:0:"
LOG_FILE="/var/log/log_oscam.log"
AU_AWAITING="20" USERNAME="localcard"
#### function to check the Standby (e2/OpenWebif power-state)
is_standby(){
[ "$(wget -q -O - $WEBIF_ENIGMA/web/powerstate | sed -n 's:.*<e2instandby>\(.*\)</e2instandby>.*:\1:p')" = "true" ]
}
#### Vypnutie primaca do stanby
wget -q -O - $WEBIF_ENIGMA/web/powerstate?newstate=5 >> /dev/null 2>&1 &
echo "$(date '+%Y-%m-%d %H:%M:%S'): Enabled StandBy mode" >> "$LOG_FILE" # Používa pôvodný LOG_FILE
#### Zapnutie AU na primaci
#curl -s -o /dev/null "$WEBIF_OSCAM/user_edit.html?user=$USERNAME&au=1&action=Save"
#echo "$(date '+%Y-%m-%d %H:%M:%S'): Enabled AU and waiting $AU_AWAITING seconds" >> $LOG_FILE
sleep $AU_AWAITING
#### Spustenie descramblinku nastavenych programov
for program in $SRC_MARKIZA $SRC_NOVAACTION; do
wget -q -O - "$WEBIF_ENIGMA/web/zap?sRef=$program" >> /dev/null 2>&1
echo "$(date '+%Y-%m-%d %H:%M:%S'): Start channel descrambling - $program + waiting for EMM arrival for $EMM_AWAITING time." >> "$LOG_FILE" # Používa pôvodný LOG_FILE
sleep $EMM_AWAITING
done
#### Vypnutie AU na primaci
#curl -s -o /dev/null "$WEBIF_OSCAM/user_edit.html?user=$USERNAME&au=0&action=Save"
#echo "$(date '+%Y-%m-%d %H:%M:%S'): Disabled AU" >> $LOG_FILE
sleep 5
# --- NOVÉ: Synchronizácia s oscam_dynamic_monitor.sh ---
# Zmažeme lock file po dokončení
rm -f "$LOCK_FILE"
echo "$(date '+%Y-%m-%d %H:%M:%S'): oscam_emm_refresh.sh finished. Lock file removed: $LOCK_FILE" >> "$MONITOR_LOG"
# --- KONIEC NOVÉHO KÓDU ---
exit 0
no aj tak sa mi niekedy stalo ze nebol RSA na niektorej karte spravny. Prisiel som na to ze ked urobim restart oscamu servera a nasledne restart oscamu primaca tak sa to napravi. tento script toto vykona ale len vtedy ked nebezi refresh_emu a v api rozhrani najde hlasku not found a urobi o tom zaznam do logu. Par dni to fungovalo ale nemal som cas to otestovat na 100%. mozno niekto nadviaze a dorobi si to davam to len ako namet.
Kód: Vybrat vše
#!/bin/bash
#### USER CONFIGURATION:
# URL of the Oscam instance running directly on your receiver.
# This one will be monitored continuously.
RECEIVER_OSCAM_URL="http://192.168.1.155:8888"
# Zoznam mien citaciek na PRIJIMACI, ktore ma skript monitorovat na "not found" spravy.
# Ak sa "not found" objavi pre niektoru z nich, spusti sa restart.
RECEIVER_READERS=("Skylink_private" "CSLink_private")
# Define other Oscam instances (servers) and their associated reader labels.
# These will be monitored ONLY to find out which server the receiver is connected to.
# DÔLEŽITÉ: Tieto URL by mali smerovať na WebIF serverov, nie na Newcamd porty (10001, 10003)!
# Skript sa k nim pripája cez WebIF, aby kontroloval klientov a logy.
# Format: "URL|ReaderLabel1,ReaderLabel2,..."
OTHER_OSCAM_INSTANCES=(
"http://192.168.1.157:9999|CSLink_private" # TENTO JE TERAZ PRVÝ
"http://192.168.1.157:8888|SkyLink_private" # TENTO JE TERAZ DRUHÝ
)
# Hostname or IP address of your Enigma2 receiver, as it appears in Oscam client list.
# This is crucial for detecting if the receiver is connected to an Oscam server.
# Overte, ze tento nazov presne zodpoveda nazvu v Oscam WebIF na serveri.
ENIGMA2_CLIENT_NAME="gigablue"
# --- KONFIGURÁCIA PRE SYNCHRONIZÁCIU S oscam_emm_refresh.sh ---
# Cesta k lock súboru, ktorý vytvára oscam_emm_refresh.sh pri spustení a maže pri ukončení.
# MUSÍ byť zhodná s cestou v oscam_emm_refresh.sh!
EMM_REFRESH_LOCK_FILE="/tmp/oscam_emm_refresh.lock"
# Ako často kontrolovať existenciu lock súboru, kým zmizne (kým oscam_emm_refresh.sh neskončí).
LOCK_CHECK_INTERVAL="5s"
LOG_MONITOR_FILE="/var/log/oscam_dynamic_monitor.log" # File to log the findings of this script
LOG_MAXSIZE=50000 # Max log file size for this script [Bytes]
POLLING_INTERVAL="10s" # How often to check Oscam logs (e.g., 10s for 10 seconds)
LOG_LINES_TO_FETCH=100 # Number of recent log lines to fetch from Oscam WebIF API
RESTART_COOLDOWN_SECONDS=3600 # Cooldown period in seconds (e.g., 3600s = 1 hour) between restart sequences
LAST_RESTART_TIMESTAMP_FILE="/tmp/last_oscam_restart.timestamp" # File to store the last restart timestamp
#### function to reduce the log file size, if necessary
reduce_log_size(){
if [ -f "$LOG_MONITOR_FILE" ] && [ $(wc -c < "$LOG_MONITOR_FILE") -gt "$LOG_MAXSIZE" ]; then
echo "$(date '+%Y-%m-%d %H:%M:%S'): Reducing size of $LOG_MONITOR_FILE..." >> "$LOG_MONITOR_FILE"
sed -i -e 1,20d "$LOG_MONITOR_FILE"
fi
}
#### Function to restart Oscam
restart_oscam_instance(){
local oscam_url="$1"
echo "$(date '+%Y-%m-%d %H:%M:%S'): Attempting to restart Oscam at $oscam_url..." >> "$LOG_MONITOR_FILE"
# Using direct curl command as no authentication is required
if curl -s -o /dev/null "$oscam_url/admin/restart.html"; then
echo "$(date '+%Y-%m-%d %H:%M:%S'): Oscam at $oscam_url successfully sent restart command." >> "$LOG_MONITOR_FILE"
return 0
else
echo "$(date '+%Y-%m-%d %H:%M:%S'): ERROR: Failed to send restart command to Oscam at $oscam_url. Curl error." >> "$LOG_MONITOR_FILE"
return 1
fi
}
#### Check if restart cooldown is active
is_cooldown_active(){
if [ -f "$LAST_RESTART_TIMESTAMP_FILE" ]; then
local last_restart_timestamp=$(cat "$LAST_RESTART_TIMESTAMP_FILE")
local current_timestamp=$(date +%s)
if [ "$((current_timestamp - last_restart_timestamp))" -lt "$RESTART_COOLDOWN_SECONDS" ]; then
local remaining_time=$((RESTART_COOLDOWN_SECONDS - (current_timestamp - last_restart_timestamp)))
echo "$(date '+%Y-%m-%d %H:%M:%S'): Restart cooldown is active. Next Oscam restart sequence possible in approx. $((remaining_time / 60)) minutes." >> "$LOG_MONITOR_FILE"
return 0 # Cooldown is active
fi
fi
return 1 # Cooldown is not active
}
#### Update last restart timestamp
update_last_restart_timestamp(){
date +%s > "$LAST_RESTART_TIMESTAMP_FILE"
echo "$(date '+%Y-%m-%d %H:%M:%S'): Updated last Oscam restart timestamp." >> "$LOG_MONITOR_FILE"
}
#### Function to check if Enigma2 receiver is connected to a given Oscam instance
# This checks the client list of Oscam by parsing the main WebIF HTML page.
# This approach is used because oscamapi.html?part=clients may not be supported on all Oscam versions.
is_receiver_connected(){
local oscam_url="$1"
local client_name="$2" # "gigablue"
# Try to fetch the main status page where clients are typically displayed
# Some Oscam versions might have clients directly on / or on /status.html
local webif_page_url="${oscam_url}/" # Assume clients are on the main page or /status.html
echo "$(date '+%Y-%m-%d %H:%M:%S'): DEBUG: Fetching clients from HTML page: $webif_page_url" >> "$LOG_MONITOR_FILE"
client_data=$(curl -s "$webif_page_url")
# If the response is empty, try /status.html as a fallback
if [ -z "$client_data" ] && curl -s -o /dev/null "$oscam_url/status.html"; then
echo "$(date '+%Y-%m-%d %H:%M:%S'): DEBUG: Empty response from main page. Trying ${oscam_url}/status.html" >> "$LOG_MONITOR_FILE"
webif_page_url="${oscam_url}/status.html"
client_data=$(curl -s "$webif_page_url")
fi
# DEBUGGING LINE: Displays first 500 characters of the fetched HTML
echo "$(date '+%Y-%m-%d %H:%M:%S'): DEBUG: Raw client HTML data for $oscam_url (first 500 chars): ${client_data:0:500}" >> "$LOG_MONITOR_FILE"
# ------------------------------------
if [ $? -ne 0 ] || [ -z "$client_data" ]; then
echo "$(date '+%Y-%m-%d %H:%M:%S'): ERROR: Curl failed to get client list HTML from $webif_page_url. (Connection issue or empty response?)" >> "$LOG_MONITOR_FILE"
return 1 # Failed to connect to Oscam or empty response
else
# Hľadáme názov klienta v HTML obsahu stránky.
# Názov "gigablue" sa nachádza napr. v <a href="user_edit.html?user=gigablue">gigablue</a>
# alebo v TITLE="Edit User: gigablue"
if echo "$client_data" | grep -iq "user_edit.html?user=$client_name\"" || \
echo "$client_data" | grep -iq "TITLE=\"[^>]*User: $client_name\""; then
echo "$(date '+%Y-%m-%d %H:%M:%S'): DEBUG: Client '$client_name' FOUND in data from $oscam_url." >> "$LOG_MONITOR_FILE"
return 0 # Receiver is connected
else
echo "$(date '+%Y-%m-%d %H:%M:%S'): DEBUG: Client '$client_name' NOT found in HTML data from $oscam_url." >> "$LOG_MONITOR_FILE"
return 1 # Receiver is not connected
fi
fi
}
#### Main monitoring loop
echo "$(date '+%Y-%m-%d %H:%M:%S'): Starting Oscam dynamic monitor." >> "$LOG_MONITOR_FILE"
echo "--------------------------------------------------------" >> "$LOG_MONITOR_FILE"
while true; do
reduce_log_size
# --- CHECK FOR EMM REFRESH LOCK FILE BEFORE STARTING MONITORING ---
if [ -f "$EMM_REFRESH_LOCK_FILE" ]; then
echo "$(date '+%Y-%m-%d %H:%M:%S'): Detected $EMM_REFRESH_LOCK_FILE. Pausing monitoring until it's removed..." >> "$LOG_MONITOR_FILE"
# Wait until the lock file is removed
while [ -f "$EMM_REFRESH_LOCK_FILE" ]; do
sleep "$LOCK_CHECK_INTERVAL"
done
echo "$(date '+%Y-%m-%d %H:%M:%S'): $EMM_REFRESH_LOCK_FILE removed. Resuming monitoring." >> "$LOG_MONITOR_FILE"
# After resuming, wait a short period for the system to stabilize after EMM refresh
sleep 5
fi
# ------------------------------------------------------------------
# --- 1. Always monitor the Receiver Oscam ---
oscam_url="$RECEIVER_OSCAM_URL"
echo "$(date '+%Y-%m-%d %H:%M:%S'): Checking primary Oscam (receiver) at $oscam_url..." >> "$LOG_MONITOR_FILE"
# Get log from the primary Oscam
latest_oscam_log=$(curl -s "$oscam_url/oscamapi.html?part=log&label=$LOG_LINES_TO_FETCH")
# Check for curl failure or empty log
if [ $? -ne 0 ] || [ -z "$latest_oscam_log" ]; then
echo "$(date '+%Y-%m-%d %H:%M:%S'): ERROR: Could not retrieve log from primary Oscam ($oscam_url). Check URL/status." >> "$LOG_MONITOR_FILE"
else
RESTART_NEEDED=false
DETECTED_READER_PROBLEM=""
# Iterate through all defined readers on the receiver (Skylink_private, CSLink_private)
for reader in "${RECEIVER_READERS[@]}"; do
if echo "$latest_oscam_log" | grep -E "not found.*($reader)"; then
echo "$(date '+%Y-%m-%d %H:%M:%S'): CRITICAL: 'not found' message detected for reader '$reader' on primary Oscam ($oscam_url). Initiating restart sequence..." >> "$LOG_MONITOR_FILE"
RESTART_NEEDED=true
DETECTED_READER_PROBLEM="$reader" # Store which reader caused the problem
break # Stop at the first problem found
fi
done
if [ "$RESTART_NEEDED" = true ]; then
if ! is_cooldown_active; then
# Find which server the receiver is connected to
CONNECTED_SERVER_URL=""
for instance_config in "${OTHER_OSCAM_INSTANCES[@]}"; do
# Parse server instance config: URL|READER_LABELS
IFS='|' read -r server_oscam_url server_reader_labels_str <<< "$instance_config"
echo "$(date '+%Y-%m-%d %H:%M:%S'): Checking if receiver '$ENIGMA2_CLIENT_NAME' is connected to $server_oscam_url..." >> "$LOG_MONITOR_FILE"
if is_receiver_connected "$server_oscam_url" "$ENIGMA2_CLIENT_NAME"; then
CONNECTED_SERVER_URL="$server_oscam_url"
echo "$(date '+%Y-%m-%d %H:%M:%S'): Receiver '$ENIGMA2_CLIENT_NAME' found connected to server: $CONNECTED_SERVER_URL." >> "$LOG_MONITOR_FILE"
break # Found connected server, stop searching
fi
done
# If a connected server was found, restart it, then the receiver
if [ -n "$CONNECTED_SERVER_URL" ]; then
echo "$(date '+%Y-%m-%d %H:%M:%S'): Restarting connected server Oscam at $CONNECTED_SERVER_URL..." >> "$LOG_MONITOR_FILE"
if restart_oscam_instance "$CONNECTED_SERVER_URL"; then
sleep 5 # Wait for server to stabilize
echo "$(date '+%Y-%m-%d %H:%M:%S'): Restarting receiver Oscam at $RECEIVER_OSCAM_URL..." >> "$LOG_MONITOR_FILE"
if restart_oscam_instance "$RECEIVER_OSCAM_URL"; then
update_last_restart_timestamp
fi
fi
else
# If "not found" on receiver, but no server connected,
# restart only the primary Oscam.
echo "$(date '+%Y-%m-%d %H:%M:%S'): WARNING: 'not found' on receiver for '$DETECTED_READER_PROBLEM', but no connected server Oscam found. Restarting only receiver Oscam." >> "$LOG_MONITOR_FILE"
if restart_oscam_instance "$oscam_url"; then
update_last_restart_timestamp
fi
fi
fi # End of if ! is_cooldown_active
fi # End of if RESTART_NEEDED
# Display "found" and "EMM written" messages for all monitored receiver readers
for reader in "${RECEIVER_READERS[@]}"; do
if echo "$latest_oscam_log" | grep -E "found.*($reader)"; then echo "$(date '+%Y-%m-%d %H:%M:%S'): SUCCESS: 'found' message detected for reader '$reader' on primary Oscam ($oscam_url)." >> "$LOG_MONITOR_FILE"; fi
if echo "$latest_oscam_log" | grep -q "EMM written to $reader"; then echo "$(date '+%Y-%m-%d %H:%M:%S'): INFO: 'EMM written' message detected for reader '$reader' on primary Oscam ($oscam_url)." >> "$LOG_MONITOR_FILE"; fi
done
fi
# --- 2. Section for secondary monitoring of server Oscams ---
# This section is kept as an additional safeguard. If "not found" appears directly
# on a server Oscam (even if the receiver doesn't report an issue), this section detects it
# and triggers a restart of that server and the receiver.
# If you only want server Oscams to restart when initiated by the primary Oscam,
# you can DELETE this entire "2." section.
for instance_config in "${OTHER_OSCAM_INSTANCES[@]}"; do
# Parse server instance config: URL|READER_LABELS
IFS='|' read -r oscam_url reader_labels_str <<< "$instance_config"
IFS=',' read -r -a current_reader_labels <<< "$reader_labels_str"
# Check if the receiver is connected to this server before monitoring it
if is_receiver_connected "$oscam_url" "$ENIGMA2_CLIENT_NAME"; then
echo "$(date '+%Y-%m-%d %H:%M:%S'): Receiver '$ENIGMA2_CLIENT_NAME' detected as connected to $oscam_url. Monitoring this Oscam for server-side issues..." >> "$LOG_MONITOR_FILE"
latest_oscam_log=$(curl -s "$oscam_url/oscamapi.html?part=log&label=$LOG_LINES_TO_FETCH")
if [ $? -ne 0 ] || [ -z "$latest_oscam_log" ]; then
echo "$(date '+%Y-%m-%d %H:%M:%S'): ERROR: Could not retrieve log from server Oscam ($oscam_url). Check URL/status." >> "$LOG_MONITOR_FILE"
else
RESTART_SERVER_NEEDED=false
DETECTED_SERVER_READER_PROBLEM=""
if [ ${#current_reader_labels[@]} -gt 0 ]; then
for reader in "${current_reader_labels[@]}"; do
if echo "$latest_oscam_log" | grep -E "not found.*($reader)"; then
echo "$(date '+%Y-%m-%d %H:%M:%S'): CRITICAL: 'not found' message detected for reader '$reader' on server Oscam ($oscam_url). Initiating restart sequence (server and receiver)..." >> "$LOG_MONITOR_FILE"
RESTART_SERVER_NEEDED=true
DETECTED_SERVER_READER_PROBLEM="$reader"
break
fi
done
fi
if [ "$RESTART_SERVER_NEEDED" = true ]; then
if ! is_cooldown_active; then
# 1. Restart server Oscam
if restart_oscam_instance "$oscam_url"; then
sleep 5
# 2. Always restart the Oscam on the receiver after a server Oscam issue
echo "$(date '+%Y-%m-%d %H:%M:%S'): Also restarting receiver Oscam at $RECEIVER_OSCAM_URL..." >> "$LOG_MONITOR_FILE"
restart_oscam_instance "$RECEIVER_OSCAM_URL"
update_last_restart_timestamp
fi
fi
fi
# Display "found" and "EMM written" messages for server readers
if [ ${#current_reader_labels[@]} -gt 0 ]; then
for reader in "${current_reader_labels[@]}"; do
if echo "$latest_oscam_log" | grep -E "found.*($reader)"; then echo "$(date '+%Y-%m-%d %H:%M:%S'): SUCCESS: 'found' message detected for reader '$reader' on server Oscam ($oscam_url)." >> "$LOG_MONITOR_FILE"; fi
if echo "$latest_oscam_log" | grep -q "EMM written to $reader"; then echo "$(date '+%Y-%m-%d %H:%M:%S'): INFO: 'EMM written' message detected for reader '$reader' on server Oscam ($oscam_url)." >> "$LOG_MONITOR_FILE"; fi
done
fi
fi
else
echo "$(date '+%Y-%m-%d %H:%M:%S'): Receiver not connected to $oscam_url. Skipping monitoring." >> "$LOG_MONITOR_FILE"
fi
done
sleep "$POLLING_INTERVAL"
done
exit 0