Skip to content

TiM00R/ThermostatPublicServer

Repository files navigation

Thermostat Public Server

Cloud-based monitoring and control system for RadioThermostat CT50 WiFi thermostats

Python 3.10+ FastAPI PostgreSQL



System Overview

Complete two-part system for managing RadioThermostat devices across multiple locations:

What You Need to Deploy

  1. Local Server (at each property)

    • Hardware: Raspberry Pi or any Linux device
    • Purpose: Polls thermostats on local network every 30 seconds
    • Repository: ThermostatLocalServer
    • One local server per physical location
  2. Public Server (cloud-hosted - this repository)

    • Hardware: AWS Lightsail, DigitalOcean, or any cloud server
    • Purpose: Aggregates data from all local servers, provides web dashboard
    • Repository: This repository (ThermostatPublicServer)
    • One public server for all locations

How It Works

Simple 3-Step Process:

How It Works

Simple 3-Step Process:

STEP 1: At Your Property          STEP 2: Cloud Server              STEP 3: Access Anywhere
┌─────────────────────┐           ┌──────────────────────┐          ┌─────────────────────┐
│   Your Home WiFi    │           │   Public Server      │          │   Web Browser       │
│                     │           │   (This Repo)        │          │   (Phone/Laptop)    │
│  [Thermostat 1]     │           │                      │          │                     │
│  [Thermostat 2]     │  HTTPS    │  ┌────────────────┐  │ HTTPS/   │  • View temps       │
│  [Thermostat 3]     │◄─────────►│  │   PostgreSQL   │  │  WSS     │  • Control stats    │
│         ↕           │           │  │    Database    │  │◄────────►│  • View graphs      │
│  [Local Server]     │           │  └────────────────┘  │          │  • Set schedules    │
│  (Raspberry Pi)     │           │                      │          │                     │
│                     │           │  ┌────────────────┐  │          │                     │
│  • Polls every 30s  │           │  │  Web Dashboard │  │          │                     │
│  • Sends to cloud   │           │  └────────────────┘  │          │                     │
└─────────────────────┘           └──────────────────────┘          └─────────────────────┘

Data Flow:

  1. Local Server (Raspberry Pi at your home) polls thermostats every 30 seconds
  2. Local Server sends data to Public Server (cloud) via HTTPS REST API
  3. Public Server stores data in PostgreSQL database
  4. You access web dashboard from anywhere via HTTPS (initial load) and WSS (real-time updates)
  5. Commands flow backwards: You → Public Server → Local Server → Thermostat

Data Flow:

  1. Local Server (Raspberry Pi at your home) polls thermostats every 30 seconds
  2. Local Server sends data to Public Server (cloud) via HTTPS
  3. Public Server stores data in PostgreSQL database
  4. You access web dashboard from anywhere (phone, laptop, tablet)
  5. Commands flow backwards: You → Public Server → Local Server → Thermostat

Data Flow:

  1. Local Server discovers and polls thermostats on your local network (every 30 seconds)
  2. Local Server sends data to Public Server via HTTPS
  3. Public Server stores data in PostgreSQL database
  4. You access web dashboard from anywhere to monitor and control

Deployment Requirements:

  • 1× Public Server (cloud) - Deploy this repository
  • 1× Local Server per property (Raspberry Pi) - Deploy ThermostatLocalServer
  • Domain name for HTTPS access (optional but recommended)

What Is This Project?

ThermostatPublicServer is a complete cloud-based monitoring and control system for RadioThermostat CT50 WiFi thermostats (also known as 3M-50, RTCOA CT50, Filtrete 3M-50, Radio Thermostat Company of America CT50).

The Problem

RadioThermostat CT50 was one of the first WiFi thermostats with an open API, introduced around 2012. On May 15, 2023, the company discontinued cloud support, effectively converting these smart WiFi thermostats into basic local-only devices with no remote access or historical data tracking.

For users with multiple thermostats across different locations, this created significant challenges:

  • ❌ No remote monitoring or control
  • ❌ No historical data collection
  • ❌ No efficiency analysis across locations
  • ❌ No centralized management dashboard

Why Existing Solutions Don't Work

