[RELEASE] Advanced Sleep Metrics - Contactless Sleep Tracking

Version 2.0 Available

Hey everyone,

I wanted to share a project I’ve been building to solve one of the most frustrating aspects of smart home presence: accurate, contactless sleep tracking. Wearables are great, but I wanted my house to know when we were actually asleep, just getting up to pee, or tossing and turning—using only standard vibration and motion sensors. Simple "If vibration stops and motion starts" rules always lead to false positives (like folding laundry on the bed, or a parent checking on a sleeping child).

So, I built Advanced Sleep Metrics (BMS Edition). It shifts away from basic "A then B" rules and uses Behavioral Telemetry and Signal Processing to figure out what’s actually happening in the room.

It is designed to run independently, but it pairs perfectly with my Advanced Good Night application to drive your home's ambient routines.

:sparkles: Key Features & Logic Engines

:brain: Machine Learning Behavioral Engine The app maintains a rolling 14-day ledger of your sleep patterns (separating Weekdays from Weekends). Once it learns your baseline, it dynamically adjusts its own sensitivity. If you get into bed near your learned average time, it fast-tracks your entry. If you trigger a motion sensor near your average wake time, it accelerates your morning routines. (Can be disabled per-user for guest rooms).

:ghost: Pre-Emptive Presence Lockout (Ghost Filter & Parental Guard) Tired of your kids being marked "Awake" because they rolled over right as you walked in to check on them? The app takes a microsecond snapshot of room motion when bed vibration stops. If motion was already active before the bed stopped moving, it flags an "External Presence Override" and protects the sleeper's status.

:bed: Sustained Entry (Anti-Bounce) & Settling Locks If you sit on the bed to fold laundry, the app puts you in a "Pending Entry" state and watches the room for 3 minutes. If you keep moving around, it aborts the entry. Once you are officially "In Bed," it gives you a 30-minute absolute Settling Lock where you can toss, turn, and adjust blankets without triggering a false exit.

:shield: The Partner Shield (Cross-Talk Cancellation) When one partner physically gets out of bed, the mattress naturally bounces. The app intelligently deafens the sleeping partner's vibration sensor for 60 seconds to prevent false movement tracking.

:toilet: Dynamic Stitching & Terminal Wake (Shower Sensor) If you get up to use the bathroom in the middle of the deep sleep window, the app gives you a 45-minute grace period to return and seamlessly stitches your sleep session back together. But, if you walk into the bathroom and trigger the Shower Motion Sensor within 10 minutes, the app triggers a "Terminal Wake," rolls back the bathroom trip, and instantly wakes the house up for the day.

:running_man: Kinetic Speed Limits You can define exact "Wake Sequences" (Step 1: Bedside Motion -> Step 2: Hallway Motion). The app enforces physical kinetic speed limits. If Step 2 triggers 1 second after Step 1, it rejects it as a physical impossibility (ignoring dogs running by or parents walking out).

:bar_chart: Live HTML Dashboards Automatically generates virtual info devices with beautiful HTML tiles showing live Sleep Scores, Session Durations, Nightly Movements, Bathroom Trips, and AI-predicted target times for your Hubitat dashboards.

Hardware Requirements

  • 1x Vibration/Acceleration Sensor per sleeper (under the mattress or taped to the slats).
  • Standard Room/Bathroom Motion Sensors (to track wake paths and bathroom trips).
  • (Optional) Dedicated bedside, hallway, and shower motion sensors for ultra-strict tracking sequences.

:scroll: The Code & Support This app is entirely free to use. You are welcome to take the code, strip it down, repurpose the logic for your own apps, or use it exactly as is.

I’m actively running this in my own home, so if you run into any bugs, have weird edge-case use cases (pets, unusual shift-work schedules), or have feature requests, please let me know below and I’m more than happy to help patch the code!

APP:
raw.githubusercontent.com/ShaneAllen334/Hubitat_Apps/refs/heads/main/Advanced_Sleep_Metrics/Advanced_Sleep_Metrics.groovy

Driver:
raw.githubusercontent.com/ShaneAllen334/Hubitat_Apps/refs/heads/main/Advanced_Sleep_Metrics/Advanced_Sleep_Metrics_Dashboard_Device.groovy



Capture246

1 Like


Capture246

Hey everyone,

I am excited to announce a massive overhaul to the Advanced Sleep Metrics (ASM) application. What started as a local tracking app has been completely re-engineered into a BMS-grade (Building Management System) sleep orchestration platform.

