refactor: rename component from nut_ups to ups_hid

Signed-off-by: bullshit <coding@ow-software.pl>
This commit is contained in:
bullshit committed 2025-08-08 15:25:03 +02:00
1 parent 03766881e1
commit a5b43af89c
24 files changed
+1077 -1000

No files matched your search

+694
View File
@@ -0,0 +1,694 @@
# UPS HID Component for ESPHome
A production-ready ESPHome component for monitoring UPS devices via USB connection on ESP32-S3. Direct USB HID communication with support for APC, CyberPower, and generic HID UPS devices.
## Features
- 🔋 **Real-time UPS monitoring**: Battery level, voltages, load, runtime, status
- 🌈 **Visual status indicator**: RGB LED with customizable status colors
- 🏠 **Home Assistant integration**: Automatic entity discovery via ESPHome API
- 🔌 **Multi-protocol support**: APC Smart, APC HID, CyberPower HID, Generic HID
- 🎯 **Auto-detection**: Intelligent protocol detection based on USB vendor IDs
- 🛡️ **Production-ready**: Thread-safe, error rate limiting, comprehensive logging
- 🧪 **Simulation mode**: Test integration without physical UPS device
## Quick Start
### Hardware Requirements
- **ESP32-S3-DevKitC-1 v1.1** with USB OTG support
- **UPS device** with USB monitoring port
- **RGB LED** (optional, connected to GPIO38)
- **USB cable** (UPS to ESP32-S3)
### Basic Configuration
```yaml
# example.yaml
esphome:
name: ups-monitor
platform: ESP32
board: esp32-s3-devkitc-1
# Enable external components
external_components:
- source:
type: local
path: components
# Configure the UPS HID component
ups_hid:
id: ups_monitor # Required ID for referencing
update_interval: 30s # How often to poll UPS data
usb_vendor_id: 0x051D # APC vendor ID (auto-detected if omitted)
usb_product_id: 0x0002 # Optional: specific product ID
protocol_timeout: 15s # USB communication timeout
auto_detect_protocol: true # Enable automatic protocol detection
simulation_mode: false # Set to true for testing without UPS
# Optional: RGB status LED (configured separately)
light:
- platform: esp32_rmt_led_strip
rgb_order: GRB
pin: GPIO38
num_leds: 1
chipset: ws2812
name: "UPS Status LED"
id: ups_status_led
# Define sensors (each sensor requires separate platform entry)
sensor:
- platform: ups_hid
ups_hid_id: ups_monitor
type: battery_level
name: "UPS Battery Level"
unit_of_measurement: "%"
device_class: battery
- platform: ups_hid
ups_hid_id: ups_monitor
type: input_voltage
name: "UPS Input Voltage"
unit_of_measurement: "V"
device_class: voltage
- platform: ups_hid
ups_hid_id: ups_monitor
type: output_voltage
name: "UPS Output Voltage"
unit_of_measurement: "V"
device_class: voltage
- platform: ups_hid
ups_hid_id: ups_monitor
type: load_percent
name: "UPS Load"
unit_of_measurement: "%"
- platform: ups_hid
ups_hid_id: ups_monitor
type: runtime
name: "UPS Runtime"
unit_of_measurement: "min"
device_class: duration
- platform: ups_hid
ups_hid_id: ups_monitor
type: frequency
name: "UPS Frequency"
unit_of_measurement: "Hz"
binary_sensor:
- platform: ups_hid
ups_hid_id: ups_monitor
type: online
name: "UPS Online"
device_class: connectivity
- platform: ups_hid
ups_hid_id: ups_monitor
type: on_battery
name: "UPS On Battery"
device_class: battery
- platform: ups_hid
ups_hid_id: ups_monitor
type: low_battery
name: "UPS Low Battery"
device_class: battery
- platform: ups_hid
ups_hid_id: ups_monitor
type: charging
name: "UPS Charging"
device_class: battery
- platform: ups_hid
ups_hid_id: ups_monitor
type: fault
name: "UPS Fault"
device_class: problem
text_sensor:
- platform: ups_hid
ups_hid_id: ups_monitor
type: manufacturer
name: "UPS Manufacturer"
- platform: ups_hid
ups_hid_id: ups_monitor
type: model
name: "UPS Model"
- platform: ups_hid
ups_hid_id: ups_monitor
type: protocol
name: "UPS Protocol"
- platform: ups_hid
ups_hid_id: ups_monitor
type: status
name: "UPS Status"
```
## Hardware Setup
### ESP32-S3 USB OTG Connection
```
UPS USB Port (Type-B) ←→ USB Cable ←→ ESP32-S3 USB OTG Port
```
### RGB LED Wiring (Optional)
```
GPIO38 (ESP32-S3) → RGB LED Data Pin
3.3V → RGB LED VCC
GND → RGB LED GND
```
### LED Status Indicators
- 🟢 **Green**: UPS online, normal operation
- 🟠 **Orange**: UPS running on battery power
- 🔴 **Red (blinking)**: Low battery or critical status
- 🔵 **Blue**: Charging or maintenance mode
- ⚫ **Off**: UPS disconnected or component error
## Supported UPS Devices
### Tested Compatible Models
| Vendor | Models | Protocol | Vendor ID |
|--------|--------|----------|-----------|
| **APC** | Back-UPS ES Series, Smart-UPS | APC Smart, APC HID | 0x051D |
| **CyberPower** | CP1500EPFCLCD, CP1000PFCLCD | CyberPower HID | 0x0764 |
| **Tripp Lite** | SMART1500LCDT, UPS series | Generic HID | 0x09AE |
| **Eaton/MGE** | Ellipse, Evolution series | Generic HID | 0x06DA |
| **Belkin** | Older USB UPS models | Generic HID | 0x050D |
### Protocol Compatibility Matrix
| Protocol | Communication | Auto-Detection | Features |
|----------|---------------|----------------|----------|
| **APC Smart** | Serial over USB | ✅ | Full monitoring, legacy APC |
| **APC HID** | USB HID reports | ✅ | Modern APC, enhanced features |
| **CyberPower HID** | Vendor-specific HID | ✅ | CyberPower optimized |
| **Generic HID** | Standard HID-PDC | ✅ | Universal fallback |
## Configuration Reference
### Component Options
```yaml
ups_hid:
id: ups_monitor # Required component ID for sensor references
update_interval: 30s # Polling interval (minimum 5s recommended)
# USB Device Configuration
usb_vendor_id: 0x051D # USB Vendor ID (hex), auto-detected if omitted
usb_product_id: 0x0002 # USB Product ID (hex), optional
# Protocol Settings
auto_detect_protocol: true # Enable automatic protocol detection
protocol_timeout: 15s # Communication timeout (5s-60s)
# Testing Options
simulation_mode: false # Enable simulation for testing (no USB required)
# Status LED configured separately (not part of ups_hid component)
light:
- platform: esp32_rmt_led_strip
rgb_order: GRB
pin: GPIO38 # GPIO pin for RGB LED
num_leds: 1
chipset: ws2812 # LED type (ws2812, ws2811, etc.)
name: "UPS Status LED"
id: ups_status_led
```
### Sensor Platform
Each sensor requires a separate platform entry with `ups_hid_id` and `type`:
```yaml
sensor:
- platform: ups_hid
ups_hid_id: ups_monitor # Reference to component ID
type: battery_level # Battery charge percentage (0-100%)
name: "Battery Level"
unit_of_measurement: "%"
device_class: battery
accuracy_decimals: 1
- platform: ups_hid
ups_hid_id: ups_monitor
type: input_voltage # AC input voltage (V)
name: "Input Voltage"
unit_of_measurement: "V"
device_class: voltage
accuracy_decimals: 1
- platform: ups_hid
ups_hid_id: ups_monitor
type: output_voltage # AC output voltage (V)
name: "Output Voltage"
unit_of_measurement: "V"
device_class: voltage
accuracy_decimals: 1
- platform: ups_hid
ups_hid_id: ups_monitor
type: load_percent # UPS load percentage (0-100%)
name: "Load Percentage"
unit_of_measurement: "%"
accuracy_decimals: 1
- platform: ups_hid
ups_hid_id: ups_monitor
type: runtime # Estimated runtime (minutes)
name: "Runtime"
unit_of_measurement: "min"
device_class: duration
accuracy_decimals: 0
- platform: ups_hid
ups_hid_id: ups_monitor
type: frequency # AC frequency (Hz)
name: "Frequency"
unit_of_measurement: "Hz"
accuracy_decimals: 1
```
**Available sensor types:**
- `battery_level`: Battery charge percentage (0-100%)
- `input_voltage`: AC input voltage (V)
- `output_voltage`: AC output voltage (V)
- `load_percent`: UPS load percentage (0-100%)
- `runtime`: Estimated runtime (minutes)
- `frequency`: AC frequency (Hz)
### Binary Sensor Platform
Each binary sensor requires `ups_hid_id` and `type`:
```yaml
binary_sensor:
- platform: ups_hid
ups_hid_id: ups_monitor
type: online # UPS is online (AC power available)
name: "UPS Online"
device_class: connectivity
- platform: ups_hid
ups_hid_id: ups_monitor
type: on_battery # UPS running on battery
name: "On Battery"
device_class: battery
- platform: ups_hid
ups_hid_id: ups_monitor
type: low_battery # Battery level is low
name: "Low Battery"
device_class: battery
- platform: ups_hid
ups_hid_id: ups_monitor
type: charging # Battery is charging
name: "Charging"
device_class: battery
- platform: ups_hid
ups_hid_id: ups_monitor
type: fault # UPS fault condition
name: "Fault"
device_class: problem
- platform: ups_hid
ups_hid_id: ups_monitor
type: overload # UPS is overloaded
name: "Overload"
device_class: problem
```
**Available binary sensor types:**
- `online`: UPS is online (AC power available)
- `on_battery`: UPS running on battery power
- `low_battery`: Battery level is critically low
- `charging`: Battery is currently charging
- `fault`: UPS has a fault condition
- `overload`: UPS is overloaded
### Text Sensor Platform
Each text sensor requires `ups_hid_id` and `type`:
```yaml
text_sensor:
- platform: ups_hid
ups_hid_id: ups_monitor
type: manufacturer # UPS manufacturer name
name: "Manufacturer"
- platform: ups_hid
ups_hid_id: ups_monitor
type: model # UPS model number
name: "Model"
- platform: ups_hid
ups_hid_id: ups_monitor
type: serial_number # UPS serial number (if available)
name: "Serial Number"
- platform: ups_hid
ups_hid_id: ups_monitor
type: firmware_version # UPS firmware version (if available)
name: "Firmware"
- platform: ups_hid
ups_hid_id: ups_monitor
type: protocol # Detected protocol name
name: "Protocol"
- platform: ups_hid
ups_hid_id: ups_monitor
type: status # Combined status string
name: "Status"
```
**Available text sensor types:**
- `manufacturer`: UPS manufacturer name
- `model`: UPS model number/name
- `serial_number`: UPS serial number (if available)
- `firmware_version`: UPS firmware version (if available)
- `protocol`: Currently detected protocol name
- `status`: Combined UPS status text
## Advanced Configuration
### Custom Protocol Priority
```yaml
ups_hid:
auto_detect_protocol: false # Disable auto-detection
# Component will use APC Smart Protocol by default
```
### Performance Tuning
```yaml
ups_hid:
id: ups_monitor
update_interval: 10s # Faster polling (minimum 5s recommended)
protocol_timeout: 5s # Faster timeout for responsive networks
# Individual sensor update intervals are controlled by the component
```
### Simulation Mode
For testing without physical UPS:
```yaml
ups_hid:
id: ups_monitor
simulation_mode: true # Enables realistic simulated data
update_interval: 5s # Faster updates to see simulation changes
logger:
level: DEBUG # See simulation data changes
```
## Troubleshooting
### Common Issues
#### 1. "No UPS devices found during initial enumeration"
**Cause**: USB connection or device power issues
**Solutions**:
- Verify USB cable connection (UPS ↔ ESP32-S3)
- Ensure UPS is powered on and USB monitoring is enabled
- Check ESP32-S3 USB OTG is functioning
- Try different USB cable
#### 2. "No compatible UPS protocol detected"
**Cause**: Unsupported UPS model or communication failure
**Solutions**:
- Check if your UPS model is in the supported devices list
- Enable debug logging: `logger: level: DEBUG`
- Try manual protocol selection: `auto_detect_protocol: false`
- Verify USB vendor/product IDs in logs
#### 3. "Failed to acquire USB mutex" errors
**Cause**: USB communication conflicts or hardware issues
**Solutions**:
- Increase protocol timeout: `protocol_timeout: 15s`
- Check for USB hardware conflicts
- Restart ESP32-S3 device
- Verify stable power supply
#### 4. "Protocol detection rate limited" warnings
**Cause**: Multiple failed detection attempts (normal protection)
**Solutions**:
- Wait 5 seconds for rate limit reset
- This is normal behavior protecting the UPS device
- Check physical connections if persistent
### Debug Logging
Enable detailed logging for troubleshooting:
```yaml
logger:
level: DEBUG
logs:
ups_hid: DEBUG
ups_hid.apc: DEBUG
ups_hid.cyberpower: DEBUG
ups_hid.generic: DEBUG
```
### Log Analysis
**Normal operation logs**:
```
[D][ups_hid:240] Detected known UPS vendor: APC (0x051D)
[I][ups_hid:371] Successfully detected APC HID protocol (took 156ms)
[D][ups_hid.apc:89] Battery: 85.0%, Runtime: 45.2 min
```
**Connection issues**:
```
[W][ups_hid:461] Failed to acquire USB mutex for write
[E][ups_hid:264] No compatible UPS protocol detected for vendor 0x051D
```
**Rate limiting (normal)**:
```
[W][ups_hid:185] Suppressed 5 similar error messages in the last 5000 ms
```
### Performance Monitoring
Monitor these metrics in Home Assistant:
- Update intervals (should be consistent)
- Protocol detection time (< 500ms typical)
- Error rates (should be minimal)
- USB communication success rate
## Advanced LED Status Control
The component can control an RGB LED to display UPS status with priority-based visual indicators:
### LED Priority System
1. **🔴 Critical** (Highest Priority): Red blinking - Low battery, UPS fault, overload
2. **🟠 Battery Operation** (Medium Priority): Orange pulsing - Running on battery (normal level)
3. **🟡 Charging** (Low Priority): Yellow pulsing - Battery charging while online
4. **🟢 Normal Operation**: Green breathing - Online, normal operation
5. **⚫ Offline/Unknown**: LED off - UPS disconnected or error
### Complete LED Configuration
```yaml
# RGB LED with custom effects
light:
- platform: esp32_rmt_led_strip
rgb_order: GRB
pin: GPIO38
num_leds: 1
chipset: ws2812
name: "UPS Status LED"
id: ups_status_led
restore_mode: ALWAYS_OFF
effects:
- strobe:
name: "Critical Strobe"
colors:
- state: true
brightness: 100%
red: 100%
green: 0%
blue: 0%
duration: 250ms
- state: false
duration: 250ms
- pulse:
name: "Battery Pulse"
transition_length: 1s
update_interval: 1s
min_brightness: 20%
max_brightness: 80%
- pulse:
name: "Normal Breathing"
transition_length: 2s
update_interval: 2s
min_brightness: 30%
max_brightness: 70%
- pulse:
name: "Battery Operation"
transition_length: 800ms
update_interval: 800ms
min_brightness: 40%
max_brightness: 90%
# Priority-based LED control logic
interval:
- interval: 2s
then:
- lambda: |-
// Advanced UPS status LED control with priorities
// Critical conditions (highest priority) - Red blinking
if (id(low_battery).state || id(ups_fault).state || id(overload_warning).state) {
auto call = id(ups_status_led).turn_on();
call.set_effect("Critical Strobe");
call.perform();
}
// Battery operation (medium priority) - Orange pulsing
else if (id(on_battery).state && !id(low_battery).state) {
auto call = id(ups_status_led).turn_on();
call.set_rgb(1.0, 0.6, 0.0); // Orange
call.set_effect("Battery Operation");
call.perform();
}
// Charging (low priority) - Yellow pulsing
else if (id(battery_charging).state && id(ups_online).state) {
auto call = id(ups_status_led).turn_on();
call.set_rgb(1.0, 1.0, 0.0); // Yellow
call.set_effect("Battery Pulse");
call.perform();
}
// Normal operation (online, not on battery) - Green breathing
else if (id(ups_online).state && !id(on_battery).state) {
auto call = id(ups_status_led).turn_on();
call.set_rgb(0.0, 1.0, 0.0); // Green
call.set_effect("Normal Breathing");
call.perform();
}
// Offline/Unknown - LED off
else {
auto call = id(ups_status_led).turn_off();
call.perform();
}
```
## Integration Examples
### Home Assistant Automation
```yaml
# automation.yaml
automation:
- alias: "UPS Power Loss Alert"
trigger:
- platform: state
entity_id: binary_sensor.ups_on_battery
to: 'on'
action:
- service: notify.mobile_app
data:
message: "⚡ Power outage detected! UPS running on battery."
- alias: "UPS Low Battery Critical"
trigger:
- platform: state
entity_id: binary_sensor.ups_low_battery
to: 'on'
action:
- service: script.shutdown_servers
- service: notify.mobile_app
data:
message: "🔋 UPS battery critically low! Initiating shutdown sequence."
```
## FAQ
**Q: Can I monitor multiple UPS devices?**
A: Each ESP32-S3 supports one UPS via USB OTG. Use multiple ESP32-S3 devices for multiple UPS units.
**Q: Does this work with network-attached UPS devices?**
A: No, this component requires direct USB connection. For network UPS monitoring, use a different ESPHome component that supports network communication.
**Q: What's the power consumption?**
A: Typical ESP32-S3 power consumption: ~100-200mA @ 5V during normal operation.
**Q: Can I use this with other ESP32 variants?**
A: Only ESP32-S3 supports USB OTG required for direct UPS communication.
## Development
### Adding Custom Protocols
1. Inherit from `UpsProtocolBase`
2. Implement required methods: `detect()`, `initialize()`, `read_data()`
3. Add to protocol detection in `detect_ups_protocol()`
4. Update vendor ID mapping in `ups_vendors.h`
### Testing
```yaml
# Use simulation mode for development
ups_hid:
simulation_mode: true
```
## Support
For issues and questions:
1. **Check this documentation first** - Most common issues are covered
2. **Enable debug logging** and analyze the output:
```yaml
logger:
level: DEBUG
logs:
ups_hid: DEBUG
```
3. **Search existing issues**: [GitHub Issues](https://github.com/bullshit/esphome-components/issues)
4. **Create new issue** with:
- Complete ESPHome configuration
- Relevant log output
- UPS model and vendor/product IDs
- ESP32-S3 board information
### Reporting Bugs
Include this information in bug reports:
- ESPHome version
- ESP32-S3 board model
- UPS make/model and USB vendor/product IDs
- Complete error logs with DEBUG level enabled
- Your ESPHome configuration (sanitized)
### Feature Requests
For new UPS protocol support:
- UPS vendor and model information
- USB vendor/product IDs (check logs)
- Any available protocol documentation
- Sample communication logs if possible
+111
View File
@@ -0,0 +1,111 @@
"""UPS HID Component for ESPHome - Enhanced validation and configuration."""
import esphome.codegen as cg
import esphome.config_validation as cv
from esphome.const import (
CONF_ID,
CONF_UPDATE_INTERVAL,
)
DEPENDENCIES = ["esp32"]
MULTI_CONF = True
CONF_SIMULATION_MODE = "simulation_mode"
CONF_USB_VENDOR_ID = "usb_vendor_id"
CONF_USB_PRODUCT_ID = "usb_product_id"
CONF_PROTOCOL_TIMEOUT = "protocol_timeout"
CONF_AUTO_DETECT_PROTOCOL = "auto_detect_protocol"
CONF_UPS_HID_ID = "ups_hid_id"
# Known UPS vendor IDs for validation
KNOWN_VENDOR_IDS = {
0x0463: "MGE Office Protection Systems",
0x050D: "Belkin",
0x051D: "APC",
0x05B8: "SVEN",
0x0665: "Cypress/Belkin",
0x06DA: "MGE UPS Systems",
0x0764: "CyberPower",
0x0925: "Richcomm",
0x09AE: "Tripp Lite",
0x09D6: "Micropower",
}
ups_hid_ns = cg.esphome_ns.namespace("ups_hid")
UpsHidComponent = ups_hid_ns.class_("UpsHidComponent", cg.PollingComponent)
def validate_usb_config(config):
"""Validate USB configuration with helpful warnings."""
vendor_id = config.get(CONF_USB_VENDOR_ID, 0x051D)
product_id = config.get(CONF_USB_PRODUCT_ID, 0x0002)
# Validate non-zero IDs
if vendor_id == 0 or product_id == 0:
raise cv.Invalid("USB vendor and product IDs must be non-zero")
# Warn about unknown vendor IDs
if vendor_id not in KNOWN_VENDOR_IDS:
raise cv.Invalid("Unknown vendor id")
return config
def validate_protocol_timeout(value):
"""Validate protocol timeout with reasonable bounds."""
value = cv.positive_time_period_milliseconds(value)
ms = value.total_milliseconds
if ms < 5000:
raise cv.Invalid(
"Protocol timeout must be at least 5 seconds for reliable communication"
)
if ms > 60000:
raise cv.Invalid(
"Protocol timeout must be at most 60 seconds to avoid blocking"
)
return value
def validate_update_interval(value):
"""Validate update interval for UPS HID monitoring."""
value = cv.update_interval(value)
ms = value.total_milliseconds
if ms < 5000:
cg.global_ns.logger.LOGGER.warning(
"Update interval less than 5 seconds may cause excessive USB traffic. "
"Consider using 10s or higher for production."
)
return value
CONFIG_SCHEMA = cv.All(
cv.Schema(
{
cv.GenerateID(): cv.declare_id(UpsHidComponent),
cv.Optional(CONF_UPDATE_INTERVAL, default="30s"): validate_update_interval,
cv.Optional(CONF_SIMULATION_MODE, default=False): cv.boolean,
cv.Optional(CONF_USB_VENDOR_ID, default=0x051D): cv.hex_uint16_t,
cv.Optional(CONF_USB_PRODUCT_ID, default=0x0002): cv.hex_uint16_t,
cv.Optional(
CONF_PROTOCOL_TIMEOUT, default="15s"
): validate_protocol_timeout,
cv.Optional(CONF_AUTO_DETECT_PROTOCOL, default=True): cv.boolean,
}
).extend(cv.COMPONENT_SCHEMA),
validate_usb_config,
)
async def to_code(config):
var = cg.new_Pvariable(config[CONF_ID])
await cg.register_component(var, config)
cg.add(var.set_simulation_mode(config[CONF_SIMULATION_MODE]))
cg.add(var.set_usb_vendor_id(config[CONF_USB_VENDOR_ID]))
cg.add(var.set_usb_product_id(config[CONF_USB_PRODUCT_ID]))
cg.add(var.set_protocol_timeout(config[CONF_PROTOCOL_TIMEOUT]))
cg.add(var.set_auto_detect_protocol(config[CONF_AUTO_DETECT_PROTOCOL]))
+343
View File
@@ -0,0 +1,343 @@
#include "apc_hid_protocol.h"
#include "esphome/core/log.h"
#include "esphome/core/helpers.h"
#include <cstring>
namespace esphome {
namespace ups_hid {
static const char *const APC_HID_TAG = "ups_hid.apc_hid";
// APC HID Usage Pages and Usage IDs (based on NUT project research)
static const uint16_t APC_USAGE_PAGE_UPS = 0x84;
static const uint16_t APC_USAGE_PAGE_BATTERY = 0x85;
static const uint16_t APC_USAGE_PAGE_POWER = 0x80;
// HID Report IDs commonly used by APC UPS devices
static const uint8_t APC_REPORT_ID_STATUS = 0x01;
static const uint8_t APC_REPORT_ID_BATTERY = 0x02;
static const uint8_t APC_REPORT_ID_VOLTAGE = 0x03;
static const uint8_t APC_REPORT_ID_POWER = 0x04;
static const uint8_t APC_REPORT_ID_CONFIG = 0x05;
// APC-specific date conversion (hex-as-decimal format)
static std::string convert_apc_date(uint32_t apc_date) {
if (apc_date == 0) return "Unknown";
// APC uses hex-as-decimal format, e.g., 0x102202 = 10/22/02
uint8_t month = (apc_date >> 16) & 0xFF;
uint8_t day = (apc_date >> 8) & 0xFF;
uint8_t year = apc_date & 0xFF;
// Convert 2-digit year to 4-digit (Y2K handling)
uint16_t full_year = (year <= 69) ? (2000 + year) : (1900 + year);
char date_str[16];
snprintf(date_str, sizeof(date_str), "%02d/%02d/%04d", month, day, full_year);
return std::string(date_str);
}
// APC HID Protocol implementation
ApcHidProtocol::ApcHidProtocol(UpsHidComponent *parent) : UpsProtocolBase(parent) {}
bool ApcHidProtocol::detect() {
ESP_LOGD(APC_HID_TAG, "Detecting APC HID Protocol...");
// Try to read device descriptor or status report
HidReport status_report;
if (read_hid_report(APC_REPORT_ID_STATUS, status_report)) {
ESP_LOGD(APC_HID_TAG, "APC HID response received, report ID: 0x%02X", status_report.report_id);
return true;
}
ESP_LOGD(APC_HID_TAG, "No APC HID Protocol response");
return false;
}
bool ApcHidProtocol::initialize() {
ESP_LOGD(APC_HID_TAG, "Initializing APC HID Protocol...");
// Initialize HID communication
if (!init_hid_communication()) {
ESP_LOGE(APC_HID_TAG, "Failed to initialize HID communication");
return false;
}
// Read basic device information
read_device_info();
ESP_LOGI(APC_HID_TAG, "APC HID Protocol initialized successfully");
return true;
}
bool ApcHidProtocol::read_data(UpsData &data) {
ESP_LOGV(APC_HID_TAG, "Reading APC HID UPS data...");
bool success = true;
// Read status report
HidReport status_report;
if (read_hid_report(APC_REPORT_ID_STATUS, status_report)) {
parse_status_report(status_report, data);
} else {
ESP_LOGW(APC_HID_TAG, "Failed to read status report");
success = false;
}
// Read battery report
HidReport battery_report;
if (read_hid_report(APC_REPORT_ID_BATTERY, battery_report)) {
parse_battery_report(battery_report, data);
} else {
ESP_LOGW(APC_HID_TAG, "Failed to read battery report");
}
// Read voltage/power report
HidReport voltage_report;
if (read_hid_report(APC_REPORT_ID_VOLTAGE, voltage_report)) {
parse_voltage_report(voltage_report, data);
} else {
ESP_LOGW(APC_HID_TAG, "Failed to read voltage report");
}
HidReport power_report;
if (read_hid_report(APC_REPORT_ID_POWER, power_report)) {
parse_power_report(power_report, data);
} else {
ESP_LOGV(APC_HID_TAG, "No power report available");
}
return success;
}
bool ApcHidProtocol::init_hid_communication() {
// Set up HID communication parameters
// For APC devices, we typically use standard HID interrupt transfers
return true;
}
bool ApcHidProtocol::read_hid_report(uint8_t report_id, HidReport &report) {
// Prepare HID Get Report request
std::vector<uint8_t> request = {
0x21, // bmRequestType: Class, Interface, Host-to-device
0x01, // bRequest: GET_REPORT
report_id, 0x03, // wValue: Report Type (Input=0x01, Output=0x02, Feature=0x03) and Report ID
0x00, 0x00, // wIndex: Interface
0x40, 0x00 // wLength: Maximum report length (64 bytes)
};
std::vector<uint8_t> response;
if (!send_command(request, response, 2000)) {
return false;
}
if (response.empty()) {
return false;
}
report.report_id = report_id;
report.data = response;
return true;
}
bool ApcHidProtocol::write_hid_report(const HidReport &report) {
std::vector<uint8_t> request = {report.report_id};
request.insert(request.end(), report.data.begin(), report.data.end());
std::vector<uint8_t> response;
return send_command(request, response, 1000);
}
void ApcHidProtocol::parse_status_report(const HidReport &report, UpsData &data) {
if (report.data.size() < 4) {
ESP_LOGW(APC_HID_TAG, "Status report too short: %zu bytes", report.data.size());
return;
}
uint32_t status_flags = 0;
// Parse common APC HID status bits
uint8_t status_byte_1 = report.data[0];
uint8_t status_byte_2 = report.data[1];
// Online/AC Present
if (status_byte_1 & 0x04) {
status_flags |= UPS_STATUS_ONLINE;
}
// On Battery
if (status_byte_1 & 0x10) {
status_flags |= UPS_STATUS_ON_BATTERY;
}
// Low Battery
if (status_byte_1 & 0x02) {
status_flags |= UPS_STATUS_LOW_BATTERY;
}
// Replace Battery
if (status_byte_1 & 0x08) {
status_flags |= UPS_STATUS_REPLACE_BATTERY;
}
// Charging
if (status_byte_2 & 0x01) {
status_flags |= UPS_STATUS_CHARGING;
}
// Overload
if (status_byte_2 & 0x20) {
status_flags |= UPS_STATUS_OVERLOAD;
}
// Fault/Shutdown
if (status_byte_2 & 0x40) {
status_flags |= UPS_STATUS_FAULT;
}
data.status_flags = status_flags;
ESP_LOGV(APC_HID_TAG, "Status flags: 0x%08X (bytes: 0x%02X 0x%02X)",
status_flags, status_byte_1, status_byte_2);
}
void ApcHidProtocol::parse_battery_report(const HidReport &report, UpsData &data) {
if (report.data.size() < 8) {
ESP_LOGW(APC_HID_TAG, "Battery report too short: %zu bytes", report.data.size());
return;
}
// Battery charge level (typically at offset 0-1, 16-bit value, percentage)
uint16_t battery_raw = (report.data[1] << 8) | report.data[0];
if (battery_raw <= 100) {
data.battery_level = static_cast<float>(battery_raw);
ESP_LOGV(APC_HID_TAG, "Battery Level: %.1f%%", data.battery_level);
} else {
ESP_LOGW(APC_HID_TAG, "Battery level out of range: %u", battery_raw);
}
// Runtime remaining (typically at offset 2-3, 16-bit value, minutes)
uint16_t runtime_raw = (report.data[3] << 8) | report.data[2];
if (runtime_raw > 0 && runtime_raw < 65535) {
data.runtime_minutes = static_cast<float>(runtime_raw);
ESP_LOGV(APC_HID_TAG, "Runtime: %.1f min", data.runtime_minutes);
}
// Battery voltage (if available, typically at offset 4-5)
if (report.data.size() >= 6) {
uint16_t battery_voltage_raw = (report.data[5] << 8) | report.data[4];
if (battery_voltage_raw > 0) {
// Convert from raw value to voltage (scaling depends on UPS model)
float battery_voltage = static_cast<float>(battery_voltage_raw) / 100.0f;
ESP_LOGV(APC_HID_TAG, "Battery Voltage: %.2fV", battery_voltage);
}
}
}
void ApcHidProtocol::parse_voltage_report(const HidReport &report, UpsData &data) {
if (report.data.size() < 8) {
ESP_LOGW(APC_HID_TAG, "Voltage report too short: %zu bytes", report.data.size());
return;
}
// Input voltage (typically at offset 0-1, 16-bit value)
uint16_t input_voltage_raw = (report.data[1] << 8) | report.data[0];
if (input_voltage_raw > 0) {
// Most APC devices report voltage in tenths of volts
float voltage = static_cast<float>(input_voltage_raw) / 10.0f;
// Sanity check - typical UPS voltages are between 80-300V
if (voltage >= 80.0f && voltage <= 300.0f) {
data.input_voltage = voltage;
ESP_LOGV(APC_HID_TAG, "Input Voltage: %.1fV", data.input_voltage);
} else {
ESP_LOGW(APC_HID_TAG, "Input voltage out of range: %.1fV", voltage);
}
}
// Output voltage (typically at offset 2-3, 16-bit value)
uint16_t output_voltage_raw = (report.data[3] << 8) | report.data[2];
if (output_voltage_raw > 0) {
float voltage = static_cast<float>(output_voltage_raw) / 10.0f;
// Sanity check - typical UPS voltages are between 80-300V
if (voltage >= 80.0f && voltage <= 300.0f) {
data.output_voltage = voltage;
ESP_LOGV(APC_HID_TAG, "Output Voltage: %.1fV", data.output_voltage);
} else {
ESP_LOGW(APC_HID_TAG, "Output voltage out of range: %.1fV", voltage);
}
}
// Line frequency (if available, typically at offset 4-5)
if (report.data.size() >= 6) {
uint16_t frequency_raw = (report.data[5] << 8) | report.data[4];
if (frequency_raw > 0) {
data.frequency = static_cast<float>(frequency_raw) / 10.0f;
ESP_LOGV(APC_HID_TAG, "Frequency: %.1f Hz", data.frequency);
}
}
}
void ApcHidProtocol::parse_power_report(const HidReport &report, UpsData &data) {
if (report.data.size() < 4) {
ESP_LOGW(APC_HID_TAG, "Power report too short: %zu bytes", report.data.size());
return;
}
// Load percentage (typically at offset 0-1, 16-bit value)
uint16_t load_raw = (report.data[1] << 8) | report.data[0];
if (load_raw <= 100) {
data.load_percent = static_cast<float>(load_raw);
ESP_LOGV(APC_HID_TAG, "Load: %.1f%%", data.load_percent);
} else {
ESP_LOGW(APC_HID_TAG, "Load percentage out of range: %u", load_raw);
// Clamp to valid range like Smart Protocol does
data.load_percent = std::max(0.0f, std::min(100.0f, static_cast<float>(load_raw)));
}
// Apparent power (if available, typically at offset 2-3)
if (report.data.size() >= 4) {
uint16_t apparent_power_raw = (report.data[3] << 8) | report.data[2];
if (apparent_power_raw > 0) {
ESP_LOGV(APC_HID_TAG, "Apparent Power: %u VA", apparent_power_raw);
}
}
}
void ApcHidProtocol::read_device_info() {
// Read configuration report for device information
HidReport config_report;
if (read_hid_report(APC_REPORT_ID_CONFIG, config_report)) {
parse_device_info_report(config_report);
}
}
void ApcHidProtocol::parse_device_info_report(const HidReport &report) {
if (report.data.size() < 16) {
ESP_LOGW(APC_HID_TAG, "Device info report too short: %zu bytes", report.data.size());
return;
}
// Manufacturer date (APC hex-as-decimal format, typically at offset 8-11)
if (report.data.size() >= 12) {
uint32_t mfr_date = (report.data[11] << 24) | (report.data[10] << 16) |
(report.data[9] << 8) | report.data[8];
if (mfr_date != 0) {
std::string date_str = convert_apc_date(mfr_date);
ESP_LOGD(APC_HID_TAG, "Manufacture Date: %s", date_str.c_str());
}
}
// Battery replacement date (if available, typically at offset 12-15)
if (report.data.size() >= 16) {
uint32_t battery_date = (report.data[15] << 24) | (report.data[14] << 16) |
(report.data[13] << 8) | report.data[12];
if (battery_date != 0) {
std::string date_str = convert_apc_date(battery_date);
ESP_LOGD(APC_HID_TAG, "Battery Date: %s", date_str.c_str());
}
}
}
} // namespace ups_hid
} // namespace esphome
+40
View File
@@ -0,0 +1,40 @@
#pragma once
#include "ups_hid.h"
namespace esphome {
namespace ups_hid {
// APC HID Protocol implementation for modern APC UPS devices
class ApcHidProtocol : public UpsProtocolBase {
public:
explicit ApcHidProtocol(UpsHidComponent *parent);
bool detect() override;
bool initialize() override;
bool read_data(UpsData &data) override;
UpsProtocol get_protocol_type() const override { return PROTOCOL_APC_HID; }
std::string get_protocol_name() const override { return "APC HID Protocol"; }
private:
struct HidReport {
uint8_t report_id;
std::vector<uint8_t> data;
HidReport() : report_id(0) {}
};
bool init_hid_communication();
bool read_hid_report(uint8_t report_id, HidReport &report);
bool write_hid_report(const HidReport &report);
void parse_status_report(const HidReport &report, UpsData &data);
void parse_battery_report(const HidReport &report, UpsData &data);
void parse_voltage_report(const HidReport &report, UpsData &data);
void parse_power_report(const HidReport &report, UpsData &data);
void read_device_info();
void parse_device_info_report(const HidReport &report);
};
} // namespace ups_hid
} // namespace esphome
+487
View File
@@ -0,0 +1,487 @@
#include "ups_hid.h"
#include "esphome/core/log.h"
#include "esphome/core/helpers.h"
#include "esphome/core/hal.h"
#include <cstdlib>
#include <cctype>
namespace esphome
{
namespace ups_hid
{
static const char *const APC_TAG = "ups_hid.apc";
// APC Smart Protocol Commands
static const char APC_CMD_STATUS = 'Q'; // Status inquiry
static const char APC_CMD_BATTERY_LEVEL = 'f'; // Battery level
static const char APC_CMD_INPUT_VOLTAGE = 'L'; // Input line voltage
static const char APC_CMD_OUTPUT_VOLTAGE = 'O'; // Output voltage
static const char APC_CMD_LOAD = 'P'; // Output load in %
static const char APC_CMD_RUNTIME = 'j'; // Runtime remaining
static const char APC_CMD_FREQUENCY = 'F'; // Line frequency
static const char APC_CMD_MODEL = '\x01'; // UPS model
static const char APC_CMD_FIRMWARE = 'V'; // Firmware version
static const char APC_CMD_SERIAL = 'n'; // Serial number
static const char APC_CMD_SELFTEST = 'A'; // Self test
// Helper function to safely parse float from string
static bool parse_float_safe(const std::string &str, float &result)
{
if (str.empty())
{
return false;
}
// Simple validation - check if string contains valid float characters
bool has_digit = false;
bool has_dot = false;
size_t start_pos = 0;
// Skip leading whitespace
while (start_pos < str.length() && std::isspace(str[start_pos]))
{
start_pos++;
}
if (start_pos >= str.length())
{
return false;
}
// Check for optional negative sign
if (str[start_pos] == '-' || str[start_pos] == '+')
{
start_pos++;
}
// Validate characters
for (size_t i = start_pos; i < str.length(); i++)
{
char c = str[i];
if (std::isdigit(c))
{
has_digit = true;
}
else if (c == '.' && !has_dot)
{
has_dot = true;
}
else if (std::isspace(c))
{
// Allow trailing whitespace
for (size_t j = i; j < str.length(); j++)
{
if (!std::isspace(str[j]))
{
return false;
}
}
break;
}
else
{
return false;
}
}
if (!has_digit)
{
return false;
}
// Use atof for conversion (doesn't throw exceptions)
char *endptr = nullptr;
const char *cstr = str.c_str();
result = strtof(cstr, &endptr);
// Check if conversion was successful
if (endptr == cstr || (*endptr != '\0' && !std::isspace(*endptr)))
{
return false;
}
return true;
}
// Helper function to safely parse unsigned long from string (for hex parsing)
static bool parse_hex_safe(const std::string &str, uint8_t &result)
{
if (str.empty() || str.length() > 2)
{
return false;
}
// Validate hex characters
for (char c : str)
{
if (!std::isxdigit(c))
{
return false;
}
}
char *endptr = nullptr;
unsigned long val = strtoul(str.c_str(), &endptr, 16);
if (endptr == str.c_str() || *endptr != '\0' || val > 0xFF)
{
return false;
}
result = static_cast<uint8_t>(val);
return true;
}
bool ApcSmartProtocol::detect()
{
ESP_LOGD(APC_TAG, "Detecting APC Smart Protocol...");
// Try to get a response from the UPS with a simple status command
std::string response;
if (send_smart_command(APC_CMD_STATUS, response))
{
ESP_LOGD(APC_TAG, "APC response received: %s", response.c_str());
return true;
}
ESP_LOGD(APC_TAG, "No APC Smart Protocol response");
return false;
}
bool ApcSmartProtocol::initialize()
{
ESP_LOGD(APC_TAG, "Initializing APC Smart Protocol...");
// Get basic device information
std::string model, firmware, serial;
if (send_smart_command(APC_CMD_MODEL, model))
{
ESP_LOGD(APC_TAG, "UPS Model: %s", model.c_str());
}
if (send_smart_command(APC_CMD_FIRMWARE, firmware))
{
ESP_LOGD(APC_TAG, "Firmware: %s", firmware.c_str());
}
if (send_smart_command(APC_CMD_SERIAL, serial))
{
ESP_LOGD(APC_TAG, "Serial: %s", serial.c_str());
}
ESP_LOGI(APC_TAG, "APC Smart Protocol initialized successfully");
return true;
}
bool ApcSmartProtocol::read_data(UpsData &data)
{
ESP_LOGV(APC_TAG, "Reading APC UPS data...");
std::string response;
bool success = true;
// Read status flags first
if (send_smart_command(APC_CMD_STATUS, response))
{
data.status_flags = parse_status_flags(response);
ESP_LOGV(APC_TAG, "Status: %s (flags: 0x%08X)", response.c_str(), data.status_flags);
}
else
{
ESP_LOGW(APC_TAG, "Failed to read status");
success = false;
}
// Read battery level
if (send_smart_command(APC_CMD_BATTERY_LEVEL, response))
{
data.battery_level = parse_percentage(response);
ESP_LOGV(APC_TAG, "Battery Level: %.1f%%", data.battery_level);
}
else
{
ESP_LOGW(APC_TAG, "Failed to read battery level");
data.battery_level = NAN;
}
// Read input voltage
if (send_smart_command(APC_CMD_INPUT_VOLTAGE, response))
{
data.input_voltage = parse_voltage(response);
ESP_LOGV(APC_TAG, "Input Voltage: %.1fV", data.input_voltage);
}
else
{
ESP_LOGW(APC_TAG, "Failed to read input voltage");
data.input_voltage = NAN;
}
// Read output voltage
if (send_smart_command(APC_CMD_OUTPUT_VOLTAGE, response))
{
data.output_voltage = parse_voltage(response);
ESP_LOGV(APC_TAG, "Output Voltage: %.1fV", data.output_voltage);
}
else
{
ESP_LOGW(APC_TAG, "Failed to read output voltage");
data.output_voltage = NAN;
}
// Read load percentage
if (send_smart_command(APC_CMD_LOAD, response))
{
data.load_percent = parse_percentage(response);
ESP_LOGV(APC_TAG, "Load: %.1f%%", data.load_percent);
}
else
{
ESP_LOGW(APC_TAG, "Failed to read load");
data.load_percent = NAN;
}
// Read runtime
if (send_smart_command(APC_CMD_RUNTIME, response))
{
// Runtime is typically returned in minutes
if (!response.empty())
{
float runtime;
if (parse_float_safe(response, runtime))
{
data.runtime_minutes = runtime;
ESP_LOGV(APC_TAG, "Runtime: %.1f min", data.runtime_minutes);
}
else
{
ESP_LOGW(APC_TAG, "Failed to parse runtime: %s", response.c_str());
data.runtime_minutes = NAN;
}
}
}
else
{
ESP_LOGW(APC_TAG, "Failed to read runtime");
data.runtime_minutes = NAN;
}
// Read frequency
if (send_smart_command(APC_CMD_FREQUENCY, response))
{
if (!response.empty())
{
float frequency;
if (parse_float_safe(response, frequency))
{
data.frequency = frequency;
ESP_LOGV(APC_TAG, "Frequency: %.1f Hz", data.frequency);
}
else
{
ESP_LOGW(APC_TAG, "Failed to parse frequency: %s", response.c_str());
data.frequency = NAN;
}
}
}
else
{
ESP_LOGW(APC_TAG, "Failed to read frequency");
data.frequency = NAN;
}
// Read device information (less frequently updated)
static uint32_t last_info_read = 0;
uint32_t now = millis();
if (now - last_info_read > 60000)
{ // Update every 60 seconds
if (send_smart_command(APC_CMD_MODEL, response))
{
data.model = response;
data.manufacturer = "APC";
}
if (send_smart_command(APC_CMD_FIRMWARE, response))
{
data.firmware_version = response;
}
if (send_smart_command(APC_CMD_SERIAL, response))
{
data.serial_number = response;
}
last_info_read = now;
}
return success;
}
bool ApcSmartProtocol::send_smart_command(char cmd, std::string &response)
{
ESP_LOGVV(APC_TAG, "Sending APC command: 0x%02X ('%c')", cmd, cmd);
std::vector<uint8_t> command = {static_cast<uint8_t>(cmd)};
std::vector<uint8_t> raw_response;
if (!send_command(command, raw_response, 2000))
{
ESP_LOGW(APC_TAG, "Failed to send command 0x%02X", cmd);
return false;
}
response = bytes_to_string(raw_response);
// Remove any trailing newlines or carriage returns
while (!response.empty() && (response.back() == '\n' || response.back() == '\r'))
{
response.pop_back();
}
ESP_LOGVV(APC_TAG, "Command 0x%02X response: '%s'", cmd, response.c_str());
return true;
}
float ApcSmartProtocol::parse_voltage(const std::string &response)
{
if (response.empty())
{
return NAN;
}
float voltage;
if (!parse_float_safe(response, voltage))
{
ESP_LOGW(APC_TAG, "Failed to parse voltage: '%s'", response.c_str());
return NAN;
}
// Sanity check - typical UPS voltages are between 80-300V
if (voltage >= 80.0f && voltage <= 300.0f)
{
return voltage;
}
else
{
ESP_LOGW(APC_TAG, "Voltage value out of range: %.1f", voltage);
return NAN;
}
}
float ApcSmartProtocol::parse_percentage(const std::string &response)
{
if (response.empty())
{
return NAN;
}
float percentage;
if (!parse_float_safe(response, percentage))
{
ESP_LOGW(APC_TAG, "Failed to parse percentage: '%s'", response.c_str());
return NAN;
}
// Sanity check - percentages should be 0-100
if (percentage >= 0.0f && percentage <= 100.0f)
{
return percentage;
}
else
{
ESP_LOGW(APC_TAG, "Percentage value out of range: %.1f", percentage);
return std::max(0.0f, std::min(100.0f, percentage)); // Clamp to valid range
}
}
uint32_t ApcSmartProtocol::parse_status_flags(const std::string &response)
{
if (response.empty())
{
return UPS_STATUS_UNKNOWN;
}
uint32_t flags = 0;
// APC Smart Protocol status response format varies by model
// Common responses include status bits or text responses
// Check for common status indicators in the response
std::string upper_response = response;
std::transform(upper_response.begin(), upper_response.end(), upper_response.begin(), ::toupper);
// Parse hex status byte if present (some APC models return hex status)
if (response.length() == 2 || response.length() == 1)
{
uint8_t status_byte;
if (parse_hex_safe(response, status_byte))
{
// APC status bits (varies by model, these are common interpretations)
if (status_byte & 0x08)
flags |= UPS_STATUS_ONLINE;
if (status_byte & 0x10)
flags |= UPS_STATUS_ON_BATTERY;
if (status_byte & 0x01)
flags |= UPS_STATUS_LOW_BATTERY;
if (status_byte & 0x40)
flags |= UPS_STATUS_REPLACE_BATTERY;
if (status_byte & 0x04)
flags |= UPS_STATUS_CHARGING;
return flags;
}
// If hex parsing failed, continue with text parsing
}
// Parse text-based status responses
if (upper_response.find("ONLINE") != std::string::npos)
{
flags |= UPS_STATUS_ONLINE;
}
if (upper_response.find("ONBATT") != std::string::npos ||
upper_response.find("ON BATTERY") != std::string::npos)
{
flags |= UPS_STATUS_ON_BATTERY;
}
if (upper_response.find("LOWBATT") != std::string::npos ||
upper_response.find("LOW BATTERY") != std::string::npos)
{
flags |= UPS_STATUS_LOW_BATTERY;
}
if (upper_response.find("CHARGING") != std::string::npos)
{
flags |= UPS_STATUS_CHARGING;
}
if (upper_response.find("REPLACE") != std::string::npos)
{
flags |= UPS_STATUS_REPLACE_BATTERY;
}
if (upper_response.find("OVERLOAD") != std::string::npos)
{
flags |= UPS_STATUS_OVERLOAD;
}
if (upper_response.find("FAULT") != std::string::npos ||
upper_response.find("ERROR") != std::string::npos)
{
flags |= UPS_STATUS_FAULT;
}
// If no status detected but we got a response, assume online
if (flags == 0 && !response.empty())
{
flags |= UPS_STATUS_ONLINE;
}
return flags;
}
} // namespace ups_hid
} // namespace esphome
+16
View File
@@ -0,0 +1,16 @@
#include "binary_sensor.h"
#include "esphome/core/log.h"
namespace esphome {
namespace ups_hid {
static const char *const TAG_BINARY = "ups_hid.binary_sensor";
void UpsHidBinarySensor::dump_config() {
ESP_LOGCONFIG(TAG_BINARY, "UPS HID Binary Sensor:");
ESP_LOGCONFIG(TAG_BINARY, " Type: %s", sensor_type_.c_str());
LOG_BINARY_SENSOR(" ", "Binary Sensor", this);
}
} // namespace ups_hid
} // namespace esphome
+23
View File
@@ -0,0 +1,23 @@
#pragma once
#include "esphome/core/component.h"
#include "esphome/components/binary_sensor/binary_sensor.h"
#include "ups_hid.h"
namespace esphome
{
namespace ups_hid
{
class UpsHidBinarySensor : public binary_sensor::BinarySensor, public Component
{
public:
void set_sensor_type(const std::string &type) { sensor_type_ = type; }
void dump_config() override;
protected:
std::string sensor_type_;
};
} // namespace ups_hid
} // namespace esphome
+65
View File
@@ -0,0 +1,65 @@
import esphome.codegen as cg
import esphome.config_validation as cv
from esphome.components import binary_sensor
from esphome.const import (
CONF_TYPE,
DEVICE_CLASS_CONNECTIVITY,
DEVICE_CLASS_BATTERY,
DEVICE_CLASS_PROBLEM,
DEVICE_CLASS_POWER,
)
from . import ups_hid_ns, UpsHidComponent, CONF_UPS_HID_ID
DEPENDENCIES = ["ups_hid"]
UpsHidBinarySensor = ups_hid_ns.class_(
"UpsHidBinarySensor", binary_sensor.BinarySensor, cg.Component
)
BINARY_SENSOR_TYPES = {
"online": {
"device_class": DEVICE_CLASS_CONNECTIVITY,
},
"on_battery": {
"device_class": DEVICE_CLASS_BATTERY,
},
"low_battery": {
"device_class": DEVICE_CLASS_BATTERY,
},
"fault": {
"device_class": DEVICE_CLASS_PROBLEM,
},
"overload": {
"device_class": DEVICE_CLASS_POWER,
},
"charging": {
"device_class": DEVICE_CLASS_BATTERY,
},
}
CONFIG_SCHEMA = binary_sensor.binary_sensor_schema(UpsHidBinarySensor).extend(
{
cv.GenerateID(CONF_UPS_HID_ID): cv.use_id(UpsHidComponent),
cv.Required(CONF_TYPE): cv.one_of(*BINARY_SENSOR_TYPES, lower=True),
}
)
async def to_code(config):
parent = await cg.get_variable(config[CONF_UPS_HID_ID])
var = await binary_sensor.new_binary_sensor(config)
await cg.register_component(var, config)
sensor_type = config[CONF_TYPE]
cg.add(var.set_sensor_type(sensor_type))
cg.add(parent.register_binary_sensor(var, sensor_type))
# Apply sensor type specific configuration
if sensor_type in BINARY_SENSOR_TYPES:
sensor_config = BINARY_SENSOR_TYPES[sensor_type]
# Override config with sensor type defaults if not specified
if "device_class" not in config and "device_class" in sensor_config:
cg.add(var.set_device_class(sensor_config["device_class"]))
+361
View File
@@ -0,0 +1,361 @@
#include "ups_hid.h"
#include "esphome/core/log.h"
namespace esphome {
namespace ups_hid {
static const char *const CP_TAG = "ups_hid.cyberpower";
// CyberPower HID Report IDs and data structures
static const uint8_t CP_REPORT_ID_UPS_STATUS = 0x01;
static const uint8_t CP_REPORT_ID_BATTERY_INFO = 0x02;
static const uint8_t CP_REPORT_ID_VOLTAGE_INFO = 0x03;
static const uint8_t CP_REPORT_ID_DEVICE_INFO = 0x04;
// HID Usage Page definitions for UPS (Power Device) - Based on NUT reference
static const uint16_t HID_USAGE_PAGE_POWER_DEVICE = 0x84;
static const uint16_t HID_USAGE_PAGE_BATTERY = 0x85;
static const uint16_t HID_USAGE_PAGE_UPS = 0x84;
// Power Device Class HID Usages (from NUT cps-hid.c)
static const uint16_t HID_USAGE_UPS_BATTERY_CHARGE = 0x66;
static const uint16_t HID_USAGE_UPS_RUNTIME_TO_EMPTY = 0x68;
static const uint16_t HID_USAGE_UPS_AC_PRESENT = 0x5A;
static const uint16_t HID_USAGE_UPS_BATTERY_PRESENT = 0x5B;
static const uint16_t HID_USAGE_UPS_CHARGING = 0x44;
static const uint16_t HID_USAGE_UPS_DISCHARGING = 0x45;
static const uint16_t HID_USAGE_UPS_NEED_REPLACEMENT = 0x4B;
static const uint16_t HID_USAGE_UPS_FULLY_CHARGED = 0x49;
static const uint16_t HID_USAGE_UPS_INPUT_VOLTAGE = 0x30;
static const uint16_t HID_USAGE_UPS_OUTPUT_VOLTAGE = 0x31;
static const uint16_t HID_USAGE_UPS_INPUT_FREQUENCY = 0x32;
static const uint16_t HID_USAGE_UPS_PERCENT_LOAD = 0x35;
bool CyberPowerProtocol::detect() {
ESP_LOGD(CP_TAG, "Detecting CyberPower HID Protocol...");
// First try vendor/product ID detection (like NUT does)
// CyberPower vendor ID is 0x0764
if (parent_->get_usb_vendor_id() == 0x0764) {
ESP_LOGD(CP_TAG, "CyberPower vendor ID detected: 0x%04X", parent_->get_usb_vendor_id());
// Try to get basic HID report to confirm communication
HidReport request;
request.report_id = CP_REPORT_ID_UPS_STATUS;
request.data = {0x00};
HidReport response;
if (send_hid_report(request, response)) {
ESP_LOGD(CP_TAG, "CyberPower HID communication confirmed");
return true;
}
}
// Fallback: try device info request for unknown devices
HidReport request;
request.report_id = CP_REPORT_ID_DEVICE_INFO;
request.data = {0x00};
HidReport response;
if (send_hid_report(request, response)) {
// Check if response contains CyberPower identifiers
std::string info = bytes_to_string(response.data);
if (info.find("CP") != std::string::npos ||
info.find("CYBER") != std::string::npos ||
info.find("CyberPower") != std::string::npos) {
ESP_LOGD(CP_TAG, "CyberPower device identified from response");
return true;
}
}
ESP_LOGD(CP_TAG, "No CyberPower HID Protocol detected");
return false;
}
bool CyberPowerProtocol::initialize() {
ESP_LOGD(CP_TAG, "Initializing CyberPower HID Protocol...");
// Get device information
HidReport device_info_request;
device_info_request.report_id = CP_REPORT_ID_DEVICE_INFO;
device_info_request.data = {0x00};
HidReport device_info_response;
if (send_hid_report(device_info_request, device_info_response)) {
ESP_LOGD(CP_TAG, "Device info received, %d bytes", device_info_response.data.size());
// Parse manufacturer and model from device info
// CyberPower HID devices typically include this in the device descriptor
if (device_info_response.data.size() >= 8) {
ESP_LOGD(CP_TAG, "CyberPower device detected");
}
}
ESP_LOGI(CP_TAG, "CyberPower HID Protocol initialized successfully");
return true;
}
bool CyberPowerProtocol::read_data(UpsData &data) {
ESP_LOGV(CP_TAG, "Reading CyberPower UPS data...");
bool success = true;
// Read UPS status
HidReport status_request;
status_request.report_id = CP_REPORT_ID_UPS_STATUS;
status_request.data = {0x00};
HidReport status_response;
if (send_hid_report(status_request, status_response)) {
if (parse_hid_data(status_response, data)) {
ESP_LOGV(CP_TAG, "Status data parsed successfully");
} else {
ESP_LOGW(CP_TAG, "Failed to parse status data");
success = false;
}
} else {
ESP_LOGW(CP_TAG, "Failed to read UPS status");
success = false;
}
// Read battery information
HidReport battery_request;
battery_request.report_id = CP_REPORT_ID_BATTERY_INFO;
battery_request.data = {0x00};
HidReport battery_response;
if (send_hid_report(battery_request, battery_response)) {
if (parse_hid_data(battery_response, data)) {
ESP_LOGV(CP_TAG, "Battery data parsed successfully");
} else {
ESP_LOGW(CP_TAG, "Failed to parse battery data");
}
} else {
ESP_LOGW(CP_TAG, "Failed to read battery info");
}
// Read voltage information
HidReport voltage_request;
voltage_request.report_id = CP_REPORT_ID_VOLTAGE_INFO;
voltage_request.data = {0x00};
HidReport voltage_response;
if (send_hid_report(voltage_request, voltage_response)) {
if (parse_hid_data(voltage_response, data)) {
ESP_LOGV(CP_TAG, "Voltage data parsed successfully");
} else {
ESP_LOGW(CP_TAG, "Failed to parse voltage data");
}
} else {
ESP_LOGW(CP_TAG, "Failed to read voltage info");
}
// Set manufacturer and model for CyberPower
if (data.manufacturer.empty()) {
data.manufacturer = "CyberPower";
}
return success;
}
bool CyberPowerProtocol::send_hid_report(const HidReport &report, HidReport &response) {
ESP_LOGVV(CP_TAG, "Sending HID report ID: 0x%02X, %d bytes", report.report_id, report.data.size());
// Construct HID report packet
std::vector<uint8_t> hid_packet;
hid_packet.push_back(report.report_id);
hid_packet.insert(hid_packet.end(), report.data.begin(), report.data.end());
std::vector<uint8_t> raw_response;
if (!send_command(hid_packet, raw_response, 2000)) {
ESP_LOGW(CP_TAG, "Failed to send HID report");
return false;
}
if (raw_response.empty()) {
ESP_LOGW(CP_TAG, "Empty HID response");
return false;
}
// Parse response
response.report_id = raw_response[0];
response.data.clear();
if (raw_response.size() > 1) {
response.data.assign(raw_response.begin() + 1, raw_response.end());
}
ESP_LOGVV(CP_TAG, "HID response ID: 0x%02X, %d bytes", response.report_id, response.data.size());
return true;
}
bool CyberPowerProtocol::parse_hid_data(const HidReport &report, UpsData &data) {
if (report.data.empty()) {
return false;
}
ESP_LOGVV(CP_TAG, "Parsing HID report ID: 0x%02X", report.report_id);
switch (report.report_id) {
case CP_REPORT_ID_UPS_STATUS:
return parse_status_report(report, data);
case CP_REPORT_ID_BATTERY_INFO:
return parse_battery_report(report, data);
case CP_REPORT_ID_VOLTAGE_INFO:
return parse_voltage_report(report, data);
case CP_REPORT_ID_DEVICE_INFO:
return parse_device_info_report(report, data);
default:
ESP_LOGW(CP_TAG, "Unknown HID report ID: 0x%02X", report.report_id);
return false;
}
}
bool CyberPowerProtocol::parse_status_report(const HidReport &report, UpsData &data) {
if (report.data.size() < 4) {
ESP_LOGW(CP_TAG, "Status report too short: %d bytes", report.data.size());
return false;
}
// CyberPower status format (varies by model, this is a common interpretation)
uint8_t status_byte = report.data[0];
uint8_t flags_byte = report.data[1];
data.status_flags = 0;
// Parse status bits (CyberPower specific)
if (status_byte & 0x01) data.status_flags |= UPS_STATUS_ONLINE;
if (status_byte & 0x02) data.status_flags |= UPS_STATUS_ON_BATTERY;
if (status_byte & 0x04) data.status_flags |= UPS_STATUS_LOW_BATTERY;
if (status_byte & 0x08) data.status_flags |= UPS_STATUS_REPLACE_BATTERY;
if (status_byte & 0x10) data.status_flags |= UPS_STATUS_CHARGING;
if (status_byte & 0x20) data.status_flags |= UPS_STATUS_FAULT;
if (status_byte & 0x40) data.status_flags |= UPS_STATUS_OVERLOAD;
ESP_LOGV(CP_TAG, "Status: 0x%02X, Flags: 0x%08X", status_byte, data.status_flags);
return true;
}
bool CyberPowerProtocol::parse_battery_report(const HidReport &report, UpsData &data) {
if (report.data.size() < 6) {
ESP_LOGW(CP_TAG, "Battery report too short: %d bytes", report.data.size());
return false;
}
// CyberPower battery format (little-endian)
uint16_t battery_level_raw = report.data[0] | (report.data[1] << 8);
uint16_t runtime_raw = report.data[2] | (report.data[3] << 8);
// Battery level validation with clamping (NUT-style approach)
float battery_level;
if (battery_level_raw <= 100) {
battery_level = static_cast<float>(battery_level_raw);
} else if (battery_level_raw <= 1000) {
battery_level = static_cast<float>(battery_level_raw) / 10.0f;
} else {
ESP_LOGW(CP_TAG, "Battery level out of range: %u", battery_level_raw);
battery_level = static_cast<float>(battery_level_raw) / 10.0f; // Try scaling anyway
}
// Clamp to valid range (0-100%) like NUT does
data.battery_level = std::max(0.0f, std::min(100.0f, battery_level));
// Runtime is typically in seconds or minutes
if (runtime_raw < 3600) { // Assume minutes if < 3600
data.runtime_minutes = static_cast<float>(runtime_raw);
} else { // Assume seconds if >= 3600
data.runtime_minutes = static_cast<float>(runtime_raw) / 60.0f;
}
ESP_LOGV(CP_TAG, "Battery: %.1f%%, Runtime: %.1f min", data.battery_level, data.runtime_minutes);
return true;
}
bool CyberPowerProtocol::parse_voltage_report(const HidReport &report, UpsData &data) {
if (report.data.size() < 8) {
ESP_LOGW(CP_TAG, "Voltage report too short: %d bytes", report.data.size());
return false;
}
// CyberPower voltage format (little-endian, typically in 0.1V units)
uint16_t input_voltage_raw = report.data[0] | (report.data[1] << 8);
uint16_t output_voltage_raw = report.data[2] | (report.data[3] << 8);
uint16_t load_raw = report.data[4] | (report.data[5] << 8);
uint16_t frequency_raw = report.data[6] | (report.data[7] << 8);
// Convert raw values to actual units with NUT-style validation
float input_voltage = static_cast<float>(input_voltage_raw) / 10.0f;
float output_voltage = static_cast<float>(output_voltage_raw) / 10.0f;
// Voltage range validation (80-300V like NUT does)
if (input_voltage >= 80.0f && input_voltage <= 300.0f) {
data.input_voltage = input_voltage;
} else {
ESP_LOGW(CP_TAG, "Input voltage out of range: %.1fV", input_voltage);
data.input_voltage = NAN;
}
if (output_voltage >= 80.0f && output_voltage <= 300.0f) {
data.output_voltage = output_voltage;
} else {
ESP_LOGW(CP_TAG, "Output voltage out of range: %.1fV", output_voltage);
data.output_voltage = NAN;
}
// Load percentage validation with clamping (like NUT does)
if (load_raw <= 100) {
data.load_percent = static_cast<float>(load_raw);
} else if (load_raw <= 1000) {
// Some models report in 0.1% units
data.load_percent = static_cast<float>(load_raw) / 10.0f;
} else {
ESP_LOGW(CP_TAG, "Load value out of range: %u", load_raw);
data.load_percent = std::max(0.0f, std::min(100.0f, static_cast<float>(load_raw) / 10.0f));
}
// Frequency validation (NUT expects 47-53 Hz typically)
float frequency = static_cast<float>(frequency_raw) / 10.0f;
if (frequency >= 40.0f && frequency <= 70.0f) {
data.frequency = frequency;
} else {
ESP_LOGW(CP_TAG, "Frequency out of range: %.1f Hz", frequency);
data.frequency = NAN;
}
ESP_LOGV(CP_TAG, "Input: %.1fV, Output: %.1fV, Load: %.1f%%, Freq: %.1fHz",
data.input_voltage, data.output_voltage, data.load_percent, data.frequency);
return true;
}
bool CyberPowerProtocol::parse_device_info_report(const HidReport &report, UpsData &data) {
if (report.data.size() < 16) {
ESP_LOGW(CP_TAG, "Device info report too short: %d bytes", report.data.size());
return false;
}
// Extract model and serial number from device info
// This is a simplified parser - actual format varies by model
std::string info_string = bytes_to_string(report.data);
// Look for model information
if (info_string.find("CP") != std::string::npos ||
info_string.find("CYBER") != std::string::npos) {
size_t start = info_string.find_first_not_of(" \t\n\r");
size_t end = info_string.find_first_of(" \t\n\r", start);
if (start != std::string::npos) {
data.model = info_string.substr(start, end - start);
}
}
data.manufacturer = "CyberPower";
ESP_LOGV(CP_TAG, "Device: %s %s", data.manufacturer.c_str(), data.model.c_str());
return true;
}
} // namespace ups_hid
} // namespace esphome
+235
View File
@@ -0,0 +1,235 @@
#include "ups_hid.h"
#include "esphome/core/log.h"
namespace esphome {
namespace ups_hid {
static const char *const GEN_TAG = "ups_hid.generic";
// Standard HID Usage Pages (based on NUT usbhid-ups.c)
static const uint16_t HID_USAGE_PAGE_POWER_DEVICE = 0x84;
static const uint16_t HID_USAGE_PAGE_BATTERY = 0x85;
static const uint16_t HID_USAGE_PAGE_UPS = 0x84;
// Common HID Power Device Class Usages
static const uint16_t HID_USAGE_UPS_BATTERY_CHARGE = 0x66;
static const uint16_t HID_USAGE_UPS_RUNTIME_TO_EMPTY = 0x68;
static const uint16_t HID_USAGE_UPS_AC_PRESENT = 0x5A;
static const uint16_t HID_USAGE_UPS_BATTERY_PRESENT = 0x5B;
static const uint16_t HID_USAGE_UPS_CHARGING = 0x44;
static const uint16_t HID_USAGE_UPS_DISCHARGING = 0x45;
static const uint16_t HID_USAGE_UPS_NEED_REPLACEMENT = 0x4B;
static const uint16_t HID_USAGE_UPS_FULLY_CHARGED = 0x49;
static const uint16_t HID_USAGE_UPS_INPUT_VOLTAGE = 0x30;
static const uint16_t HID_USAGE_UPS_OUTPUT_VOLTAGE = 0x31;
static const uint16_t HID_USAGE_UPS_PERCENT_LOAD = 0x35;
// Common HID Report IDs found in UPS devices
static const uint8_t HID_REPORT_FEATURE = 0x03;
static const uint8_t HID_REPORT_INPUT = 0x01;
bool GenericHidProtocol::detect() {
ESP_LOGD(GEN_TAG, "Detecting Generic HID Protocol...");
// Try HID Get Feature Report (like NUT does)
std::vector<uint8_t> get_feature_request = {
0x21, // bmRequestType: Class, Interface, Host-to-device
0x01, // bRequest: GET_REPORT
0x00, HID_REPORT_FEATURE, // wValue: Report Type and Report ID
0x00, 0x00, // wIndex: Interface
0x08, 0x00 // wLength: 8 bytes
};
std::vector<uint8_t> response;
if (send_command(get_feature_request, response, 2000)) {
if (!response.empty()) {
ESP_LOGD(GEN_TAG, "Generic HID Feature Report received, %zu bytes", response.size());
return true;
}
}
// Fallback: Try Input Report
std::vector<uint8_t> get_input_request = {
0x21, // bmRequestType
0x01, // bRequest: GET_REPORT
0x00, HID_REPORT_INPUT, // wValue: Input Report
0x00, 0x00, // wIndex
0x08, 0x00 // wLength
};
if (send_command(get_input_request, response, 2000)) {
if (!response.empty()) {
ESP_LOGD(GEN_TAG, "Generic HID Input Report received, %zu bytes", response.size());
return true;
}
}
ESP_LOGD(GEN_TAG, "No Generic HID response - device may not support standard HID reports");
return false;
}
bool GenericHidProtocol::initialize() {
ESP_LOGD(GEN_TAG, "Initializing Generic HID Protocol...");
// Generic initialization - just verify we can communicate
std::vector<uint8_t> init_command = {0x00}; // Null command
std::vector<uint8_t> response;
if (send_command(init_command, response, 2000)) {
ESP_LOGI(GEN_TAG, "Generic HID Protocol initialized successfully");
return true;
}
ESP_LOGW(GEN_TAG, "Generic HID Protocol initialization failed");
return false;
}
bool GenericHidProtocol::read_data(UpsData &data) {
ESP_LOGV(GEN_TAG, "Reading Generic HID UPS data...");
bool success = false;
std::vector<uint8_t> response;
// Try different HID report types (like NUT does)
std::vector<std::pair<std::string, std::vector<uint8_t>>> report_requests = {
{"Feature", {0x21, 0x01, 0x00, HID_REPORT_FEATURE, 0x00, 0x00, 0x20, 0x00}},
{"Input", {0x21, 0x01, 0x00, HID_REPORT_INPUT, 0x00, 0x00, 0x20, 0x00}},
{"Report1", {0x21, 0x01, 0x01, HID_REPORT_INPUT, 0x00, 0x00, 0x08, 0x00}},
{"Report2", {0x21, 0x01, 0x02, HID_REPORT_INPUT, 0x00, 0x00, 0x08, 0x00}}
};
for (const auto& req : report_requests) {
if (send_command(req.second, response, 1000) && response.size() >= 2) {
success = true;
ESP_LOGV(GEN_TAG, "%s report received: %zu bytes", req.first.c_str(), response.size());
if (parse_generic_report(response, data)) {
ESP_LOGV(GEN_TAG, "Successfully parsed %s report", req.first.c_str());
break;
}
}
}
// Set generic device information
if (data.manufacturer.empty()) {
data.manufacturer = "Generic";
}
if (data.model.empty()) {
data.model = "HID UPS";
}
if (!success) {
ESP_LOGW(GEN_TAG, "Failed to read any generic HID data");
// Provide minimal status to indicate device presence
data.status_flags = UPS_STATUS_ONLINE;
data.manufacturer = "Generic";
data.model = "Unknown UPS";
success = true; // Still consider it successful to maintain connection
}
return success;
}
bool GenericHidProtocol::parse_generic_report(const std::vector<uint8_t>& response, UpsData& data) {
if (response.size() < 2) {
return false;
}
bool found_data = false;
// NUT-style heuristic parsing - try multiple approaches
// Approach 1: Look for status bits in first bytes
for (size_t i = 0; i < std::min(response.size(), size_t(4)); ++i) {
uint8_t status_byte = response[i];
if (status_byte != 0x00 && status_byte != 0xFF) {
data.status_flags = 0;
// Common status bit patterns found in various UPS devices
if (status_byte & 0x01) data.status_flags |= UPS_STATUS_ONLINE;
if (status_byte & 0x02) data.status_flags |= UPS_STATUS_ON_BATTERY;
if (status_byte & 0x04) data.status_flags |= UPS_STATUS_LOW_BATTERY;
if (status_byte & 0x08) data.status_flags |= UPS_STATUS_CHARGING;
if (status_byte & 0x10) data.status_flags |= UPS_STATUS_REPLACE_BATTERY;
if (status_byte & 0x20) data.status_flags |= UPS_STATUS_OVERLOAD;
found_data = true;
ESP_LOGV(GEN_TAG, "Status bits found at offset %zu: 0x%02X -> flags 0x%08X",
i, status_byte, data.status_flags);
break;
}
}
// Approach 2: Look for percentage values (0-100) in 16-bit words
for (size_t i = 0; i <= response.size() - 2; i += 2) {
uint16_t value_le = response[i] | (response[i+1] << 8); // Little-endian
uint16_t value_be = (response[i] << 8) | response[i+1]; // Big-endian
// Check if either interpretation gives a valid percentage
if (value_le <= 100) {
data.battery_level = static_cast<float>(value_le);
found_data = true;
ESP_LOGV(GEN_TAG, "Battery level found at offset %zu (LE): %.1f%%", i, data.battery_level);
} else if (value_be <= 100) {
data.battery_level = static_cast<float>(value_be);
found_data = true;
ESP_LOGV(GEN_TAG, "Battery level found at offset %zu (BE): %.1f%%", i, data.battery_level);
}
// Check for scaled percentages (0-1000 -> 0.0-100.0)
if (value_le <= 1000 && value_le > 100) {
float scaled_battery = static_cast<float>(value_le) / 10.0f;
if (scaled_battery <= 100.0f) {
data.battery_level = scaled_battery;
found_data = true;
ESP_LOGV(GEN_TAG, "Scaled battery level found at offset %zu: %.1f%%", i, data.battery_level);
}
}
}
// Approach 3: Look for voltage values (80-300V range)
for (size_t i = 0; i <= response.size() - 2; i += 2) {
uint16_t value_le = response[i] | (response[i+1] << 8);
uint16_t value_be = (response[i] << 8) | response[i+1];
// Check for voltage values (direct or scaled by 10)
std::vector<std::pair<uint16_t, float>> voltage_candidates = {
{value_le, 1.0f}, {value_be, 1.0f},
{value_le, 0.1f}, {value_be, 0.1f}
};
for (const auto& candidate : voltage_candidates) {
float voltage = static_cast<float>(candidate.first) * candidate.second;
if (voltage >= 80.0f && voltage <= 300.0f) {
if (std::isnan(data.input_voltage)) {
data.input_voltage = voltage;
found_data = true;
ESP_LOGV(GEN_TAG, "Input voltage found at offset %zu: %.1fV", i, voltage);
} else if (std::isnan(data.output_voltage) && std::abs(voltage - data.input_voltage) > 5.0f) {
data.output_voltage = voltage;
ESP_LOGV(GEN_TAG, "Output voltage found at offset %zu: %.1fV", i, voltage);
}
break;
}
}
}
// Approach 4: Look for runtime values (reasonable minute ranges)
for (size_t i = 0; i <= response.size() - 2; i += 2) {
uint16_t value_le = response[i] | (response[i+1] << 8);
// Runtime typically 0-999 minutes for most UPS devices
if (value_le > 0 && value_le <= 999) {
data.runtime_minutes = static_cast<float>(value_le);
found_data = true;
ESP_LOGV(GEN_TAG, "Runtime found at offset %zu: %.1f min", i, data.runtime_minutes);
}
}
return found_data;
}
} // namespace ups_hid
} // namespace esphome
+19
View File
@@ -0,0 +1,19 @@
#include "sensor.h"
#include "esphome/core/log.h"
namespace esphome
{
namespace ups_hid
{
static const char *const S_TAG = "ups_hid.sensor";
void UpsHidSensor::dump_config()
{
ESP_LOGCONFIG(S_TAG, "UPS HID Sensor:");
ESP_LOGCONFIG(S_TAG, " Type: %s", sensor_type_.c_str());
LOG_SENSOR(" ", "Sensor", this);
}
} // namespace ups_hid
} // namespace esphome
+23
View File
@@ -0,0 +1,23 @@
#pragma once
#include "esphome/core/component.h"
#include "esphome/components/sensor/sensor.h"
#include "ups_hid.h"
namespace esphome
{
namespace ups_hid
{
class UpsHidSensor : public sensor::Sensor, public Component
{
public:
void set_sensor_type(const std::string &type) { sensor_type_ = type; }
void dump_config() override;
protected:
std::string sensor_type_;
};
} // namespace ups_hid
} // namespace esphome
+97
View File
@@ -0,0 +1,97 @@
import esphome.codegen as cg
import esphome.config_validation as cv
from esphome.components import sensor
from esphome.const import (
CONF_TYPE,
DEVICE_CLASS_BATTERY,
DEVICE_CLASS_VOLTAGE,
DEVICE_CLASS_POWER_FACTOR,
DEVICE_CLASS_DURATION,
STATE_CLASS_MEASUREMENT,
UNIT_PERCENT,
UNIT_VOLT,
UNIT_MINUTE,
UNIT_HERTZ,
)
from . import ups_hid_ns, UpsHidComponent, CONF_UPS_HID_ID
DEPENDENCIES = ["ups_hid"]
UpsHidSensor = ups_hid_ns.class_("UpsHidSensor", sensor.Sensor, cg.Component)
SENSOR_TYPES = {
"battery_level": {
"unit": UNIT_PERCENT,
"device_class": DEVICE_CLASS_BATTERY,
"state_class": STATE_CLASS_MEASUREMENT,
"accuracy_decimals": 0,
},
"input_voltage": {
"unit": UNIT_VOLT,
"device_class": DEVICE_CLASS_VOLTAGE,
"state_class": STATE_CLASS_MEASUREMENT,
"accuracy_decimals": 1,
},
"output_voltage": {
"unit": UNIT_VOLT,
"device_class": DEVICE_CLASS_VOLTAGE,
"state_class": STATE_CLASS_MEASUREMENT,
"accuracy_decimals": 1,
},
"load_percent": {
"unit": UNIT_PERCENT,
"device_class": DEVICE_CLASS_POWER_FACTOR,
"state_class": STATE_CLASS_MEASUREMENT,
"accuracy_decimals": 0,
},
"runtime": {
"unit": UNIT_MINUTE,
"device_class": DEVICE_CLASS_DURATION,
"state_class": STATE_CLASS_MEASUREMENT,
"accuracy_decimals": 0,
},
"frequency": {
"unit": UNIT_HERTZ,
"state_class": STATE_CLASS_MEASUREMENT,
"accuracy_decimals": 1,
},
}
CONFIG_SCHEMA = sensor.sensor_schema(
UpsHidSensor,
accuracy_decimals=1,
).extend(
{
cv.GenerateID(CONF_UPS_HID_ID): cv.use_id(UpsHidComponent),
cv.Required(CONF_TYPE): cv.one_of(*SENSOR_TYPES, lower=True),
}
)
async def to_code(config):
parent = await cg.get_variable(config[CONF_UPS_HID_ID])
var = await sensor.new_sensor(config)
await cg.register_component(var, config)
sensor_type = config[CONF_TYPE]
cg.add(var.set_sensor_type(sensor_type))
cg.add(parent.register_sensor(var, sensor_type))
# Apply sensor type specific configuration
if sensor_type in SENSOR_TYPES:
sensor_config = SENSOR_TYPES[sensor_type]
# Override config with sensor type defaults if not specified
if "unit_of_measurement" not in config and "unit" in sensor_config:
cg.add(var.set_unit_of_measurement(sensor_config["unit"]))
if "device_class" not in config and "device_class" in sensor_config:
cg.add(var.set_device_class(sensor_config["device_class"]))
if "state_class" not in config and "state_class" in sensor_config:
cg.add(var.set_state_class(sensor_config["state_class"]))
if "accuracy_decimals" not in config and "accuracy_decimals" in sensor_config:
cg.add(var.set_accuracy_decimals(sensor_config["accuracy_decimals"]))
+19
View File
@@ -0,0 +1,19 @@
#include "text_sensor.h"
#include "esphome/core/log.h"
namespace esphome
{
namespace ups_hid
{
static const char *const TXT_TAG = "ups_hid.text_sensor";
void UpsHidTextSensor::dump_config()
{
ESP_LOGCONFIG(TXT_TAG, "UPS HID Text Sensor:");
ESP_LOGCONFIG(TXT_TAG, " Type: %s", sensor_type_.c_str());
LOG_TEXT_SENSOR(" ", "Text Sensor", this);
}
} // namespace ups_hid
} // namespace esphome
+23
View File
@@ -0,0 +1,23 @@
#pragma once
#include "esphome/core/component.h"
#include "esphome/components/text_sensor/text_sensor.h"
#include "ups_hid.h"
namespace esphome
{
namespace ups_hid
{
class UpsHidTextSensor : public text_sensor::TextSensor, public Component
{
public:
void set_sensor_type(const std::string &type) { sensor_type_ = type; }
void dump_config() override;
protected:
std::string sensor_type_;
};
} // namespace ups_hid
} // namespace esphome
+41
View File
@@ -0,0 +1,41 @@
import esphome.codegen as cg
import esphome.config_validation as cv
from esphome.components import text_sensor
from esphome.const import (
CONF_TYPE,
)
from . import ups_hid_ns, UpsHidComponent, CONF_UPS_HID_ID
DEPENDENCIES = ["ups_hid"]
UpsHidTextSensor = ups_hid_ns.class_(
"UpsHidTextSensor", text_sensor.TextSensor, cg.Component
)
TEXT_SENSOR_TYPES = [
"model",
"manufacturer",
"status",
"protocol",
"serial_number",
"firmware_version",
]
CONFIG_SCHEMA = text_sensor.text_sensor_schema(UpsHidTextSensor).extend(
{
cv.GenerateID(CONF_UPS_HID_ID): cv.use_id(UpsHidComponent),
cv.Required(CONF_TYPE): cv.one_of(*TEXT_SENSOR_TYPES, lower=True),
}
)
async def to_code(config):
parent = await cg.get_variable(config[CONF_UPS_HID_ID])
var = await text_sensor.new_text_sensor(config)
await cg.register_component(var, config)
sensor_type = config[CONF_TYPE]
cg.add(var.set_sensor_type(sensor_type))
cg.add(parent.register_text_sensor(var, sensor_type))
File diff suppressed because it is too large. Load diff
+337
View File
@@ -0,0 +1,337 @@
#pragma once
#include "esphome/core/component.h"
#include "esphome/core/defines.h"
#include "esphome/core/helpers.h"
#include "esphome/core/log.h"
#include "sensor.h"
#include "binary_sensor.h"
#include "text_sensor.h"
#include <memory>
#include <vector>
#include <unordered_map>
#include <string>
#include <mutex>
#ifdef USE_ESP32
#include "esp_err.h"
#include "usb/usb_host.h"
#include "usb/usb_types_ch9.h"
#include "freertos/FreeRTOS.h"
#include "freertos/semphr.h"
#include "freertos/task.h"
// USB HID Class defines
#ifndef USB_CLASS_HID
#define USB_CLASS_HID 0x03
#endif
#endif
namespace esphome
{
namespace ups_hid
{
static const char *const TAG = "ups_hid";
// UPS status flags
enum UpsStatus
{
UPS_STATUS_UNKNOWN = 0,
UPS_STATUS_ONLINE = 1 << 0,
UPS_STATUS_ON_BATTERY = 1 << 1,
UPS_STATUS_LOW_BATTERY = 1 << 2,
UPS_STATUS_REPLACE_BATTERY = 1 << 3,
UPS_STATUS_CHARGING = 1 << 4,
UPS_STATUS_FAULT = 1 << 5,
UPS_STATUS_OVERLOAD = 1 << 6,
UPS_STATUS_CALIBRATING = 1 << 7,
UPS_STATUS_OFF = 1 << 8
};
// UPS protocols
enum UpsProtocol
{
PROTOCOL_UNKNOWN = 0,
PROTOCOL_APC_SMART,
PROTOCOL_APC_HID,
PROTOCOL_CYBERPOWER_HID,
PROTOCOL_GENERIC_HID
};
// UPS data structure with proper initialization
struct UpsData
{
float battery_level{NAN};
float input_voltage{NAN};
float output_voltage{NAN};
float load_percent{NAN};
float runtime_minutes{NAN};
float frequency{NAN};
uint32_t status_flags{UPS_STATUS_UNKNOWN};
std::string model{};
std::string manufacturer{};
std::string serial_number{};
std::string firmware_version{};
UpsProtocol detected_protocol{PROTOCOL_UNKNOWN};
// Reset all data to default values
void reset() {
battery_level = NAN;
input_voltage = NAN;
output_voltage = NAN;
load_percent = NAN;
runtime_minutes = NAN;
frequency = NAN;
status_flags = UPS_STATUS_UNKNOWN;
model.clear();
manufacturer.clear();
serial_number.clear();
firmware_version.clear();
detected_protocol = PROTOCOL_UNKNOWN;
}
// Check if core data is valid
bool is_valid() const {
return !std::isnan(battery_level) || !std::isnan(input_voltage) ||
!std::isnan(output_voltage) || status_flags != UPS_STATUS_UNKNOWN;
}
};
// Forward declarations
class UpsProtocolBase;
class ApcSmartProtocol;
class ApcHidProtocol;
class CyberPowerProtocol;
class GenericHidProtocol;
class UpsHidComponent : public PollingComponent
{
public:
UpsHidComponent() : usb_device_{}, usb_mutex_(nullptr), usb_task_handle_(nullptr),
usb_host_initialized_(false), device_connected_(false) {
#ifdef USE_ESP32
memset(&usb_device_, 0, sizeof(usb_device_));
#endif
}
~UpsHidComponent() {
#ifdef USE_ESP32
// Log any remaining suppressed errors before cleanup
log_suppressed_errors(usb_error_limiter_);
log_suppressed_errors(protocol_error_limiter_);
usb_deinit();
#endif
}
void setup() override;
void update() override;
void dump_config() override;
float get_setup_priority() const override { return setup_priority::DATA; }
// Configuration setters with validation
void set_simulation_mode(bool simulation_mode) { simulation_mode_ = simulation_mode; }
void set_usb_vendor_id(uint16_t vendor_id) {
if (vendor_id != 0) usb_vendor_id_ = vendor_id;
}
void set_usb_product_id(uint16_t product_id) {
if (product_id != 0) usb_product_id_ = product_id;
}
void set_protocol_timeout(uint32_t timeout_ms) {
// Bound timeout between 5 seconds and 5 minutes for safety
protocol_timeout_ms_ = std::max(static_cast<uint32_t>(5000),
std::min(timeout_ms, static_cast<uint32_t>(300000)));
}
void set_auto_detect_protocol(bool auto_detect) { auto_detect_protocol_ = auto_detect; }
// Data getters for sensors (thread-safe)
UpsData get_ups_data() const {
std::lock_guard<std::mutex> lock(data_mutex_);
return ups_data_;
}
bool is_connected() const { return connected_; }
std::string get_protocol_name() const;
// USB device info getters
uint16_t get_usb_vendor_id() const { return usb_vendor_id_; }
uint16_t get_usb_product_id() const { return usb_product_id_; }
// Sensor registration methods
void register_sensor(sensor::Sensor *sens, const std::string &type);
void register_binary_sensor(binary_sensor::BinarySensor *sens, const std::string &type);
void register_text_sensor(text_sensor::TextSensor *sens, const std::string &type);
protected:
bool simulation_mode_{false};
uint16_t usb_vendor_id_{0x051D}; // APC default
uint16_t usb_product_id_{0x0002}; // Back-UPS ES series default
uint32_t protocol_timeout_ms_{10000};
bool auto_detect_protocol_{true};
bool connected_{false};
uint32_t last_successful_read_{0};
uint32_t consecutive_failures_{0};
uint32_t max_consecutive_failures_{5}; // Limit re-detection attempts
UpsData ups_data_;
mutable std::mutex data_mutex_; // Protect ups_data_ access
// Error rate limiting to prevent log spam
struct ErrorRateLimit {
uint32_t last_error_time{0};
uint32_t error_count{0};
uint32_t suppressed_count{0};
static constexpr uint32_t RATE_LIMIT_MS = 5000; // 5 seconds between repeated errors
static constexpr uint32_t MAX_BURST = 3; // Allow 3 errors before rate limiting
};
ErrorRateLimit usb_error_limiter_;
ErrorRateLimit protocol_error_limiter_;
std::unique_ptr<UpsProtocolBase> active_protocol_;
std::unordered_map<std::string, sensor::Sensor *> sensors_;
std::unordered_map<std::string, binary_sensor::BinarySensor *> binary_sensors_;
std::unordered_map<std::string, text_sensor::TextSensor *> text_sensors_;
// Core methods
bool initialize_usb();
bool detect_ups_protocol();
bool read_ups_data();
void update_sensors();
void simulate_ups_data();
// Error rate limiting helpers
bool should_log_error(ErrorRateLimit& limiter);
void log_suppressed_errors(ErrorRateLimit& limiter);
public:
// USB communication methods (accessible by protocol classes)
bool usb_write(const std::vector<uint8_t> &data);
bool usb_read(std::vector<uint8_t> &data, uint32_t timeout_ms = 1000);
protected:
#ifdef USE_ESP32
// USB Host structures
struct UsbDevice {
usb_host_client_handle_t client_hdl;
usb_device_handle_t dev_hdl;
uint8_t dev_addr;
uint16_t vid;
uint16_t pid;
bool is_hid_device;
uint8_t interface_num;
uint8_t ep_in;
uint8_t ep_out;
uint16_t max_packet_size;
};
// USB Host member variables
UsbDevice usb_device_;
SemaphoreHandle_t usb_mutex_;
TaskHandle_t usb_task_handle_;
bool usb_host_initialized_;
bool device_connected_;
// ESP32-specific USB handling
esp_err_t usb_init();
void usb_deinit();
esp_err_t usb_host_lib_init();
esp_err_t usb_client_register();
esp_err_t usb_device_enumerate();
bool usb_is_ups_device(const usb_device_desc_t *desc);
esp_err_t usb_claim_interface();
esp_err_t usb_get_endpoints();
// USB communication
esp_err_t usb_transfer_sync(const std::vector<uint8_t> &data_out, std::vector<uint8_t> &data_in, uint32_t timeout_ms);
// USB Host event handling
static void usb_host_lib_task(void *arg);
static void usb_client_event_callback(const usb_host_client_event_msg_t *event_msg, void *arg);
#endif
};
// Base class for UPS protocols
class UpsProtocolBase
{
public:
explicit UpsProtocolBase(UpsHidComponent *parent) : parent_(parent) {}
virtual ~UpsProtocolBase() = default;
virtual bool detect() = 0;
virtual bool initialize() = 0;
virtual bool read_data(UpsData &data) = 0;
virtual UpsProtocol get_protocol_type() const = 0;
virtual std::string get_protocol_name() const = 0;
protected:
UpsHidComponent *parent_;
bool send_command(const std::vector<uint8_t> &cmd, std::vector<uint8_t> &response, uint32_t timeout_ms = 1000);
std::string bytes_to_string(const std::vector<uint8_t> &data);
};
// APC Smart Protocol implementation
class ApcSmartProtocol : public UpsProtocolBase
{
public:
explicit ApcSmartProtocol(UpsHidComponent *parent) : UpsProtocolBase(parent) {}
bool detect() override;
bool initialize() override;
bool read_data(UpsData &data) override;
UpsProtocol get_protocol_type() const override { return PROTOCOL_APC_SMART; }
std::string get_protocol_name() const override { return "APC Smart Protocol"; }
private:
bool send_smart_command(char cmd, std::string &response);
float parse_voltage(const std::string &response);
float parse_percentage(const std::string &response);
uint32_t parse_status_flags(const std::string &response);
};
// CyberPower HID Protocol implementation
class CyberPowerProtocol : public UpsProtocolBase
{
public:
explicit CyberPowerProtocol(UpsHidComponent *parent) : UpsProtocolBase(parent) {}
bool detect() override;
bool initialize() override;
bool read_data(UpsData &data) override;
UpsProtocol get_protocol_type() const override { return PROTOCOL_CYBERPOWER_HID; }
std::string get_protocol_name() const override { return "CyberPower HID"; }
private:
struct HidReport
{
uint8_t report_id;
std::vector<uint8_t> data;
};
bool send_hid_report(const HidReport &report, HidReport &response);
bool parse_hid_data(const HidReport &report, UpsData &data);
bool parse_status_report(const HidReport &report, UpsData &data);
bool parse_battery_report(const HidReport &report, UpsData &data);
bool parse_voltage_report(const HidReport &report, UpsData &data);
bool parse_device_info_report(const HidReport &report, UpsData &data);
};
// Generic HID Protocol implementation
class GenericHidProtocol : public UpsProtocolBase
{
public:
explicit GenericHidProtocol(UpsHidComponent *parent) : UpsProtocolBase(parent) {}
bool detect() override;
bool initialize() override;
bool read_data(UpsData &data) override;
UpsProtocol get_protocol_type() const override { return PROTOCOL_GENERIC_HID; }
std::string get_protocol_name() const override { return "Generic HID"; }
private:
bool parse_generic_report(const std::vector<uint8_t>& response, UpsData& data);
};
} // namespace ups_hid
} // namespace esphome
+76
View File
@@ -0,0 +1,76 @@
#pragma once
/**
* @file ups_vendors.h
* @brief Known UPS vendor IDs for device identification and validation
*
* This file contains the definitive list of known UPS vendor IDs
* shared between C++ runtime code and Python configuration validation.
*/
namespace esphome
{
namespace ups_hid
{
// Known UPS vendor IDs with their names
struct UpsVendor
{
uint16_t vendor_id;
const char *name;
const char *description;
};
// Definitive list of known UPS vendors (based on NUT project driver.list)
static constexpr UpsVendor KNOWN_UPS_VENDORS[] = {
//{0x0001, "Generic/Other", "Generic UPS vendors (multiple brands)"},
{0x0463, "MGE Office Protection Systems", "MGE Office Protection Systems"},
{0x050D, "Belkin", "Belkin (older USB UPS models)"},
{0x051D, "APC", "American Power Conversion"},
{0x05B8, "SVEN", "SVEN UPS devices"},
{0x0665, "Cypress/Belkin", "Cypress or Belkin UPS devices"},
{0x06DA, "MGE UPS Systems", "MGE UPS Systems (now Eaton)"},
{0x0764, "CyberPower", "CyberPower Systems"},
{0x0925, "Richcomm", "Richcomm Technologies (Digitus, Sweex)"},
{0x09AE, "Tripp Lite", "Tripp Lite"},
{0x09D6, "Micropower", "Micropower UPS devices"},
};
static constexpr size_t KNOWN_UPS_VENDORS_COUNT = sizeof(KNOWN_UPS_VENDORS) / sizeof(KNOWN_UPS_VENDORS[0]);
/**
* Check if a vendor ID is in the known UPS vendors list
* @param vendor_id The USB vendor ID to check
* @return True if vendor ID is known, false otherwise
*/
inline bool is_known_ups_vendor(uint16_t vendor_id)
{
for (size_t i = 0; i < KNOWN_UPS_VENDORS_COUNT; i++)
{
if (KNOWN_UPS_VENDORS[i].vendor_id == vendor_id)
{
return true;
}
}
return false;
}
/**
* Get vendor name for a given vendor ID
* @param vendor_id The USB vendor ID
* @return Vendor name or nullptr if unknown
*/
inline const char *get_ups_vendor_name(uint16_t vendor_id)
{
for (size_t i = 0; i < KNOWN_UPS_VENDORS_COUNT; i++)
{
if (KNOWN_UPS_VENDORS[i].vendor_id == vendor_id)
{
return KNOWN_UPS_VENDORS[i].name;
}
}
return nullptr;
}
} // namespace ups_hid
} // namespace esphome