Skip to content

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#

  1. Home Assistant Trigger - Monitors state changes
  2. Device State Parser - Extracts sensor and device data
  3. Condition Logic - Determines when to trigger actions
  4. Action Executor - Controls devices and sends notifications
  5. External Integrations - Connects to other services

πŸ“ Step-by-Step Guide#

1. Configure Home Assistant API#

  1. Generate Long-lived Access Token: - Go to Home Assistant > Profile - Scroll down to "Long-lived access tokens" - Create new token and save it securely

  2. Enable API access: - Ensure default_config is in your configuration.yaml - Verify API is accessible from your n8n instance

  3. 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#

  1. Add Home Assistant Trigger node
  2. Configure connection: - URL: Your Home Assistant instance URL - Access Token: Your long-lived token
  3. 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
// Process temperature sensor data
if ($json.entity_id === 'sensor.living_room_temperature') {
  const temperature = parseFloat($json.new_state.state);
  const previousTemp = parseFloat($json.old_state.state);

  return {
    entity: 'living_room_temperature',
    current_temp: temperature,
    previous_temp: previousTemp,
    change: temperature - previousTemp,
    timestamp: $json.last_changed
  };
}

Motion Detection#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
// Handle motion sensor events
if ($json.entity_id === 'binary_sensor.motion_sensor_1') {
  const motionDetected = $json.new_state.state === 'on';

  return {
    entity: 'motion_sensor_1',
    motion: motionDetected,
    timestamp: $json.last_changed,
    location: 'hallway'
  };
}

Door/Window Sensors#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
// Monitor door and window sensors
if ($json.entity_id.startsWith('binary_sensor.door_')) {
  const isOpen = $json.new_state.state === 'on';
  const doorName = $json.attributes.friendly_name;

  return {
    entity: $json.entity_id,
    door_name: doorName,
    is_open: isOpen,
    timestamp: $json.last_changed
  };
}

🏠 Automation Scenarios#

Climate Control Automation#

  1. 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'
      };
    }
    

  2. 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#

  1. 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
        }
      };
    }
    

  2. 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#

  1. 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'
      };
    }
    

  2. 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#

  1. 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'
      }
    }
    

  2. 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}`
    }
    

  3. 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#

  1. 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#

  1. 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#

  1. 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#

  1. 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#

  1. 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#

  1. 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#

  1. Manual Testing - Use Home Assistant Developer Tools to trigger state changes - Test with different device types and values - Verify webhook delivery to n8n

  2. 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#

  1. Home Assistant Logs - Check home-assistant.log for API errors - Monitor webhook delivery status - Review entity state changes

  2. 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