Skip to content
BotServBotServ
Node-REDHome AssistantSmart HomeAutomationIoT

Node-RED with Home Assistant

Connect Node-RED to Home Assistant. Control entities, build automations, AI in smart home with practical examples.

S

schutzgeist

6 min read
Node-RED with Home Assistant

Node-RED with Home Assistant

What this article covers

  • How to connect Node-RED with Home Assistant.
  • How to control entities and react to state changes.
  • What complex automations look like in Node-RED.
  • How to integrate AI into smart home flows.
  • Practical examples for lighting, climate, security, and energy.

Introduction: Node-RED with Home Assistant explained

Home Assistant has built-in automations, but they have limits. Node-RED as a complement enables complex logic: conditional chains with multiple conditions, time-based rules, delays, and AI-driven decisions. Together, they form the standard for advanced smart home automation.

This article is for Home Assistant users who want to extend their setup with Node-RED. You’ll find the basics in Node-RED installation and Home automation.

Why do you need Node-RED with Home Assistant?

Home Assistant automations are YAML-based and linear. If you need “If temperature > 25 AND nobody home AND sun is shining, then lower blinds,” YAML becomes hard to manage. Node-RED makes this visual: sensor → conditions → action, all as a flow.

Node-RED with Home Assistant in a nutshell

Node-RED connects to Home Assistant via WebSocket. You see all entities, can react to state changes, and call services. Flows are visual and more powerful than YAML automations.

The core idea: Home Assistant provides data, Node-RED provides logic.

Who this article is for

  • Home Assistant users who need more advanced automation.
  • Smart home builders who want to add AI to their automations.
  • Node-RED users who want to integrate Home Assistant.
  • Self-hosters who control their smart home themselves.

Prior knowledge of Home Assistant and Node-RED helps.

Key terms

  • Node-RED - Flow editor. Use when: you need complex logic.
  • Home Assistant - Smart home platform. Use when: it’s your foundation.
  • Entity - A device or sensor in Home Assistant. Use when: defining what to control.
  • Service - An action in Home Assistant. Use when: triggering what to do.
  • WebSocket - Connection between Home Assistant and Node-RED. Use when: you need real-time updates.
  • Ollama - Local model server. Use when: adding AI to flows.

Setup: Node-RED plus Home Assistant

1. Home Assistant Add-on (easiest approach)

If you run Home Assistant OS:

  1. Settings → Add-ons → Add-on Store
  2. Search for “Node-RED” and install
  3. Enable “Start on boot”
  4. Open Node-RED

The connection is configured automatically.

2. Docker (manual)

version: "3.8"

services:
  homeassistant:
    image: homeassistant/home-assistant:latest
    container_name: homeassistant
    restart: unless-stopped
    ports:
      - "8123:8123"
    volumes:
      - ha_config:/config
    networks:
      - smarthome

  nodered:
    image: nodered/node-red:latest
    container_name: nodered
    restart: unless-stopped
    ports:
      - "1880:1880"
    volumes:
      - nodered_data:/data
    networks:
      - smarthome

volumes:
  ha_config:
  nodered_data:

networks:
  smarthome:
    driver: bridge

3. Connect Node-RED to Home Assistant

# In Node-RED: Palette → Install
node-red-contrib-home-assistant-websocket

Then in Node-RED:

  1. Add an events: state node.
  2. Click the gear icon → “Add new server”.
  3. Home Assistant URL: http://homeassistant:8123
  4. Access Token from Home Assistant (Profile → Long-Lived Access Tokens).

Essential nodes

NodePurpose
events: stateRespond to state changes
events: allAll events
call serviceCall a service (light.turn_on)
current stateRead current state
trigger: stateTrigger on state change
poll statePoll state periodically
wait untilWait until state is reached
apiCall any Home Assistant API

Example 1: Lights on motion

[events: state: binary_sensor.bewegung_flur]
    │
    ▼ (state == "on")
[time range: 18:00 - 06:00]  ← nights only
    │
    ▼
[call service: light.turn_on]
  Entity: light.flur
  Data: {"brightness": 128}
    │
    ▼
[delay: 5 minutes]
    │
    ▼
[call service: light.turn_off]
  Entity: light.flur

Example 2: Climate automation

[poll state: sensor.aussentemperatur] (every 5 min)
    │
    ▼
[function: Decision logic]
  const temp = msg.payload;
  const innen = global.get("innentemperatur") || 21;
  if (temp > 25 && innen > 23) {
    msg.payload = "kuehlen";
  } else if (temp < 5 && innen < 19) {
    msg.payload = "heizen";
  } else {
    msg.payload = "nichts";
  }
    │
    ▼
[switch]
    ├─ kuehlen → [call service: climate.set_hvac_mode cool]
    ├─ heizen → [call service: climate.set_hvac_mode heat]
    └─ nichts → [call service: climate.set_hvac_mode off]

Example 3: Presence detection with AI

[events: state: person.max]
    │
    ▼
