中文 English

Never Open the Utility App Again: The Complete Beginner's Guide to Integrating State Grid into Home Assistant (Zero-Loss Restarts & Automated Alerts)

Published: 2026-10-28 · Views --
homeassistant HA Smart Home 网上国网 SGCC 电费 电力监测 新手教程 Beginner Automation Automation Troubleshooting Troubleshooting

Anyone managing a smart home has experienced the same anxiety: during scorching summer heatwaves or freezing winter nights, heaters and air conditioners run around the clock, leaving you wondering how much electricity was consumed yesterday and whether your prepaid balance is about to run out.

Historically, the only option was tedious: open a sluggish commercial utility app on your smartphone, sit through splash screens and slow loading spinners, and manually check an isolated balance figure. Worse, if an unexpected zero-balance blackout occurs in the middle of the night, refrigerators shut down and expensive perishables spoil before anyone notices.

The true value of a smart home is not shifting physical remotes into smartphone screens; it is making essential household indicators work autonomously for your family. Having yesterday’s kilowatt-hours, real-time prepaid balance, and monthly comparisons visible on a wall-mounted dashboard—or receiving an automated gentle voice alert from smart speakers and instant notifications via mobile apps whenever balance drops below 50 CNY—is where practical home automation truly shines.

This guide provides a step-by-step, zero-confusion walkthrough designed specifically for Home Assistant beginners. Whether you have just set up your first Home Assistant server or have struggled in the past with disappearing entities after system reboots, following this tutorial will get your State Grid integration running reliably in 15 minutes with permanent persistence safeguards.

Original hero cover: Complete beginner workflow for State Grid into Home Assistant

Figure 1. Original illustration. An end-to-end overview showing fast installation, pitfall mitigation, and home automation delivery.


The Three Core Roles: How Data Actually Reaches Your Dashboard

Before opening terminal windows or editing configuration files, let us spend two minutes breaking down the data pipeline using an analogy that any elementary school student can immediately grasp.

A common misconception among beginners is imagining that the smart electricity meter in the hallway is broadcasting real-time wireless numbers directly into Home Assistant. In reality, the integration consists of three distinct, cooperative roles:

Architecture diagram: State Grid utility, collector add-on, and Home Assistant

Figure 2. Elementary school analogy. The utility central ledger, the background courier add-on, and Home Assistant the household butler.

  1. Role 1: State Grid (The Utility Central Ledger) Your smart meter transmits electricity pulses over powerline carrier or cellular utility networks to the provincial power company. Every morning at midnight, utility mainframes batch-process millions of household meters, calculating yesterday’s daily kilowatt-hours and updated balance. This ledger lives entirely in the utility cloud and provides no direct local LAN interfaces.

  2. Role 2: The SGCC Collector Add-on (The Scheduled Courier) To bring cloud records into your local home, the open-source community created dedicated add-ons (such as ARC-MX/sgcc_electricity_new). It acts like a punctual courier: every morning at a scheduled time (e.g., 07:00), it logs into the utility portal, solves the graphical CAPTCHA, pulls your meter statements, and delivers the readings to your doorstep.

  3. Role 3: Home Assistant (The Household Smart Butler) When the courier arrives, it hands the numbers to Home Assistant through the REST API. Your smart butler receives the data, updates high-visibility Lovelace dashboard cards, and triggers speaker announcements if the balance is low.

Understanding this division of labor makes troubleshooting instant: if login fails, check the courier; if tiles turn red after a reboot, configure the butler; if today’s reading shows yesterday’s date, that is simply the utility’s overnight batching schedule.

Real screenshot: Household power dashboard showing balance and recent history

Figure 3. Actual Home Assistant dashboard crop. With proper persistence mirrors, electricity balance, daily usage, and billing history remain stable across reboots (account numbers and private readings masked).


Pre-Flight Checklist: Everything You Need Before Installation

Before configuring software, ensure you have the following four prerequisites ready:

  1. Utility Account & Customer Number Verification: Download the official State Grid app on your smartphone and ensure your 10-digit utility customer account number is linked. Perform a manual query inside the app to verify you can see the account name, balance, and previous daily usage.

    [!NOTE] This guide applies to State Grid operating provinces (North, East, Central, Northeast, and Northwest China). Southern Power Grid provinces (Guangdong, Guangxi, Yunnan, Guizhou, Hainan) require different provider integrations.

  2. Home Assistant Environment Identification:

    • HA OS / Supervised (Recommended for beginners): Features the native Add-on Store with visual one-click installation;
    • HA Container / Docker: Requires deploying a standalone collector container via Docker Compose; the underlying data structures remain identical.
  3. Long-Lived Access Token Creation:

    • In the Home Assistant web interface, click your profile icon in the lower-left corner;
    • Scroll to the bottom to the “Long-Lived Access Tokens” section and click “Create Token”;
    • Name it “SGCC-Collector”, copy the generated token string, and save it securely in a text editor (it will only be displayed once). This serves as the courier’s key to deliver states to HA.
  4. Vision API for CAPTCHA Solving (Crucial Pitfall!): Utility login requires passing an icon-click or slider challenge. The add-on supports OpenAI-compatible Vision APIs. You can utilize existing multimodal endpoints (such as budget-friendly commercial vision models or self-hosted local vision models).


