{"id":29886955,"url":"https://github.com/tsaplia/energy-controller-refactored","last_synced_at":"2026-05-04T01:31:38.650Z","repository":{"id":304568074,"uuid":"1018898125","full_name":"tsaplia/energy-controller-refactored","owner":"tsaplia","description":"ESP8266 Energy Consumption Controller measures AC power with PZEM-014/016 sensor via Modbus. It offers a web interface for live data, charts, and settings.","archived":false,"fork":false,"pushed_at":"2025-08-18T13:06:54.000Z","size":550,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-08-18T15:07:36.058Z","etag":null,"topics":["arduino","cpp","esp8266","html-css-javascript","iot","platformio","webinterface","websocket"],"latest_commit_sha":null,"homepage":"","language":"C++","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/tsaplia.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2025-07-13T09:45:07.000Z","updated_at":"2025-08-18T13:06:57.000Z","dependencies_parsed_at":"2025-07-14T00:23:25.206Z","dependency_job_id":"f7311fd0-5741-4543-8570-e3767fa3d96c","html_url":"https://github.com/tsaplia/energy-controller-refactored","commit_stats":null,"previous_names":["tsaplia/energy-controller-refactored"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/tsaplia/energy-controller-refactored","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tsaplia%2Fenergy-controller-refactored","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tsaplia%2Fenergy-controller-refactored/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tsaplia%2Fenergy-controller-refactored/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tsaplia%2Fenergy-controller-refactored/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/tsaplia","download_url":"https://codeload.github.com/tsaplia/energy-controller-refactored/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tsaplia%2Fenergy-controller-refactored/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":283073600,"owners_count":26774726,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-11-06T02:00:06.180Z","response_time":55,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["arduino","cpp","esp8266","html-css-javascript","iot","platformio","webinterface","websocket"],"created_at":"2025-07-31T18:00:40.937Z","updated_at":"2026-05-04T01:31:38.642Z","avatar_url":"https://github.com/tsaplia.png","language":"C++","funding_links":[],"categories":[],"sub_categories":[],"readme":"# ⚡ Energy Consumption Controller\n\n[![PlatformIO](https://img.shields.io/badge/PlatformIO-Compatible-orange.svg)](https://platformio.org/)\n[![ESP8266](https://img.shields.io/badge/ESP8266-Compatible-blue.svg)](https://www.espressif.com/en/products/socs/esp8266)\n[![PZEM](https://img.shields.io/badge/PZEM-014%2F016-green.svg)](#hardware-requirements)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)\n\n\u003e **Professional-grade AC power monitoring system** for home and industrial applications. Monitor voltage, current, power consumption, and energy usage with real-time web interface and historical analytics.\n\n## ✨ Features Overview\n\n**📊 Real-time Power Monitoring**\n- Live voltage, current, power, energy, frequency, and power factor readings\n- Interactive charts showing consumption trends over time\n- Day/night energy consumption tracking with separate statistics\n\n**🌐 Smart Web Interface**\n- Fully responsive design - works on mobile, tablet, and desktop\n- WebSocket-based real-time updates (no page refreshing needed)\n- WiFi setup portal with automatic fallback to Access Point mode\n- Real-time system logs\n\n**💾 Intelligent Data Management**\n- Automatic CSV data logging with configurable intervals\n- Configurable data retention periods to manage storage\n- Energy statistics export for day/night consumption analysis\n- FTP server for bulk file operations and remote access\n\n**🔧 Advanced System Features**\n- Over-the-air (OTA) firmware updates without USB cable\n- Automatic NTP time synchronization with timezone support\n- Dual WiFi mode operation (Access Point + Station)\n- System reliability with watchdog protection and auto-restart\n\n## 🎯 Why Choose This Controller?\n\n✅ **Industrial Accuracy** - 0.5% measurement precision with PZEM sensors  \n✅ **Real-time Monitoring** - Live data streaming with interactive charts  \n✅ **Smart Data Management** - Automatic CSV logging with configurable retention  \n✅ **Mobile-First Design** - Responsive web interface works on any device  \n✅ **Professional Features** - OTA updates, FTP access, advanced analytics  \n✅ **Easy Setup** - WiFi portal setup, automatic network recovery  \n✅ **Reliable Operation** - 24-hour auto-restart, memory monitoring, error recovery  \n✅ **Developer Friendly** - Full API, WebSocket support, modular architecture  \n\n## 📋 Table of Contents\n\n- [⚠️ Safety \u0026 Prerequisites](#️-safety--prerequisites)\n- [🛠️ Hardware Requirements](#️-hardware-requirements)\n- [🚀 Quick Start](#-quick-start)\n- [📱 Detailed Setup](#-detailed-setup)\n- [🌐 Web Interface Guide](#-web-interface-guide)\n- [🔄 API Reference](#-api-reference)\n- [📂 Project Structure](#-project-structure)\n- [🔧 Troubleshooting](#-troubleshooting)\n\n---\n\n## ⚠️ Safety \u0026 Prerequisites\n\n### ⚡ Important Safety Notice\n\n\u003e **Working with AC Power**  \n\u003e This project measures AC mains voltage. While the PZEM sensors provide isolation, basic electrical safety is important. Turn off power when making connections and double-check your wiring.\n\n**Basic Safety Steps:**\n- ⚡ Turn off circuit breaker when connecting wires\n- 🔌 Use proper wire connections (no loose wires)\n- 📦 Keep electronics in a suitable enclosure\n- 🔍 Double-check connections before powering on\n\n### 📋 What You Need to Know\n\n**Coding Experience:**\n- **None required!** Just follow the setup instructions\n- Copy and paste - the code is ready to use\n- Basic computer skills (downloading, uploading files)\n\n**Basic Electronics:**\n- Connecting wires (positive, negative, data lines)\n- Using a USB cable to program the ESP8266\n- Basic understanding that electricity can be dangerous\n\n### ⏱️ Time Estimate\n\n- **Hardware assembly**: 1-2 hours (simple wire connections)\n- **Software setup**: 15-30 minutes (mostly downloading and uploading)\n- **Getting it working**: Usually works right away if wired correctly\n\n### 🛡️ Quick Safety Checklist\n\n- [ ] I'll turn off power when connecting wires\n- [ ] I'll double-check connections before turning power back on  \n- [ ] I understand this involves electrical work (but it's manageable)\n- [ ] I'll ask for help if I'm unsure about anything\n\n---\n\n## 🛠️ Hardware Requirements\n\n### 📦 Shopping List\n\n#### **Core Components**\n\n**ESP8266 Development Board**\n- Any ESP8266 board with accessible GPIO pins\n- Examples: NodeMCU, Wemos D1 Mini, ESP-01 (with adapter), etc.\n- Must have 3.3V and 5V power available\n- USB programming interface recommended for easy setup\n\n**Power Monitoring Sensor:**\n\n| Model | Max Current | Best For |\n|-------|-------------|----------|\n| **PZEM-014** | 10A | Household circuits, small appliances |\n| **PZEM-016** | 100A | Main panels, large loads (needs external CT) |\n\n\u003e 📖 **Detailed specifications**: See [PZEM-014/016 Technical Manual](docs/PZEM-014,016%20specification.pdf) for complete electrical specifications and communication protocol details.\n\n**Note**: This project is specifically designed for PZEM-014/016 sensors due to their Modbus RTU communication protocol. Other power sensors would require code modifications.\n\n#### **Additional Components**\n- **Jumper wires** (male-to-female, 4 pieces minimum)\n- **5V Power supply** (USB phone charger works fine)\n- **Project enclosure** (optional but recommended for permanent installation)\n\n### 🔌 Component Selection Guide\n\n**Choose PZEM-014 if:**\n- ✅ Monitoring individual appliances or circuits under 10A\n- ✅ Want simpler installation (built-in current measurement)\n- ✅ Most household applications (lights, outlets, small appliances)\n\n**Choose PZEM-016 if:**\n- ✅ Monitoring main electrical panel or large loads\n- ✅ Need to measure over 10A (up to 100A)\n- ✅ Already have or can install current transformer (CT)\n\n### 🔧 Wiring \u0026 Connections\n\n#### **ESP8266 to PZEM Connection**\n```\nESP8266                PZEM-014/016\n==================    ============\n5V or VIN        --\u003e  VCC (+5V)\nGND              --\u003e  GND  \nGPIO13 (D7)*     --\u003e  TX (Data out from PZEM)\nGPIO15 (D8)*     --\u003e  RX (Data in to PZEM)\n```\n*Pin numbers may vary by board - check your specific ESP8266 board pinout\n\n#### **PZEM Power Connections**\n\n⚡ **IMPORTANT**: Turn off circuit breaker before making these connections!\n\n**For PZEM-014:**\n- Connect **L** (Live/Hot) wire through the device  \n- Connect **N** (Neutral) wire through the device\n- Built-in current sensing - no external wires needed\n\n**For PZEM-016:**\n- Connect **L** and **N** for voltage sensing\n- Install **current transformer (CT)** around the main wire\n- CT connects to designated terminals on PZEM-016\n\n\u003e 🔗 **Detailed wiring diagrams**: See figures 4.1 and 4.2 in the [PZEM Technical Manual](docs/PZEM-014,016%20specification.pdf) for complete wiring instructions and safety guidelines.\n\n### 📋 Optional Accessories\n\n- **Project enclosure**: Protect electronics (DIN rail mount available)\n- **Heat shrink tubing**: Professional wire connections\n- **Terminal blocks**: Easier wire connections\n- **Current transformer**: Required for PZEM-016 (usually included)\n\n---\n\n## 🚀 Quick Start\n\n\u003e **For experienced users** - Get running in 30 minutes. Need more detail? Jump to [Detailed Setup](#-detailed-setup).\n\n**Prerequisites:** [PlatformIO](https://platformio.org/) installed (VS Code extension or CLI)\n\n### **Step 1: Wire Hardware**\n```\nESP8266 → PZEM-014/016\n5V/VIN  → VCC\nGND     → GND  \nGPIO13  → TX\nGPIO15  → RX\n```\nConnect PZEM to your AC circuit (⚡ **power off first**). See [PZEM Technical Manual](docs/PZEM-014,016%20specification.pdf) for detailed wiring instructions.\n\n### **Step 2: Clone \u0026 Setup**\n```bash\ngit clone https://github.com/tsaplia/energy-controller-refactored.git\ncd energy-controller-refactored\n```\n\n### **Step 3: Build \u0026 Upload**\n```bash\nplatformio run --target upload          # Upload firmware via USB\nplatformio run --target uploadfs        # Upload web interface files\n```\n*Or use VS Code PlatformIO extension buttons*\n\n### **Step 4: Configure WiFi**\n1. ESP creates AP `ESP8266-Sensor` (password: `password`)\n2. Connect and enter your WiFi credentials  \n3. Device connects to your network and shows IP address\n4. **AP automatically disconnects** - reconnect to your home WiFi network\n5. Access web interface using the displayed IP address\n\n### **Step 5: Access Interface**\n- Find ESP IP address (router admin or serial monitor)\n- Open `http://ESP_IP_ADDRESS` in browser\n- Start monitoring power consumption!\n\n### **⚡ Quick Troubleshooting**\n- **No sensor data?** → Check wiring, verify PZEM power\n- **Can't connect to WiFi?** → Reset and try AP mode again  \n- **Upload failed?** → Check USB cable, try different port\n- **Web interface not loading (Error 404)?** → Verify filesystem upload completed\n\n📖 **Need help?** See [Detailed Setup](#-detailed-setup) or [Troubleshooting](#-troubleshooting) sections.\n\n---\n\n## 📱 Detailed Setup\n\n\u003e **Step-by-step guide for beginners** - No prior experience needed!\n\n### **Step 1: Install Development Environment**\n\n#### **Option A: VS Code + PlatformIO (Recommended)**\n1. **Download VS Code**: Go to [code.visualstudio.com](https://code.visualstudio.com/) and install\n2. **Install PlatformIO extension**:\n   - Open VS Code\n   - Click Extensions icon (left sidebar) \n   - Search \"PlatformIO IDE\"\n   - Click Install on the official extension\n   - **Wait for PlatformIO Core to download and install** (this may take several minutes)\n   - Restart VS Code when prompted\n\n\u003e ⚠️ **Important**: Wait for PlatformIO to fully initialize before opening projects. If you encounter project configuration issues, try: **View → Command Palette → \"PlatformIO: Rebuild IntelliSense Index\"**\n\n#### **Option B: PlatformIO CLI**\n1. **Install Python** (if not already installed)\n2. **Install PlatformIO Core**:\n   ```bash\n   pip install platformio\n   ```\n\n### **Step 2: Download Project Files**\n\n#### **If you have Git:**\n```bash\ngit clone https://github.com/tsaplia/energy-controller-refactored.git\ncd energy-controller-refactored\n```\n\n#### **If you don't have Git:**\n1. Go to the project's GitHub page\n2. Click green \"Code\" button → \"Download ZIP\"  \n3. Extract ZIP file to a folder\n4. Remember the folder location\n\n### **Step 3: Hardware Assembly**\n\n#### **Gather Your Components**\n- ESP8266 board (any model with GPIO pins)\n- PZEM-014 or PZEM-016 sensor\n- 4 jumper wires (male-to-female)\n- USB cable for ESP8266\n\n#### **Make Connections**\n⚡ **IMPORTANT**: Do this with power OFF!\n\n1. **Connect ESP8266 to PZEM**:\n   ```\n   ESP8266 Pin    →    PZEM Pin\n   ============        =========\n   5V or VIN      →    VCC\n   GND            →    GND  \n   GPIO13 (D7)*   →    TX\n   GPIO15 (D8)*   →    RX\n   ```\n   *Pin labels may vary - check your board's pinout\n\n2. **Connect PZEM to AC Power** (⚡ **Turn off circuit breaker first!**):\n   - **PZEM-014**: Connect Live and Neutral wires through the device\n   - **PZEM-016**: Connect L/N for voltage, install CT for current\n   - See [PZEM Technical Manual](docs/PZEM-014,016%20specification.pdf) for detailed wiring diagrams\n\n3. **Double-check all connections** before powering on\n\n### **Step 4: Configure \u0026 Upload Software**\n\n#### **Open Project**\n- **VS Code**: File → Open Folder → Select your project folder\n- **CLI**: Navigate to project folder in terminal\n\n#### **Upload Firmware**\n\n**Using VS Code:**\n1. Click PlatformIO icon in left sidebar\n2. Under \"PROJECT TASKS\" → \"nodemcuv3\" → \"General\"\n3. Click \"Upload\" (this compiles and uploads firmware)\n4. Wait for \"SUCCESS\" message\n\n**Using CLI:**\n```bash\nplatformio run --target upload\n```\n\n#### **Upload Web Interface Files**\n\n**Using VS Code:**\n1. Same location as above\n2. Click \"Upload Filesystem Image\"\n3. Wait for completion\n\n**Using CLI:**\n```bash\nplatformio run --target uploadfs\n```\n\n### **Step 5: First Boot \u0026 WiFi Setup**\n\n#### **What to Expect**\n1. **ESP8266 starts** and creates its own WiFi network\n2. **Network name**: `ESP8266-Sensor` (password: `password`)\n3. **Connection process**:\n   - Connect your phone/computer to ESP8266's WiFi\n   - Open any webpage - it will redirect to setup page\n   - Enter your home WiFi name and password\n   - Device connects to your network and **displays IP address on the page**\n   - **AP automatically disconnects** - you must reconnect to your home WiFi network to access the web interface\n\n![Connect to WiFi interface](docs/img/auth.png)\n  \n#### **Find Your Device**\n**Method 1 - Router Admin:**\n- Log into your router (usually 192.168.1.1 or 192.168.0.1)\n- Look for new device in connected devices list\n\n**Method 2 - Serial Monitor:**\n- Keep USB cable connected\n- Open serial monitor in PlatformIO (9600 baud)\n- Device will print its IP address\n\n### **Step 6: Access Web Interface**\n\n1. **Open browser** and go to: `http://YOUR_ESP_IP_ADDRESS`\n2. **You should see** the energy monitoring dashboard\n3. **If sensor is connected properly**, you'll see live voltage/current/power readings\n\n### **🎉 Success! What Now?**\n\n- **Dashboard**: View real-time power consumption\n- **Settings**: Configure data intervals, timezones, export your energy data, etc.\n- **Logs**: Monitor system operation\n\n### **❌ Something Not Working?**\n\n**No sensor data showing?**\n- Check wiring connections\n- Verify PZEM has power (AC connected)\n- Try different GPIO pins if needed\n\n**Can't connect to WiFi?**\n- Reset ESP8266 (power cycle)\n- Try connecting to AP again\n- Check WiFi password\n\n**Upload failed?**\n- Check USB cable connection\n- Try different USB port\n- Make sure ESP8266 drivers are installed\n\n**Still stuck?** Check the [Troubleshooting](#-troubleshooting) section below!\n\n---\n\n## 🌐 Web Interface Guide\n\nOnce your device is connected to WiFi, open its IP address in your browser to access the monitoring interface.\n\n### Dashboard Overview\n\nThe main dashboard provides real-time monitoring with:\n\n#### **Live Data Display**\n- **Real-time sensor readings** updated via WebSocket connection\n- **Voltage, current, power, energy** consumption metrics\n- **Frequency and power factor** measurements\n- **Interactive charts** showing voltage and power trends over time\n\n#### **Dashboard Features**\n- 📱 **Fully responsive design** — works perfectly on mobile phones, tablets, and desktop\n- 🔄 **Auto-updating data** — no need to refresh the page\n- 📊 **Visual charts** — easily spot power consumption patterns\n\n\n\u003e ![Dashboard Screenshot](docs/img/main.jpg)\n\n### Settings Configuration\n\nAccess the settings page at `/settings` to configure your controller:\n\n#### **Data Collection Settings**\n- **Data Save Interval**: How often to record sensor data (default: 30 seconds)\n- **Data Retention**: How long to keep historical data (default: 1 day)\n- **Timezone Offset**: Set your local timezone for accurate timestamps\n\n#### **Day/Night Phases**\n- **Day Phase Start**: When \"day\" energy tracking begins (default: 7:00 AM)\n- **Night Phase Start**: When \"night\" energy tracking begins (default: 11:00 PM)\n- Automatically calculates separate day and night energy consumption\n\n#### **System Settings**\n- **Log Level**: Control detail level of system logs (DEBUG, INFO, WARNING, ERROR)\n- **WiFi Credentials**: Update network connection settings\n- **Energy Reset**: Reset energy counter to start fresh measurements\n\n#### **Data Export**\n- **Download sensor data**: Export CSV with all recorded measurements\n- **Download energy stats**: Export day/night energy consumption summaries\n\n\u003e ⚠️ **WiFi Changes**: After updating WiFi credentials, the device will disconnect and connect to the new network. You'll need to find the new IP address to access the interface again.\n\n\u003e ![Settings Screenshot](docs/img/settings.png)\n\n### System Logs\n\nThe logs page at `/logs` provides:\n\n#### **Real-time Log Monitoring**\n- **Live log stream** via WebSocket connection\n- **Historical logs** from device storage\n- **Timestamp information** for troubleshooting\n\n#### **Log Categories**\n- **DEBUG**: Detailed technical information\n- **INFO**: General operational messages  \n- **WARNING**: Important notices and state changes\n- **ERROR**: Problems that need attention\n\n---\n\n## 🔄 API Reference\n\nThe controller provides a comprehensive HTTP API for automation and integration with other systems.\n\n### 🔧 System Control Routes\n\n| Route | Method | Description | Response |\n|-------|---------|-------------|----------|\n| `/api/restart` | GET | Restart the ESP8266 controller | `{\"detail\": \"Restarting...\"}` |\n| `/api/pause` | GET | Pause data collection and processing | `{\"detail\": \"Pausing...\"}` |\n| `/api/resume` | GET | Resume normal operation | `{\"detail\": \"Resuming...\"}` |\n| `/api/system-info` | GET | Get detailed system information | JSON with chip, memory, filesystem data |\n| `/api/clear-old` | GET | Remove old data based on retention settings | `{\"detail\": \"Cleared old data\"}` |\n\n### ⚙️ Configuration Routes\n\n| Route | Method | Description | Body | Response |\n|-------|---------|-------------|------|----------|\n| `/api/settings` | GET | Get current configuration | - | JSON with all settings |\n| `/api/settings` | POST | Update configuration | JSON with settings to change | `{\"detail\": \"OK\"}` |\n| `/api/reset-energy` | PUT | Reset energy measurement baseline | - | `{\"detail\": \"OK\"}` |\n| `/api/connect-wifi` | POST | Update WiFi credentials | `{\"ssid\": \"...\", \"password\": \"...\"}` | `{\"ip\": \"192.168.x.x\"}` |\n\n### 📡 WebSocket Endpoints\n\n| Socket Path | Purpose | Message Format |\n|------------|---------|----------------|\n| `/ws/data` | Real-time sensor data | `{\"type\": \"data\", \"data\": {...}}` |\n| `/ws/logs` | Live system logs | `{\"type\": \"log\", \"data\": \"log message\"}` |\n\n#### **WebSocket Data Format**\n\n**Sensor Data Messages:**\n```json\n{\n  \"type\": \"data\",\n  \"data\": {\n    \"time\": 1640995200,\n    \"voltage\": 230.5,\n    \"current\": 2.150,\n    \"power\": 495.6,\n    \"energy\": \"12.5\",\n    \"frequency\": 50.0,\n    \"pf\": 0.95\n  }\n}\n```\n\n**Log Messages:**\n```json\n{\n  \"type\": \"log\",\n  \"data\": \"2024-01-01 12:00:00 [INFO] WiFi connected on IP: 192.168.1.100\"\n}\n```\n\n### 📂 File Access Routes\n\n| Route | Description |\n|-------|-------------|\n| `/sensor-data.csv` | Raw sensor measurements |\n| `/energy-stats.csv` | Day/night energy summaries |\n| `/configs.json` | Current device configuration |\n| `/logs.txt` | System log file |\n\n### 📥 FTP Access\n\nFiles can also be accessed via FTP for bulk operations:\n- **Host**: ESP8266 IP address\n- **User**: `esp`\n- **Password**: `password`\n- **Port**: 21 (standard FTP)\n\n---\n\n## 📂 Project Structure\n\nUnderstanding the project layout helps you navigate the codebase and customize functionality as needed.\n\n### 🗂️ Root Directory\n\n```\nenergy-consumption-controller/\n├── 📁 .vscode/                    # VS Code configuration\n├── 📁 data/                       # Web interface files (uploaded to ESP8266)\n├── 📁 docs/                       # Documentation and images\n├── 📁 external-data/              # Stores large external resources not kept on the ESP8266\n├── 📁 include/                    # C++ header files\n├── 📁 lib/FTPClientServer-master/ # FTP server library\n├── 📁 src/                        # C++ source code\n├── 📄 .gitignore                  # Git ignore rules\n├── 📄 LICENSE                     # Project license\n├── 📄 README.md                   # This file\n└── 📄 platformio.ini              # PlatformIO configuration\n```\n\n### 🌐 Web Interface Files (`/data`)\n\nThese files are uploaded to the ESP8266's filesystem and served by the web server:\n\n```\ndata/\n├── 📄 auth.html          # WiFi setup page (AP mode)\n├── 📄 data.js            # WebSocket data handling\n├── 📄 index.html         # Main dashboard page\n├── 📄 logs.html          # System logs viewer\n├── 📄 logs.js            # Log WebSocket handling\n├── 📄 settings.html      # Configuration page\n├── 📄 settings.js        # Settings management\n├── 📄 shared.js          # Common JavaScript functions\n└── 📄 style.css          # All page styling\nexternal-data/\n└── 📄 bootstrap.min.css  # Bootstrap styling, loaded via GitHub CDN instead of controller storage\n```\n\n### 🧠 Core Source Code (`/src`)\n\nMain application logic organized by functionality:\n\n```\nsrc/\n├── 📄 main.cpp           # Application entry point \u0026 setup\n├── 📄 configs.cpp        # Configuration management\n├── 📄 globals.cpp        # Global variables initialization\n├── 📄 logger.cpp         # Logging system implementation\n├── 📄 loop-handlers.cpp  # Main loop logic handlers\n├── 📄 sensor.cpp         # PZEM sensor communication\n├── 📄 utils.cpp          # Utility functions (time, files, etc.)\n├── 📄 wifi-tools.cpp     # WiFi management (AP/STA modes)\n└── 📁 web/               # Web server components\n    ├── 📄 api-handlers.cpp    # HTTP API endpoint handlers\n    ├── 📄 web-server.cpp      # Web server setup \u0026 routing\n    └── 📄 web-utils.cpp       # Web utility functions\n```\n\n### 🔧 Header Files (`/include`)\n\nInterface definitions and constants:\n\n```\ninclude/\n├── 📄 configs.h          # Configuration class definition\n├── 📄 constants.h        # System constants and defaults\n├── 📄 globals.h          # Global variable declarations\n├── 📄 logger.h           # Logging system interface\n├── 📄 loop-handlers.h    # Loop handler function declarations\n├── 📄 sensor.h           # Sensor data structures \u0026 functions\n├── 📄 utils.h            # Utility function declarations\n├── 📄 wifi-tools.h       # WiFi management interface\n└── 📁 web/               # Web server headers\n    ├── 📄 api-handlers.h      # API handler declarations\n    ├── 📄 web-server.h        # Web server declarations\n    └── 📄 web-utils.h         # Web utility declarations\n```\n\n### 🔍 Important Files to Know\n\n#### **For Customization:**\n- `platformio.ini` - Build configuration, board settings, libraries\n- `main.cpp` - Add new sensors or modify startup behavior\n- `constants.h` - Modify default settings, intervals, passwords\n- `style.css` - Customize web interface appearance \n\n#### **For Troubleshooting:**\n- `logger.cpp` - Understand logging system\n- `wifi-tools.cpp` - WiFi connection issues\n- `sensor.cpp` - PZEM communication problems\n\n#### **For API Integration:**\n- `api-handlers.cpp` - Add new API endpoints\n- `web-server.cpp` - Modify routing or WebSocket behavior\n\n### 💾 Runtime Files (Created on ESP8266)\n\nWhen running, the controller creates these files in its filesystem:\n\n```\nESP8266 Filesystem:\n├── 📄 /configs.json          # Saved configuration\n├── 📄 /sensor-data.csv       # Historical sensor readings  \n├── 📄 /energy-stats.csv      # Daily/nightly energy summaries\n└── 📄 /logs.txt              # System log history\n```\n\n---\n\n## 🔧 Troubleshooting\n\n### 🌐 Web Interface Issues\n\n**Pages loading slowly or not fully:**\n- **Try reloading** the page (Ctrl+F5 or Cmd+Shift+R)\n- **Wait a few seconds** between page requests - ESP8266 has limited resources\n\n**Charts not loading properly:**\n- **Slow internet connection** may prevent all data from loading\n- **Reduce data retention** in settings to keep less historical data\n- Check your router for connection issues\n- Try accessing `/api/restart` to restart the ESP8266 controller \n\n### 🛠️ PlatformIO Setup Issues\n\n**Extension not working properly:**\n- **Wait for PlatformIO Core** to fully download and install\n- **Project configuration errors**: Go to **View → Command Palette → \"PlatformIO: Rebuild IntelliSense Index\"**\n- **Build issues**: Try **PlatformIO: Clean** then **PlatformIO: Build**\n- **Still having problems**: Restart VS Code and wait for initialization\n\n### 🔌 Hardware \u0026 Connection Problems\n\n**No sensor data showing:**\n- Check wiring connections between ESP8266 and PZEM\n- Verify PZEM has AC power connected\n- Try different GPIO pins if needed\n- Check serial monitor for sensor communication errors\n\n**Can't connect to WiFi:**\n- Reset ESP8266 (power cycle)\n- Try connecting to AP mode again\n- Check WiFi password spelling\n- Ensure WiFi network is 2.4GHz (ESP8266 doesn't support 5GHz)\n\n**Upload failed:**\n- Check USB cable connection\n- Try different USB port\n- Check platformio.ini configuration: \"board = nodemcuv2\" or \"[env:nodemcuv3]\" must match your actual board\n- Ensure ESP8266 drivers are installed\n- Press and hold FLASH button during upload if needed\n\n---\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftsaplia%2Fenergy-controller-refactored","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ftsaplia%2Fenergy-controller-refactored","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftsaplia%2Fenergy-controller-refactored/lists"}