Un webhook è un metodo di comunicazione tra applicazioni che permette a un servizio esterno di “chiamare” Home Assistant inviando una richiesta HTTP quando si verifica un evento specifico. In pratica, è come dare un “numero di telefono” a Home Assistant che servizi esterni possono chiamare per innescare automazioni.
Differenza con API tradizionali:
-
API classica: Home Assistant chiede periodicamente “ci sono novità?” (polling)
-
Webhook: il servizio esterno avvisa Home Assistant immediatamente “è successo questo!” (push)
I webhook sono più efficienti, istantanei e consumano meno risorse perché eliminano il polling continuo.
Perché usare i webhook in Home Assistant
Casi d’uso pratici:
-
Integrazioni servizi esterni: ricevi notifiche da IFTTT, Zapier, n8n quando succedono eventi nel web
-
App smartphone personalizzate: Tasker (Android) o Shortcuts (iOS) inviano comandi a Home Assistant
-
Sistemi di pagamento: notifica quando ricevi pagamento online (Stripe, PayPal webhook)
-
Monitoraggio server: alert da servizi monitoring quando server va down
-
Social media: notifiche da Twitter, Instagram, Reddit quando qualcuno menziona parole chiave
-
Posta/pacchi: tracking spedizioni con aggiornamenti automatici a Home Assistant
-
Calendari esterni: eventi da Google Calendar, Outlook che triggherano automazioni
-
Sistemi terzi: allarmi, NVR, sensori IoT che non hanno integrazione Home Assistant nativa
Architettura webhook Home Assistant
Come funziona tecnicamente
-
Generazione webhook URL: Home Assistant crea URL univoco per ogni webhook
-
Servizio esterno invia richiesta HTTP POST: quando evento si verifica, servizio chiama l’URL
-
Home Assistant riceve dati: payload JSON/XML viene processato
-
Trigger automazione: evento webhook innesca automazione configurata
-
Azione eseguita: Home Assistant esegue azioni definite (accendi luci, invia notifica, ecc.)
Componenti necessari:
-
webhook integration (nativa in Home Assistant)
-
Accesso esterno sicuro a Home Assistant (DuckDNS + Let’s Encrypt, Cloudflare Tunnel, o Nabu Casa)
-
Automazioni YAML per gestire trigger webhook
Configurare webhook in Home Assistant
Passo 1: Creare webhook ID
Ogni webhook necessita un webhook_id univoco che identifica quale automazione triggherare.
Convenzione naming:
webhook_id: "nome_servizio_evento_descrittivo"
Esempi:
-
ifttt_porta_aperta -
tasker_arrivato_casa -
telegram_comando_emergenza -
stripe_pagamento_ricevuto
Passo 2: Configurare trigger automazione
Nel file automations.yaml o tramite interfaccia UI:
automation:
- alias: "Webhook - Notifica da IFTTT"
description: "Riceve notifica quando IFTTT rileva evento"
trigger:
- platform: webhook
webhook_id: "ifttt_porta_aperta"
action:
- service: notify.telegram
data:
message: "🚪 Porta principale aperta rilevata da sensore IFTTT!"
- service: light.turn_on
target:
entity_id: light.ingresso
data:
brightness: 255
Componenti trigger webhook:
-
platform: webhook→ specifica trigger tipo webhook -
webhook_id→ identificatore univoco -
Opzionalmente:
allowed_methods(POST, GET),local_only(solo rete locale)
Passo 3: Generare URL webhook
L’URL completo del webhook è:
https://tuodominio.duckdns.org/api/webhook/WEBHOOK_ID
Dove:
-
tuodominio.duckdns.org→ tuo dominio esterno Home Assistant -
/api/webhook/→ endpoint fisso webhook API -
WEBHOOK_ID→ il tuo webhook_id definito
Esempio concreto:
https://casarossi.duckdns.org/api/webhook/ifttt_porta_aperta
Sicurezza webhook
Problema: webhook pubblici sono vulnerabili
Se pubblichi l’URL webhook su Internet, chiunque lo conosca può inviare richieste e triggherare automazioni. Questo è un rischio di sicurezza.
Soluzione 1: Webhook ID complessi casuali
Usa webhook_id lunghi e casuali impossibili da indovinare:
webhook_id: "ifttt_g8k2Hs9pLm3nQ7vX4zR"
Generatori online: uuidgenerator.net per stringhe casuali sicure.
Soluzione 2: Validazione dati payload
Verifica che la richiesta contenga segreti o token condivisi:
automation:
- alias: "Webhook sicuro con token"
trigger:
- platform: webhook
webhook_id: "servizio_esterno"
condition:
- condition: template
value_template: "{{ trigger.json.secret_token == 'MioTokenSegreto123' }}"
action:
- service: light.turn_on
target:
entity_id: light.soggiorno
Solo richieste con secret_token corretto nel JSON triggherano automazione.
Soluzione 3: IP whitelisting
Limita webhook a indirizzi IP specifici fidati:
automation:
- alias: "Webhook solo da IP fidato"
trigger:
- platform: webhook
webhook_id: "servizio_ip_limitato"
condition:
- condition: template
value_template: "{{ trigger.headers['X-Forwarded-For'] == '203.0.113.45' }}"
action:
- service: switch.turn_on
target:
entity_id: switch.irrigazione
Soluzione 4: Webhook local_only
Per webhook chiamati solo da rete locale (es: Tasker su smartphone WiFi casa):
trigger:
- platform: webhook
webhook_id: "tasker_locale"
local_only: true
Rifiuta richieste da Internet esterno.
Esempi pratici webhook
Esempio 1: IFTTT → Home Assistant
Scenario: Quando ricevi email importante su Gmail, accendi luce studio rossa.
Setup IFTTT:
-
Crea applet IFTTT: “If new email from [sender] → Then Webhooks”
-
URL:
https://tuacasa.duckdns.org/api/webhook/ifttt_email_importante -
Method: POST
-
Content Type: application/json
-
Body:
{"sender":"{{FromAddress}}"}
Automazione Home Assistant:
automation:
- alias: "Email importante - Luce rossa studio"
trigger:
- platform: webhook
webhook_id: "ifttt_email_importante"
action:
- service: light.turn_on
target:
entity_id: light.studio
data:
rgb_color: [255, 0, 0]
brightness: 255
- service: notify.mobile_app
data:
message: "📧 Email importante ricevuta da {{ trigger.json.sender }}"
Esempio 2: Tasker (Android) → Home Assistant
Scenario: Quando premi pulsante widget smartphone, attiva scena “Film” in soggiorno.
Configurazione Tasker:
-
Crea Task: “Scena Film HA”
-
Aggiungi azione: Net → HTTP Request
-
URL:
https://tuacasa.duckdns.org/api/webhook/tasker_scena_film -
Method: POST
-
Headers:
Content-Type: application/json -
Body:
{"device":"smartphone","location":"casa"}
Automazione Home Assistant:
automation:
- alias: "Tasker - Attiva scena film"
trigger:
- platform: webhook
webhook_id: "tasker_scena_film"
action:
- service: scene.turn_on
target:
entity_id: scene.soggiorno_film
- service: notify.mobile_app
data:
message: "🎬 Scena film attivata da smartphone"
Esempio 3: Telegram Bot → Home Assistant
Scenario: Invia comandi testuali a Home Assistant via bot Telegram usando webhook.
Setup Telegram Bot:
-
Crea bot con @BotFather
-
Configura webhook Telegram:
https://api.telegram.org/bot<TOKEN>/setWebhook?url=https://tuacasa.duckdns.org/api/webhook/telegram_bot_comandi
Automazione parsing comandi:
automation:
- alias: "Telegram Bot - Parser comandi"
trigger:
- platform: webhook
webhook_id: "telegram_bot_comandi"
action:
- choose:
- conditions:
- condition: template
value_template: "{{ trigger.json.message.text == '/luci_on' }}"
sequence:
- service: light.turn_on
target:
entity_id: all
- conditions:
- condition: template
value_template: "{{ trigger.json.message.text == '/stato_casa' }}"
sequence:
- service: telegram_bot.send_message
data:
message: "Temperatura: {{ states('sensor.temperatura_soggiorno') }}°C"
Esempio 4: n8n Workflow → Home Assistant
Scenario: Workflow n8n monitora API meteo, se pioggia prevista chiude tende automaticamente.
n8n Workflow:
-
Trigger: Schedule (ogni ora)
-
HTTP Request: chiama API meteo OpenWeatherMap
-
IF node: se
rain > 0 -
Webhook node: POST a
https://tuacasa.duckdns.org/api/webhook/n8n_pioggia_prevista
Automazione Home Assistant:
automation:
- alias: "n8n - Chiudi tende se pioggia"
trigger:
- platform: webhook
webhook_id: "n8n_pioggia_prevista"
condition:
- condition: state
entity_id: cover.tende_soggiorno
state: "open"
action:
- service: cover.close_cover
target:
entity_id: cover.tende_soggiorno
- service: notify.telegram
data:
message: "☔ Pioggia prevista, tende chiuse automaticamente"
Accedere ai dati webhook nelle automazioni
I dati inviati dal webhook sono accessibili tramite variabile trigger:
Struttura dati trigger webhook:
trigger.json # Payload JSON completo trigger.data # Alias di trigger.json trigger.id # Webhook ID trigger.headers # Headers HTTP richiesta
Esempio accesso campi specifici:
action:
- service: notify.telegram
data:
message: >
Webhook ricevuto:
- ID: {{ trigger.id }}
- Timestamp: {{ trigger.json.timestamp }}
- Valore: {{ trigger.json.sensor_value }}
- IP sorgente: {{ trigger.headers['X-Forwarded-For'] }}
Webhook vs alternative
Webhook vs Polling
Webhook (consigliato):
-
Istantaneo (latenza <1s)
-
Efficiente (nessun polling continuo)
-
Scalabile (migliaia di webhook senza overhead)
-
Richiede accesso esterno Home Assistant
Polling:
-
Non richiede accesso esterno
-
Lento (ritardo da 30s a minuti)
-
Inefficiente (richieste continue anche senza eventi)
Webhook vs MQTT
Webhook:
-
Standard web universale (HTTP)
-
Nessun broker aggiuntivo
-
Unidirezionale (solo esterno → HA)
MQTT:
-
Bidirezionale
-
Pub/Sub per scenari complessi
-
Richiede broker MQTT configurato
Verdetto: Usa webhook per trigger esterni semplici, MQTT per comunicazione bidirezionale dispositivi IoT.
Testare webhook
Tool per test manuali
1. curl da terminale:
curl -X POST \
-H "Content-Type: application/json" \
-d '{"test":"valore"}' \
https://tuacasa.duckdns.org/api/webhook/test_webhook
2. Postman/Insomnia:
-
Crea richiesta POST
-
URL: webhook Home Assistant
-
Body JSON: payload test
-
Invia e verifica automazione triggherata
3. Webhook.site:
-
Genera URL temporaneo webhook.site
-
Configura servizio esterno per inviare lì
-
Analizza payload ricevuto
-
Copia formato e adatta a Home Assistant
Debug webhook
Abilita log dettagliati in configuration.yaml:
logger:
default: info
logs:
homeassistant.components.webhook: debug
Riavvia HA, richieste webhook compaiono in log con payload completo.
Limitazioni e troubleshooting
Webhook non triggera:
-
Verifica accesso esterno HA funzionante (testa da browser esterno)
-
Controlla webhook_id corretto nell’URL
-
Verifica certificato SSL valido (webhook richiedono HTTPS)
-
Controlla firewall/router non blocchi porta 443
Automazione triggera ma non esegue azioni:
-
Verifica condition non blocchino esecuzione
-
Controlla log Home Assistant per errori
-
Testa payload JSON corretto (usa Developer Tools)
Troppi trigger indesiderati:
-
Implementa validazione token/secret
-
Usa IP whitelisting
-
Genera webhook_id più complessi