[function: Gather context]
  const context = {
    person: msg.payload,
    uhrzeit: new Date().toLocaleTimeString(),
    wochentag: new Date().toLocaleDateString('de', {weekday: 'long'}),
    licht: global.get("licht_status"),
    temperatur: global.get("temperatur")
  };
  msg.payload = JSON.stringify(context);
    │
    ▼
[HTTP Request: Ollama]
  "Based on the context, what should happen?
   Context: {{msg.payload}}
   Options: licht_an, musik_an, heizung_an, nichts
   Respond as JSON."
    │
    ▼
[function: Parse JSON]
    │
    ▼
[switch: action]
    ├─ licht_an → [call service: light.turn_on]
    ├─ musik_an → [call service: media_player.play]
    └─ heizung_an → [call service: climate.set_temperature]

Example 4: Energy management

[poll state: sensor.strompreis] (every 15 min)
    │
    ▼
[function: Analyze price]
  const preis = parseFloat(msg.payload);
  msg.guenstig = preis < 0.25;  // Cents/kWh
  msg.teuer = preis > 0.40;
    │
    ▼
[switch]
    ├─ guenstig → [call service: switch.turn_on waschmaschine]
    │             [call service: switch.turn_on geschirrspueler]
    └─ teuer → [call service: switch.turn_off nicht_notwendig]

Example 5: Security monitoring

[events: state: group.alle_sensoren]
    │
    ▼
[function: Check alarm]
  const state = msg.payload;
  const uhrzeit = new Date().getHours();
  const nacht = uhrzeit < 6 || uhrzeit > 22;

  if (state === "on" && nacht) {
    msg.alarm = true;
    msg.grund = "Night motion detected";
  }
    │
    ▼
[switch: alarm?]
    │
    ▼ (yes)
[call service: notify.notify]
  "Alarm! {{msg.grund}}"
    │
    ▼
[call service: light.turn_on]
  All lights on
    │
    ▼
[call service: camera.snapshot]
  Capture snapshot

AI in smart home flows

Natural language commands

[HTTP In: /api/voice-command]
    │
    ▼
[HTTP Request: Ollama]
  "Interpret the command: '{{msg.payload.command}}'
   Available entities: {{entities}}
   Respond as JSON: {action, entity, params}"
    │
    ▼
[function: Parse JSON and call service]
  const cmd = JSON.parse(msg.payload);
  msg.service = cmd.action;
  msg.entity = cmd.entity;
  msg.data = cmd.params;
    │
    ▼
[call service]

Anomaly Detection

// Function Node: Detect unusual patterns
const history = context.get("history") || [];
history.push({ temp: msg.payload, time: Date.now() });
if (history.length > 100) history.shift();

// Send to AI for analysis
msg.payload = `Temperature history: ${JSON.stringify(history.slice(-20))}
Do you detect any anomalies? Reply: normal/anomaly + reasoning`;
return msg;

Security Considerations

  • Access Token: Create a dedicated token for Node-RED with minimal permissions.
  • Don’t expose: Keep Node-RED and Home Assistant off the public internet.
  • Critical actions: For security-sensitive operations (alarms, locks), require human confirmation. See Human Approval.
  • Validate: Check AI output before executing actions.

Common Pitfalls

  • Wrong Entity IDs: Entities are named light.wohnzimmer, not Wohnzimmer.
  • Expired tokens: Long-Lived Access Tokens can expire. Regenerate as needed.
  • Too many events: events: all can overwhelm your system. Filter to what you need.
  • Race conditions: Two flows controlling the same entity can contradict each other.
  • No fallback: If Node-RED goes down, critical automations should still run in Home Assistant.

Further Reading

Key Takeaways:

  • Node-RED plus Home Assistant creates powerful smart home automation.
  • Use node-red-contrib-home-assistant-websocket for the connection.
  • Trigger with events: state, execute actions with call service.
  • Leverage AI via Ollama for intelligent decisions.
  • Build complex logic visually instead of YAML.

FAQ

How do I connect Node-RED to Home Assistant?

Install node-red-contrib-home-assistant-websocket, create a Long-Lived Access Token in Home Assistant, and configure the server in Node-RED.

Node-RED or Home Assistant automations?

Use Home Assistant automations for simple if-then logic. Use Node-RED for complex workflows with multiple conditions, delays, and AI. Both can coexist.

How do I find Entity IDs?

In Home Assistant, go to Settings → Devices & Services → Entities. Or in Node-RED’s node editor when configuring a Home Assistant node.

How do I build AI into smart home flows?

Use an HTTP Request node to call Ollama. AI can analyze context, interpret commands, or detect anomalies.

Is this secure?

Yes, when local. Both services stay in your network. Create a dedicated token with minimal permissions and don’t expose anything to the internet.

What happens if Node-RED goes down?

Flows stop running. Critical automations (alarms, heating) should have a fallback that runs directly in Home Assistant.

How performant is this?

WebSocket connections are realtime (milliseconds). AI requests take 2-10 seconds. For time-critical operations (motion detection to light), Node-RED without AI is faster.

How do I debug flows?

Insert debug nodes after each step and check messages in the debug panel. The events: all node shows all Home Assistant events.

Sources and Further Reading

Back to Blog
Share:

Related Posts