Step-by-Step Walkthrough: Installing the Collector Add-on

Step 1: Add the Gitee Repository Mirror

Due to international routing constraints, reaching GitHub directly from home networks in mainland China often suffers from connection drops and timeouts.

Community developers maintain a complete mirror repository on Gitee for fast local deployment:

  1. In Home Assistant, navigate to Settings → Add-ons;
  2. Click the Add-on Store button in the lower-right corner;
  3. Click the Three Dots menu in the upper-right corner and select Repositories;
  4. Paste the Gitee mirror URL into the dialog and click Add: https://gitee.com/ARC-MX/sgcc_electricity_new
  5. Close the dialog and refresh the page. Scroll to the bottom of the Add-on Store to locate “SGCC Electricity”. Click it and select Install (typically finishes in under 10 seconds).

Step 2: Configure Add-on Parameters

After installation, do not start the add-on immediately. Switch to the Configuration tab and fill in the required fields:

Real screenshot: Upstream repository caching and scheduled collection code

Figure 4. Upstream source screenshot showing republish() cache logic, which eliminates excessive logins while keeping sensor states fresh.


The 50-Token Trap: Why Reasoning Models Fail at CAPTCHAs

This is the number-one pitfall where over 90% of newcomers hit an unexpected wall.

Attempting to achieve maximum accuracy, beginners frequently configure top-tier reasoning models (such as deep thinking models). The add-on log immediately erupts with repeated errors: Captcha recognition failed, response is empty!

Analogy diagram: 50-token CAPTCHA budget trap vs fast vision models

Figure 5. Original architectural breakdown of the 50-token output limit and optimal model selection.

The underlying root cause is simple: Inside the add-on source code handling icon-click challenges, the author hardcoded an exceptionally tight constraint: max_tokens: 50 to prevent runaway token costs.

Consider an everyday classroom analogy: The teacher asks: “Where is the red apple on the blackboard? Give me just the coordinate numbers.”

[!IMPORTANT] Model Selection Rule: Always select lightweight, fast, direct vision models without extended reasoning chains. Never use thinking-first reasoning models for rapid 50-token CAPTCHA challenges.


Four Common Traps Every Beginner Should Avoid

Once the add-on starts and logs display Login success and Push state success, the courier has completed its delivery.

However, beginners often encounter four classic points of confusion:

Trap 1: Why Can’t I See “Today’s” Electricity Usage Yet?

The most frequent beginner question: “I ran the air conditioning all day today. Why is today’s usage empty in Home Assistant?”

Three dates analogy: Ordering, shipping, and delivery vs utility billing delay

Figure 6. Original parcel delivery analogy. Separating energy consumption date, utility billing date, and arrival date.

Remember the three dates of parcel delivery:

You cannot claim an item was purchased on Wednesday simply because it was delivered on Wednesday. State Grid daily metrics have a natural T+1 or T+2 delay. What appears on your dashboard this morning represents the complete 24 hours of yesterday (or the day before). Waiting for billing publication is normal utility behavior, not a broken integration.

Trap 2: Never Confuse Real-Time Power (W) with Energy (kWh)

State Grid reports billed energy; if you need instantaneous household wattage, install a dedicated smart power monitor at the distribution panel.

Trap 3: Do Not Blindly Add total_increasing to Daily Usage

Home Assistant’s Energy dashboard requires monitored sensors to declare state_class: total_increasing.

Beginners often think: “Can I just tag daily usage as total_increasing so it appears on the Energy board?” Never do this! The total_increasing class tells Home Assistant that numbers only ever rise. Daily usage is a daily slice: 12 kWh Monday, 5 kWh Tuesday, 8 kWh Wednesday. When the value drops from 12 to 5, Home Assistant assumes the meter was reset or replaced, causing massive negative spikes in statistical databases.

Trap 4: Multiple Account Suffix Clashes

When managing multiple apartments, the add-on appends the last four digits of each account number (e.g., _0310 and _1720). When copying dashboard examples, remember to match your own entity suffix.


