Skip to content

Latest commit

ย 

History

62 Commits

Folders and files

NameName
Last commit message
Last commit date
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

PC User Statistics

Version Home Assistant Quality Scale License

A Home Assistant custom integration for tracking gaming PC usage statistics per user. Monitor power consumption, session time, and electricity costs โ€” with a full custom sidebar panel, historical graphs, push notifications, and more.


๐Ÿ“‹ Features

โœ… What It Does

  • Multi-User Tracking: Individual statistics per user, configurable via UI
  • Live Session Monitoring: Real-time power (watt gauge), time, cost, and live kr/time tracking
  • Cost Breakdown Views: Average kr/time per user (Statistik tab) and kr/kWh comparison over time (Historik tab) โ€” see whether a costly day comes from more playtime or a pricier electricity rate
  • Robust Price Handling: Falls back to the last known valid electricity price if the price sensor is temporarily unavailable, instead of silently counting that period as free โ€” with an Admin tab health indicator showing fallback status
  • Monthly Summaries: Automated monthly statistics per user
  • Historical Graphs: Daily bar charts for the last 30 days per metric (time / energy / cost / kr-per-kWh)
  • Leaderboard: Monthly ranking with ๐Ÿฅ‡๐Ÿฅˆ๐Ÿฅ‰ medals
  • Push Notifications: Configurable rules with test and repeat support
  • InfluxDB Integration: Long-term data storage for historical analysis
  • Custom Sidebar Panel: Full-featured UI built directly into Home Assistant
  • Dark/Light Theme: Automatically follows your HA theme
  • Multi-Language Support: English and Danish translations included

๐Ÿ“Š Tracked Metrics

Metric Unit Description
Session Time seconds Active PC usage time for current session
Session Energy kWh Power consumption for current session
Session Cost DKK Electricity cost for current session
Monthly Time seconds Total usage time for current month
Monthly Energy kWh Total power consumption for current month
Monthly Cost DKK Total electricity cost for current month

๐Ÿš€ Installation

Prerequisites

  • Home Assistant: 2024.1 or newer
  • InfluxDB: Running and accessible (v1.x)
  • Required Sensors:
    • User login sensor (returns current username as state)
    • Power consumption sensor (PC wattage in W)
    • Energy price sensor (DKK per kWh)
    • (Optional) Device self-consumption sensor (only needed for plugs that expose it separately)

Manual Installation

  1. Copy the custom_components/pc_user_statistics/ folder to your HA /config/custom_components/ directory
  2. Restart Home Assistant
  3. Go to Settings โ†’ Devices & Services โ†’ + Add Integration
  4. Search for PC User Statistics
  5. Enter your InfluxDB connection details

HACS (Coming Soon)

HACS submission pending


โš™๏ธ Configuration

Initial Setup (Config Flow)

Field Example Description
Host a0d7b954-influxdb InfluxDB hostname or IP
Port 8086 InfluxDB port
Database homeassistant Database name
Username homeassistant InfluxDB username
Password โ€ขโ€ขโ€ขโ€ขโ€ขโ€ขโ€ขโ€ข InfluxDB password

The integration will verify the InfluxDB connection, confirm the database exists, load existing monthly data, and start tracking immediately.

Sensor & User Configuration (Panel UI)

After setup, open the ๐Ÿ”ง Konfiguration tab in the sidebar panel to:

  • Edit all 4 sensor entity IDs without touching any files
  • Add, edit, or remove user mappings (sensor state โ†’ user ID)
  • Reorder sidebar tabs via drag-and-drop

Changes are saved instantly and trigger an automatic integration reload.


๐Ÿ–ฅ๏ธ Sidebar Panel

The integration adds a ๐ŸŽฎ PC Statistik entry to your HA sidebar with 6 tabs:

๐Ÿ“Š Statistik

  • Live session cards (tid, energi, pris)
  • Donut-diagram med mรฅnedlig fordeling per bruger
  • Mรฅnedlige totalkort per bruger
  • ๐Ÿ† Leaderboard med guld/sรธlv/bronze ranking

๐Ÿ‘ค Brugere

  • Aktiv bruger med LIVE-badge
  • Oversigt over alle konfigurerede brugere og sensor-mappings

๐Ÿ”” Notifikationer

  • Konfigurer modtagerenheder (HA Companion app)
  • 4 premade regler klar til brug:
    • โฑ๏ธ Pausepรฅmindelse โ€” gentages hvert 60 min
    • ๐ŸŒ™ Lang session โ€” advarsel efter 3 timer
    • ๐Ÿ’ฐ Prisgrรฆnse โ€” notifikation ved 10 kr
    • ๐ŸŒ… PC glemt tรฆndt โ€” gentages hvert 30 min ved inaktivitet
  • Opret egne regler med valgfri trigger, besked og repeat-interval
  • Test-knap sender รธjeblikkelig push

๐Ÿ“ˆ Historik

  • SVG sรธjlediagram โ€” daglige totaler de seneste 30 dage
  • Skift mellem Tid / Energi / Pris
  • 7-dages tabel med mini-sรธjler per bruger

๐Ÿ”ง Konfiguration

  • Rediger sensor entity IDs
  • Administrer bruger-mappings
  • Omarranger tabs via drag-and-drop

โš™๏ธ Admin

  • System-info og version
  • InfluxDB write buffer status
  • Bruger-mappings oversigt

๐Ÿ”Œ Supported Devices

Smart Power Plug

The integration requires a smart plug with power monitoring. The plug's watt sensor is read every 60 seconds to track energy consumption and cost.

โœ… TP-Link Kasa HS110 (tested)

Hardware version 1.0
Firmware version 1.2.6
HA integration TP-Link Smart Home (built-in)
Local control Yes โ€” no cloud account required
HA polling Every 5 seconds

The HS110 exposes a current_consumption sensor (W) that is used directly for watt tracking. It does not expose a separate device self-consumption sensor โ€” the "Plug self-power" field in the configuration should be left empty when using HS110.

โš ๏ธ Do not update HS110 firmware. Firmware version 1.1.0 on certain hardware revisions broke local Home Assistant access. Version 1.2.6 on HW 1.0 is stable.

Entity IDs created by HS110 (example device name gamer_pc_power_monitor):

Sensor Entity ID Unit
Current power sensor.gamer_pc_power_monitor_current_consumption W
Total energy sensor.gamer_pc_power_monitor_total_consumption kWh

Other compatible plugs

Any smart plug that exposes a watt (W) sensor in Home Assistant will work. The "Plug self-power" field is optional and only relevant for plugs that report their own power draw separately (e.g. Shelly Plug S/Plus).


User Login Sensor (HASS.Agent)

HASS.Agent runs on the Windows gaming PC and reports the currently logged-in Windows username as a HA sensor state.

Platform Windows only
Sensor type Logged In Users / Windows User
State example Konge, Lukas, Sebas
Entity example sensor.flemming_gamer_satellite_loggeduser

The sensor state is matched to a user ID via the mappings configured in the ๐Ÿ”ง Konfiguration tab.


Electricity Price Sensor

Any sensor returning a float value in DKK per kWh is supported. For Danish users, Energi Data Service (available via HACS) provides real-time spot prices including tariffs.


๐Ÿ”Œ Device Structure

Statistics Hub

  • sensor.statistics_hub_current_user
  • sensor.statistics_hub_current_session_time
  • sensor.statistics_hub_current_session_energy
  • sensor.statistics_hub_current_session_cost

Per-User Devices (e.g. Statistics Flemming)

  • sensor.statistics_flemming_monthly_time
  • sensor.statistics_flemming_monthly_energy
  • sensor.statistics_flemming_monthly_cost

(Same pattern for each configured user)


๐Ÿ“ˆ InfluxDB Data Structure

Measurement: pc_usage
Write frequency: Every 60 seconds (when user is active)

Field Type Description
power float Current power in watts
time_delta float Seconds since last write
energy_delta float kWh since last write
cost_delta float DKK since last write

Tags: user (string)

-- Total energy per user this month
SELECT SUM("energy_delta") AS "total_energy"
FROM "pc_usage"
WHERE time >= now() - 30d
GROUP BY "user"

๐Ÿ”„ Data Update Strategy

The integration uses a DataUpdateCoordinator with a 60-second polling interval.

Event What happens
State change (user/power sensor) async_track_state_change_event triggers immediately
Every 60 seconds Coordinator polls, calculates deltas, writes to InfluxDB
HA startup Monthly totals loaded from InfluxDB with exponential backoff (30s / 60s / 120s)
InfluxDB write failure Point buffered (FIFO, max 100) and retried next poll
5+ consecutive failures RepairIssue raised in HA UI โ€” visible under Settings โ†’ Repairs

Deltas (time, energy, cost) are only written to InfluxDB when a user is actively logged in and the power sensor reports a positive value.

Price Sensor Fallback

If the configured electricity price sensor becomes temporarily unavailable or unknown (common with forecast-based price sensors around midnight rollovers or brief integration reloads), the integration no longer treats that period as free electricity. Instead, it falls back to the last known valid price:

Situation Behavior
Price sensor reports normally Used directly, cached as "last known valid price"
Price sensor unavailable/unknown/unparsable Falls back to the last known valid price instead of 0.0 DKK/kWh
No valid price has ever been read (e.g. right after HA startup) Falls back to 0.0 DKK/kWh until the sensor reports