Modern smart thermostats (Nest, Ecobee, Honeywell) have cloud services, but they fail to provide:

  1. Quality Historical Data - Most services provide only basic daily summaries
  2. High-Resolution Metrics - Minute-level temperature, setpoint, and runtime data
  3. Multi-Location Management - Centralized control across multiple properties
  4. HVAC Runtime Tracking - Actual time heating/cooling system was running
  5. Outside Temperature Correlation - Local weather data alongside indoor conditions

Why This Data Matters

Quality historical data enables:

  • Efficiency Analysis - Understand how long it takes to heat/cool your space
  • Predictive Control - Know how far in advance to adjust setpoints for desired arrival temperature
  • Cost Prediction - Correlate setpoint changes with utility bills
  • System Health - Detect failing equipment through runtime pattern changes
  • Seasonal Trends - Compare heating/cooling efficiency year-over-year

High-resolution data over entire seasons (not just daily summaries) is crucial for meaningful analysis.

The Solution

This project provides:

  • Remote Access - Control thermostats from anywhere via web dashboard
  • Multi-Site Management - Manage 20+ thermostats across multiple properties
  • High-Resolution History - Minute-level data: temperature, setpoint, runtime, weather
  • HVAC Runtime Tracking - Precise measurement of heating/cooling system operation
  • Real-Time Monitoring - WebSocket-based live updates
  • Open Source - Self-hosted on your infrastructure, no vendor lock-in
  • REST API - Open API for integration with other systems

Web Dashboard Screenshots

Login Screen

Login Screen

Secure authentication with JWT token-based login. Default credentials can be changed after first login.


Site Overview

Site Overview

Multi-thermostat view showing all thermostats at a location:

  • Current temperature and setpoint for each thermostat
  • HVAC mode and state (heating/cooling/off)
  • Real-time status updates via WebSocket
  • Quick controls for each device
  • Away temperature management

Thermostat Details

Thermostat Details

Individual thermostat control and monitoring:

  • Current temperature, setpoint, and outside temperature
  • HVAC mode selection (Heat/Cool/Off)
  • Setpoint adjustment controls
  • Hold mode toggle
  • Real-time status indicator
  • Historical data access

Historical Analysis & HVAC Runtime

Historical Graphs

HVAC runtime visualization with efficiency metrics:

Temperature Line Charts:

  • Blue line: Indoor temperature over time
  • Orange line: Temperature setpoint
  • Green line: Outside temperature (weather correlation)

Pink Bar Chart - HVAC Runtime Analysis:

  • Each pink bar represents a time interval (bar width = interval duration)
  • Bar height shows runtime percentage for that interval
  • Example: A bar at 75% means the heating/cooling system ran for 75% of that time period

Total Runtime Display (Top of Graph):

  • Shows cumulative runtime: 4.0h / 24h
  • Meaning: Out of a 24-hour period, the heating system was actively running for 4.0 hours
  • This total allows efficiency estimation:
    • 4h/24h = 16.7% daily runtime
    • Compare across days to see efficiency changes
    • Correlate with outside temperature to understand heating loads
    • Identify inefficient equipment (unusually high runtime percentages)

Selectable Time Ranges:

  • 6 hours - Detailed minute-by-minute analysis for recent activity
  • 24 hours - Full day view showing daily patterns and peak usage
  • 7 days - Weekly trends and day-to-day comparisons
  • 30 days - Monthly overview for seasonal analysis

Navigation:

  • ← (Left Arrow) - View previous time interval
  • → (Right Arrow) - View next time interval
  • Example: In 24h mode, arrows move backward/forward by one day

Efficiency Insights:

  • Low runtime % with desired indoor temp = efficient system
  • High runtime % with poor temperature control = potential equipment issues
  • Runtime vs temperature delta = heating/cooling capacity indicator
  • Compare same time periods across different weeks/months to track degradation

HVAC runtime visualization with efficiency metrics:

Temperature Line Charts:

  • Blue line: Indoor temperature over time
  • Orange line: Temperature setpoint
  • Green line: Outside temperature

Pink Bar Chart - HVAC Runtime Analysis:

  • Each pink bar represents a time interval (bar width = interval duration)
  • Bar height shows runtime percentage for that interval
  • Example: A bar at 75% means the heating/cooling system ran for 75% of that time period

