feat(usp-hid): data provider pattern

Signed-off-by: bullshit <coding@ow-software.pl>
This commit is contained in:
bullshit committed 2025-08-31 15:03:28 +02:00
1 parent 1df84b0473
commit 49e24d3170
5 files changed
+306 -42

No files matched your search

+123 -2
View File
@@ -101,9 +101,15 @@ void UpsHidComponent::dump_config() {
ESP_LOGCONFIG(TAG, " Status: %s", status::DISCONNECTED);
}
#ifdef USE_SENSOR
ESP_LOGCONFIG(TAG, " Registered Sensors: %zu", sensors_.size());
#endif
#ifdef USE_BINARY_SENSOR
ESP_LOGCONFIG(TAG, " Registered Binary Sensors: %zu", binary_sensors_.size());
#endif
#ifdef USE_TEXT_SENSOR
ESP_LOGCONFIG(TAG, " Registered Text Sensors: %zu", text_sensors_.size());
#endif
}
// Transport abstraction methods
@@ -252,7 +258,28 @@ bool UpsHidComponent::read_ups_data() {
void UpsHidComponent::update_sensors() {
std::lock_guard<std::mutex> lock(data_mutex_);
// Check if any sensors are registered - if not, skip sensor updates
size_t total_sensors = 0;
#ifdef USE_SENSOR
total_sensors += sensors_.size();
#endif
#ifdef USE_BINARY_SENSOR
total_sensors += binary_sensors_.size();
#endif
#ifdef USE_TEXT_SENSOR
total_sensors += text_sensors_.size();
#endif
if (total_sensors == 0) {
// Data provider mode - no sensor entities, just providing data for direct access
ESP_LOGVV(TAG, "Data provider mode: no sensors registered, data available via direct access methods");
return;
}
ESP_LOGVV(TAG, "Updating %zu registered sensor entities", total_sensors);
// Update all registered sensors with current data
#ifdef USE_SENSOR
for (auto& sensor_pair : sensors_) {
const std::string& type = sensor_pair.first;
sensor::Sensor* sensor = sensor_pair.second;
@@ -304,8 +331,10 @@ void UpsHidComponent::update_sensors() {
sensor->publish_state(value);
}
}
#endif
// Update binary sensors
#ifdef USE_BINARY_SENSOR
for (auto& sensor_pair : binary_sensors_) {
const std::string& type = sensor_pair.first;
binary_sensor::BinarySensor* sensor = sensor_pair.second;
@@ -322,8 +351,10 @@ void UpsHidComponent::update_sensors() {
sensor->publish_state(state);
}
#endif
// Update text sensors
#ifdef USE_TEXT_SENSOR
for (auto& sensor_pair : text_sensors_) {
const std::string& type = sensor_pair.first;
text_sensor::TextSensor* sensor = sensor_pair.second;
@@ -364,6 +395,7 @@ void UpsHidComponent::update_sensors() {
sensor->publish_state(value);
}
}
#endif
// Update delay number components
for (auto* delay_number : delay_numbers_) {
@@ -375,25 +407,48 @@ void UpsHidComponent::update_sensors() {
}
}
// Log sensor counts (conditional on platform availability)
#ifdef USE_SENSOR
size_t sensor_count = sensors_.size();
#else
size_t sensor_count = 0;
#endif
#ifdef USE_BINARY_SENSOR
size_t binary_sensor_count = binary_sensors_.size();
#else
size_t binary_sensor_count = 0;
#endif
#ifdef USE_TEXT_SENSOR
size_t text_sensor_count = text_sensors_.size();
#else
size_t text_sensor_count = 0;
#endif
ESP_LOGV(TAG, "Updated %zu sensors, %zu binary sensors, %zu text sensors",
sensors_.size(), binary_sensors_.size(), text_sensors_.size());
sensor_count, binary_sensor_count, text_sensor_count);
}
// Sensor registration methods
// Sensor registration methods (conditional on platform availability)
#ifdef USE_SENSOR
void UpsHidComponent::register_sensor(sensor::Sensor *sens, const std::string &type) {
sensors_[type] = sens;
ESP_LOGD(TAG, "Registered sensor: %s", type.c_str());
}
#endif
#ifdef USE_BINARY_SENSOR
void UpsHidComponent::register_binary_sensor(binary_sensor::BinarySensor *sens, const std::string &type) {
binary_sensors_[type] = sens;
ESP_LOGD(TAG, "Registered binary sensor: %s", type.c_str());
}
#endif
#ifdef USE_TEXT_SENSOR
void UpsHidComponent::register_text_sensor(text_sensor::TextSensor *sens, const std::string &type) {
text_sensors_[type] = sens;
ESP_LOGD(TAG, "Registered text sensor: %s", type.c_str());
}
#endif
void UpsHidComponent::register_delay_number(UpsDelayNumber *number) {
delay_numbers_.push_back(number);
@@ -614,6 +669,72 @@ void UpsHidComponent::set_fast_polling_mode(bool enable) {
}
}
// Convenient state getters for lambda expressions (no sensor entities required)
bool UpsHidComponent::is_online() const {
std::lock_guard<std::mutex> lock(data_mutex_);
// UPS is online when input voltage is valid (same logic as binary sensor update)
return ups_data_.power.input_voltage_valid();
}
bool UpsHidComponent::is_on_battery() const {
std::lock_guard<std::mutex> lock(data_mutex_);
// UPS is on battery when NOT online (opposite of online state)
return !ups_data_.power.input_voltage_valid();
}
bool UpsHidComponent::is_low_battery() const {
std::lock_guard<std::mutex> lock(data_mutex_);
// Use battery's built-in low battery detection
return ups_data_.battery.is_low();
}
bool UpsHidComponent::is_charging() const {
std::lock_guard<std::mutex> lock(data_mutex_);
// Charging when online AND battery level is not 100%
return ups_data_.power.input_voltage_valid() &&
ups_data_.battery.is_valid() &&
!std::isnan(ups_data_.battery.level) &&
ups_data_.battery.level < 100.0f;
}
bool UpsHidComponent::has_fault() const {
std::lock_guard<std::mutex> lock(data_mutex_);
// Check for various fault conditions based on available data
return ups_data_.power.is_input_out_of_range() ||
(!ups_data_.power.is_valid() && !ups_data_.battery.is_valid());
}
bool UpsHidComponent::is_overloaded() const {
std::lock_guard<std::mutex> lock(data_mutex_);
// Use power's built-in overload detection
return ups_data_.power.is_overloaded();
}
float UpsHidComponent::get_battery_level() const {
std::lock_guard<std::mutex> lock(data_mutex_);
return ups_data_.battery.is_valid() ? ups_data_.battery.level : NAN;
}
float UpsHidComponent::get_input_voltage() const {
std::lock_guard<std::mutex> lock(data_mutex_);
return ups_data_.power.input_voltage;
}
float UpsHidComponent::get_output_voltage() const {
std::lock_guard<std::mutex> lock(data_mutex_);
return ups_data_.power.output_voltage;
}
float UpsHidComponent::get_load_percent() const {
std::lock_guard<std::mutex> lock(data_mutex_);
return ups_data_.power.load_percent;
}
float UpsHidComponent::get_runtime_minutes() const {
std::lock_guard<std::mutex> lock(data_mutex_);
return ups_data_.battery.runtime_minutes;
}
} // namespace ups_hid
} // namespace esphome
+41 -1
View File
@@ -4,9 +4,22 @@
#include "esphome/core/defines.h"
#include "esphome/core/helpers.h"
#include "esphome/core/log.h"
// Forward declarations for optional sensor platforms
#ifdef USE_SENSOR
#include "sensor_numeric.h"
namespace esphome { namespace sensor { class Sensor; } }
#endif
#ifdef USE_BINARY_SENSOR
#include "sensor_binary.h"
namespace esphome { namespace binary_sensor { class BinarySensor; } }
#endif
#ifdef USE_TEXT_SENSOR
#include "sensor_text.h"
namespace esphome { namespace text_sensor { class TextSensor; } }
#endif
#include <memory>
#include <vector>
@@ -84,6 +97,19 @@ namespace esphome
uint32_t get_protocol_timeout() const { return protocol_timeout_ms_; }
float get_fallback_nominal_voltage() const { return fallback_nominal_voltage_; }
// Convenient state getters for lambda expressions (no sensor entities required)
bool is_online() const;
bool is_on_battery() const;
bool is_low_battery() const;
bool is_charging() const;
bool has_fault() const;
bool is_overloaded() const;
float get_battery_level() const;
float get_input_voltage() const;
float get_output_voltage() const;
float get_load_percent() const;
float get_runtime_minutes() const;
// Test control methods
bool start_battery_test_quick();
bool start_battery_test_deep();
@@ -103,10 +129,16 @@ namespace esphome
bool set_reboot_delay(int seconds);
void request_delay_refresh() { /* No-op for now - could trigger update if needed */ }
// Sensor registration methods
// Sensor registration methods (conditional on platform availability)
#ifdef USE_SENSOR
void register_sensor(sensor::Sensor *sens, const std::string &type);
#endif
#ifdef USE_BINARY_SENSOR
void register_binary_sensor(binary_sensor::BinarySensor *sens, const std::string &type);
#endif
#ifdef USE_TEXT_SENSOR
void register_text_sensor(text_sensor::TextSensor *sens, const std::string &type);
#endif
void register_delay_number(class UpsDelayNumber *number);
// Protocol access for button components
@@ -146,9 +178,17 @@ namespace esphome
// Clean architecture members
std::unique_ptr<IUsbTransport> transport_;
std::unique_ptr<UpsProtocolBase> active_protocol_;
// Sensor storage (conditional on platform availability)
#ifdef USE_SENSOR
std::unordered_map<std::string, sensor::Sensor *> sensors_;
#endif
#ifdef USE_BINARY_SENSOR
std::unordered_map<std::string, binary_sensor::BinarySensor *> binary_sensors_;
#endif
#ifdef USE_TEXT_SENSOR
std::unordered_map<std::string, text_sensor::TextSensor *> text_sensors_;
#endif
std::vector<class UpsDelayNumber *> delay_numbers_;
// Core methods
+46 -6
View File
@@ -1,6 +1,6 @@
# UPS HID Configuration Management
This directory provides a modular, maintainable approach to UPS HID device configuration using ESPHome packages with the new Protocol Factory system. Instead of maintaining large, complex configuration files, you can compose configurations from reusable components.
This directory provides a modular, maintainable approach to UPS HID device configuration using ESPHome packages with the a Protocol Factory system. Instead of maintaining large, complex configuration files, you can compose configurations from reusable components.
## 📦 Modular Configuration Packages
@@ -11,9 +11,9 @@ Essential foundation for all UPS devices:
- ESP32-S3 hardware configuration
- Network setup (WiFi, OTA, Web server)
- UPS HID component initialization with Protocol Factory
- Status LED with smart patterns
- Essential binary sensors: `online`, `on_battery`, `low_battery`, `fault`
- Essential text sensors: `status` (as "UPS Status"), `protocol` (as "Detected Protocol")
- **Data Provider Pattern**: LED automation accesses UPS data directly (no sensor entities required!)
- Status LED with smart patterns using `id(ups_monitor).is_online()`, etc.
- **Optional sensors**: Only `status` and `protocol` text sensors (for Home Assistant integration)
#### `essential_sensors.yaml` / `essential_sensors_grouped.yaml`
Core monitoring sensors (5 sensors) available on all protocols:
@@ -171,6 +171,21 @@ packages:
```
**Use for**: Development, CI/CD testing, feature demonstration
### `testing/minimal_data_provider.yaml`
Data provider pattern testing with zero sensor entities:
```yaml
substitutions:
simulation_mode: "true" # Enable simulation for testing
packages:
base_ups: !include base_ups.yaml
# ZERO sensor entities defined - tests pure data provider mode!
```
**Features**:
- Tests all direct data access methods: `id(ups_monitor).is_online()`, etc.
- LED automation works without any sensor entities
- Comprehensive validation of data provider pattern
- **Use for**: Testing component as pure data provider, custom automation development
## Production Examples
### `examples/apc-ups-monitor.yaml`
@@ -314,7 +329,32 @@ substitutions:
```
### 6. **Testing Strategy**
- **Protocol Testing**: Use `basic_test.yaml`
- **Protocol Testing**: Use `testing/basic_test.yaml`
- **Feature Testing**: Use specific test configurations
- **Integration Testing**: Use `simulation_test.yaml`
- **Integration Testing**: Use `testing/simulation_test.yaml`
- **Data Provider Testing**: Use `testing/minimal_data_provider.yaml`
- **Production Validation**: Use device-specific examples
### 7. **Data Provider Pattern Usage**
The UPS HID component now functions as a **data provider**, allowing direct access to UPS data without requiring sensor entities:
#### **Direct Data Access Methods**:
```yaml
interval:
- interval: 10s
then:
- lambda: |-
// Boolean state methods (no sensor entities needed!)
if (id(ups_monitor).is_online()) {
ESP_LOGI("ups", "UPS is online");
}
if (id(ups_monitor).is_on_battery()) {
ESP_LOGI("ups", "Running on battery: %.1f%% remaining",
id(ups_monitor).get_battery_level());
}
```
#### **Available Direct Access Methods**:
**Boolean States**: `is_online()`, `is_on_battery()`, `is_low_battery()`, `is_charging()`, `has_fault()`, `is_overloaded()`
**Value Getters**: `get_battery_level()`, `get_input_voltage()`, `get_output_voltage()`, `get_load_percent()`, `get_runtime_minutes()`
+8 -33
View File
@@ -104,22 +104,23 @@ light:
min_brightness: 20%
max_brightness: 60%
# LED control automation
# LED control automation (no sensor entities required!)
interval:
- interval: 2s
then:
- lambda: |-
if (id(low_battery).state || id(ups_fault).state) {
// Direct access to UPS data - no sensor entities needed
if (id(ups_monitor).is_low_battery() || id(ups_monitor).has_fault()) {
auto call = id(ups_status_led).turn_on();
call.set_rgb(1.0, 0.0, 0.0);
call.set_effect("Critical Alert");
call.perform();
} else if (id(on_battery).state) {
} else if (id(ups_monitor).is_on_battery()) {
auto call = id(ups_status_led).turn_on();
call.set_rgb(1.0, 0.5, 0.0);
call.set_effect("Battery Warning");
call.perform();
} else if (id(ups_online).state) {
} else if (id(ups_monitor).is_online()) {
auto call = id(ups_status_led).turn_on();
call.set_rgb(0.0, 1.0, 0.0);
call.set_effect("Normal Status");
@@ -128,35 +129,9 @@ interval:
id(ups_status_led).turn_off().perform();
}
# Essential binary sensors (required for LED automation)
binary_sensor:
- platform: ups_hid
ups_hid_id: ups_monitor
name: "UPS Online"
id: ups_online
type: online
device_class: connectivity
- platform: ups_hid
ups_hid_id: ups_monitor
name: "On Battery Power"
id: on_battery
type: on_battery
device_class: battery
- platform: ups_hid
ups_hid_id: ups_monitor
name: "Low Battery Warning"
id: low_battery
type: low_battery
device_class: battery
- platform: ups_hid
ups_hid_id: ups_monitor
name: "UPS Fault"
id: ups_fault
type: fault
device_class: problem
# Note: Binary sensors are now completely OPTIONAL!
# Only define them if you need Home Assistant entities
# The LED automation above works without any sensor entities
# Essential text sensors
text_sensor:
@@ -0,0 +1,88 @@
# Data Provider Testing Configuration
# Tests UPS HID component as pure data provider with comprehensive validation
# Validates all direct access methods work without any sensor entities
substitutions:
name: "data-provider-test"
friendly_name: "Data Provider Test"
simulation_mode: "true" # Enable simulation for testing
# Core ESPHome configuration
esphome:
name: ${name}
friendly_name: ${friendly_name}
# Use base UPS configuration (now has optional sensors)
packages:
base_ups: !include base_ups.yaml
# ZERO sensor entities defined - testing pure data provider mode!
# Override base_ups interval with comprehensive testing
interval:
- interval: 30s
then:
- lambda: |-
// Test all boolean state methods
ESP_LOGI("test", "=== UPS Data Provider Test ===");
ESP_LOGI("test", "Online: %s", id(ups_monitor).is_online() ? "YES" : "NO");
ESP_LOGI("test", "On Battery: %s", id(ups_monitor).is_on_battery() ? "YES" : "NO");
ESP_LOGI("test", "Low Battery: %s", id(ups_monitor).is_low_battery() ? "YES" : "NO");
ESP_LOGI("test", "Charging: %s", id(ups_monitor).is_charging() ? "YES" : "NO");
ESP_LOGI("test", "Fault: %s", id(ups_monitor).has_fault() ? "YES" : "NO");
ESP_LOGI("test", "Overload: %s", id(ups_monitor).is_overloaded() ? "YES" : "NO");
// Test all value getter methods
float battery = id(ups_monitor).get_battery_level();
float input_v = id(ups_monitor).get_input_voltage();
float output_v = id(ups_monitor).get_output_voltage();
float load = id(ups_monitor).get_load_percent();
float runtime = id(ups_monitor).get_runtime_minutes();
ESP_LOGI("test", "Battery: %.1f%%, Input: %.1fV, Output: %.1fV",
isnan(battery) ? -1.0f : battery,
isnan(input_v) ? -1.0f : input_v,
isnan(output_v) ? -1.0f : output_v);
ESP_LOGI("test", "Load: %.1f%%, Runtime: %.1f min",
isnan(load) ? -1.0f : load,
isnan(runtime) ? -1.0f : runtime);
- interval: 60s
then:
- lambda: |-
// Advanced LED state testing - cycles through different conditions
static int test_phase = 0;
test_phase = (test_phase + 1) % 6;
ESP_LOGI("led_test", "LED Test Phase: %d", test_phase);
switch(test_phase) {
case 0: // Test critical state display
if (id(ups_monitor).is_low_battery() || id(ups_monitor).has_fault()) {
ESP_LOGI("led_test", "Critical state detected - RED strobe should be active");
}
break;
case 1: // Test battery operation
if (id(ups_monitor).is_on_battery()) {
ESP_LOGI("led_test", "Battery operation - ORANGE fade should be active");
}
break;
case 2: // Test charging state
if (id(ups_monitor).is_charging()) {
ESP_LOGI("led_test", "Charging state - YELLOW pattern should be active");
}
break;
case 3: // Test normal operation
if (id(ups_monitor).is_online()) {
ESP_LOGI("led_test", "Normal operation - GREEN breathing should be active");
}
break;
case 4: // Test offline state
if (!id(ups_monitor).is_online()) {
ESP_LOGI("led_test", "Offline state - BLUE fade should be active");
}
break;
case 5: // Data provider mode validation
ESP_LOGI("led_test", "Data provider mode: Component should report zero sensors registered");
break;
}