Fallback usage is counted per month and visible as a health metric ("Prissensor") on the โš™๏ธ Admin tab, and a rate-limited warning (at most once per 5 minutes) is logged so a prolonged sensor outage is discoverable instead of silent. The fallback cache also survives a Home Assistant restart (persisted in the session snapshot, discarded if older than 6 hours).

Monthly Totals Baseline Protection

Every coordinator restart (a full Home Assistant restart, or an integration reload triggered by any configuration save) re-fetches the current month's totals from InfluxDB via a SUM() query. If InfluxDB happened to be missing recent writes at that exact moment โ€” for example because they were still sitting in the write-retry buffer during an outage โ€” the fresh sum could come back lower than what had already been tracked and displayed, silently erasing real time/energy/cost from view.

The integration now protects against this with a persisted baseline: monthly totals are saved to the config store every 60 seconds, after every successful InfluxDB load, and on shutdown. On the next load, InfluxDB's sum is only ever allowed to raise the total, never lower it โ€” and if InfluxDB is completely unreachable after 3 retries, the integration falls back to the last known baseline instead of resetting to 0. The baseline is correctly cleared at the start of a new month.

If you notice monthly totals that seem lower than expected, check the ๐Ÿ“ˆ Historik tab's daily breakdown against another independent source (e.g. Microsoft Family Safety screen time, if configured) โ€” the โš™๏ธ Admin tab's "Manuel korrektion" form can be used to add a one-off correction for a specific date if a gap is confirmed.

Daily Totals & Local Timezone

Alongside the monthly tracker, the integration also maintains a daily ("today") total per user โ€” a full parallel to the monthly tracker with the same InfluxDB-load, baseline-floor protection, and periodic persistence. This powers a fair "today vs. today" comparison against Microsoft Family Safety's screen time on the ๐Ÿ“Š Statistik tab (previously this compared MS's daily figure against the PC's whole-month total by mistake).

Both the monthly and daily rollover, and the InfluxDB query windows behind them, are computed in Europe/Copenhagen local time rather than UTC โ€” using UTC directly would shift the rollover moment by up to 2 hours during CEST (summer time).


โš ๏ธ Known Limitations

  • InfluxDB v1.x only โ€” InfluxDB v2.x / v3.x is not supported
  • Single PC โ€” one integration instance tracks one PC; multi-PC requires multiple config entries (planned for v3.0.0)
  • DKK currency โ€” electricity cost is calculated in Danish Krone (DKK); other currencies require a matching energy price sensor
  • No historical import โ€” data tracking starts from the moment the integration is installed; existing InfluxDB data from other sources is not imported
  • HA Companion app required for push notifications โ€” standard HA notify services are not supported in the notification UI

๐Ÿ› ๏ธ Troubleshooting

Sensors show "Unavailable"

Check that all required sensors exist and are working. Verify entity IDs in the ๐Ÿ”ง Konfiguration panel tab, or check HA logs filtered by pc_user_statistics.

Monthly data not loading

Verify InfluxDB is running and accessible. Check that the pc_usage measurement exists. Reload the integration: Settings โ†’ Devices & Services โ†’ PC User Statistics โ†’ โ‹ฎ โ†’ Reload

No push notifications received

  1. Install the Home Assistant Companion app on your phone
  2. Open the ๐Ÿ”” Notifikationer tab and select your device
  3. Enable at least one rule and use the ๐Ÿ“จ Test button to verify

Negative or incorrect power values

Expected when PC is idle โ€” the integration clamps negative values to 0.

Panel not appearing in sidebar

Restart Home Assistant fully (not just reload). If the panel JS file was updated, clear your browser cache.

Tablet card looks cramped or clipped on a phone screen

pc-user-statistics-tablet-card (v2.6.12+) auto-detects a narrow host width (<700px) and switches from its two-column tablet layout to a single stacked column. If you're on an older cards.js version, either update to 2.6.12+, or use pc-user-statistics-user-card (one card per user) on mobile dashboards instead โ€” it's designed for narrow widths from the start.


๐Ÿ”„ Migration from 1.x

  1. Backup any automations/dashboards using old entity IDs
  2. Delete old integration (Settings โ†’ Devices & Services โ†’ Spille PC Statistik โ†’ Delete)
  3. Install new integration and configure with your InfluxDB details
  4. Update entity ID references (see CHANGELOG.md)

Your historical data in InfluxDB is not affected.


๐Ÿ“ License

MIT License โ€” see LICENSE for details.


๐Ÿ™ Acknowledgments

  • Home Assistant community for integration guidelines
  • InfluxDB for time-series data storage

๐Ÿ“ž Support


Made with โค๏ธ for the Home Assistant community

About

No description, website, or topics provided.

Resources

Contributing

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages