diff --git a/thinkcenter_monitor.sh b/thinkcenter_monitor.sh index e6ee867..3382dcc 100644 --- a/thinkcenter_monitor.sh +++ b/thinkcenter_monitor.sh @@ -39,18 +39,37 @@ check_target() { echo "$response_code" } +get_entity_domain() { + # Extract domain from entity_id (e.g., "switch" from "switch.device_name") + local entity="$1" + echo "${entity%%.*}" +} + +get_toggle_service() { + # Determine correct service based on entity domain + local domain="$1" + case "$domain" in + switch) echo "switch/turn_off" ;; + light) echo "light/turn_off" ;; + *) echo "switch/turn_off" ;; # Default fallback + esac +} + trigger_power_cycle() { local entity="$1" + local domain=$(get_entity_domain "$entity") + local turn_off_service=$(get_toggle_service "$domain") + local turn_on_service="${turn_off_service%/*}/turn_on" - log "ALERT: Triggering power cycle for entity: $entity" + log "ALERT: Triggering power cycle for entity: $entity (domain: $domain)" # Turn off - log "Sending turn_off request to Home Assistant..." + log "Sending turn_off request to Home Assistant ($turn_off_service)..." local response=$(curl -s -w "\n%{http_code}" -X POST \ -H "Authorization: Bearer $HA_TOKEN" \ -H "Content-Type: application/json" \ - -d "{\"target\": {\"entity_id\": \"$entity\"}}" \ - "$HA_URL/api/services/switch/turn_off") + -d "{\"entity_id\": \"$entity\"}" \ + "$HA_URL/api/services/$turn_off_service") local http_code=$(echo "$response" | tail -n 1) local body=$(echo "$response" | head -n -1) @@ -66,12 +85,12 @@ trigger_power_cycle() { sleep 10 # Turn on - log "Sending turn_on request to Home Assistant..." + log "Sending turn_on request to Home Assistant ($turn_on_service)..." local response=$(curl -s -w "\n%{http_code}" -X POST \ -H "Authorization: Bearer $HA_TOKEN" \ -H "Content-Type: application/json" \ - -d "{\"target\": {\"entity_id\": \"$entity\"}}" \ - "$HA_URL/api/services/switch/turn_on") + -d "{\"entity_id\": \"$entity\"}" \ + "$HA_URL/api/services/$turn_on_service") local http_code=$(echo "$response" | tail -n 1) local body=$(echo "$response" | head -n -1)