Home Assistant Integration#
Learn how to connect n8n with Home Assistant for smart home automation, IoT monitoring, and advanced workflow integration.
π― What You'll Build#
A comprehensive Home Assistant integration that: - Monitors smart device states and changes - Triggers automations based on sensor data - Sends notifications and controls devices - Integrates with external services and APIs - Creates complex multi-step automation scenarios
π Requirements#
- Home Assistant instance running
- Home Assistant API access (Long-lived access token)
- n8n instance running
- Smart devices connected to Home Assistant
π§ Workflow Overview#
Key Components#
- Home Assistant Trigger - Monitors state changes
- Device State Parser - Extracts sensor and device data
- Condition Logic - Determines when to trigger actions
- Action Executor - Controls devices and sends notifications
- External Integrations - Connects to other services
π Step-by-Step Guide#
1. Configure Home Assistant API#
-
Generate Long-lived Access Token: - Go to Home Assistant > Profile - Scroll down to "Long-lived access tokens" - Create new token and save it securely
-
Enable API access: - Ensure
default_configis in yourconfiguration.yaml- Verify API is accessible from your n8n instance -
Test API connection:
1 2 3
curl -H "Authorization: Bearer YOUR_TOKEN" \ -H "Content-Type: application/json" \ http://your-home-assistant:8123/api/states
2. Set Up Home Assistant Trigger#
- Add Home Assistant Trigger node
- Configure connection: - URL: Your Home Assistant instance URL - Access Token: Your long-lived token
- Select trigger type: - State Changed: Monitor specific entity changes - Time Pattern: Trigger at specific times - Webhook: Custom webhook events
3. Monitor Device States#
Temperature Monitoring#
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
Motion Detection#
1 2 3 4 5 6 7 8 9 10 11 | |
Door/Window Sensors#
1 2 3 4 5 6 7 8 9 10 11 12 | |
π Automation Scenarios#
Climate Control Automation#
-
Temperature-based Control
1 2 3 4 5 6 7 8 9
// Smart thermostat control if (data.current_temp > 25 && data.entity === 'sensor.living_room_temperature') { return { service: 'climate.set_temperature', entity_id: 'climate.living_room_thermostat', temperature: 22, hvac_mode: 'cool' }; } -
Energy-saving Mode
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
// Turn off devices when away if ($json.entity_id === 'person.home' && $json.new_state.state === 'not_home') { return [ { service: 'light.turn_off', entity_id: 'all_lights' }, { service: 'climate.turn_off', entity_id: 'all_climate_devices' }, { service: 'media_player.turn_off', entity_id: 'all_media_players' } ]; }
Security and Safety#
-
Intruder Detection
1 2 3 4 5 6 7 8 9 10 11 12
// Alert when motion detected while away if (data.motion && !isSomeoneHome()) { return { service: 'notify.mobile_app', message: `π¨ Motion detected in ${data.location}!`, title: 'Security Alert', data: { priority: 'high', ttl: 0 } }; } -
Smoke/Fire Detection
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
// Emergency response for smoke detection if ($json.entity_id === 'binary_sensor.smoke_detector' && $json.new_state.state === 'on') { return [ { service: 'notify.all_devices', message: 'π₯ SMOKE DETECTED! Evacuate immediately!', title: 'EMERGENCY' }, { service: 'light.turn_on', entity_id: 'all_lights', brightness: 255 }, { service: 'switch.turn_on', entity_id: 'switch.alarm_siren' } ]; }
Energy Management#
-
Peak Hour Optimization
1 2 3 4 5 6 7 8 9 10 11 12
// Reduce energy consumption during peak hours const currentHour = new Date().getHours(); const isPeakHour = currentHour >= 18 && currentHour <= 22; if (isPeakHour) { return { service: 'climate.set_temperature', entity_id: 'climate.air_conditioner', temperature: 26, // Higher temp during peak hours hvac_mode: 'cool' }; } -
Solar Power Integration
1 2 3 4 5 6 7 8 9 10 11 12 13
// Use solar power when available if ($json.entity_id === 'sensor.solar_power_generation') { const solarPower = parseFloat($json.new_state.state); const homeConsumption = parseFloat($json.state.sensor.home_energy_consumption.state); if (solarPower > homeConsumption) { // Use excess solar power for beneficial loads return { service: 'switch.turn_on', entity_id: 'switch.water_heater' }; } }
π± Notifications and Alerts#
Multi-channel Notifications#
-
Mobile Push Notifications
1 2 3 4 5 6 7 8 9 10
{ service: 'notify.mobile_app_your_phone', message: 'Home automation triggered', title: 'Smart Home Alert', data: { entity_id: $json.entity_id, state: $json.new_state.state, priority: 'normal' } } -
Email Notifications
1 2 3 4 5
{ to: '[email protected]', subject: 'Home Assistant Alert', text: `Event detected: ${$json.entity_id}\nNew state: ${$json.new_state.state}\nTime: ${$json.last_changed}` } -
Telegram Notifications
1 2 3 4
{ chat_id: 'your_chat_id', text: `π Smart Home Alert\n\nDevice: ${$json.attributes.friendly_name}\nState: ${$json.new_state.state}\nTime: ${new Date($json.last_changed).toLocaleString()}` }
Rich Notifications#
- Image Attachments
1 2 3 4 5 6 7 8 9 10 11 12
// Send camera snapshot with notification if ($json.entity_id === 'binary_sensor.doorbell') { return { service: 'notify.mobile_app', message: 'Someone is at the door!', title: 'Doorbell Alert', data: { image: '/api/camera.door_front_camera/proxy_stream', entity_id: 'camera.door_front_camera' } }; }
π External Service Integration#
Weather-based Automation#
- Weather API Integration
1 2 3 4 5 6 7 8 9 10 11 12
// Get weather data and adjust home settings const weatherResponse = await httpGet('https://api.openweathermap.org/data/2.5/weather?q=your_city&appid=your_api_key'); const weather = JSON.parse(weatherResponse.body); if (weather.main.temp > 30) { // Turn on fans and AC return { service: 'climate.turn_on', entity_id: 'climate.living_room_ac', temperature: 22 }; }
Calendar Integration#
- Google Calendar Events
1 2 3 4 5 6 7 8 9 10 11 12 13
// Prepare home based on calendar events const events = await getGoogleCalendarEvents(); const hasImportantMeeting = events.some(event => event.summary.toLowerCase().includes('meeting') && isToday(event.start.date) ); if (hasImportantMeeting) { return { service: 'scene.turn_on', entity_id: 'scene.meeting_ready' }; }
E-commerce Integration#
- Smart Shopping
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
// Order supplies when running low if ($json.entity_id === 'sensor.toilet_paper_level' && parseFloat($json.new_state.state) < 20) { return { service: 'notify.mobile_app', message: 'Toilet paper running low. Order more?', title: 'Shopping Reminder', data: { actions: [ { action: 'URI', title: 'Order Now', uri: 'https://shopping-site.com/toilet-paper' } ] } }; }
π Data Analytics and Reporting#
Energy Consumption Tracking#
- Daily Energy Report
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
// Generate daily energy consumption report const today = new Date().toISOString().split('T')[0]; const energyData = await getEnergyData(today); const report = { date: today, total_consumption: energyData.total, by_device: energyData.devices, cost: calculateCost(energyData.total) }; // Save to Google Sheets await appendToSheet('Energy Log', report); // Send summary return { service: 'notify.mobile_app', message: `Daily energy report: ${report.total_consumption} kWh, ΰΈΏ${report.cost}`, title: 'Energy Summary' };
Device Usage Analytics#
- Track Device Usage Patterns
1 2 3 4 5 6 7 8 9
// Analyze device usage over time const usageData = analyzeDeviceUsage($json.entity_id, '7d'); return { device: $json.attributes.friendly_name, usage_hours: usageData.totalHours, most_active_time: usageData.peakHour, efficiency_score: calculateEfficiency(usageData) };
π§ͺ Testing and Debugging#
Test Scenarios#
-
Manual Testing - Use Home Assistant Developer Tools to trigger state changes - Test with different device types and values - Verify webhook delivery to n8n
-
Automated Testing
1 2 3 4 5 6 7 8 9 10
// Create test data const testData = { entity_id: 'sensor.test_temperature', old_state: { state: '20' }, new_state: { state: '25' }, last_changed: new Date().toISOString() }; // Run workflow with test data await workflowTrigger(testData);
Debug Tools#
-
Home Assistant Logs - Check
home-assistant.logfor API errors - Monitor webhook delivery status - Review entity state changes -
n8n Execution History - Review incoming payload data - Check HTTP request responses - Monitor conditional logic execution
π Troubleshooting#
Common Issues#
Connection Problems - Verify Home Assistant URL is accessible from n8n - Check firewall settings between n8n and Home Assistant - Validate access token permissions - Ensure SSL certificate is valid
State Changes Not Detected - Check entity monitoring configuration - Verify entity exists and is functional - Review trigger node settings - Check for rate limiting
Service Calls Fail - Verify service names and entity IDs - Check device availability - Review service documentation - Test service in Home Assistant UI
Performance Issues - Optimize webhook handling - Reduce unnecessary triggers - Implement proper error handling - Monitor resource usage
π‘οΈ Security Considerations#
Network Security#
- Use HTTPS for all communications
- Implement proper firewall rules
- Secure API access with strong tokens
- Regularly rotate access tokens
Data Privacy#
- Minimize personal data collection
- Implement data retention policies
- Secure data transmission and storage
- Comply with privacy regulations
π Advanced Features#
Machine Learning Integration#
- Predictive maintenance for appliances
- Anomaly detection in energy usage
- User behavior pattern recognition
- Adaptive automation based on habits
Voice Assistant Integration#
- Google Assistant routines
- Amazon Alexa skills
- Custom voice commands
- Natural language processing
Multi-location Management#
- Monitor multiple properties
- Centralized dashboard
- Cross-location automation
- Unified reporting
Related Tutorials: - Form Submission - Learn form handling basics - Email Notifications - Email integration guide
Resources: - Home Assistant API Documentation - n8n Home Assistant Integration - Home Assistant Community