feat(nut-server): nut v2.8 compatibile implementation

Signed-off-by: bullshit <coding@ow-software.pl>
This commit is contained in:
bullshit committed 2025-09-01 16:38:16 +02:00
1 parent 5ac47b9462
commit efba7a84be
14 files changed
+2306 -10

No files matched your search

+341
View File
@@ -0,0 +1,341 @@
# NUT Server Component for ESPHome
The `nut_server` component exposes UPS data from the `ups_hid` component via the Network UPS Tools (NUT) TCP protocol. This allows ESPHome devices to act as NUT servers, making UPS status and control available to NUT clients on the network.
## Features
- **Multi-client TCP Server**: Supports up to 10 simultaneous client connections (configurable)
- **NUT Protocol v2.8.0**: Compatible with standard NUT clients and monitoring tools
- **Authentication**: Optional username/password authentication for secure access
- **Real-time UPS Data**: Exposes live UPS status from the `ups_hid` component
- **Command Support**: Execute UPS commands like beeper control and battery tests
- **Thread-safe Design**: Proper mutex protection for concurrent client access
- **Non-blocking I/O**: Efficient event-driven architecture using FreeRTOS tasks
## Configuration
### Basic Configuration
```yaml
# Minimal configuration
nut_server:
ups_hid_id: my_ups
```
### Advanced Configuration
```yaml
# Full configuration with all options
nut_server:
ups_hid_id: my_ups # Required: Reference to ups_hid component
port: 3493 # Optional: TCP port (default: 3493)
ups_name: "office_ups" # Optional: UPS name in NUT (default: ups_hid ID)
username: "nutuser" # Optional: Username for authentication
password: "secretpass" # Optional: Password (empty = no auth)
max_clients: 4 # Optional: Max simultaneous clients (1-10, default: 4)
```
### Complete Example with UPS HID
```yaml
# UPS HID component configuration
ups_hid:
id: my_ups
update_interval: 10s
# NUT Server configuration
nut_server:
ups_hid_id: my_ups
port: 3493
ups_name: "esphome_ups"
username: "monitor"
password: "ups123"
max_clients: 5
# Optional: Network configuration
wifi:
ssid: "YourWiFi"
password: "YourPassword"
# Static IP recommended for server
manual_ip:
static_ip: 192.168.1.100
gateway: 192.168.1.1
subnet: 255.255.255.0
```
## Supported NUT Commands
### Query Commands
| Command | Description | Authentication Required |
|---------|-------------|------------------------|
| `HELP` | Show available commands | No |
| `VERSION` | Get NUT protocol version | No |
| `NETVER` | Get network protocol version | No |
| `UPSDVER` | Get server version | No |
| `LIST UPS` | List available UPS devices | Yes* |
| `LIST VAR <ups>` | List all variables for UPS | Yes* |
| `GET VAR <ups> <var>` | Get specific variable value | Yes* |
| `LIST CMD <ups>` | List available commands | Yes* |
| `LIST CLIENTS` | List connected clients | Yes* |
| `LIST RW <ups>` | List read-write variables | Yes* |
| `LIST ENUM <ups> <var>` | List enum values for variable | Yes* |
| `LIST RANGE <ups> <var>` | List range for variable | Yes* |
*Authentication required only if password is configured
### Control Commands
| Command | Description | Authentication Required |
|---------|-------------|------------------------|
| `LOGIN <user> <pass>` | Authenticate client | No |
| `LOGOUT` | End authenticated session | No |
| `INSTCMD <ups> <cmd>` | Execute instant command | Yes* |
### Supported Instant Commands
The following instant commands are supported when the UPS hardware supports them:
- `beeper.enable` - Enable UPS beeper
- `beeper.disable` - Disable UPS beeper
- `beeper.mute` - Temporarily mute beeper
- `test.battery.start.quick` - Start quick battery test (10-15 seconds)
- `test.battery.start.deep` - Start deep battery test (2-5 minutes)
- `test.battery.stop` - Stop battery test in progress
## Exposed NUT Variables
The following NUT variables are exposed based on available UPS data:
### Device Information
- `ups.mfr` - Manufacturer name
- `ups.model` - UPS model
- `ups.serial` - Serial number
- `ups.firmware` - Firmware version
### Battery Status
- `battery.charge` - Battery charge percentage (0-100)
- `battery.voltage` - Battery voltage
- `battery.runtime` - Estimated runtime in seconds
- `battery.type` - Battery chemistry type
### Power Status
- `input.voltage` - Input voltage from mains
- `output.voltage` - Output voltage to load
- `ups.load` - Load percentage (0-100)
- `ups.power` - Output power in watts
- `ups.status` - Combined status flags:
- `OL` - Online (mains power present)
- `OB` - On Battery
- `LB` - Low Battery
- `CHRG` - Charging
- `TEST` - Test in progress
- `ALARM` - Alarm condition
### Configuration
- `ups.delay.shutdown` - Shutdown delay in seconds
- `ups.delay.start` - Startup delay in seconds
## Client Connection Examples
### Using `upsc` (NUT client)
```bash
# List UPS status (no auth)
upsc esphome_ups@192.168.1.100
# List UPS status (with auth)
upsc -u monitor -p ups123 esphome_ups@192.168.1.100
# Get specific variable
upsc esphome_ups@192.168.1.100 battery.charge
```
### Using `telnet` for Testing
```bash
telnet 192.168.1.100 3493
# Commands to try:
HELP
VERSION
LOGIN monitor ups123
LIST UPS
LIST VAR esphome_ups
GET VAR esphome_ups battery.charge
LIST CMD esphome_ups
LIST CLIENTS
INSTCMD esphome_ups beeper.mute
LOGOUT
```
### Python Client Example
```python
import socket
def nut_query(host, port, commands):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((host, port))
responses = []
for cmd in commands:
sock.send(f"{cmd}\n".encode())
response = sock.recv(1024).decode()
responses.append(response)
sock.close()
return responses
# Query UPS
host = "192.168.1.100"
port = 3493
commands = [
"LOGIN monitor ups123",
"LIST VAR esphome_ups",
"LOGOUT"
]
results = nut_query(host, port, commands)
for r in results:
print(r)
```
## Integration with NUT Monitoring Tools
### NUT Monitor (nut-monitor)
The component is compatible with GUI monitoring tools like `nut-monitor`. Configure the connection with:
- Host: ESP32 IP address
- Port: 3493 (or configured port)
- UPS Name: As configured in `ups_name`
- Username/Password: If authentication is enabled
### Home Assistant NUT Integration
You can use Home Assistant's NUT integration to monitor the UPS:
```yaml
# Home Assistant configuration.yaml
sensor:
- platform: nut
host: 192.168.1.100
port: 3493
username: monitor
password: ups123
resources:
- battery.charge
- battery.runtime
- input.voltage
- ups.load
- ups.status
```
### Grafana + Prometheus
Use the NUT exporter for Prometheus to collect metrics:
```yaml
# prometheus-nut-exporter configuration
nut_servers:
- name: esphome_ups
host: 192.168.1.100
port: 3493
username: monitor
password: ups123
```
## Design Patterns and Architecture
### Component Architecture
The NUT server component follows several design patterns for robustness:
1. **Server/Client Pattern**: Multi-client TCP server with connection management
2. **Command Pattern**: NUT protocol commands mapped to handler methods
3. **Observer Pattern**: Real-time UPS data updates from `ups_hid` component
4. **Strategy Pattern**: Authentication strategy (optional auth vs required)
### Thread Safety
- **Mutex Protection**: Client list and UPS data access protected by mutexes
- **Non-blocking I/O**: All socket operations are non-blocking
- **FreeRTOS Tasks**: Dedicated server task for handling connections
- **Timeout Management**: Automatic cleanup of inactive clients
### SOLID Principles
- **Single Responsibility**: Separate classes for server, client, and protocol handling
- **Open/Closed**: Extensible for new NUT commands without modifying core
- **Liskov Substitution**: Compatible with standard NUT protocol expectations
- **Interface Segregation**: Clean separation between UPS data provider and NUT server
- **Dependency Inversion**: Depends on `ups_hid` interface, not implementation
## Troubleshooting
### Common Issues
1. **Connection Refused**
- Check firewall rules allow TCP port 3493
- Verify ESP32 is connected to network
- Confirm server started successfully in logs
2. **Authentication Failed**
- Verify username and password match configuration
- Check for typos in credentials
- Try without authentication first
3. **No UPS Data**
- Ensure `ups_hid` component is working
- Check USB connection to UPS
- Verify UPS is supported by `ups_hid`
4. **Client Timeout**
- Clients are disconnected after 60 seconds of inactivity
- Send periodic queries to maintain connection
- Increase client timeout if needed (requires code modification)
### Debug Logging
Enable debug logging to troubleshoot issues:
```yaml
logger:
level: DEBUG
logs:
nut_server: DEBUG
ups_hid: DEBUG
```
## Development Notes
### Adding New NUT Variables
To expose additional UPS data as NUT variables:
1. Ensure data is available in `UpsData` structure
2. Add mapping in `get_ups_var()` method
3. Include in `handle_list_var()` response
### Adding New Commands
To support additional instant commands:
1. Add command mapping in `execute_command()` method
2. Implement handler in `ups_hid` component if needed
3. Add to `get_available_commands()` list
### Future Enhancements
Planned improvements for future versions:
- [ ] Support for SET VAR (configure UPS settings)
- [ ] Event notifications (NOTIFY)
- [ ] Multiple UPS support (when multiple `ups_hid` components exist)
- [ ] Configurable client timeout
- [ ] Rate limiting for failed authentication attempts
## References
- [Network UPS Tools (NUT) Protocol](https://networkupstools.org/docs/developer-guide.chunked/ar01s09.html)
- [NUT Command Reference](https://networkupstools.org/docs/man/upsd.html)
- [ESPHome Component Development](https://esphome.io/custom/custom_component.html)
- [UPS HID Component Documentation](../ups_hid/README.md)
+72
View File
@@ -0,0 +1,72 @@
"""NUT Server Component for ESPHome - Configuration and code generation."""
import esphome.codegen as cg
import esphome.config_validation as cv
from esphome.const import (
CONF_ID,
CONF_PORT,
CONF_USERNAME,
CONF_PASSWORD,
)
DEPENDENCIES = ["esp32", "network", "ups_hid"]
AUTO_LOAD = []
MULTI_CONF = False
CONF_UPS_HID_ID = "ups_hid_id"
CONF_MAX_CLIENTS = "max_clients"
nut_server_ns = cg.esphome_ns.namespace("nut_server")
NutServerComponent = nut_server_ns.class_("NutServerComponent", cg.Component)
# Import ups_hid namespace
ups_hid_ns = cg.esphome_ns.namespace("ups_hid")
UpsHidComponent = ups_hid_ns.class_("UpsHidComponent", cg.PollingComponent)
CONFIG_SCHEMA = cv.Schema(
{
cv.GenerateID(): cv.declare_id(NutServerComponent),
cv.Required(CONF_UPS_HID_ID): cv.use_id(UpsHidComponent),
cv.Optional(CONF_PORT, default=3493): cv.port,
cv.Optional(CONF_USERNAME, default="nutuser"): cv.string,
cv.Optional(CONF_PASSWORD, default=""): cv.string,
cv.Optional(CONF_MAX_CLIENTS, default=4): cv.int_range(min=1, max=10),
}
).extend(cv.COMPONENT_SCHEMA)
def validate_config(config):
"""Validate NUT server configuration."""
# Validate authentication
if config[CONF_PASSWORD] and not config[CONF_USERNAME]:
raise cv.Invalid("Username is required when password is set")
return config
CONFIG_SCHEMA = CONFIG_SCHEMA.add_extra(validate_config)
async def to_code(config):
"""Generate C++ code for NUT server component."""
var = cg.new_Pvariable(config[CONF_ID])
await cg.register_component(var, config)
# Get reference to UPS HID component
ups_hid = await cg.get_variable(config[CONF_UPS_HID_ID])
cg.add(var.set_ups_hid(ups_hid))
# Set port
cg.add(var.set_port(config[CONF_PORT]))
# Set authentication
cg.add(var.set_username(config[CONF_USERNAME]))
if CONF_PASSWORD in config:
cg.add(var.set_password(config[CONF_PASSWORD]))
# Set max clients
cg.add(var.set_max_clients(config[CONF_MAX_CLIENTS]))
# Set UPS name automatically from the UPS HID component ID
ups_name = str(config[CONF_UPS_HID_ID])
cg.add(var.set_ups_name(ups_name))
+945
View File
@@ -0,0 +1,945 @@
#include "nut_server.h"
#include "../ups_hid/ups_hid.h"
#include "esphome/core/log.h"
#include "esphome/core/util.h"
#include "esphome/core/hal.h"
#include <algorithm>
#include <sstream>
#include <iomanip>
#include <cstring>
#ifdef USE_ESP32
#include "lwip/err.h"
#include "lwip/sys.h"
#include <fcntl.h>
#include <errno.h>
#endif
namespace esphome {
namespace nut_server {
NutServerComponent::NutServerComponent() {
clients_.reserve(DEFAULT_MAX_CLIENTS);
}
NutServerComponent::~NutServerComponent() {
stop_server();
}
void NutServerComponent::setup() {
ESP_LOGCONFIG(TAG, "Setting up NUT Server...");
if (!ups_hid_) {
ESP_LOGE(TAG, "No UPS HID component configured!");
mark_failed();
return;
}
// Initialize clients
clients_.resize(max_clients_);
for (auto &client : clients_) {
client.reset();
}
if (!start_server()) {
ESP_LOGE(TAG, "Failed to start NUT server!");
mark_failed();
return;
}
ESP_LOGCONFIG(TAG, "NUT Server started on port %d", port_);
}
void NutServerComponent::loop() {
// Main loop handles client cleanup
cleanup_inactive_clients();
}
void NutServerComponent::dump_config() {
ESP_LOGCONFIG(TAG, "NUT Server:");
ESP_LOGCONFIG(TAG, " Port: %d", port_);
ESP_LOGCONFIG(TAG, " Max Clients: %d", max_clients_);
ESP_LOGCONFIG(TAG, " UPS Name: %s", get_ups_name().c_str());
ESP_LOGCONFIG(TAG, " Username: %s", username_.c_str());
ESP_LOGCONFIG(TAG, " Authentication: %s", password_.empty() ? "Disabled" : "Enabled");
if (ups_hid_) {
ESP_LOGCONFIG(TAG, " UPS HID Component: Connected");
} else {
ESP_LOGCONFIG(TAG, " UPS HID Component: Not configured!");
}
}
bool NutServerComponent::start_server() {
#ifdef USE_ESP32
// Create server socket
server_socket_ = socket(AF_INET, SOCK_STREAM, 0);
if (server_socket_ < 0) {
ESP_LOGE(TAG, "Failed to create socket: %d", errno);
return false;
}
// Set socket options
int yes = 1;
if (setsockopt(server_socket_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)) < 0) {
ESP_LOGW(TAG, "Failed to set SO_REUSEADDR: %d", errno);
}
// Set non-blocking mode
int flags = fcntl(server_socket_, F_GETFL, 0);
if (fcntl(server_socket_, F_SETFL, flags | O_NONBLOCK) < 0) {
ESP_LOGW(TAG, "Failed to set non-blocking mode: %d", errno);
}
// Bind to port
struct sockaddr_in server_addr;
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = INADDR_ANY;
server_addr.sin_port = htons(port_);
if (bind(server_socket_, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
ESP_LOGE(TAG, "Failed to bind to port %d: %d", port_, errno);
close(server_socket_);
server_socket_ = -1;
return false;
}
// Start listening
if (listen(server_socket_, max_clients_) < 0) {
ESP_LOGE(TAG, "Failed to listen on socket: %d", errno);
close(server_socket_);
server_socket_ = -1;
return false;
}
// Create server task
server_running_ = true;
xTaskCreate(server_task, "nut_server", 4096, this, 1, &server_task_handle_);
return true;
#else
ESP_LOGE(TAG, "NUT Server requires ESP32 platform");
return false;
#endif
}
void NutServerComponent::stop_server() {
#ifdef USE_ESP32
shutdown_requested_ = true;
server_running_ = false;
// Close all client connections
{
std::lock_guard<std::mutex> lock(clients_mutex_);
for (auto &client : clients_) {
if (client.is_active()) {
disconnect_client(client);
}
}
}
// Close server socket
if (server_socket_ >= 0) {
close(server_socket_);
server_socket_ = -1;
}
// Wait for server task to finish
if (server_task_handle_) {
vTaskDelete(server_task_handle_);
server_task_handle_ = nullptr;
}
#endif
}
void NutServerComponent::server_task(void *param) {
#ifdef USE_ESP32
NutServerComponent *server = static_cast<NutServerComponent *>(param);
while (server->server_running_) {
server->accept_clients();
// Handle all connected clients
{
std::lock_guard<std::mutex> lock(server->clients_mutex_);
for (auto &client : server->clients_) {
if (client.is_active()) {
server->handle_client(client);
}
}
}
vTaskDelay(10 / portTICK_PERIOD_MS);
}
vTaskDelete(nullptr);
#endif
}
void NutServerComponent::accept_clients() {
#ifdef USE_ESP32
struct sockaddr_in client_addr;
socklen_t client_len = sizeof(client_addr);
int client_socket = accept(server_socket_, (struct sockaddr *)&client_addr, &client_len);
if (client_socket < 0) {
if (errno != EWOULDBLOCK && errno != EAGAIN) {
ESP_LOGW(TAG, "Accept failed: %d", errno);
}
return;
}
// Set client socket to non-blocking
int flags = fcntl(client_socket, F_GETFL, 0);
fcntl(client_socket, F_SETFL, flags | O_NONBLOCK);
// Find available client slot
std::lock_guard<std::mutex> lock(clients_mutex_);
for (auto &client : clients_) {
if (!client.is_active()) {
client.socket_fd = client_socket;
client.state = ClientState::CONNECTED;
uint32_t now = millis();
client.last_activity = now;
client.connect_time = now;
client.login_attempts = 0;
client.remote_ip = std::string(inet_ntoa(client_addr.sin_addr));
ESP_LOGD(TAG, "Client connected from %s", client.remote_ip.c_str());
// NUT protocol: No initial greeting - wait for client commands
return;
}
}
// No available slots
ESP_LOGW(TAG, "Maximum clients reached, rejecting connection");
const char *msg = "ERR MAX-CLIENTS Maximum number of clients reached\n";
send(client_socket, msg, strlen(msg), 0);
close(client_socket);
#endif
}
void NutServerComponent::handle_client(NutClient &client) {
#ifdef USE_ESP32
char buffer[MAX_COMMAND_LENGTH];
int bytes_received = recv(client.socket_fd, buffer, sizeof(buffer) - 1, 0);
if (bytes_received > 0) {
buffer[bytes_received] = '\0';
// Remove trailing newline
char *newline = strchr(buffer, '\n');
if (newline) *newline = '\0';
newline = strchr(buffer, '\r');
if (newline) *newline = '\0';
client.last_activity = millis();
ESP_LOGV(TAG, "Received command: %s", buffer);
process_command(client, std::string(buffer));
} else if (bytes_received == 0) {
// Client disconnected
ESP_LOGD(TAG, "Client disconnected");
disconnect_client(client);
} else {
if (errno != EWOULDBLOCK && errno != EAGAIN) {
if (errno == ECONNRESET || errno == EPIPE) {
// Client abruptly disconnected - this is normal, log at debug level
ESP_LOGD(TAG, "Client connection reset (error %d)", errno);
} else {
// Other errors are more concerning
ESP_LOGW(TAG, "Receive error: %d", errno);
}
disconnect_client(client);
}
}
#endif
}
void NutServerComponent::disconnect_client(NutClient &client) {
#ifdef USE_ESP32
if (client.socket_fd >= 0) {
close(client.socket_fd);
}
client.reset();
#endif
}
void NutServerComponent::cleanup_inactive_clients() {
uint32_t now = millis();
std::lock_guard<std::mutex> lock(clients_mutex_);
for (auto &client : clients_) {
if (client.is_active() && (now - client.last_activity) > CLIENT_TIMEOUT_MS) {
ESP_LOGD(TAG, "Client timeout, disconnecting");
disconnect_client(client);
}
}
}
void NutServerComponent::process_command(NutClient &client, const std::string &command) {
if (command.empty()) {
return;
}
// Parse command and arguments
size_t space_pos = command.find(' ');
std::string cmd = (space_pos != std::string::npos) ?
command.substr(0, space_pos) : command;
std::string args = (space_pos != std::string::npos) ?
command.substr(space_pos + 1) : "";
// Debug: Log all received commands
ESP_LOGD(TAG, "Received command: '%s' args: '%s'", cmd.c_str(), args.c_str());
// Convert command to uppercase for comparison
std::transform(cmd.begin(), cmd.end(), cmd.begin(), ::toupper);
// Commands that don't require authentication
if (cmd == "HELP") {
handle_help(client);
} else if (cmd == "VER" || cmd == "VERSION") {
handle_version(client);
} else if (cmd == "NETVER") {
handle_netver(client);
} else if (cmd == "STARTTLS") {
handle_starttls(client);
} else if (cmd == "USERNAME") {
handle_username(client, args);
} else if (cmd == "PASSWORD") {
handle_password(client, args);
} else if (cmd == "LOGIN") {
handle_login(client, args);
} else if (cmd == "LOGOUT") {
handle_logout(client);
} else if (cmd == "UPSDVER") {
handle_upsdver(client);
}
// Commands requiring authentication
else if (!password_.empty() && !client.is_authenticated()) {
send_error(client, "ACCESS-DENIED");
} else {
// Authenticated commands
if (cmd == "LIST") {
// Parse LIST subcommand
size_t sub_pos = args.find(' ');
std::string subcmd = (sub_pos != std::string::npos) ?
args.substr(0, sub_pos) : args;
std::string subargs = (sub_pos != std::string::npos) ?
args.substr(sub_pos + 1) : "";
std::transform(subcmd.begin(), subcmd.end(), subcmd.begin(), ::toupper);
if (subcmd == "UPS") {
handle_list_ups(client);
} else if (subcmd == "VAR") {
handle_list_var(client, subargs);
} else if (subcmd == "CMD") {
handle_list_cmd(client, subargs);
} else if (subcmd == "CLIENTS") {
handle_list_clients(client);
} else if (subcmd == "RW") {
handle_list_rwvar(client, subargs);
} else if (subcmd == "ENUM") {
handle_list_enum(client, subargs);
} else if (subcmd == "RANGE") {
handle_list_range(client, subargs);
} else {
send_error(client, "INVALID-ARGUMENT");
}
} else if (cmd == "GET") {
// Parse GET subcommand
size_t sub_pos = args.find(' ');
std::string subcmd = (sub_pos != std::string::npos) ?
args.substr(0, sub_pos) : args;
std::string subargs = (sub_pos != std::string::npos) ?
args.substr(sub_pos + 1) : "";
std::transform(subcmd.begin(), subcmd.end(), subcmd.begin(), ::toupper);
if (subcmd == "VAR") {
handle_get_var(client, subargs);
} else {
send_error(client, "INVALID-ARGUMENT");
}
} else if (cmd == "SET") {
// Parse SET subcommand
size_t sub_pos = args.find(' ');
std::string subcmd = (sub_pos != std::string::npos) ?
args.substr(0, sub_pos) : args;
std::string subargs = (sub_pos != std::string::npos) ?
args.substr(sub_pos + 1) : "";
std::transform(subcmd.begin(), subcmd.end(), subcmd.begin(), ::toupper);
if (subcmd == "VAR") {
handle_set_var(client, subargs);
} else {
send_error(client, "INVALID-ARGUMENT");
}
} else if (cmd == "INSTCMD") {
handle_instcmd(client, args);
} else if (cmd == "FSD") {
handle_fsd(client, args);
} else if (cmd == get_ups_name()) {
// Legacy upsc -l format: sends UPS name directly as command
// This is for old-style variable name support
handle_legacy_list_vars(client, cmd);
} else {
ESP_LOGW(TAG, "Unknown command received: '%s' with args: '%s'", cmd.c_str(), args.c_str());
send_error(client, "UNKNOWN-COMMAND");
}
}
}
void NutServerComponent::handle_login(NutClient &client, const std::string &args) {
auto parts = split_args(args);
if (parts.size() != 2) {
send_error(client, "INVALID-ARGUMENT");
return;
}
if (authenticate(parts[0], parts[1])) {
client.state = ClientState::AUTHENTICATED;
client.username = parts[0];
send_response(client, "OK\n");
ESP_LOGD(TAG, "Client authenticated as %s", parts[0].c_str());
} else {
client.login_attempts++;
if (client.login_attempts >= MAX_LOGIN_ATTEMPTS) {
ESP_LOGW(TAG, "Max login attempts exceeded, disconnecting client");
disconnect_client(client);
} else {
send_error(client, "ACCESS-DENIED");
}
}
}
void NutServerComponent::handle_logout(NutClient &client) {
send_response(client, "OK Goodbye\n");
// Close the connection after sending the goodbye message
disconnect_client(client);
}
void NutServerComponent::handle_list_ups(NutClient &client) {
std::string ups_name = get_ups_name();
std::string ups_description = get_ups_description();
std::string response = "BEGIN LIST UPS\n";
response += "UPS " + ups_name + " \"" + ups_description + "\"\n";
response += "END LIST UPS\n";
send_response(client, response);
}
void NutServerComponent::handle_list_var(NutClient &client, const std::string &args) {
if (args != get_ups_name()) {
send_error(client, "UNKNOWN-UPS");
return;
}
if (!has_ups_data()) {
send_error(client, "DATA-STALE");
return;
}
std::string ups_name = get_ups_name();
std::string response = "BEGIN LIST VAR " + ups_name + "\n";
// Standard NUT variables mapping to actual UPS data
std::vector<std::string> variables = {
"ups.mfr", "ups.model", "ups.status",
"battery.charge", "battery.voltage", "battery.runtime",
"input.voltage", "input.frequency",
"output.voltage", "ups.load"
};
for (const auto &var : variables) {
std::string value = get_ups_var(var);
if (!value.empty()) {
response += "VAR " + ups_name + " " + var + " \"" + value + "\"\n";
}
}
response += "END LIST VAR " + ups_name + "\n";
send_response(client, response);
}
void NutServerComponent::handle_get_var(NutClient &client, const std::string &args) {
auto parts = split_args(args);
if (parts.size() != 2) {
send_error(client, "INVALID-ARGUMENT");
return;
}
if (parts[0] != get_ups_name()) {
send_error(client, "UNKNOWN-UPS");
return;
}
std::string value = get_ups_var(parts[1]);
if (!value.empty()) {
std::string response = "VAR " + get_ups_name() + " " + parts[1] + " \"" + value + "\"\n";
send_response(client, response);
} else {
send_error(client, "VAR-NOT-SUPPORTED");
}
}
void NutServerComponent::handle_list_cmd(NutClient &client, const std::string &args) {
if (args != get_ups_name()) {
send_error(client, "UNKNOWN-UPS");
return;
}
std::string response = "BEGIN LIST CMD " + get_ups_name() + "\n";
auto commands = get_available_commands();
for (const auto &cmd : commands) {
response += "CMD " + get_ups_name() + " " + cmd + "\n";
}
response += "END LIST CMD " + get_ups_name() + "\n";
send_response(client, response);
}
void NutServerComponent::handle_list_clients(NutClient &client) {
std::string response = "BEGIN LIST CLIENT\n";
uint32_t now = millis();
// Note: clients_mutex_ is already held by the calling context (server loop)
for (size_t i = 0; i < clients_.size(); ++i) {
const auto &c = clients_[i];
if (c.is_active()) {
// Format: CLIENT <ip> <connected_time> <status>
std::string status = c.is_authenticated() ? "authenticated" : "connected";
uint32_t connected_time = (now - c.connect_time) / 1000; // seconds
response += "CLIENT " + c.remote_ip + " " + std::to_string(connected_time) + " " + status + "\n";
}
}
response += "END LIST CLIENT\n";
send_response(client, response);
}
void NutServerComponent::handle_instcmd(NutClient &client, const std::string &args) {
ESP_LOGD(TAG, "INSTCMD received with args: '%s'", args.c_str());
auto parts = split_args(args);
ESP_LOGD(TAG, "INSTCMD parsed into %zu parts", parts.size());
for (size_t i = 0; i < parts.size(); ++i) {
ESP_LOGD(TAG, " Part %zu: '%s'", i, parts[i].c_str());
}
if (parts.size() != 2) {
ESP_LOGW(TAG, "INSTCMD invalid argument count: %zu (expected 2)", parts.size());
send_error(client, "INVALID-ARGUMENT");
return;
}
ESP_LOGD(TAG, "UPS name comparison: received='%s', expected='%s'", parts[0].c_str(), get_ups_name().c_str());
if (parts[0] != get_ups_name()) {
ESP_LOGW(TAG, "INSTCMD unknown UPS: '%s'", parts[0].c_str());
send_error(client, "UNKNOWN-UPS");
return;
}
ESP_LOGD(TAG, "Executing command: '%s'", parts[1].c_str());
bool cmd_result = execute_command(parts[1]);
ESP_LOGD(TAG, "Command execution result: %s", cmd_result ? "SUCCESS" : "FAILED");
if (cmd_result) {
send_response(client, "OK\n");
} else {
ESP_LOGW(TAG, "Command failed or not supported: %s", parts[1].c_str());
send_error(client, "CMD-NOT-SUPPORTED");
}
}
void NutServerComponent::handle_version(NutClient &client) {
std::string response = "VERSION \"" + std::string(NUT_VERSION) + "\"\n";
send_response(client, response);
}
void NutServerComponent::handle_netver(NutClient &client) {
// NETVER returns the network protocol version only, no prefix
// NUT network protocol version 1.3 is current standard
send_response(client, "1.3\n");
}
void NutServerComponent::handle_help(NutClient &client) {
std::string response = "Commands: HELP VERSION NETVER STARTTLS USERNAME PASSWORD LOGIN LOGOUT LIST GET SET INSTCMD FSD UPSDVER\n";
send_response(client, response);
}
void NutServerComponent::handle_upsdver(NutClient &client) {
std::string response = std::string(UPSD_VERSION) + "\n";
send_response(client, response);
}
void NutServerComponent::handle_starttls(NutClient &client) {
// STARTTLS is not supported (we don't have TLS/SSL)
send_error(client, "FEATURE-NOT-SUPPORTED");
}
void NutServerComponent::handle_username(NutClient &client, const std::string &args) {
if (args.empty()) {
send_error(client, "INVALID-ARGUMENT");
return;
}
client.temp_username = args;
ESP_LOGD(TAG, "Received username: %s", args.c_str());
send_response(client, "OK\n");
}
void NutServerComponent::handle_password(NutClient &client, const std::string &args) {
if (args.empty()) {
send_error(client, "INVALID-ARGUMENT");
return;
}
client.temp_password = args;
ESP_LOGD(TAG, "Received password (authentication attempt)");
// Attempt authentication with stored credentials
if (authenticate(client.temp_username, client.temp_password)) {
client.state = ClientState::AUTHENTICATED;
client.username = client.temp_username;
client.login_attempts = 0;
ESP_LOGI(TAG, "Client authenticated successfully: %s", client.username.c_str());
send_response(client, "OK\n");
} else {
client.login_attempts++;
if (client.login_attempts >= MAX_LOGIN_ATTEMPTS) {
ESP_LOGW(TAG, "Max login attempts exceeded, disconnecting client");
disconnect_client(client);
} else {
send_error(client, "ACCESS-DENIED");
}
}
// Clear temporary credentials
client.temp_username.clear();
client.temp_password.clear();
}
void NutServerComponent::handle_fsd(NutClient &client, const std::string &args) {
// FSD (Forced Shutdown) - this is a critical command
// For now, just acknowledge but don't actually shutdown
ESP_LOGW(TAG, "FSD (Forced Shutdown) command received from client");
send_response(client, "OK FSD-SET\n");
}
void NutServerComponent::handle_set_var(NutClient &client, const std::string &args) {
// SET VAR is not supported in this implementation
send_error(client, "CMD-NOT-SUPPORTED");
}
void NutServerComponent::handle_list_rwvar(NutClient &client, const std::string &args) {
// No read-write variables supported
if (args != get_ups_name()) {
send_error(client, "UNKNOWN-UPS");
return;
}
std::string response = "BEGIN LIST RW " + get_ups_name() + "\n";
response += "END LIST RW " + get_ups_name() + "\n";
send_response(client, response);
}
void NutServerComponent::handle_list_enum(NutClient &client, const std::string &args) {
// No enum variables supported
auto parts = split_args(args);
if (parts.size() != 2 || parts[0] != get_ups_name()) {
send_error(client, "INVALID-ARGUMENT");
return;
}
std::string response = "BEGIN LIST ENUM " + get_ups_name() + " " + parts[1] + "\n";
response += "END LIST ENUM " + get_ups_name() + " " + parts[1] + "\n";
send_response(client, response);
}
void NutServerComponent::handle_list_range(NutClient &client, const std::string &args) {
// No range variables supported
auto parts = split_args(args);
if (parts.size() != 2 || parts[0] != get_ups_name()) {
send_error(client, "INVALID-ARGUMENT");
return;
}
std::string response = "BEGIN LIST RANGE " + get_ups_name() + " " + parts[1] + "\n";
response += "END LIST RANGE " + get_ups_name() + " " + parts[1] + "\n";
send_response(client, response);
}
void NutServerComponent::handle_legacy_list_vars(NutClient &client, const std::string &ups_name) {
// Legacy format for upsc -l: return simple variable names without quotes
if (!has_ups_data()) {
send_error(client, "DATA-STALE");
return;
}
std::string response = "";
// Simple list format for legacy upsc -l support
response += "ups.mfr\n";
response += "ups.model\n";
response += "battery.charge\n";
response += "input.voltage\n";
response += "output.voltage\n";
response += "ups.load\n";
response += "battery.runtime\n";
response += "ups.status\n";
send_response(client, response);
}
bool NutServerComponent::send_response(NutClient &client, const std::string &response) {
#ifdef USE_ESP32
int bytes_sent = send(client.socket_fd, response.c_str(), response.length(), 0);
if (bytes_sent < 0) {
if (errno == ECONNRESET || errno == EPIPE || errno == ENOTCONN) {
ESP_LOGD(TAG, "Client connection reset (error %d)", errno);
} else {
ESP_LOGW(TAG, "Send error: %d", errno);
}
return false;
}
return bytes_sent == (int)response.length();
#else
return false;
#endif
}
bool NutServerComponent::send_error(NutClient &client, const std::string &error) {
std::string response = "ERR " + error + "\n";
return send_response(client, response);
}
bool NutServerComponent::authenticate(const std::string &username, const std::string &password) {
if (password_.empty()) {
// No authentication required
return true;
}
return (username == username_ && password == password_);
}
std::string NutServerComponent::get_ups_var(const std::string &var_name) {
if (!has_ups_data()) {
return "";
}
// Map variable names to data using data provider pattern
if (var_name == "ups.mfr") return get_ups_manufacturer();
if (var_name == "ups.model") return get_ups_model();
if (ups_hid_) {
if (var_name == "battery.charge") {
float battery_level = ups_hid_->get_battery_level();
if (battery_level >= 0) return std::to_string(static_cast<int>(battery_level));
}
if (var_name == "input.voltage") {
float input_voltage = ups_hid_->get_input_voltage();
if (input_voltage > 0) return format_nut_value(std::to_string(input_voltage));
}
if (var_name == "output.voltage") {
float output_voltage = ups_hid_->get_output_voltage();
if (output_voltage > 0) return format_nut_value(std::to_string(output_voltage));
}
if (var_name == "ups.load") {
float load_percent = ups_hid_->get_load_percent();
if (load_percent >= 0) return std::to_string(static_cast<int>(load_percent));
}
if (var_name == "battery.runtime") {
float runtime_minutes = ups_hid_->get_runtime_minutes();
if (runtime_minutes > 0) return std::to_string(static_cast<int>(runtime_minutes * 60));
}
}
if (var_name == "ups.status") {
return get_ups_status();
}
return "";
}
std::string NutServerComponent::get_ups_name() {
// Return a consistent UPS name
// This will be set during component configuration
return ups_name_.empty() ? "ups" : ups_name_;
}
std::string NutServerComponent::get_ups_description() {
if (!has_ups_data()) {
return "ESPHome UPS";
}
std::string manufacturer = get_ups_manufacturer();
std::string model = get_ups_model();
std::string desc = manufacturer;
if (!desc.empty() && !model.empty()) {
desc += " " + model;
} else if (desc.empty()) {
desc = "ESPHome UPS";
}
return desc;
}
std::vector<std::string> NutServerComponent::get_available_commands() {
std::vector<std::string> commands;
if (ups_hid_ && ups_hid_->is_connected()) {
// Standard UPS HID commands that are always available
commands.push_back("beeper.enable");
commands.push_back("beeper.disable");
commands.push_back("beeper.mute");
commands.push_back("beeper.test");
commands.push_back("test.battery.start.quick");
commands.push_back("test.battery.start.deep");
commands.push_back("test.battery.stop");
// Standard NUT command names for panel/UPS tests
commands.push_back("test.panel.start");
commands.push_back("test.panel.stop");
// Keep legacy names for compatibility
commands.push_back("test.ups.start");
commands.push_back("test.ups.stop");
}
return commands;
}
bool NutServerComponent::execute_command(const std::string &command) {
if (!ups_hid_) {
return false;
}
// Map NUT commands to specific UPS HID methods
if (command == "beeper.enable") {
return ups_hid_->beeper_enable();
} else if (command == "beeper.disable") {
return ups_hid_->beeper_disable();
} else if (command == "beeper.mute") {
return ups_hid_->beeper_mute();
} else if (command == "beeper.test") {
return ups_hid_->beeper_test();
} else if (command == "test.battery.start.quick") {
return ups_hid_->start_battery_test_quick();
} else if (command == "test.battery.start.deep") {
return ups_hid_->start_battery_test_deep();
} else if (command == "test.battery.stop") {
return ups_hid_->stop_battery_test();
} else if (command == "test.panel.start" || command == "test.ups.start") {
return ups_hid_->start_ups_test();
} else if (command == "test.panel.stop" || command == "test.ups.stop") {
return ups_hid_->stop_ups_test();
}
return false;
}
std::string NutServerComponent::format_nut_value(const std::string &value) {
// Format floating point values to 1 decimal place
// Simple approach without exceptions
char* endptr;
float f = std::strtof(value.c_str(), &endptr);
if (endptr != value.c_str() && *endptr == '\0') {
// Valid float conversion
std::ostringstream oss;
oss << std::fixed << std::setprecision(1) << f;
return oss.str();
}
return value;
}
std::vector<std::string> NutServerComponent::split_args(const std::string &args) {
std::vector<std::string> result;
std::istringstream iss(args);
std::string token;
while (iss >> token) {
// Handle quoted strings
if (token.front() == '"') {
std::string quoted = token.substr(1);
if (quoted.back() != '"') {
std::string rest;
std::getline(iss, rest, '"');
quoted += rest;
} else {
quoted.pop_back();
}
result.push_back(quoted);
} else {
result.push_back(token);
}
}
return result;
}
bool NutServerComponent::has_ups_data() const {
return ups_hid_ && ups_hid_->is_connected();
}
std::string NutServerComponent::get_ups_status() const {
if (!ups_hid_ || !ups_hid_->is_connected()) {
return "";
}
std::string status;
if (ups_hid_->is_online()) {
status = "OL"; // Online
} else if (ups_hid_->is_on_battery()) {
status = "OB"; // On Battery
}
if (ups_hid_->is_low_battery()) {
if (!status.empty()) status += " ";
status += "LB"; // Low Battery
}
if (ups_hid_->is_charging()) {
if (!status.empty()) status += " ";
status += "CHRG"; // Charging
}
if (ups_hid_->has_fault()) {
if (!status.empty()) status += " ";
status += "ALARM"; // Alarm condition
}
return status;
}
std::string NutServerComponent::get_ups_manufacturer() const {
if (ups_hid_) {
auto ups_data = ups_hid_->get_ups_data();
if (!ups_data.device.manufacturer.empty()) {
return ups_data.device.manufacturer;
}
}
return "Unknown";
}
std::string NutServerComponent::get_ups_model() const {
if (ups_hid_) {
auto ups_data = ups_hid_->get_ups_data();
if (!ups_data.device.model.empty()) {
return ups_data.device.model;
}
}
return "Unknown UPS";
}
} // namespace nut_server
} // namespace esphome
+177
View File
@@ -0,0 +1,177 @@
#pragma once
#include "esphome/core/component.h"
#include "esphome/core/log.h"
#include <memory>
#include <vector>
#include <string>
#include <mutex>
#include <optional>
#ifdef USE_ESP32
#include "lwip/sockets.h"
#include "lwip/netdb.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#endif
namespace esphome {
// Forward declarations
namespace ups_hid {
class UpsHidComponent;
}
namespace nut_server {
static const char *const TAG = "nut_server";
// NUT protocol constants
static constexpr uint16_t DEFAULT_NUT_PORT = 3493;
static constexpr size_t MAX_COMMAND_LENGTH = 256;
static constexpr size_t MAX_RESPONSE_LENGTH = 2048;
static constexpr uint8_t DEFAULT_MAX_CLIENTS = 4;
static constexpr uint8_t MAX_LOGIN_ATTEMPTS = 3;
static constexpr uint32_t CLIENT_TIMEOUT_MS = 60000; // 60 seconds
// NUT protocol version
static constexpr const char* NUT_VERSION = "2.8.0";
static constexpr const char* UPSD_VERSION = "upsd 2.8.0 ESPHome";
// Client states
enum class ClientState {
CONNECTED,
AUTHENTICATED,
DISCONNECTED
};
// NUT client connection
struct NutClient {
int socket_fd{-1};
ClientState state{ClientState::DISCONNECTED};
uint8_t login_attempts{0};
uint32_t last_activity{0};
uint32_t connect_time{0};
std::string username;
std::string remote_ip;
std::string temp_username; // For USERNAME/PASSWORD flow
std::string temp_password; // For USERNAME/PASSWORD flow
bool is_authenticated() const { return state == ClientState::AUTHENTICATED; }
bool is_active() const { return socket_fd >= 0 && state != ClientState::DISCONNECTED; }
void reset() {
socket_fd = -1;
state = ClientState::DISCONNECTED;
login_attempts = 0;
last_activity = 0;
connect_time = 0;
username.clear();
remote_ip.clear();
temp_username.clear();
temp_password.clear();
}
};
// NUT Server Component
class NutServerComponent : public Component {
public:
NutServerComponent();
~NutServerComponent();
// ESPHome component lifecycle
void setup() override;
void loop() override;
void dump_config() override;
float get_setup_priority() const override { return setup_priority::AFTER_CONNECTION; }
// Configuration setters
void set_ups_hid(ups_hid::UpsHidComponent *ups_hid) { ups_hid_ = ups_hid; }
void set_port(uint16_t port) { port_ = port; }
void set_username(const std::string &username) { username_ = username; }
void set_password(const std::string &password) { password_ = password; }
void set_max_clients(uint8_t max_clients) {
max_clients_ = std::min(max_clients, static_cast<uint8_t>(10));
}
void set_ups_name(const std::string &ups_name) { ups_name_ = ups_name; }
protected:
// TCP server management
bool start_server();
void stop_server();
void accept_clients();
void handle_client(NutClient &client);
void disconnect_client(NutClient &client);
void cleanup_inactive_clients();
// NUT protocol handlers
void process_command(NutClient &client, const std::string &command);
void handle_login(NutClient &client, const std::string &args);
void handle_list_ups(NutClient &client);
void handle_list_var(NutClient &client, const std::string &args);
void handle_get_var(NutClient &client, const std::string &args);
void handle_list_cmd(NutClient &client, const std::string &args);
void handle_list_clients(NutClient &client);
void handle_instcmd(NutClient &client, const std::string &args);
void handle_version(NutClient &client);
void handle_netver(NutClient &client);
void handle_help(NutClient &client);
void handle_upsdver(NutClient &client);
void handle_logout(NutClient &client);
void handle_starttls(NutClient &client);
void handle_username(NutClient &client, const std::string &args);
void handle_password(NutClient &client, const std::string &args);
void handle_fsd(NutClient &client, const std::string &args);
void handle_set_var(NutClient &client, const std::string &args);
void handle_list_rwvar(NutClient &client, const std::string &args);
void handle_list_enum(NutClient &client, const std::string &args);
void handle_list_range(NutClient &client, const std::string &args);
void handle_legacy_list_vars(NutClient &client, const std::string &ups_name);
// Helper methods
bool send_response(NutClient &client, const std::string &response);
bool send_error(NutClient &client, const std::string &error);
bool authenticate(const std::string &username, const std::string &password);
std::string get_ups_var(const std::string &var_name);
std::string get_ups_description();
std::string get_ups_name(); // Dynamic UPS name from component
std::vector<std::string> get_available_commands();
bool execute_command(const std::string &command);
std::string format_nut_value(const std::string &value);
std::vector<std::string> split_args(const std::string &args);
// Data access using provider pattern (like status LED component)
bool has_ups_data() const;
std::string get_ups_status() const;
std::string get_ups_manufacturer() const;
std::string get_ups_model() const;
private:
// Server task management
static void server_task(void *param);
TaskHandle_t server_task_handle_{nullptr};
bool server_running_{false};
// Network resources
int server_socket_{-1};
uint16_t port_{DEFAULT_NUT_PORT};
// Client management
std::vector<NutClient> clients_;
uint8_t max_clients_{DEFAULT_MAX_CLIENTS};
mutable std::mutex clients_mutex_;
// Authentication
std::string username_{"nutuser"};
std::string password_{"nutpass"};
// UPS configuration
std::string ups_name_{"ups"};
ups_hid::UpsHidComponent *ups_hid_{nullptr};
// Server state
mutable std::mutex server_mutex_;
bool shutdown_requested_{false};
};
} // namespace nut_server
} // namespace esphome
+35
View File
@@ -108,6 +108,40 @@ UPS delay configuration package (3 number entities + automation scripts):
**Scripts**: Default delay application and configuration reading **Scripts**: Default delay application and configuration reading
**Home Assistant**: Number entities with proper device classes and validation **Home Assistant**: Number entities with proper device classes and validation
#### `nut_server.yaml` / `nut_server_grouped.yaml`
Network UPS Tools (NUT) TCP server for standard protocol integration:
**Server Features**:
- **Standard NUT Protocol**: v1.3 compliant TCP server on port 3493
- **Authentication**: Optional username/password protection
- **Multi-client Support**: Up to 4 simultaneous connections
- **Dynamic UPS Discovery**: Automatically exposes connected UPS data
**Protocol Support**:
- `LIST UPS` - Available UPS devices with dynamic description
- `LIST VAR` - All UPS variables with real-time data
- `LIST CMD` - Available instant commands
- `LIST CLIENT` - Connected monitoring clients
- `INSTCMD` - Execute UPS commands (beeper, tests)
- `NETVER` - Protocol version negotiation
**Data Integration**:
- Uses Data Provider Pattern from ups_hid component
- Maps UPS data to standard NUT variables (battery.charge, input.voltage, etc.)
- Dynamic manufacturer/model detection from connected device
**Client Compatibility**:
- Standard NUT tools (`upsc`, `upscmd`)
- Home Assistant NUT integration
- Any NUT-compatible monitoring software
- TCP plain-text protocol (no SSL/TLS required)
**Grouped Version Features**:
- **NUT Server Group**: All NUT-related entities in dedicated "🌐 NUT Server" section
- **Enhanced Sensors**: Connection string helper, client counter placeholder
- **Entity Categories**: Marked as diagnostic for proper Home Assistant organization
- **Web Interface**: Clean separation from UPS monitoring sensors
#### `entity_groups.yaml` #### `entity_groups.yaml`
ESPHome Web Server v3 entity organization (10 logical groups): ESPHome Web Server v3 entity organization (10 logical groups):
@@ -144,6 +178,7 @@ CyberPower CP1500 series optimizations:
| **Minimal** | `base_ups` + `essential_sensors` | **9 sensors** | Basic monitoring | | **Minimal** | `base_ups` + `essential_sensors` | **9 sensors** | Basic monitoring |
| **Complete** | + `extended_sensors` + `ups_controls` + `timer_sensors` | **32 sensors + 10 controls** | Full featured | | **Complete** | + `extended_sensors` + `ups_controls` + `timer_sensors` | **32 sensors + 10 controls** | Full featured |
| **Complete + Config** | + `delay_config` | **32 sensors + 10 controls + 3 number entities** | With UPS configuration | | **Complete + Config** | + `delay_config` | **32 sensors + 10 controls + 3 number entities** | With UPS configuration |
| **Complete + NUT Server** | + `nut_server` | **32 sensors + 10 controls + TCP server** | Network monitoring integration |
| **Device-Optimized** | + device-specific package | **33+ sensors + 13+ controls** | Production ready | | **Device-Optimized** | + device-specific package | **33+ sensors + 13+ controls** | Production ready |
| **Organized Interface** | Use `*_grouped.yaml` + `entity_groups.yaml` | **Same sensors, better layout** | Enhanced web interface | | **Organized Interface** | Use `*_grouped.yaml` + `entity_groups.yaml` | **Same sensors, better layout** | Enhanced web interface |
+3 -1
View File
@@ -31,7 +31,9 @@ logger:
baud_rate: 115200 baud_rate: 115200
hardware_uart: UART0 hardware_uart: UART0
logs: logs:
ups_hid: DEBUG ups_hid: INFO
nut_server: DEBUG
# Network configuration # Network configuration
wifi: wifi:
+7
View File
@@ -43,6 +43,13 @@ packages:
# APC-specific optimizations # APC-specific optimizations
apc_device: !include ../device_types/apc_backups_es.yaml apc_device: !include ../device_types/apc_backups_es.yaml
# NUT Server (Network UPS Tools) - uncomment to enable TCP server
# Exposes UPS data via standard NUT protocol for monitoring tools
# Standard package:
nut_server: !include ../nut_server.yaml
# OR grouped package (with NUT Server group in web interface):
# nut_server_grouped: !include ../nut_server_grouped.yaml
# Optional: Home Assistant API (uncomment to enable) # Optional: Home Assistant API (uncomment to enable)
# api: # api:
# encryption: # encryption:
+21 -9
View File
@@ -17,18 +17,25 @@ packages:
# Regional defaults (North American voltage/frequency standards) # Regional defaults (North American voltage/frequency standards)
regional_defaults: !include ../regional/north_american_base.yaml regional_defaults: !include ../regional/north_american_base.yaml
# OPTIONAL: Entity grouping (improves web interface organization)
# Uncomment to enable organized entity groups in ESPHome web interface
# entity_groups: !include ../entity_groups.yaml
# Core functionality # Core functionality
base_ups: !include ../base_ups.yaml base_ups: !include ../base_ups.yaml
# Choose EITHER grouped OR standard sensor packages (not both):
# Standard packages (current default):
essential: !include ../essential_sensors.yaml essential: !include ../essential_sensors.yaml
extended: !include ../extended_sensors.yaml # Recommended for CyberPower - rich sensor support
timers: !include ../timer_sensors.yaml # Real-time shutdown/startup monitoring
controls: !include ../ups_controls.yaml # Recommended - full beeper/test control
# Extended monitoring (recommended for CyberPower - rich sensor support) # OR grouped packages (better organization):
extended: !include ../extended_sensors.yaml # essential_grouped: !include ../essential_sensors_grouped.yaml
# extended_grouped: !include ../extended_sensors_grouped.yaml
# Timer countdown sensors (Real-time shutdown/startup monitoring) # timers_grouped: !include ../timer_sensors_grouped.yaml
timers: !include ../timer_sensors.yaml # controls_grouped: !include ../ups_controls_grouped.yaml
# Control buttons (recommended - full beeper/test control)
controls: !include ../ups_controls.yaml
# Delay configuration (Shutdown/Start/Reboot timers) # Delay configuration (Shutdown/Start/Reboot timers)
delay_config: !include ../delay_config.yaml delay_config: !include ../delay_config.yaml
@@ -36,7 +43,12 @@ packages:
# CyberPower-specific optimizations # CyberPower-specific optimizations
cyberpower_device: !include ../device_types/cyberpower_cp1500.yaml cyberpower_device: !include ../device_types/cyberpower_cp1500.yaml
controls_grouped: !include ../ups_controls_grouped.yaml # NUT Server (Network UPS Tools) - uncomment to enable TCP server
# Exposes UPS data via standard NUT protocol for monitoring tools
# Standard package:
# nut_server: !include ../nut_server.yaml
# OR grouped package (with NUT Server group in web interface):
# nut_server_grouped: !include ../nut_server_grouped.yaml
# Optional: Home Assistant API (uncomment to enable) # Optional: Home Assistant API (uncomment to enable)
# api: # api:
+7
View File
@@ -46,6 +46,13 @@ packages:
# CyberPower-specific optimizations # CyberPower-specific optimizations
cyberpower_device: !include ../device_types/cyberpower_cp1500.yaml cyberpower_device: !include ../device_types/cyberpower_cp1500.yaml
# NUT Server (Network UPS Tools) - uncomment to enable TCP server
# Exposes UPS data via standard NUT protocol for monitoring tools
# Standard package:
nut_server: !include ../nut_server.yaml
# OR grouped package (with NUT Server group in web interface):
# nut_server_grouped: !include ../nut_server_grouped.yaml
# Optional: Home Assistant API (uncomment to enable) # Optional: Home Assistant API (uncomment to enable)
# api: # api:
# encryption: # encryption:
+147
View File
@@ -0,0 +1,147 @@
# NUT Server Configuration Package
# Network UPS Tools (NUT) TCP server for exposing UPS data over standard NUT protocol
# Use with: packages: nut_server: !include configs/nut_server.yaml
# Substitutions with sensible defaults (can be overridden in parent config)
substitutions:
# NUT Server Configuration
nut_port: "3493" # Standard NUT port
nut_username: "nutuser" # Username for authentication
nut_password: "nutpass" # Password (leave empty to disable auth)
nut_max_clients: "4" # Maximum simultaneous clients (1-10)
# UPS name is now automatically derived from the ups_hid component ID
# Network Configuration (static IP recommended for servers)
use_static_ip: "false" # Set to "true" to enable static IP
static_ip: "192.168.1.100" # Static IP address
static_gateway: "192.168.1.1" # Gateway address
static_subnet: "255.255.255.0" # Subnet mask
static_dns1: "192.168.1.1" # Primary DNS server
# NUT Server Component
nut_server:
ups_hid_id: ups_monitor
port: ${nut_port}
username: "${nut_username}"
password: "${nut_password}"
max_clients: ${nut_max_clients}
# UPS name is automatically derived from ups_hid component ID (ups_monitor)
# Static IP configuration (uncomment to enable)
# Recommended for NUT server to ensure consistent network access
# Uncomment the following wifi section and customize the IP addresses:
#
# wifi:
# manual_ip:
# static_ip: ${static_ip}
# gateway: ${static_gateway}
# subnet: ${static_subnet}
# dns1: ${static_dns1}
# Enhanced logging for NUT server
logger:
logs:
nut_server: DEBUG # Set to DEBUG for troubleshooting
# Status indicators for NUT server
binary_sensor:
# Template sensors to indicate NUT server status
- platform: template
name: "NUT Server Active"
id: nut_server_status
icon: "mdi:network-outline"
lambda: |-
// NUT server is active if UPS is connected and has valid data
return id(ups_monitor).is_connected();
on_state:
then:
- if:
condition:
binary_sensor.is_on: nut_server_status
then:
- logger.log:
format: "NUT Server: Online - Serving UPS on port ${nut_port}"
level: INFO
else:
- logger.log: "NUT Server: Offline - UPS not connected or no valid data"
text_sensor:
# NUT server connection info
- platform: template
name: "NUT Server Info"
id: nut_server_info
icon: "mdi:information-outline"
lambda: |-
std::string info = "UPS: ups_monitor, Port: ${nut_port}";
if (std::string("${nut_password}").empty()) {
info += ", Auth: Disabled";
} else {
info += ", Auth: Enabled (${nut_username})";
}
info += ", Max Clients: ${nut_max_clients}";
return info;
# Automation for NUT server status monitoring
script:
- id: nut_server_status_check
then:
- lambda: |-
// Log current NUT server status and UPS data availability using data provider pattern
if (id(ups_monitor).is_connected()) {
ESP_LOGI("nut_server", "Status Check: UPS Connected=YES, Data Available=YES");
ESP_LOGI("nut_server", "Available Data: Battery=%.1f%%, Input=%.1fV, Load=%.1f%%, Status=%s",
id(ups_monitor).get_battery_level(),
id(ups_monitor).get_input_voltage(),
id(ups_monitor).get_load_percent(),
id(ups_monitor).is_online() ? "Online" : "On Battery");
} else {
ESP_LOGW("nut_server", "Status Check: UPS not connected - NUT server inactive");
}
# Status monitoring interval
interval:
- interval: 60s
then:
- script.execute: nut_server_status_check
# Client connection examples and documentation (commented)
#
# Connect with NUT client tools:
#
# 1. Using upsc command:
# upsc ups_monitor@<esp32_ip>:${nut_port}
# upsc -u ${nut_username} -p ${nut_password} ups_monitor@<esp32_ip>:${nut_port}
#
# 2. Using telnet for testing:
# telnet <esp32_ip> ${nut_port}
# Commands: HELP, VERSION, LOGIN ${nut_username} ${nut_password}, LIST UPS, LIST VAR ups_monitor
#
# 3. Home Assistant NUT integration:
# sensor:
# - platform: nut
# host: <esp32_ip>
# port: ${nut_port}
# username: ${nut_username}
# password: ${nut_password}
# resources:
# - battery.charge
# - battery.runtime
# - input.voltage
# - ups.load
# - ups.status
#
# 4. Python client example:
# import socket
# sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# sock.connect(('<esp32_ip>', ${nut_port}))
# sock.send(b"LOGIN ${nut_username} ${nut_password}\n")
# sock.send(b"LIST VAR ups_monitor\n")
# response = sock.recv(4096).decode()
# print(response)
# sock.close()
#
# Security Notes:
# - Use strong passwords in production
# - Consider firewall rules to limit access
# - Static IP recommended for consistent server access
# - Monitor logs for authentication failures
+195
View File
@@ -0,0 +1,195 @@
# NUT Server Configuration Package (Grouped Version)
# Network UPS Tools (NUT) TCP server with organized entity grouping
# Use with: packages: nut_server_grouped: !include configs/nut_server_grouped.yaml
# Substitutions with sensible defaults (can be overridden in parent config)
substitutions:
# NUT Server Configuration
nut_port: "3493" # Standard NUT port
nut_username: "nutuser" # Username for authentication
nut_password: "nutpass" # Password (leave empty to disable auth)
nut_max_clients: "4" # Maximum simultaneous clients (1-10)
# UPS name is now automatically derived from the ups_hid component ID
# Network Configuration (static IP recommended for servers)
use_static_ip: "false" # Set to "true" to enable static IP
static_ip: "192.168.1.100" # Static IP address
static_gateway: "192.168.1.1" # Gateway address
static_subnet: "255.255.255.0" # Subnet mask
static_dns1: "192.168.1.1" # Primary DNS server
# NUT Server Component
nut_server:
ups_hid_id: ups_monitor
port: ${nut_port}
username: "${nut_username}"
password: "${nut_password}"
max_clients: ${nut_max_clients}
# UPS name is automatically derived from ups_hid component ID (ups_monitor)
# Static IP configuration (uncomment to enable)
# Recommended for NUT server to ensure consistent network access
# Uncomment the following wifi section and customize the IP addresses:
#
# wifi:
# manual_ip:
# static_ip: ${static_ip}
# gateway: ${static_gateway}
# subnet: ${static_subnet}
# dns1: ${static_dns1}
# Enhanced logging for NUT server
logger:
logs:
nut_server: DEBUG # Set to DEBUG for troubleshooting
# Status indicators for NUT server - GROUPED VERSION
binary_sensor:
# Template sensors to indicate NUT server status
- platform: template
name: "NUT Server Active"
id: nut_server_status
icon: "mdi:network-outline"
entity_category: diagnostic
web_server:
sorting_group_id: nut_server_group
sorting_weight: 1
lambda: |-
// NUT server is active if UPS is connected and has valid data
return id(ups_monitor).is_connected();
on_state:
then:
- if:
condition:
binary_sensor.is_on: nut_server_status
then:
- logger.log:
format: "NUT Server: Online - Serving UPS on port ${nut_port}"
level: INFO
else:
- logger.log: "NUT Server: Offline - UPS not connected or no valid data"
text_sensor:
# NUT server connection info
- platform: template
name: "NUT Server Info"
id: nut_server_info
icon: "mdi:information-outline"
entity_category: diagnostic
web_server:
sorting_group_id: nut_server_group
sorting_weight: 2
lambda: |-
std::string info = "UPS: ups_monitor, Port: ${nut_port}";
if (std::string("${nut_password}").empty()) {
info += ", Auth: Disabled";
} else {
info += ", Auth: Enabled (${nut_username})";
}
info += ", Max Clients: ${nut_max_clients}";
return info;
# NUT server connection string for easy client setup
- platform: template
name: "NUT Connection String"
id: nut_connection_string
icon: "mdi:connection"
entity_category: diagnostic
web_server:
sorting_group_id: nut_server_group
sorting_weight: 3
lambda: |-
// Provide ready-to-use connection string for clients
return "ups_monitor@" + WiFi.localIP().toString().c_str() + ":${nut_port}";
sensor:
# NUT server connected clients counter (future feature placeholder)
- platform: template
name: "NUT Connected Clients"
id: nut_connected_clients
icon: "mdi:account-multiple"
unit_of_measurement: "clients"
accuracy_decimals: 0
entity_category: diagnostic
web_server:
sorting_group_id: nut_server_group
sorting_weight: 4
lambda: |-
// TODO: Implement client counter in nut_server component
// For now, return 0 if server inactive, -1 if active but no counter
if (!id(ups_monitor).is_connected()) {
return 0.0f;
}
return NAN; // Not yet implemented
# Define the NUT Server group for ESPHome Web Server v3
web_server:
sorting_groups:
- id: nut_server_group
name: "🌐 NUT Server"
sorting_weight: 85 # Place after Device Info (80) but before System (90)
# Automation for NUT server status monitoring
script:
- id: nut_server_status_check
then:
- lambda: |-
// Log current NUT server status and UPS data availability using data provider pattern
if (id(ups_monitor).is_connected()) {
ESP_LOGI("nut_server", "Status Check: UPS Connected=YES, Data Available=YES");
ESP_LOGI("nut_server", "Available Data: Battery=%.1f%%, Input=%.1fV, Load=%.1f%%, Status=%s",
id(ups_monitor).get_battery_level(),
id(ups_monitor).get_input_voltage(),
id(ups_monitor).get_load_percent(),
id(ups_monitor).is_online() ? "Online" : "On Battery");
} else {
ESP_LOGW("nut_server", "Status Check: UPS not connected - NUT server inactive");
}
# Status monitoring interval
interval:
- interval: 60s
then:
- script.execute: nut_server_status_check
# Client connection examples and documentation (commented)
#
# Connect with NUT client tools:
#
# 1. Using upsc command:
# upsc ups_monitor@<esp32_ip>:${nut_port}
# upsc -u ${nut_username} -p ${nut_password} ups_monitor@<esp32_ip>:${nut_port}
#
# 2. Using telnet for testing:
# telnet <esp32_ip> ${nut_port}
# Commands: HELP, VERSION, LOGIN ${nut_username} ${nut_password}, LIST UPS, LIST VAR ups_monitor
#
# 3. Home Assistant NUT integration:
# sensor:
# - platform: nut
# host: <esp32_ip>
# port: ${nut_port}
# username: ${nut_username}
# password: ${nut_password}
# resources:
# - battery.charge
# - battery.runtime
# - input.voltage
# - ups.load
# - ups.status
#
# 4. Python client example:
# import socket
# sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# sock.connect(('<esp32_ip>', ${nut_port}))
# sock.send(b"LOGIN ${nut_username} ${nut_password}\n")
# sock.send(b"LIST VAR ups_monitor\n")
# response = sock.recv(4096).decode()
# print(response)
# sock.close()
#
# Security Notes:
# - Use strong passwords in production
# - Consider firewall rules to limit access
# - Static IP recommended for consistent server access
# - Monitor logs for authentication failures
+66
View File
@@ -0,0 +1,66 @@
# NUT Server Test Configuration
# Tests the NUT server component with UPS HID integration
#
# This configuration exposes UPS data via NUT protocol on port 3493
# Connect with: upsc test_ups@<esp32_ip>
# Or telnet: telnet <esp32_ip> 3493
substitutions:
name: "ups-nut-server"
friendly_name: "UPS NUT Server"
simulation_mode: true
esphome:
name: "${name}"
friendly_name: "${friendly_name}"
# External components
external_components:
- source:
type: local
path: ../../components
# Logging
logger:
level: DEBUG
logs:
nut_server: DEBUG
ups_hid: INFO
# Use base UPS configuration (now has optional sensors)
packages:
base_ups: !include ../base_ups.yaml
# NUT Server Component Configuration
nut_server:
ups_hid_id: ups_monitor
port: 3493
username: "nutmon"
password: "nutsecret"
max_clients: 4
# Add basic sensors to ensure sensor platform is loaded
sensor:
- platform: ups_hid
ups_hid_id: ups_monitor
name: "Test Battery Level"
type: battery_level
binary_sensor:
- platform: ups_hid
ups_hid_id: ups_monitor
name: "Test UPS Online"
type: online
text_sensor:
- platform: ups_hid
ups_hid_id: ups_monitor
name: "Test UPS Status"
type: status
button:
- platform: ups_hid
ups_hid_id: ups_monitor
name: "Test Beeper Mute"
beeper_action: mute
+29
View File
@@ -8,6 +8,35 @@ This folder contains development tools for ESP32 ESPHome component development a
Lists ESP32, UPS, and related USB devices connected to the system. Useful for identifying device paths and vendor/product IDs during development. Lists ESP32, UPS, and related USB devices connected to the system. Useful for identifying device paths and vendor/product IDs during development.
## NUT Server Testing
### test_nut_server.py
Comprehensive test script for validating the NUT server component functionality. Tests NUT protocol commands, authentication, and concurrent connections.
**Usage:**
```bash
# Basic test with default settings
./test_nut_server.py 192.168.1.200
# Full test with custom parameters
./test_nut_server.py 192.168.1.200 --port 3493 --username nutmon --password nutsecret --ups test_ups
# Run specific test
./test_nut_server.py 192.168.1.200 --test auth
# Test concurrent connections
./test_nut_server.py 192.168.1.200 --test concurrent
```
**Test Categories:**
- `basic` - Test unauthenticated commands (HELP, VERSION, UPSDVER)
- `auth` - Test authenticated commands (LIST, GET VAR)
- `instant` - Test instant commands (beeper control)
- `error` - Test error handling with invalid commands
- `concurrent` - Test multiple simultaneous connections
- `all` - Run all tests (default)
## Protocol Development ## Protocol Development
The UPS HID component uses a modern self-registering protocol system. New protocols automatically register themselves using macros: The UPS HID component uses a modern self-registering protocol system. New protocols automatically register themselves using macros:
+261
View File
@@ -0,0 +1,261 @@
#!/usr/bin/env python3
"""
Test script for NUT Server Component
Tests basic NUT protocol commands against ESPHome NUT server
"""
import socket
import sys
import time
import argparse
class NutClient:
"""Simple NUT protocol client for testing."""
def __init__(self, host, port=3493):
self.host = host
self.port = port
self.sock = None
def connect(self):
"""Connect to NUT server."""
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.settimeout(5.0)
try:
self.sock.connect((self.host, self.port))
return True
except Exception as e:
print(f"Connection failed: {e}")
return False
def disconnect(self):
"""Disconnect from server."""
if self.sock:
self.sock.close()
self.sock = None
def send_command(self, command):
"""Send command and get response."""
if not self.sock:
return None
try:
# Send command
self.sock.send(f"{command}\n".encode())
# Receive response
response = ""
while True:
data = self.sock.recv(1024).decode()
if not data:
break
response += data
# Check for end markers
if "OK" in data or "ERR" in data:
break
if command.startswith("LIST") and "END LIST" in data:
break
if command == "HELP" and "\n" in data:
break
if command in ["VERSION", "UPSDVER"] and "\n" in data:
break
return response.strip()
except socket.timeout:
return response.strip() if response else "TIMEOUT"
except Exception as e:
return f"ERROR: {e}"
def login(self, username, password):
"""Authenticate with server."""
response = self.send_command(f"LOGIN {username} {password}")
return "OK" in response
def logout(self):
"""Logout from server."""
return self.send_command("LOGOUT")
def test_basic_commands(client):
"""Test basic NUT commands."""
print("\n=== Testing Basic Commands ===")
commands = [
"HELP",
"VERSION",
"UPSDVER",
]
for cmd in commands:
print(f"\n> {cmd}")
response = client.send_command(cmd)
print(f"< {response}")
time.sleep(0.1)
def test_authenticated_commands(client, username, password, ups_name):
"""Test commands requiring authentication."""
print("\n=== Testing Authenticated Commands ===")
# Login
print(f"\n> LOGIN {username} ***")
if client.login(username, password):
print("< OK - Login successful")
else:
print("< ERR - Login failed")
return
time.sleep(0.1)
# Test authenticated commands
commands = [
"LIST UPS",
f"LIST VAR {ups_name}",
f"GET VAR {ups_name} battery.charge",
f"GET VAR {ups_name} ups.status",
f"LIST CMD {ups_name}",
f"LIST RW {ups_name}",
]
for cmd in commands:
print(f"\n> {cmd}")
response = client.send_command(cmd)
print(f"< {response[:500]}") # Truncate long responses
time.sleep(0.1)
# Logout
print("\n> LOGOUT")
response = client.logout()
print(f"< {response}")
def test_instant_commands(client, username, password, ups_name):
"""Test instant commands."""
print("\n=== Testing Instant Commands ===")
# Login first
print(f"\n> LOGIN {username} ***")
if not client.login(username, password):
print("< ERR - Login failed, skipping instant commands")
return
print("< OK - Login successful")
# Test safe instant commands
commands = [
f"INSTCMD {ups_name} beeper.mute",
]
for cmd in commands:
print(f"\n> {cmd}")
response = client.send_command(cmd)
print(f"< {response}")
time.sleep(0.5)
client.logout()
def test_error_handling(client, ups_name):
"""Test error handling."""
print("\n=== Testing Error Handling ===")
# Test invalid commands
invalid_commands = [
"INVALID_COMMAND",
f"GET VAR invalid_ups battery.charge",
f"GET VAR {ups_name} invalid.variable",
"LOGIN", # Missing credentials
"LIST", # Missing subcommand
]
for cmd in invalid_commands:
print(f"\n> {cmd}")
response = client.send_command(cmd)
print(f"< {response}")
time.sleep(0.1)
def test_concurrent_connections(host, port, num_clients=3):
"""Test multiple concurrent connections."""
print(f"\n=== Testing {num_clients} Concurrent Connections ===")
clients = []
for i in range(num_clients):
client = NutClient(host, port)
if client.connect():
print(f"Client {i+1}: Connected")
response = client.send_command("VERSION")
print(f"Client {i+1}: {response}")
clients.append(client)
else:
print(f"Client {i+1}: Connection failed")
# Clean up
for client in clients:
client.disconnect()
print(f"All {len(clients)} clients disconnected")
def main():
parser = argparse.ArgumentParser(description="Test NUT Server Component")
parser.add_argument("host", help="ESP32 IP address")
parser.add_argument("--port", type=int, default=3493, help="NUT server port")
parser.add_argument("--username", default="nutmon", help="Username for auth")
parser.add_argument("--password", default="nutsecret", help="Password for auth")
parser.add_argument("--ups", default="test_ups", help="UPS name")
parser.add_argument("--test", choices=["basic", "auth", "instant", "error", "concurrent", "all"],
default="all", help="Test to run")
args = parser.parse_args()
print(f"Testing NUT Server at {args.host}:{args.port}")
print(f"UPS Name: {args.ups}")
print(f"Username: {args.username}")
print("=" * 50)
# Create client
client = NutClient(args.host, args.port)
# Connect
if not client.connect():
print("Failed to connect to server")
sys.exit(1)
print("Connected to NUT server")
try:
# Run tests
if args.test in ["basic", "all"]:
test_basic_commands(client)
if args.test in ["auth", "all"]:
test_authenticated_commands(client, args.username, args.password, args.ups)
if args.test in ["instant", "all"]:
test_instant_commands(client, args.username, args.password, args.ups)
if args.test in ["error", "all"]:
test_error_handling(client, args.ups)
# Disconnect for concurrent test
client.disconnect()
if args.test in ["concurrent", "all"]:
test_concurrent_connections(args.host, args.port)
except KeyboardInterrupt:
print("\nTest interrupted")
except Exception as e:
print(f"Test error: {e}")
finally:
client.disconnect()
print("\n" + "=" * 50)
print("Test completed")
if __name__ == "__main__":
main()