Checks for HA API result

This commit is contained in:
2025-12-05 22:33:24 +01:00
parent 257e4c2062
commit 8968a84fcd

View File

@@ -40,46 +40,52 @@ check_target() {
} }
trigger_power_cycle() { trigger_power_cycle() {
local entity="$1" local entity="$1"
log "ALERT: Triggering power cycle for entity: $entity" log "ALERT: Triggering power cycle for entity: $entity"
# Turn off # Turn off
log "Sending turn_off request to Home Assistant..." log "Sending turn_off request to Home Assistant..."
curl -s -X POST \ local response=$(curl -s -w "\n%{http_code}" -X POST \
-H "Authorization: Bearer $HA_TOKEN" \ -H "Authorization: Bearer $HA_TOKEN" \
-H "Content-Type: application/json" \ -H "Content-Type: application/json" \
-d "{\"entity_id\": \"$entity\"}" \ -d "{\"entity_id\": \"$entity\"}" \
"$HA_URL/api/services/switch/turn_off" > /dev/null 2>&1 "$HA_URL/api/services/switch/turn_off")
if [[ $? -eq 0 ]]; then local http_code=$(echo "$response" | tail -n 1)
log "Turn off request sent successfully" local body=$(echo "$response" | head -n -1)
else
log "ERROR: Failed to send turn_off request" if [[ "$http_code" =~ ^[2][0-9]{2}$ ]]; then
fi log "Turn off request sent successfully (HTTP $http_code)"
else
# Wait 10 seconds log "ERROR: Failed to send turn_off request (HTTP $http_code). Response: $body"
log "Waiting 10 seconds before power-on..." fi
sleep 10
# Wait 10 seconds
# Turn on log "Waiting 10 seconds before power-on..."
log "Sending turn_on request to Home Assistant..." sleep 10
curl -s -X POST \
-H "Authorization: Bearer $HA_TOKEN" \ # Turn on
-H "Content-Type: application/json" \ log "Sending turn_on request to Home Assistant..."
-d "{\"entity_id\": \"$entity\"}" \ local response=$(curl -s -w "\n%{http_code}" -X POST \
"$HA_URL/api/services/switch/turn_on" > /dev/null 2>&1 -H "Authorization: Bearer $HA_TOKEN" \
-H "Content-Type: application/json" \
if [[ $? -eq 0 ]]; then -d "{\"entity_id\": \"$entity\"}" \
log "Turn on request sent successfully" "$HA_URL/api/services/switch/turn_on")
log "Power cycle completed for $entity"
else local http_code=$(echo "$response" | tail -n 1)
log "ERROR: Failed to send turn_on request" local body=$(echo "$response" | head -n -1)
fi
if [[ "$http_code" =~ ^[2][0-9]{2}$ ]]; then
# Reset state log "Turn on request sent successfully (HTTP $http_code)"
ERROR_START_TIME="" log "Power cycle completed for $entity"
IN_GRACE_PERIOD=false else
log "ERROR: Failed to send turn_on request (HTTP $http_code). Response: $body"
fi
# Reset state
ERROR_START_TIME=""
IN_GRACE_PERIOD=false
} }
log "=== Thinkcentre Monitor Started ===" log "=== Thinkcentre Monitor Started ==="