Power Pilot
Published on

Authors
  • avatar
    Name
    Seb Burrell
    Twitter

Home automation is often heralded as the epitome of convenience and intelligence in modern living. Yet, one glaring gap in Home Assistant's otherwise robust ecosystem is its ability to accurately detect presence in a room or area without requiring complex setups, intricate templates, or a mountain of automations.

Enter Area Occupancy Detection a solution I've been working on to simplify this aspect of smart homes, and its companion the Smart Lighting Control Blueprint.


The Problem: Presence Detection

While Home Assistant excels in managing sensors, entities, and integrations, presence detection is one area where it still feels clunky for many users. For something as fundamental as "Is someone in this room?" there’s no simple, out-of-the-box method. Typically, achieving this requires:

  • A mix of motion, door, cameras, or even sound sensors.
  • Manually crafted automations to correlate sensor states.
  • Templates to handle edge cases and advanced logic.

This complexity often alienates those who aren't comfortable diving into YAML or creating advanced logic chains. It also makes maintaining automations harder as your smart home evolves.


The Solution: Area Occupancy Detection Integration

The Area Occupancy Detection integration I developed focuses on simplicity and accessibility. With just a few strategically placed sensors (motion and door sensors, for example), you can achieve reliable presence detection. The integration handles the logic of correlating multiple inputs to provide a binary occupancy state for each area or room.

Key Features:

  • Simplified Setup: Define the area, assign relevant sensors, and you're done.
  • Dynamic Logic: The integration interprets motion and other sensor events to update room occupancy in real-time.
  • Scalability: Add or remove sensors without rewriting automations or templates.

This tool bridges the gap between beginners wanting straightforward functionality and power users desiring a robust, scalable system.


Use of Bayesian Probability for Real-Time Calculations

One of the standout features of the Area Occupancy Detection integration is its clever use of Bayesian probability. By leveraging the Home Assistant statistics and history features, the integration calculates real-time occupancy probabilities based on the state of multiple sensors and historical patterns.

How It Works:

  • Bayesian Framework: The integration considers each sensor's data as a "piece of evidence" contributing to the overall occupancy probability. Motion sensors, environmental sensors (like temperature, humidity, and illuminance), and device states (like a TV or gaming console being on) are all factored in.
  • Weighted Contributions: Not all sensors are treated equally—motion sensors, for instance, have a higher weight in the calculation, while environmental sensors provide secondary confirmation.
  • Historical Data for Priors: The system uses historical data to establish a baseline probability for occupancy. This "prior probability" ensures better accuracy by accounting for trends and typical usage patterns in each room.
  • Dynamic Decay Logic: The integration includes a decay mechanism to reduce the probability of occupancy over time when no new motion or activity is detected. This decay can follow either a linear or exponential curve, depending on the configuration.

Real-Time Adaptation:

Home Assistant's native support for sensor states and historical statistics is seamlessly integrated into the calculation pipeline. By tracking sensor availability, last motion timestamps, and environmental readings in real-time, the integration dynamically adjusts the occupancy probability. This approach ensures immediate responsiveness to events while maintaining a high degree of reliability even when some sensors are temporarily unavailable.

The result is a system that doesn't just rely on binary states like "motion detected" but provides a nuanced, probabilistic view of occupancy. This enhances automation reliability, particularly for scenarios like lighting control, heating, or security.


Here's a code snippet from the integration demonstrating the Bayesian probability calculation, along with an explanation:

Code Snippet: Bayesian Calculation

class ProbabilityCalculator:
    def calculate(
        self, # Store the state of itelf
        sensor_states: SensorStates, # The current state of the sensors
        motion_timestamps: dict[str, datetime], # The timestamps of the last detected motion
    ) -> ProbabilityResult:
        """Calculate overall area occupancy probability."""
        motion_result = self._calculate_motion_probability(sensor_states, motion_timestamps) # Calculate the motion probability (refers to another method)
        env_result = self._calculate_environmental_probability(sensor_states) # Calculate the environmental probability (refers to another method)

        # Weighted combination: Motion has higher priority
        combined_prob = (motion_result.probability * 0.7) + (env_result.probability * 0.3)

        # Confidence score based on sensor availability
        available_sensors = sum(1 for state in sensor_states.values() if state["availability"]) # Count the number of available sensors
        total_sensors = len(self._get_all_configured_sensors()) # Count the total number of sensors (refer to another method)
        confidence_score = (min(available_sensors / total_sensors, 1.0) if total_sensors > 0 else 0.0) # Calculate the confidence score

        return {
            "probability": combined_prob, # The combined probability
            "prior_probability": motion_result.probability, # The prior probability
            "active_triggers": motion_result.triggers + env_result.triggers, # The active triggers
            "sensor_probabilities": { # The probabilities of individual sensors
                "motion_probability": motion_result.probability,
                "environmental_probability": env_result.probability,
            },
            "confidence_score": confidence_score, # The confidence score
        }