The Disappearing Entity Bug: Why Do Cards Turn Red on Reboot?

You spend hours assembling a pristine dashboard. Then, after restarting Home Assistant Core to apply another update, disaster strikes: Your electricity balance, monthly cost, and yearly totals turn into bright red “Entity Not Found” boxes!

Analogy diagram: Classroom blackboard chalk vs student hardcover notebook

Figure 7. Blackboard vs notebook analogy. Revealing why in-memory REST states vanish upon restart and how template mirrors restore them.

Root Cause: Blackboard Chalk vs The Student Notebook

Reviewing Home Assistant’s architecture documentation reveals the core mechanism:

Real screenshot: Home Assistant REST API documentation on state lifespan

Figure 8. Official documentation crop. The POST /api/states/<entity_id> endpoint only creates temporary in-memory runtime states and does not register persistent entities.

When the collector delivers data, it calls Home Assistant’s POST /api/states/<entity_id> endpoint. This is like a messenger walking into a classroom and writing “Balance: 128.5 CNY” with chalk on the blackboard. While class is in session, everyone sees it clearly.

However, when you restart Home Assistant Core, the janitor wipes the blackboard completely clean! Because REST-injected states exist only in runtime memory, the system does not know how to recreate them upon reboot. You are forced to wait up to 60 minutes for the add-on’s next scheduled refresh. During that 60-minute gap, your dashboard displays “Entity Not Found”.

The Fix: Official Trigger-Based Template Mirrors

The permanent cure is giving your smart butler a hardcover personal notebook:

Real screenshot: Home Assistant documentation on trigger-based template restoration

Figure 9. Official documentation confirmation. Trigger-based template entities automatically persist states and attributes to disk and restore them after restarts.

In Home Assistant, Trigger-based Template Sensors possess a vital property: their states serialize to disk. When Core restarts, the system restores the last known value immediately.

The core YAML logic is straightforward:

template:
  - triggers:
      - trigger: state
        entity_id: sensor.electricity_charge_balance_xxxx
    sensor:
      - name: "SGCC Mirror Balance"
        unique_id: sgcc_mirror_balance_xxxx
        unit_of_measurement: "CNY"
        device_class: monetary
        state: >-
          {% set v = states('sensor.electricity_charge_balance_xxxx') %}
          {{ v if is_number(v) else this.state }}

The final line {{ v if is_number(v) else this.state }} provides the fail-safe:


Lovelace Dashboard & Automated Low-Balance Alerts

Clean Dashboard Card Configuration

Once persistent mirror entities are active, configure an elegant overview card in your Lovelace dashboard:

type: vertical-stack
title: ⚡ Household Electricity Monitor
cards:
  - type: glance
    show_name: true
    show_icon: true
    show_state: true
    entities:
      - entity: sensor.sgcc_mirror_balance_xxxx
        name: Balance
        icon: mdi:wallet-outline
      - entity: sensor.sgcc_mirror_daily_xxxx
        name: Yesterday Usage
        icon: mdi:lightning-bolt-circle
      - entity: sensor.sgcc_mirror_month_charge_xxxx
        name: Last Month Bill
        icon: mdi:receipt-text-outline
  - type: entities
    title: 📊 Yearly Totals & Accounting
    entities:
      - entity: sensor.sgcc_mirror_year_usage_xxxx
        name: Year-to-Date Energy
      - entity: sensor.sgcc_mirror_year_charge_xxxx
        name: Year-to-Date Cost
      - type: attribute
        entity: sensor.sgcc_mirror_daily_xxxx
        attribute: data_date
        name: Accounting Date

Real screenshot: Long-term statistics chart showing monthly usage and cost

Figure 10. Real statistics graph. Monthly consumption bars and billing totals clearly visualized.


Real-World Automation: Low-Balance Voice and Push Alerts

Set up an automated trigger whenever your electricity balance drops below 50 CNY:

automation:
  - id: alert_power_balance_low
    alias: "Alert: Electricity Balance Below 50 CNY"
    trigger:
      - trigger: numeric_state
        entity_id: sensor.sgcc_mirror_balance_xxxx
        below: 50.00
    condition:
      - condition: template
        value_template: "{{ trigger.from_state.state not in ['unknown', 'unavailable'] }}"
    action:
      # Push notification to smartphones
      - action: notify.notify
        data:
          title: "⚠️ Low Electricity Balance Alert"
          message: "Prepaid electricity balance is down to {{ states('sensor.sgcc_mirror_balance_xxxx') }} CNY. Please recharge via the State Grid app."
      # Daytime voice broadcast via smart speakers (suppressed at night)
      - condition: time
        after: "08:00:00"
        before: "21:00:00"
      - action: tts.speak
        target:
          entity_id: media_player.living_room_speaker
        data:
          media_player_entity_id: media_player.living_room_speaker
          message: "Reminder: Household electricity balance is below 50 CNY. Please recharge today."

