Home
Softono
HA-Optimizer

HA-Optimizer

Open source MIT HTML
72
Stars
3
Forks
11
Issues
4
Watchers
1 month
Last Commit

About HA-Optimizer

HA Optimizer is a Home Assistant integration for automatic cleanup, analysis, and health monitoring. It scans the entire HA instance to detect dead entities, broken automations, orphaned registry entries, stale devices, and suspicious naming patterns, assigning risk levels and a 0-100 health score. A safe purge engine uses soft-delete by default, disabling entities reversibly with a trash bin for restoration and configurable auto-expiry. Critical devices like smoke detectors and locks are protected from deletion suggestions. The integration includes a built-in add-on manager listing all installed add-ons sorted by update status, with live CPU and RAM monitoring refreshing every five seconds and one-click update, start, and stop actions. Real-time system resource gauges show host CPU, RAM, and disk usage across all tabs. Additional tools include a recorder database analyzer that identifies top writers and suggests optimizations, a Lovelace dashboard audit for cards referencing unavailable entities, a state sto

Platforms

Web Self-hosted

Languages

HTML

Links

๐Ÿงน HA Optimizer

hacs_badge version HA license Python languages themes

๐Ÿ‡ป๐Ÿ‡ณ Phiรชn bแบฃn tiแบฟng Viแป‡t: README_vi.md

The smart cleanup, analysis and health-check integration for Home Assistant.

Most Home Assistant instances accumulate hundreds of dead entities, broken automations, database bloat, and silently-failing devices over time โ€” and nobody notices until something breaks. HA Optimizer surfaces all of it automatically, so you can clean up with confidence.

โšก Set it up once. Let it scan. Know exactly what's cluttering your HA instance โ€” and clean it up safely.


๐Ÿ“ธ Preview

Preview 1 Preview 2 Preview 3


๐Ÿ”ฅ Why You Need This

Problem HA Optimizer
๐Ÿ’€ Dead entities from removed devices Detects & flags them with risk level
๐Ÿค– Broken automations nobody knows about Dead code scan โ€” triggers/actions pointing to nothing
๐Ÿ—„๏ธ Recorder DB growing out of control Finds top writers, suggests YAML optimizations
๐Ÿ“Š Dashboard cards calling unavailable entities Full Lovelace audit
๐ŸŒฉ๏ธ Entities spamming state updates 100ร—/minute State storm detector
๐Ÿ”Œ Integration that keeps disconnecting Integration health scorer with reconnect analysis
โ“ "Is my HA acting weird today?" Fingerprint anomaly detection vs your own history
๐Ÿงฉ Add-ons scattered across HA settings Unified add-on panel with live CPU/RAM monitoring
๐Ÿ–ฅ๏ธ No visibility into host resource usage Real-time CPU / RAM / Disk gauges always on screen

โœจ Features

๐Ÿ” Smart Entity Scanner

  • Scans all entities, automations, scripts, and helpers in one pass
  • Assigns risk levels (Low / Medium / High) so you know what's safe to delete
  • Detects: stale entities (no change in N days), orphaned registry entries, suspicious naming patterns (test_, temp_, backup_, etc.), and YAML-defined entities that can't be auto-deleted
  • Safety first โ€” smoke detectors, door/window sensors, locks, motion sensors, CO/gas detectors are never suggested for deletion (configurable)
  • Outputs a health_score (0โ€“100) for your HA instance

๐Ÿ—‘๏ธ Safe Purge Engine with Soft Delete

  • Soft delete by default โ€” disables entities instead of deleting them, fully reversible
  • Trash bin tab โ€” all soft-deleted entities are listed with timestamps, remaining days before auto-expiry, and a one-click restore button
  • Auto-expiry โ€” trash is cleaned up automatically after N days (configurable)
  • Handles automations and scripts correctly (UI-created vs YAML-defined)
  • Detects already-disabled entities and still tracks them properly

๐Ÿงฉ Add-on Manager (new)