If you are trying to track occupancy based on complex, conflicting real-world data (pressure mats vs. headboard vibrations vs. motion sensors), you know how easily false positives can wreck your house automations. This update introduces multi-sensor kinetic shielding, advanced signal processing, and a stunning, professional UI that brings high-end commercial display aesthetics directly into your Hubitat ecosystem.

Here is a detailed breakdown of what’s new in the BMS Edition:


:bar_chart: 1. High-End BMS Visual Analytics Architecture

The presentation layer has been entirely rewritten from the ground up to eliminate boring text grids and walls of text, separating human diagnostics from background automation logic.

  • Circular Donut Score Metrics: Uses dynamic, pure CSS conic-gradients to generate a live, color-coded circular score gauge. It visually shifts from green to amber or red based on your calculated sleep performance.
  • Sleep Stages Pie Chart: A custom, auto-scaling pie chart rendered completely on-hub that visually partitions your night into Deep Sleep, Light Sleep, and Awake/Restless windows.
  • Segmented Proportional Bar Chart: Tracks and weights your time-in-bed categories horizontally, sitting right below your core metrics for high-glance telemetry on wall tablets.
  • The 2x2 Data Matrix: Consolidates your critical boundaries: In/Out timelines, total Bathroom Trips (with progressive duration tracking), total Movement Events (with a stabilized hourly movement index), and Room Health (temperature and humidity cross-correlation).

:jigsaw: 2. Dual-Device Child Provisioning Engine

To streamline ecosystem integration, the application can now provision two distinct types of child devices per occupant with a single click:

  • The HTML Dashboard Device (ASM Dashboard Device): Purely built for rendering human visual telemetry. It targets a new, hyper-minified HTML generator designed to fit completely inside Hubitat's strict 1024-character string attribute limit. It strips whitespace and compresses code on the fly so it never truncates or blanks out on wall dashboards.
  • The User Virtual Switch (Virtual Switch): Built strictly for rule building. It mirrors the core binary logic of the bed state, turning ON retroactively when entry is committed and OFF during wake events, making it seamless to trigger lighting profiles, HVAC restrictions, or security locks via Rule Machine.

:shield: 3. Advanced Signal Processing & False Positive Filters

Bed tracking hardware is notoriously noisy. To fix this, we've implemented a suite of filters that treat your body movements like mechanical inputs:

  • Anti-Bounce Entry Verification: When a pressure mat or mattress sensor trips, the app stalls, entering a PENDING ENTRY state. It monitors room motion sensors for a user-configured window to ensure you aren't just tossing laundry or setting a basket down before it retroactively commits the session boundary.
  • Teleportation Rejection: People don't teleport into bed. If a sensor reports a sudden bed entry but the fallback room motion sensor hasn't registered human activity within the last 10 minutes, the reading is discarded as a phantom pet trigger.
  • Edge-of-Bed Fusion: If your pressure mat reports an open state (pending bed exit) but a mattress or headboard vibration sensor reports active kinetic energy, the exit timer is cleared. The system assumes a roll-to-edge or posture adjustment and seamlessly keeps your automation states locked.
  • Pre-Emptive Ghost Filter: If room motion is detected before bed vibration stops, the exit sequence is locked out. This prevents a family member or parent stepping into the room to check on someone from accidentally triggering a terminal wake-up automation.

:shushing_face: 4. Quiet House Return & Dynamic Stitching

  • Quiet House Watchdog: If an occupant is stuck in a BATHROOM TRIP state but the global house motion sensors go completely quiet for a user-defined period, the engine assumes they sneaked back into bed without triggering a stubborn vibration sensor. It rescues the stuck state, calculates the away duration, and stitches the sleep session back together.
  • Contextual Dynamic Stitching: The app now allows for two separate stitching windows. During normal hours, a bed exit might expire in 15 minutes. During your custom "Deep Sleep Window" (the dead of night), the stitching window automatically scales up (e.g., to 45 minutes) to handle extended baby or bathroom trips without breaking your nightly profile metrics.

:brain: 5. AI Behavioral Learning & Deep Insights

  • Outlier-Rejected Rolling Bedtimes: The native ML engine processes a 14-day rolling profile of your exact sleep entries and wake schedules. It applies a trimmed robust average (dropping extreme high/low statistical anomalies) to automatically reduce anti-bounce validation friction when you go to bed on schedule.
  • Score Insight Breakdown: The App UI now includes an automatic contextual text logger that mathematically explains the state of your sleep card (e.g., “Your base efficiency was 94%, but a -8 point penalty was applied for 4 restlessness events...”).

Version 2.0 released.