Notice the condition trigger.from_state.state not in [‘unknown’, ‘unavailable’]: it prevents false alarms during initial boot, triggering only when a genuine reading crosses the 50 CNY threshold.


Cross-Platform Automation Toolkit: Zero Manual YAML Editing

To simplify setup, the complete persistence generator, configuration validator, and safe rollback workflow are packaged in an open-source, zero-dependency toolkit:

Architecture diagram: Automation pipeline covering probe, backup, injection, and rollback

Figure 11. Original automation pipeline. Environment probe, snapshot backup, template injection, REST syntax validation, and instant recovery.

Toolkit Download: SGCC Beginner Toolkit Archive (ZIP).

Design Principles


Workflow 1: Manual One-Click Execution

Windows 11 (PowerShell 7 / Windows PowerShell)

# 1. Unpack archive and copy mapping template
Copy-Item mapping.example.json mapping.local.json
# Edit mapping.local.json with your sensor IDs

# 2. Set temporary session variables (destroyed on window close)
$env:HOME_ASSISTANT_URL = "http://homeassistant.local:8123"
$env:HOME_ASSISTANT_TOKEN = "your_long_lived_token"
$env:HA_CONFIG_DIR = "Z:\config"  # Network mounted HA config directory

# 3. Three steps: preview -> check -> apply
.\windows-11.ps1 plan      # Read-only preview of generated YAML
.\windows-11.ps1 check     # Verify connectivity and sensor presence
.\windows-11.ps1 apply --restart  # Backup, write config, validate, and restart

Ubuntu 26.04 LTS (Bash)

# 1. Configure mapping and environment
cp mapping.example.json mapping.local.json
export HOME_ASSISTANT_URL="http://homeassistant.local:8123"
export HOME_ASSISTANT_TOKEN="your_long_lived_token"
export HA_CONFIG_DIR="/mnt/homeassistant_config"

# 2. Generate and apply
bash ubuntu-26.04.sh plan
bash ubuntu-26.04.sh check
bash ubuntu-26.04.sh apply --restart

macOS 27 (Zsh)

# 1. Configure mapping and environment
cp mapping.example.json mapping.local.json
export HOME_ASSISTANT_URL="http://homeassistant.local:8123"
export HOME_ASSISTANT_TOKEN="your_long_lived_token"
export HA_CONFIG_DIR="/Volumes/config"

# 2. Check and apply
bash macos-27.sh plan
bash macos-27.sh check
bash macos-27.sh apply --restart

Workflow 2: Delegating to an AI Operations Agent

If you utilize an autonomous coding or DevOps agent, delegate the deployment with this prompt:

You are my Home Assistant automation specialist.
Transform the collected State Grid entities into high-availability persistent mirrors:

1. Inspect existing collector entities, identify customer account suffixes, and read current states;
2. Download and unpack sgcc-beginner-toolkit, generating mapping.local.json;
3. Run `plan` to inspect the generated packages/sgcc_electricity.yaml template;
4. Ensure a full timestamped backup is captured before touching native configuration;
5. Validate configuration syntax via HA Core's /api/config/core/check_config API;
6. Only if status is valid, apply changes and reload templates;
7. Verify all 6 mirror entities accept current readings with `this.state` fallback protection;
8. Never echo access tokens or passwords to the console.

Frequently Asked Questions (FAQ)

Q1: Why does State Grid report “Daily Login Limit Exceeded”?

The utility portal enforces strict rate limits on failed authentication attempts.

Q2: I see a negative balance on my card. Is that an error?

In many billing regions, negative numbers represent pending charges or automated direct-debit draws. The toolkit supports negative monetary values; never filter balances with “greater than zero”, or negative balances will turn into missing entities.

Q3: Why can’t I add electricity costs to the official Energy dashboard?

Real screenshot: Official documentation on long-term statistics format and monetary rules

Figure 12. Official documentation screenshot. Long-term statistics require strict adherence to sensor types, measurement units, and state classes.

The Energy dashboard enforces strict rules:

Q4: Is this method secure against household intrusion?

Completely secure:


References & Acknowledgments

Home Assistant logos and naming are trademarks of the Open Home Foundation. All diagrams are original vector assets, and UI screenshots reflect real operating environments with opaque masking applied to private accounts, local IPs, and monetary figures.

Comments

Sign in with GitHub to comment. Chinese and English versions share the same discussion. Discuss on GitHub

Views --