A full-featured add-on control panel built right into the optimizer โ€” no more jumping between HA menus.

  • Lists all installed add-ons sorted by priority: updates available first, then running, then stopped
  • Shows live CPU % and RAM usage per add-on, refreshing every 5 seconds automatically โ€” no page reload needed
  • One-click actions: Update, Start, Stop, and open add-on details โ€” all without leaving the panel
  • Clearly highlights add-ons with pending updates (old version struck-through, new version highlighted in blue)
  • Summary chips at the top: total count, running count, stopped count, available updates count

๐Ÿ–ฅ๏ธ Real-time System Resource Gauges (new)

Always visible at the top of every tab โ€” you never lose sight of your host's health while using any feature.

  • Three animated semi-circle gauges for CPU, RAM, and Disk usage
  • Gradient color arc that flows green โ†’ orange โ†’ red as load increases (0 โ†’ 50% โ†’ 100%)
  • Animated needle that glides smoothly to the exact usage value
  • Shows absolute values beneath each gauge (e.g. 6.6 GB / 23.2 GB for RAM)
  • Displays OS name, hostname, HA version, and kernel version
  • Refreshes every 5 seconds automatically when the Add-ons tab is open; available on all tabs via the Refresh button

๐Ÿ“ก Fingerprint Anomaly Detection (unique)

Compares today's HA behaviour against your own historical baseline (up to 30 days). Uses statistical methods (ฯƒ or IQR depending on available data) to detect:

  • Abnormal spike in state writes (DB load surge)
  • Unusual automation trigger volume
  • Integration reconnect storms
  • HA lifecycle event anomalies (unexpected restarts, reloads)

Confidence level grows with more baseline days (20% โ†’ 99%). Completely private โ€” compares only against your own past data, never against other users.

๐Ÿ—„๏ธ Recorder DB Analyzer

  • Queries the recorder SQLite/MySQL database directly
  • Identifies top-writing entities (DB bloat culprits)
  • Detects wasteful records โ€” many writes, few distinct states
  • Generates a ready-to-paste YAML snippet for recorder: optimizations
  • Domain-level write statistics

๐Ÿ“Š Lovelace Dashboard Analyzer

  • Reads .storage/lovelace* config files
  • Flags: heavy/complex cards, missing entities, duplicate entity references, uninstalled custom cards, Jinja2 template cards, WebSocket push pressure
  • Cross-references with recorder data to identify dashboard-driven DB waste

๐ŸŒฉ๏ธ State Storm Detector

  • Finds entities updating state abnormally fast vs their domain baseline
  • Includes severity rating, ratio vs normal, and suggested fixes
  • Catches misconfigured sensors before they fill your database

๐Ÿค– Automation Dead Code Analyzer

  • Scans all UI-created automations for broken references
  • Checks: triggers pointing to removed devices, actions calling deleted entities/services, conditions using non-existent entity states
  • Silent failures in automations are exposed before they cause problems

๐Ÿ”Œ Integration Health Scorer

  • Analyzes 7 days of recorder data per integration
  • Scores each integration (0โ€“100) based on reconnect frequency and unavailability patterns
  • Flags abnormal disconnection bursts vs rolling average
  • Detailed score breakdown showing exactly which factors caused deductions
  • Diagnosis messages: "๐Ÿ“ถ Possible RF interference or device too far from hub"

๐ŸŽจ 11 Built-in Themes (new)

Switch the entire panel's look with one click โ€” your preference is saved automatically.

Theme Style
๐ŸŒŒ Deep Space Dark navy + electric blue (default)
๐ŸŸฃ Midnight Purple Deep dark + violet
๐ŸŒฒ Forest Dark Dark green + emerald
๐ŸŒ… Sunset Warm dark + orange
๐ŸŒŠ Ocean Light Light blue โ€” bright mode
๐Ÿชจ Slate Pro Dark indigo + purple accent
๐ŸŒน Rose Gold Dark crimson + rose
โšก Cyber Neon Near-black + cyan glow
๐ŸŸก Amber Dark Dark sepia + golden amber
๐ŸงŠ Arctic Icy white โ€” bright mode
๐Ÿง› Dracula Classic Dracula dark + soft purple

๐ŸŒ 12 Interface Languages (new)

The entire panel UI โ€” every label, button, message, and error โ€” is fully translated into 12 languages. Switch instantly from the language selector in the top bar; your choice persists across sessions.

Supported: ๐Ÿ‡ป๐Ÿ‡ณ Tiแบฟng Viแป‡t ยท ๐Ÿ‡ฌ๐Ÿ‡ง English ยท ๐Ÿ‡ฉ๐Ÿ‡ช Deutsch ยท ๐Ÿ‡ซ๐Ÿ‡ท Franรงais ยท ๐Ÿ‡ณ๐Ÿ‡ฑ Nederlands ยท ๐Ÿ‡ต๐Ÿ‡ฑ Polski ยท ๐Ÿ‡ธ๐Ÿ‡ช Svenska ยท ๐Ÿ‡ญ๐Ÿ‡บ Magyar ยท ๐Ÿ‡จ๐Ÿ‡ฟ ฤŒeลกtina ยท ๐Ÿ‡ฎ๐Ÿ‡น Italiano ยท ๐Ÿ‡ต๐Ÿ‡น Portuguรชs ยท ๐Ÿ‡ธ๐Ÿ‡ฎ Slovenลกฤina


๐Ÿ› ๏ธ Installation

Method 1: HACS (Recommended)

Step 1 โ€” Add this repository to HACS:

Open HACS Repository

If the button doesn't work, add manually:

  1. Open HACS โ†’ Integrations โ†’ click the โ‹ฎ menu โ†’ Custom repositories
  2. Add this repository URL and select category Integration
  3. Find HA Optimizer in the HACS store and click Download
  4. Restart Home Assistant
  5. Go to Settings โ†’ Devices & Services โ†’ Add Integration โ†’ search for HA Optimizer
  6. Complete the setup wizard

Method 2: Manual

  1. Download or clone this repository
  2. Copy the ha_optimizer/ folder into config/custom_components/:
    config/
    โ””โ”€โ”€ custom_components/
        โ””โ”€โ”€ ha_optimizer/
            โ”œโ”€โ”€ __init__.py
            โ”œโ”€โ”€ const.py
            โ”œโ”€โ”€ config_flow.py
            โ”œโ”€โ”€ scanner.py
            โ”œโ”€โ”€ purge_engine.py
            โ”œโ”€โ”€ store.py
            โ”œโ”€โ”€ fingerprint.py
            โ”œโ”€โ”€ manifest.json
            โ”œโ”€โ”€ services.yaml
            โ”œโ”€โ”€ strings.json
            โ””โ”€โ”€ panel.html
  3. Restart Home Assistant
  4. Go to Settings โ†’ Devices & Services โ†’ Add Integration โ†’ search for HA Optimizer

โš™๏ธ Configuration

During setup you will be asked for:

Setting Default Description
Auto-scan interval (days) 7 Set to 0 to disable automatic scanning
Stale days threshold 30 Days without state change before an entity is flagged
Enable soft delete true Disable entities before permanently deleting (reversible)
Soft delete days 7 Days in trash before auto-permanent deletion
Exclude device classes (safety defaults) Comma-separated list of device classes to never suggest deleting

All settings can be changed at any time via Settings โ†’ Devices & Services โ†’ HA Optimizer โ†’ Configure.


๐Ÿš€ Using the Panel

Open the ๐Ÿงน HA Optimizer panel from the HA sidebar. The panel connects automatically using the HA WebSocket session โ€” no token or extra authentication required. Everything is done through the UI โ€” no YAML or manual service calls needed.

โœ… No Long-Lived Access Token needed. The panel uses Home Assistant's own authenticated connection, the same one your browser already has open.

The panel has 9 tabs across the top:


๐Ÿ“‹ Scan Tab โ€” Overview & Cleanup

The main tab. See your system health at a glance and manage unused entities.

  1. Click ๐Ÿ” Start Scan โ€” the scanner analyzes all entities, automations, scripts and helpers (takes a few seconds)
  2. The Overview Dashboard appears showing:
    • Health Score gauge (0โ€“100)
    • Total entities, candidates to review, breakdown by risk (๐Ÿ”ด High / ๐ŸŸก Medium / ๐ŸŸข Low)
    • Trash count and last scan timestamp
  3. The table lists all flagged items. You can filter by risk, type or source, and search by name or entity_id
  4. Tick the checkboxes to select items, then use the floating action bar at the bottom:
    • ๐Ÿ—‘๏ธ Disable โ†’ soft delete (reversible โ€” entity moves to Trash tab)
    • โŒ Hard Delete โ†’ permanent removal โš ๏ธ irreversible
    • โœ• Deselect โ†’ cancel

โš ๏ธ Always backup your HA before using Hard Delete.


๐Ÿ“Š Recorder Tab

  1. Click ๐Ÿ“Š Analyze Recorder
  2. See DB size, top-writing entities, wasteful records and write stats by domain
  3. Copy the ready-to-paste YAML block into configuration.yaml under recorder: and restart HA to reduce DB growth

๐Ÿ–ฅ๏ธ Dashboard Tab

  1. Click ๐Ÿ–ฅ๏ธ Analyze Dashboard
  2. The panel reads your Lovelace .storage/lovelace* files and reports: heavy cards, missing/unavailable entities, duplicate references, uninstalled custom cards, Jinja2 template cards
  3. Issues are marked Critical or Warning

โ„น๏ธ Only UI-mode dashboards stored in .storage/lovelace* are supported. YAML-mode dashboards cannot be read automatically.


โšก State Storm Tab

  1. Click โšก Detect State Storms
  2. Entities updating far more frequently than their domain baseline are listed with severity, ratio vs normal, and fix suggestions
  3. These are the most common cause of database bloat and slow Lovelace

๐Ÿ” Dead Code Tab

  1. Click ๐Ÿ” Analyze Dead Code
  2. UI-created automations are scanned for broken references: triggers pointing to removed devices, actions targeting deleted entities/services, conditions using non-existent states
  3. Each automation with issues shows a direct "Open Editor" link to fix it immediately

๐Ÿ’š Health Tab

  1. Click ๐Ÿ’š Check Integration Health
  2. Each integration gets a score (0โ€“100) based on 7 days of reconnect and unavailability data
  3. Problem devices show: reconnect count today vs daily average, battery level (if available), and diagnosis messages
  4. Status badges: Good / Warning / Critical

๐Ÿซ† Fingerprint Tab

Compares today's HA behaviour against your own historical baseline โ€” private to your instance, never compared to other users.

First-time setup:

  1. Click ๐Ÿ“ฅ Collect Baseline โ€” saves yesterday's metrics snapshot
  2. Repeat daily, or it runs automatically at 00:05 every night
  3. After 3โ€“7 days, results become meaningful (confidence reaches 75%+)

Running an analysis:

  1. Click ๐Ÿซ† Analyze Fingerprint
  2. Results show confidence level, anomaly count, hours elapsed today (extrapolated to 24h for fair comparison)
  3. Each anomaly shows today's value vs baseline average with the method used (ฯƒ or IQR)
  4. โœ… green = normal ยท โš ๏ธ orange = anomaly detected

๐Ÿงฉ Add-ons Tab

Full add-on control panel with live host resource data.

  • Lists all add-ons with status, version, and update availability
  • Live CPU % and RAM per running add-on, auto-refreshing every 5 seconds
  • System gauges at the top always show host CPU / RAM / Disk
  • One-click Update / Start / Stop without leaving the panel

โ„น๏ธ Requires Home Assistant OS or Supervised (Supervisor API). Not available on Container or Core installs.


๐Ÿ—‘๏ธ Trash Tab

All soft-deleted entities appear here with the date they were disabled.

  • โ™ป๏ธ Restore โ€” re-enables the entity and removes it from trash
  • โŒ Hard Delete โ€” permanently removes from HA
  • Entities are auto-hard-deleted after the configured number of days (default: 7)

Automation Example โ€” Weekly Scan & Notify

automation:
  alias: "HA Optimizer - Weekly Scan"
  trigger:
    - platform: time
      at: "03:00:00"
    - platform: template
      value_template: "{{ now().weekday() == 6 }}"  # Sunday
  action:
    - service: ha_optimizer.scan
    - wait_for_trigger:
        platform: event
        event_type: ha_optimizer_scan_complete
      timeout: "00:05:00"
    - service: notify.mobile_app_your_phone
      data:
        title: "๐Ÿงน HA Optimizer"
        message: >
          Scan complete. Found {{ trigger.event.data.statistics.candidates_found }}
          candidates. Health score: {{ trigger.event.data.statistics.health_score }}/100

๐Ÿ“‹ Services Reference

Service Description
ha_optimizer.scan Full scan โ€” entities, automations, scripts, helpers
ha_optimizer.purge Disable (soft) or permanently delete entities
ha_optimizer.restore Re-enable a soft-deleted entity
ha_optimizer.get_results Return last scan results as service response
ha_optimizer.analyze_recorder Recorder DB deep analysis + YAML suggestions
ha_optimizer.analyze_dashboard Lovelace dashboard audit
ha_optimizer.analyze_storms State storm / high-frequency writer detection
ha_optimizer.analyze_dead_code Broken trigger/action/condition scanner
ha_optimizer.analyze_health Integration health scoring (7-day window)
ha_optimizer.analyze_fingerprint Anomaly detection vs personal baseline
ha_optimizer.analyze_addons Add-on list + live CPU/RAM + host resource data
ha_optimizer.collect_baseline Manual baseline snapshot collection

๐Ÿ›ก๏ธ Safety

  • Soft delete is the default โ€” entities are disabled, not removed. Fully reversible.
  • Safety device classes are hardcoded โ€” smoke, CO/gas, moisture, motion, occupancy, door, window, lock, vibration, sound, battery, problem sensors are never suggested.
  • YAML entities are flagged, never auto-deleted โ€” they require manual action.
  • Risk scoring โ€” every result has a risk level so you make informed decisions.

๐Ÿ–ฅ๏ธ Compatibility

Home Assistant 2023.7+ (2023.1+ for most features)
Database SQLite (default) and MySQL/MariaDB
Config UI config flow โ€” no YAML required
Dependencies None โ€” uses only HA built-ins
Python 3.11+

Why 2023.7+? The panel uses return_response on service calls (introduced in HA 2023.7). All other features work on 2023.1+.


๐Ÿ“‹ Changelog

v1.0.0 โ€” Initial Release

  • ๐Ÿ” Smart entity scanner with risk levels and health score
  • ๐Ÿ—‘๏ธ Soft delete + restore + auto-expiry trash bin tab
  • ๐Ÿ“ก Fingerprint anomaly detection (ฯƒ / IQR, 30-day baseline)
  • ๐Ÿ—„๏ธ Recorder DB analyzer with YAML suggestions
  • ๐Ÿ“Š Lovelace dashboard auditor
  • ๐ŸŒฉ๏ธ State storm detector
  • ๐Ÿค– Automation dead code analyzer
  • ๐Ÿ”Œ Integration health scorer with reconnect analysis
  • ๐Ÿงฉ Add-on manager with live CPU/RAM per add-on (5s auto-refresh)
  • ๐Ÿ–ฅ๏ธ Real-time system gauges (CPU / RAM / Disk) โ€” always visible
  • ๐ŸŽจ 11 built-in themes, saved per session
  • ๐ŸŒ 12 UI languages, fully translated
  • โš™๏ธ Full UI config flow with options
  • ๐Ÿ” No Long-Lived Access Token required โ€” panel authenticates via HA WebSocket session

๐Ÿ“„ License

MIT License โ€” free to use, modify, and distribute. If you find this useful, please โญ star the repo โ€” it helps a lot!


๐Ÿ™ Credits

Designed and developed by @doanlong1412 from ๐Ÿ‡ป๐Ÿ‡ณ Vietnam.


โ˜• Support

If HA Optimizer saves you time and keeps your Home Assistant clean, consider buying me a coffee!

PayPal

Every contribution is greatly appreciated and motivates further development. Thank you! ๐Ÿ™