Time Interval Analysis:

  • Configurable intervals: hourly, daily, weekly
  • Smaller intervals (hourly) show usage patterns throughout the day
  • Larger intervals (daily) show seasonal trends
  • Pink bars make it easy to visually identify peak usage periods

Efficiency Insights:

  • Low runtime % with desired indoor temp = efficient system
  • High runtime % with poor temperature control = potential equipment issues
  • Runtime vs temperature delta = heating/cooling capacity indicator

Total Runtime Display (Top of Graph):

  • Shows cumulative runtime: 4.0h / 24h
  • Meaning: Out of a 24-hour period, the heating system was actively running for 4.0 hours
  • This total allows efficiency estimation:
    • 4h/24h = 16.7% daily runtime
    • Compare across days to see efficiency changes
    • Correlate with outside temperature to understand heating loads
    • Identify inefficient equipment (unusually high runtime percentages)

Architecture Overview

Three-Tier Architecture:

┌─────────────────────────────────────────────────────────────┐
│                    WEB DASHBOARD                            │
│              (Monitor & Control from Anywhere)              │
└────────────────────────┬────────────────────────────────────┘
                         │ HTTPS/WebSocket
                         │
┌────────────────────────▼────────────────────────────────────┐
│              THERMOSTATPUBLICSERVER (Cloud)                 │
│                                                             │
│  • FastAPI Application (Python)                             │
│  • PostgreSQL Database (Minute-level history)               │
│  • WebSocket Broadcasting (Real-time updates)               │
│  • REST API (Data ingestion & control)                      │
│  • AWS Lightsail / Your Cloud Server                        │
└────────────────────────┬────────────────────────────────────┘
                         │ HTTPS/REST API
                         │
        ┌────────────────┼────────────────┐
        │                │                │
┌───────▼──────┐  ┌──────▼──────┐  ┌─────▼───────┐
│ LOCAL SERVER │  │LOCAL SERVER │  │LOCAL SERVER │
│  (Cape Cod)  │  │(Framingham) │  │(NH House)   │
│              │  │             │  │             │
│ • Discovery  │  │ • Discovery │  │ • Discovery │
│ • Polling    │  │ • Polling   │  │ • Polling   │
│ • Control    │  │ • Control   │  │ • Control   │
└───────┬──────┘  └──────┬──────┘  └─────┬───────┘
        │                │                │
   ┌────┴───┐       ┌────┴───┐      ┌────┴───┐
   │CT50(s) │       │CT50(s) │      │CT50(s) │
   │Local   │       │Local   │      │Local   │
   │Network │       │Network │      │Network │
   └────────┘       └────────┘      └────────┘

Components

  1. Local Servers (ThermostatLocalServer - separate repository)

    • Run on Raspberry Pi or similar at each physical location
    • Discover and poll thermostats every 30 seconds
    • Send data to public server via REST API
    • Execute control commands from public server
  2. Public Server (This Repository - ThermostatPublicServer)

    • Cloud-hosted FastAPI application
    • Receives data from all local servers
    • Stores minute-level historical data
    • Provides web dashboard for monitoring and control
    • Real-time WebSocket updates
  3. Web Dashboard (Included in this repository)

    • Single-page JavaScript application
    • Real-time temperature monitoring
    • Historical charts and analysis
    • Thermostat control interface
    • Multi-site management

Key Features

Data Collection

  • High-Resolution History - Minute-level data storage

    • Current temperature (indoor)
    • Setpoint temperature
    • HVAC mode (heat/cool/off)
    • HVAC state (actively heating/cooling)
    • Outside temperature (local weather)
    • Runtime percentage per minute
  • Long-Term Storage - Configurable retention (default: 90 days)

  • Efficient Storage - Optimized database schema for millions of records

Monitoring

  • Real-Time Dashboard - WebSocket-based live updates (no page refresh)
  • Multi-Site View - Monitor all locations from single interface
  • Historical Charts - Temperature and runtime analysis
  • Efficiency Metrics - HVAC runtime percentage over time
  • Weather Correlation - Indoor vs outdoor temperature analysis