Explanation

  1. Input Data:

    • sensor_states: Real-time states of motion, environmental, and device sensors (e.g., on/off or numeric values).
    • motion_timestamps: Timestamps of the last detected motion.
  2. Step 1: Motion Probability:

    • Motion sensors are evaluated first because they are the most reliable indicator of presence.
    • Each motion sensor contributes a base probability. If motion is not currently detected but occurred recently, a decay factor adjusts its contribution.
  3. Step 2: Environmental Probability:

    • Environmental sensors (e.g., temperature, humidity, light levels) provide secondary evidence.
    • If significant changes are detected (e.g., increased light indicating someone turned on a light), these sensors contribute to the probability.
  4. Step 3: Weighted Combination:

    • The integration gives 70% weight to motion sensors and 30% to environmental factors, reflecting their relative reliability.
    • This weighted sum produces the combined probability of room occupancy.
  5. Confidence Score:

    • The integration also calculates a confidence score, which measures how many sensors are available and contributing data. This helps the system gracefully handle situations like temporary sensor unavailability.

Example Output

For a room with motion detected 10 seconds ago, high light levels, and a working temperature sensor:

{
    "probability": 0.85,  # 85% chance the room is occupied
    "prior_probability": 0.95,  # Based on motion
    "active_triggers": ["motion_sensor_1", "light_sensor_2"],
    "sensor_probabilities": {
        "motion_probability": 0.95,
        "environmental_probability": 0.60
    },
    "confidence_score": 0.9  # High confidence due to many working sensors
}

Why Bayesian?

The Bayesian approach is ideal for presence detection because it:

  • Combines evidence from multiple sensors into a single probability.
  • Handles uncertainty gracefully, such as noisy or missing data.
  • Dynamically updates based on sensor input and historical data.

This method significantly enhances reliability and accuracy, providing a smarter foundation for automations like lighting control.

Adding Decay Logic

The integration also includes a decay mechanism to reduce the occupancy probability over time when no new motion or activity is detected. This decay can follow either a linear or exponential curve, depending on the configuration.


Elevating the Experience: Smart Lighting Control Blueprint

To complement the occupancy detection, I created the Smart Lighting Control Blueprint. Lighting automation is one of the most requested use cases for presence detection, but it often suffers from the same pitfalls of complexity and maintenance. With this blueprint:

  1. Minimal Configuration: Pair your room's lights with its occupancy sensor(s).
  2. Automatic Handling: Lights turn on when someone is detected and off when the room is unoccupied.
  3. Customizable Timers: Specify delays for turning off lights after inactivity.

This blueprint makes smart lighting setups a breeze, especially when combined with the Area Occupancy Detection integration.


The Simplicity Advantage

By addressing presence detection and lighting automation holistically, this approach offers a straightforward, user-friendly solution for smart homes. Whether you're a Home Assistant novice or a seasoned expert, the goal is to eliminate friction in setup and operation.

No more:

  • Writing complex YAML.
  • Debugging unreliable automations.
  • Feeling like you need a PhD in smart home tech.

With just a few sensors per room, you can unlock advanced presence-based automation without the headaches.


Get Started

  1. Install Area Occupancy Detection: GitHub Repo Link
  2. Set Up Your Sensors: There are a myriad of sensors you can use, from motion sensors to door sensors, temperature sensors, and more, as long as they're compatible with Home Assistant (and everything is) then you're good to go.
  3. Use the Smart Lighting Blueprint: Blueprint YAML Link

Import it into your Home Assistant instance and enjoy seamless lighting control.


With these tools, I hope to make smart home automation more approachable and enjoyable for everyone. Whether you're automating a single room or a whole house, simplicity and reliability are just a few clicks away.

Check out the code, try it out, and share your feedback!