Control

  • Remote Commands - Change setpoints, modes from anywhere
  • Network Discovery - Discover new thermostats remotely
  • Away Mode - Set away temperatures for all thermostats
  • Command Queue - Reliable command delivery to local servers

Analysis

  • HVAC Runtime Analysis - Hourly, daily, weekly, monthly aggregations
  • Temperature Trends - Identify heating/cooling patterns
  • Efficiency Reports - Compare runtime vs temperature changes
  • Cost Estimation - Correlate runtime with utility costs
  • System Health - Detect anomalies in heating/cooling performance

Use Cases

Multi-Property Management

Manage vacation homes, rental properties, or multiple buildings:

  • Monitor all properties from single dashboard
  • Adjust temperatures before arrival
  • Detect heating/cooling failures remotely
  • Track energy usage across properties

Efficiency Analysis

Understand your heating/cooling system:

  • How long does it take to heat from 60°F to 70°F?
  • What's the optimal pre-heat time before arrival?
  • How does runtime correlate with outside temperature?
  • Is my system efficiency declining over time?

Cost Management

Predict and control heating/cooling costs:

  • Correlate setpoint changes with utility bills
  • Find optimal temperature setpoints
  • Identify inefficient equipment
  • Plan equipment upgrades based on data

System Monitoring

Detect problems early:

  • Unusual runtime patterns (system running constantly)
  • Failed heating/cooling (no temperature change despite runtime)
  • Thermostat offline detection
  • Historical comparison (this year vs last year)

What It Does

ThermostatPublicServer is a cloud-based FastAPI application that:

  • Aggregates Data - Collects data from multiple local servers at different physical locations
  • Stores History - Maintains minute-level historical data in PostgreSQL database
  • Real-Time Updates - Broadcasts thermostat status changes via WebSocket
  • Command Management - Queues and tracks thermostat control commands
  • Web Dashboard - Serves responsive HTML/JS frontend for monitoring and control
  • Authentication - JWT-based auth for users, token-based auth for local servers
  • API Access - RESTful API for integration with other systems

Technology Stack

Backend:

  • FastAPI 0.104+ (Python async web framework)
  • PostgreSQL 15+ (Database)
  • asyncpg (Async database driver)
  • uvicorn (ASGI server)

Frontend:

  • Vanilla JavaScript (Single-page application)
  • Chart.js (Historical charts)
  • WebSocket (Real-time updates)

Infrastructure:

  • AWS Lightsail (Ubuntu 22.04) or any cloud server
  • Docker (PostgreSQL container)
  • systemd (Service management)
  • Let's Encrypt (SSL certificates)

Quick Start

Prerequisites

  • Ubuntu 22.04+ server (1GB+ RAM, 2GB recommended)
  • Python 3.10+
  • Docker (for PostgreSQL)
  • Domain name (for SSL/HTTPS)

Installation

# 1. Clone repository
cd ~
git clone https://github.com/TiM00R/ThermostatPublicServer.git
cd ThermostatPublicServer

# 2. Create PostgreSQL container
./deployment/step3-create-postgresql-container.sh

# 3. Setup Python virtual environment
./deployment/step7-setup-venv.sh

# 4. Install dependencies
source venv/bin/activate
./deployment/step4-install-python-requirements.sh

# 5. Configure application
cp config/config.yaml.template config/config.yaml
nano config/config.yaml  # Edit configuration

# 6. Create .env file
cp .env.example .env
nano .env  # Add secrets

# 7. Initialize database
./deployment/step8-init-database.sh

# 8. Test application
./deployment/step9-test-application.sh

# 9. Setup SSL (production)
./deployment/step11-create-ssl-certificate.sh

# 10. Create systemd service
./deployment/step13-create-ssl-systemd-service.sh

Quick Test (Development)

# Start server manually
cd ~/ThermostatPublicServer
source venv/bin/activate
python src/main.py

# Access dashboard
# HTTP: http://your-server:8000
# HTTPS: https://your-server:8000

Configuration

Minimum Required Configuration

config/config.yaml:

database:
  host: localhost
  port: 5432
  database: thermostat
  user: postgres
  
server:
  host: 0.0.0.0
  port: 8000
  ssl_enabled: true
  ssl_cert_path: ./config/ssl/thermostat.crt
  ssl_key_path: ./config/ssl/thermostat.key

sites:
  cape:
    name: "Cape House"
    token: "REPLACE_WITH_SECURE_RANDOM_TOKEN_1"
  fram:
    name: "Framingham"
    token: "REPLACE_WITH_SECURE_RANDOM_TOKEN_2"
  nh:
    name: "New Hampshire"
    token: "REPLACE_WITH_SECURE_RANDOM_TOKEN_3"

.env file:

POSTGRES_PASSWORD=your_secure_password
JWT_SECRET_KEY=your_jwt_secret_key

Generate secure tokens:

# Site tokens
openssl rand -hex 32

# JWT secret
openssl rand -hex 64

API Overview

Data Ingestion (from Local Servers)

Local servers push data to these endpoints:

Endpoint Method Purpose
/api/v1/sites/{site_id}/thermostats/register POST Register thermostats
/api/v1/sites/{site_id}/status POST Status updates (every 30s)
/api/v1/sites/{site_id}/minute POST Minute aggregations
/api/v1/sites/{site_id}/commands/progress POST Discovery progress

Authentication: X-Site-Token header

Command Management (to Local Servers)

Local servers poll for commands:

Endpoint Method Purpose
/api/v1/sites/{site_id}/commands/pending GET Get pending commands
/api/v1/sites/{site_id}/commands/results POST Submit command results

Web Dashboard (for Users)

Dashboard uses these endpoints:

Endpoint Method Purpose
/api/v1/auth/login POST User login (JWT)
/api/v1/commands/create POST Create commands
/api/v1/sites/{site_id}/thermostats GET Get thermostats
/api/v1/history/runtime GET HVAC runtime data
/api/v1/history/temperature GET Temperature history
/ws/{site_id} WebSocket Real-time updates

Authentication: JWT Bearer token


Database Schema

Key Tables

sites - Physical locations with authentication tokens

site_id      TEXT PRIMARY KEY
name         TEXT NOT NULL
timezone     TEXT DEFAULT 'America/New_York'
site_token   TEXT NOT NULL UNIQUE
created_at   TIMESTAMP WITH TIME ZONE

thermostats - Registered devices

site_id        TEXT NOT NULL
thermostat_id  TEXT NOT NULL
name           TEXT NOT NULL
model          TEXT
ip_address     INET
away_temp      REAL
PRIMARY KEY (site_id, thermostat_id)

status_cache - Current thermostat state

site_id       TEXT NOT NULL
thermostat_id TEXT NOT NULL
ts            TIMESTAMP WITH TIME ZONE
temp          REAL
setpoint      REAL
mode          TEXT
hvac_state    TEXT
PRIMARY KEY (site_id, thermostat_id)

history_minute - Historical aggregations

site_id              TEXT NOT NULL
thermostat_id        TEXT NOT NULL
minute_ts            TIMESTAMP WITH TIME ZONE
temp_avg             REAL
setpoint_last        REAL
mode_last            TEXT
hvac_runtime_percent REAL
PRIMARY KEY (site_id, thermostat_id, minute_ts)

commands_queue - Command queue

cmd_id        TEXT PRIMARY KEY
site_id       TEXT NOT NULL
thermostat_id TEXT
cmd           TEXT NOT NULL
params_json   JSONB
status        TEXT
ts_created    TIMESTAMP WITH TIME ZONE

See: docs/DATABASE_SCHEMA.md for complete schema


Documentation


Related Projects

ThermostatLocalServer (Companion Project)

  • Runs on Raspberry Pi at each physical location
  • Discovers and polls CT50 thermostats
  • Sends data to this public server
  • Executes control commands
  • Repository: TiM00R/ThermostatLocalServer
  • Description: Local server for RadioThermostat CT50, CT80, 3M50 thermostats with multi-location support

System Requirements

Public Server (This Application)

Minimum:

  • 1 CPU core
  • 1GB RAM
  • 20GB storage
  • Ubuntu 22.04+
  • Python 3.10+
  • PostgreSQL 15+

Recommended:

  • 2 CPU cores
  • 2GB RAM
  • 40GB storage
  • Static IP address
  • Domain name for SSL

Database Storage

Per thermostat, 90 days:

  • ~130MB storage
  • ~130,000 minute records

5 thermostats, 90 days:

  • ~650MB storage
  • ~650,000 minute records

Growth rate:

  • ~1.4MB per day (5 thermostats)
  • ~500MB per year (5 thermostats)

Current Limitations

This project was designed for personal use managing 4 locations with fewer than 50 thermostats.

Security & Access Control

✅ Implemented:

  • Password-based login with JWT authentication
  • SSL/HTTPS certificates for encrypted communication
  • Site token authentication for local servers
  • Multiple user accounts supported
  • bcrypt password hashing

⚠️ Limitations:

  • All users have equal access - No role-based permissions beyond admin/viewer
  • Users must be added manually by administrator via database
  • No user registration - No self-service account creation
  • All users see all sites - Cannot restrict users to specific locations only

Scalability Considerations

Current Design:

  • Tested with: 4 locations, ~50 thermostats
  • Database: 1 year of minute-level data (~500 MB per 5 thermostats)
  • Server: Optimized for 1GB RAM AWS Lightsail instance

⚠️ Not Designed For:

  • 100+ users - Database size would grow significantly
  • 1000+ thermostats - Would require database optimization and partitioning
  • Multi-tenant SaaS - No tenant isolation or per-user data segregation

Production Service Requirements

To scale this for commercial/multi-user deployment, you would need:

  1. User Management:

    • Self-service user registration with email verification
    • Role-based access control (RBAC)
    • Per-user site access restrictions
    • User groups and permissions system
  2. Site Management:

    • Self-service site registration
    • Site ownership and access delegation
    • Per-site user invitations
    • Site-level privacy controls
  3. Database Optimization:

    • Table partitioning by site_id and date
    • Configurable data retention per user/site
    • Archived data storage (move old data to cheaper storage)
    • Read replicas for query performance
    • Connection pooling optimization
  4. Infrastructure:

    • Horizontal scaling (multiple app servers)
    • Load balancer
    • CDN for static assets
    • Separate database server
    • Redis for session/cache management
    • Monitoring and alerting (Prometheus, Grafana)
  5. Data Volume Example:

    • 1 thermostat, 1 year: ~130 MB
    • 1000 users × 5 thermostats average × 1 year: ~650 GB
    • Consider aggregating to 5-minute or hourly resolution after 90 days

Use This Project If:

  • ✅ Managing your own properties (1-10 locations)
  • ✅ Small team or family with shared access
  • ✅ Under 100 thermostats total
  • ✅ Comfortable with manual user management
  • ✅ Self-hosting on your own infrastructure

Don't Use This Project If:

  • ❌ Building a commercial SaaS service
  • ❌ Need per-user access controls
  • ❌ Managing 100+ users
  • ❌ Need automatic user registration
  • ❌ Need commercial-grade compliance and auditing

Support

Logs location:

  • Application: logs/application.txt
  • PostgreSQL: docker logs thermostat_postgres
  • Systemd: sudo journalctl -u thermostat-public-server

Database backups:

  • Auto backups: backups/ directory
  • Manual backup: ./deployment/backup-database.sh

Performance monitoring:

  • Health endpoint: https://your-server:8000/health

License

MIT License - see LICENSE file for details

You are free to use, modify, and distribute this software. See LICENSE file for full terms.


Version History

  • v2.0.0 (December 2024) - Initial public release

    • Simplified discovery protocol
    • Runtime state optimization for low-memory servers
    • Complete documentation
    • GitHub publication
  • v1.5 - Added away temperature feature

  • v1.0 - Initial multi-site aggregation server


Contributing

Contributions welcome! Please read the contributing guidelines before submitting pull requests.


Acknowledgments

This project was created to restore cloud functionality to RadioThermostat CT50 devices after the manufacturer discontinued support on May 15, 2023.

Special thanks to the RadioThermostat community for documenting the open API.


Last Updated: December 2024

About

Multi-location thermostat monitoring system with cloud aggregation and real-time HVAC runtime tracking. Works with ThermostatLocalServer for distributed edge computing.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors