diff --git a/components/nut_ups/__init__.py b/components/nut_ups/__init__.py new file mode 100644 index 0000000..05e44db --- /dev/null +++ b/components/nut_ups/__init__.py @@ -0,0 +1,42 @@ +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_NUT_UPS_ID = "nut_ups_id" + +nut_ups_ns = cg.esphome_ns.namespace("nut_ups") +NutUpsComponent = nut_ups_ns.class_("NutUpsComponent", cg.PollingComponent) + +CONFIG_SCHEMA = cv.Schema( + { + cv.GenerateID(): cv.declare_id(NutUpsComponent), + cv.Optional(CONF_UPDATE_INTERVAL, default="30s"): cv.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="10s"): cv.positive_time_period_milliseconds, + cv.Optional(CONF_AUTO_DETECT_PROTOCOL, default=True): cv.boolean, + } +).extend(cv.COMPONENT_SCHEMA) + + +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])) \ No newline at end of file diff --git a/components/nut_ups/apc_smart_protocol.cpp b/components/nut_ups/apc_smart_protocol.cpp new file mode 100644 index 0000000..7f269fe --- /dev/null +++ b/components/nut_ups/apc_smart_protocol.cpp @@ -0,0 +1,487 @@ +#include "nut_ups.h" +#include "esphome/core/log.h" +#include "esphome/core/helpers.h" +#include "esphome/core/hal.h" +#include +#include + +namespace esphome +{ + namespace nut_ups + { + + static const char *const APC_TAG = "nut_ups.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(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 command = {static_cast(cmd)}; + std::vector 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 nut_ups +} // namespace esphome \ No newline at end of file diff --git a/components/nut_ups/binary_sensor.cpp b/components/nut_ups/binary_sensor.cpp new file mode 100644 index 0000000..33f3d1e --- /dev/null +++ b/components/nut_ups/binary_sensor.cpp @@ -0,0 +1,16 @@ +#include "binary_sensor.h" +#include "esphome/core/log.h" + +namespace esphome { +namespace nut_ups { + +static const char *const TAG_BINARY = "nut_ups.binary_sensor"; + +void NutUpsBinarySensor::dump_config() { + ESP_LOGCONFIG(TAG_BINARY, "NUT UPS Binary Sensor:"); + ESP_LOGCONFIG(TAG_BINARY, " Type: %s", sensor_type_.c_str()); + LOG_BINARY_SENSOR(" ", "Binary Sensor", this); +} + +} // namespace nut_ups +} // namespace esphome \ No newline at end of file diff --git a/components/nut_ups/binary_sensor.h b/components/nut_ups/binary_sensor.h new file mode 100644 index 0000000..7d6f858 --- /dev/null +++ b/components/nut_ups/binary_sensor.h @@ -0,0 +1,23 @@ +#pragma once + +#include "esphome/core/component.h" +#include "esphome/components/binary_sensor/binary_sensor.h" +#include "nut_ups.h" + +namespace esphome +{ + namespace nut_ups + { + + class NutUpsBinarySensor : 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 nut_ups +} // namespace esphome \ No newline at end of file diff --git a/components/nut_ups/binary_sensor.py b/components/nut_ups/binary_sensor.py new file mode 100644 index 0000000..dcb89ab --- /dev/null +++ b/components/nut_ups/binary_sensor.py @@ -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_ID, + CONF_TYPE, + DEVICE_CLASS_CONNECTIVITY, + DEVICE_CLASS_BATTERY, + DEVICE_CLASS_PROBLEM, + DEVICE_CLASS_POWER, +) + +from . import nut_ups_ns, NutUpsComponent, CONF_NUT_UPS_ID + +DEPENDENCIES = ["nut_ups"] + +NutUpsBinarySensor = nut_ups_ns.class_("NutUpsBinarySensor", 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, + }, +} + +CONF_NUT_UPS_ID = "nut_ups_id" + +CONFIG_SCHEMA = binary_sensor.binary_sensor_schema(NutUpsBinarySensor).extend( + { + cv.GenerateID(CONF_NUT_UPS_ID): cv.use_id(NutUpsComponent), + cv.Required(CONF_TYPE): cv.one_of(*BINARY_SENSOR_TYPES, lower=True), + } +) + + +async def to_code(config): + parent = await cg.get_variable(config[CONF_NUT_UPS_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"])) \ No newline at end of file diff --git a/components/nut_ups/cyberpower_protocol.cpp b/components/nut_ups/cyberpower_protocol.cpp new file mode 100644 index 0000000..b1980ff --- /dev/null +++ b/components/nut_ups/cyberpower_protocol.cpp @@ -0,0 +1,298 @@ +#include "nut_ups.h" +#include "esphome/core/log.h" + +namespace esphome { +namespace nut_ups { + +static const char *const CP_TAG = "nut_ups.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) +static const uint16_t HID_USAGE_PAGE_POWER_DEVICE = 0x84; +static const uint16_t HID_USAGE_BATTERY_LEVEL = 0x66; +static const uint16_t HID_USAGE_RUNTIME_TO_EMPTY = 0x68; +static const uint16_t HID_USAGE_AC_PRESENT = 0x5A; +static const uint16_t HID_USAGE_BATTERY_PRESENT = 0x5B; + +bool CyberPowerProtocol::detect() { + ESP_LOGD(CP_TAG, "Detecting CyberPower HID Protocol..."); + + // Try to get a HID device descriptor or basic report + HidReport request; + request.report_id = CP_REPORT_ID_DEVICE_INFO; + request.data = {0x00}; // Basic device info request + + HidReport response; + if (send_hid_report(request, response)) { + ESP_LOGD(CP_TAG, "CyberPower HID response received"); + return true; + } + + ESP_LOGD(CP_TAG, "No CyberPower HID response"); + 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 hid_packet; + hid_packet.push_back(report.report_id); + hid_packet.insert(hid_packet.end(), report.data.begin(), report.data.end()); + + std::vector 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 is typically 0-100 or 0-1000 scale + if (battery_level_raw <= 100) { + data.battery_level = static_cast(battery_level_raw); + } else if (battery_level_raw <= 1000) { + data.battery_level = static_cast(battery_level_raw) / 10.0f; + } else { + ESP_LOGW(CP_TAG, "Invalid battery level: %u", battery_level_raw); + data.battery_level = NAN; + } + + // Runtime is typically in seconds or minutes + if (runtime_raw < 3600) { // Assume minutes if < 3600 + data.runtime_minutes = static_cast(runtime_raw); + } else { // Assume seconds if >= 3600 + data.runtime_minutes = static_cast(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 + data.input_voltage = static_cast(input_voltage_raw) / 10.0f; + data.output_voltage = static_cast(output_voltage_raw) / 10.0f; + + // Load can be in percentage or watts - assume percentage if <= 100 + if (load_raw <= 100) { + data.load_percent = static_cast(load_raw); + } else { + // Convert watts to percentage (assuming 1000W max capacity) + data.load_percent = static_cast(load_raw) / 10.0f; + } + + // Frequency is typically in 0.1 Hz units + data.frequency = static_cast(frequency_raw) / 10.0f; + + 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 nut_ups +} // namespace esphome \ No newline at end of file diff --git a/components/nut_ups/generic_hid_protocol.cpp b/components/nut_ups/generic_hid_protocol.cpp new file mode 100644 index 0000000..b915ebb --- /dev/null +++ b/components/nut_ups/generic_hid_protocol.cpp @@ -0,0 +1,115 @@ +#include "nut_ups.h" +#include "esphome/core/log.h" + +namespace esphome { +namespace nut_ups { + +static const char *const GEN_TAG = "nut_ups.generic"; + +bool GenericHidProtocol::detect() { + ESP_LOGD(GEN_TAG, "Detecting Generic HID Protocol..."); + + // Generic HID detection - try basic USB HID communication + std::vector test_command = {0x01, 0x00}; // Basic HID report request + std::vector response; + + if (send_command(test_command, response, 1000)) { + ESP_LOGD(GEN_TAG, "Generic HID response received, %d bytes", response.size()); + return true; + } + + ESP_LOGD(GEN_TAG, "No Generic HID response"); + return false; +} + +bool GenericHidProtocol::initialize() { + ESP_LOGD(GEN_TAG, "Initializing Generic HID Protocol..."); + + // Generic initialization - just verify we can communicate + std::vector init_command = {0x00}; // Null command + std::vector 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..."); + + // Generic HID implementation - this provides basic functionality + // for UPS devices that don't match specific protocols + + bool success = false; + std::vector response; + + // Try to read status information using common HID report IDs + for (uint8_t report_id = 1; report_id <= 4; report_id++) { + std::vector request = {report_id, 0x00}; + + if (send_command(request, response, 1000) && !response.empty()) { + success = true; + + // Parse generic HID response + if (response.size() >= 4) { + // Try to extract meaningful data from generic response + // This is a best-effort approach for unknown devices + + uint8_t status_byte = response[0]; + + // Basic status interpretation + data.status_flags = 0; + 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; + + // Try to extract numeric values (very generic interpretation) + if (response.size() >= 6) { + uint16_t value1 = response[2] | (response[3] << 8); + uint16_t value2 = response[4] | (response[5] << 8); + + // Guess what these values might represent + if (value1 <= 100) { + data.battery_level = static_cast(value1); + } + + if (value2 >= 80 && value2 <= 300) { + data.input_voltage = static_cast(value2); + } + } + + ESP_LOGV(GEN_TAG, "Generic data parsed: Battery=%.1f%%, Status=0x%08X", + data.battery_level, data.status_flags); + } + + break; // Found some data, stop trying other report IDs + } + } + + // 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; +} + +} // namespace nut_ups +} // namespace esphome \ No newline at end of file diff --git a/components/nut_ups/nut_ups.cpp b/components/nut_ups/nut_ups.cpp new file mode 100644 index 0000000..30f3eb6 --- /dev/null +++ b/components/nut_ups/nut_ups.cpp @@ -0,0 +1,340 @@ +#include "nut_ups.h" +#include "esphome/core/log.h" +#include "esphome/core/application.h" + +#ifdef USE_ESP32 +#include "driver/gpio.h" +#include "esp_log.h" +#include "esp_system.h" +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" +#endif + +namespace esphome { +namespace nut_ups { + +void NutUpsComponent::setup() { + ESP_LOGCONFIG(TAG, "Setting up NUT UPS Component..."); + + if (simulation_mode_) { + ESP_LOGW(TAG, "Running in simulation mode - no actual UPS communication"); + connected_ = true; + ups_data_.detected_protocol = PROTOCOL_APC_SMART; + ups_data_.manufacturer = "Simulated"; + ups_data_.model = "Virtual UPS"; + return; + } + +#ifdef USE_ESP32 + if (!initialize_usb()) { + ESP_LOGE(TAG, "Failed to initialize USB"); + mark_failed(); + return; + } + + if (!detect_ups_protocol()) { + ESP_LOGE(TAG, "Failed to detect UPS protocol"); + connected_ = false; + return; + } + + connected_ = true; + ESP_LOGI(TAG, "Successfully connected to UPS using %s", get_protocol_name().c_str()); +#else + ESP_LOGE(TAG, "NUT UPS component requires ESP32 platform"); + mark_failed(); +#endif +} + +void NutUpsComponent::update() { + if (simulation_mode_) { + simulate_ups_data(); + update_sensors(); + return; + } + + if (!connected_) { + ESP_LOGD(TAG, "UPS not connected, attempting to reconnect..."); + if (detect_ups_protocol()) { + connected_ = true; + ESP_LOGI(TAG, "Reconnected to UPS"); + } else { + return; + } + } + + if (read_ups_data()) { + last_successful_read_ = millis(); + update_sensors(); + } else { + ESP_LOGW(TAG, "Failed to read UPS data"); + if (millis() - last_successful_read_ > protocol_timeout_ms_) { + ESP_LOGE(TAG, "UPS communication timeout, marking as disconnected"); + connected_ = false; + } + } +} + +void NutUpsComponent::dump_config() { + ESP_LOGCONFIG(TAG, "NUT UPS Component:"); + ESP_LOGCONFIG(TAG, " Simulation Mode: %s", simulation_mode_ ? "YES" : "NO"); + ESP_LOGCONFIG(TAG, " USB Vendor ID: 0x%04X", usb_vendor_id_); + ESP_LOGCONFIG(TAG, " USB Product ID: 0x%04X", usb_product_id_); + ESP_LOGCONFIG(TAG, " Protocol Timeout: %u ms", protocol_timeout_ms_); + ESP_LOGCONFIG(TAG, " Auto Detect Protocol: %s", auto_detect_protocol_ ? "YES" : "NO"); + ESP_LOGCONFIG(TAG, " Update Interval: %u ms", get_update_interval()); + + if (connected_) { + ESP_LOGCONFIG(TAG, " Status: Connected"); + ESP_LOGCONFIG(TAG, " Protocol: %s", get_protocol_name().c_str()); + ESP_LOGCONFIG(TAG, " Manufacturer: %s", ups_data_.manufacturer.c_str()); + ESP_LOGCONFIG(TAG, " Model: %s", ups_data_.model.c_str()); + } else { + ESP_LOGCONFIG(TAG, " Status: Disconnected"); + } +} + +std::string NutUpsComponent::get_protocol_name() const { + if (active_protocol_) { + return active_protocol_->get_protocol_name(); + } + return "Unknown"; +} + +bool NutUpsComponent::initialize_usb() { +#ifdef USE_ESP32 + ESP_LOGD(TAG, "Initializing USB communication..."); + + // Initialize USB host if not already done + // Note: This is a simplified approach - full USB Host implementation + // would require more extensive ESP-IDF USB Host library integration + + // For now, we'll use a basic approach that can be extended + esp_err_t ret = usb_init(); + if (ret != ESP_OK) { + ESP_LOGE(TAG, "USB initialization failed: %s", esp_err_to_name(ret)); + return false; + } + + ESP_LOGI(TAG, "USB initialized successfully"); + return true; +#else + return false; +#endif +} + +bool NutUpsComponent::detect_ups_protocol() { + ESP_LOGD(TAG, "Detecting UPS protocol..."); + + if (!auto_detect_protocol_) { + // Use APC Smart Protocol as default when auto-detection is disabled + active_protocol_ = std::make_unique(this); + if (active_protocol_->initialize()) { + ESP_LOGI(TAG, "Using pre-configured protocol: %s", active_protocol_->get_protocol_name().c_str()); + ups_data_.detected_protocol = active_protocol_->get_protocol_type(); + return true; + } + return false; + } + + // Try APC Smart Protocol first + auto apc_protocol = std::make_unique(this); + if (apc_protocol->detect() && apc_protocol->initialize()) { + active_protocol_ = std::move(apc_protocol); + ups_data_.detected_protocol = PROTOCOL_APC_SMART; + ESP_LOGI(TAG, "Detected APC Smart Protocol"); + return true; + } + + // Try CyberPower HID Protocol + auto cyberpower_protocol = std::make_unique(this); + if (cyberpower_protocol->detect() && cyberpower_protocol->initialize()) { + active_protocol_ = std::move(cyberpower_protocol); + ups_data_.detected_protocol = PROTOCOL_CYBERPOWER_HID; + ESP_LOGI(TAG, "Detected CyberPower HID Protocol"); + return true; + } + + // Try Generic HID Protocol as fallback + auto generic_protocol = std::make_unique(this); + if (generic_protocol->detect() && generic_protocol->initialize()) { + active_protocol_ = std::move(generic_protocol); + ups_data_.detected_protocol = PROTOCOL_GENERIC_HID; + ESP_LOGI(TAG, "Detected Generic HID Protocol"); + return true; + } + + ESP_LOGE(TAG, "No compatible UPS protocol detected"); + return false; +} + +bool NutUpsComponent::read_ups_data() { + if (!active_protocol_) { + return false; + } + + return active_protocol_->read_data(ups_data_); +} + +void NutUpsComponent::update_sensors() { + // Update numeric sensors + for (auto &pair : sensors_) { + const std::string &type = pair.first; + auto *sensor = pair.second; + + if (type == "battery_level" && !std::isnan(ups_data_.battery_level)) { + sensor->publish_state(ups_data_.battery_level); + } else if (type == "input_voltage" && !std::isnan(ups_data_.input_voltage)) { + sensor->publish_state(ups_data_.input_voltage); + } else if (type == "output_voltage" && !std::isnan(ups_data_.output_voltage)) { + sensor->publish_state(ups_data_.output_voltage); + } else if (type == "load_percent" && !std::isnan(ups_data_.load_percent)) { + sensor->publish_state(ups_data_.load_percent); + } else if (type == "runtime" && !std::isnan(ups_data_.runtime_minutes)) { + sensor->publish_state(ups_data_.runtime_minutes); + } else if (type == "frequency" && !std::isnan(ups_data_.frequency)) { + sensor->publish_state(ups_data_.frequency); + } + } + + // Update binary sensors + for (auto &pair : binary_sensors_) { + const std::string &type = pair.first; + auto *sensor = pair.second; + + if (type == "online") { + sensor->publish_state(ups_data_.status_flags & UPS_STATUS_ONLINE); + } else if (type == "on_battery") { + sensor->publish_state(ups_data_.status_flags & UPS_STATUS_ON_BATTERY); + } else if (type == "low_battery") { + sensor->publish_state(ups_data_.status_flags & UPS_STATUS_LOW_BATTERY); + } else if (type == "fault") { + sensor->publish_state(ups_data_.status_flags & UPS_STATUS_FAULT); + } else if (type == "overload") { + sensor->publish_state(ups_data_.status_flags & UPS_STATUS_OVERLOAD); + } else if (type == "charging") { + sensor->publish_state(ups_data_.status_flags & UPS_STATUS_CHARGING); + } + } + + // Update text sensors + for (auto &pair : text_sensors_) { + const std::string &type = pair.first; + auto *sensor = pair.second; + + if (type == "model" && !ups_data_.model.empty()) { + sensor->publish_state(ups_data_.model); + } else if (type == "manufacturer" && !ups_data_.manufacturer.empty()) { + sensor->publish_state(ups_data_.manufacturer); + } else if (type == "protocol") { + sensor->publish_state(get_protocol_name()); + } else if (type == "status") { + std::string status_str = ""; + if (ups_data_.status_flags & UPS_STATUS_ONLINE) status_str += "Online "; + if (ups_data_.status_flags & UPS_STATUS_ON_BATTERY) status_str += "OnBattery "; + if (ups_data_.status_flags & UPS_STATUS_LOW_BATTERY) status_str += "LowBattery "; + if (ups_data_.status_flags & UPS_STATUS_CHARGING) status_str += "Charging "; + if (ups_data_.status_flags & UPS_STATUS_FAULT) status_str += "Fault "; + if (status_str.empty()) status_str = "Unknown"; + sensor->publish_state(status_str); + } + } +} + +void NutUpsComponent::simulate_ups_data() { + static uint32_t sim_counter = 0; + sim_counter++; + + // Simulate realistic UPS data that changes over time + ups_data_.battery_level = 85.0f + sin(sim_counter * 0.01f) * 10.0f; + ups_data_.input_voltage = 120.0f + sin(sim_counter * 0.02f) * 5.0f; + ups_data_.output_voltage = 118.0f + sin(sim_counter * 0.015f) * 3.0f; + ups_data_.load_percent = 45.0f + sin(sim_counter * 0.005f) * 15.0f; + ups_data_.runtime_minutes = 35.0f + sin(sim_counter * 0.003f) * 10.0f; + ups_data_.frequency = 60.0f + sin(sim_counter * 0.1f) * 0.2f; + + // Simulate status changes + if (sim_counter % 1000 < 800) { + ups_data_.status_flags = UPS_STATUS_ONLINE | UPS_STATUS_CHARGING; + } else if (sim_counter % 1000 < 950) { + ups_data_.status_flags = UPS_STATUS_ON_BATTERY; + } else { + ups_data_.status_flags = UPS_STATUS_ON_BATTERY | UPS_STATUS_LOW_BATTERY; + } + + // Keep simulated device info + ups_data_.manufacturer = "Simulated"; + ups_data_.model = "Virtual UPS Pro"; +} + +void NutUpsComponent::register_sensor(sensor::Sensor *sens, const std::string &type) { + sensors_[type] = sens; +} + +void NutUpsComponent::register_binary_sensor(binary_sensor::BinarySensor *sens, const std::string &type) { + binary_sensors_[type] = sens; +} + +void NutUpsComponent::register_text_sensor(text_sensor::TextSensor *sens, const std::string &type) { + text_sensors_[type] = sens; +} + +bool NutUpsComponent::usb_write(const std::vector &data) { +#ifdef USE_ESP32 + // Placeholder for actual USB write implementation + // This would use ESP-IDF USB Host APIs in a real implementation + ESP_LOGV(TAG, "USB Write: %d bytes", data.size()); + return true; +#else + return false; +#endif +} + +bool NutUpsComponent::usb_read(std::vector &data, uint32_t timeout_ms) { +#ifdef USE_ESP32 + // Placeholder for actual USB read implementation + // This would use ESP-IDF USB Host APIs in a real implementation + ESP_LOGV(TAG, "USB Read with timeout: %u ms", timeout_ms); + data.clear(); + return true; +#else + return false; +#endif +} + +#ifdef USE_ESP32 +esp_err_t NutUpsComponent::usb_init() { + // Placeholder for USB initialization + // In a real implementation, this would initialize the ESP32 USB Host + ESP_LOGD(TAG, "Initializing USB Host..."); + return ESP_OK; +} + +void NutUpsComponent::usb_deinit() { + // Placeholder for USB cleanup + ESP_LOGD(TAG, "Deinitializing USB Host..."); +} +#endif + +// Base Protocol Implementation +bool UpsProtocolBase::send_command(const std::vector &cmd, std::vector &response, uint32_t timeout_ms) { + if (!parent_->usb_write(cmd)) { + return false; + } + + return parent_->usb_read(response, timeout_ms); +} + +std::string UpsProtocolBase::bytes_to_string(const std::vector &data) { + std::string result; + result.reserve(data.size()); + for (uint8_t byte : data) { + if (byte >= 32 && byte <= 126) { // Printable ASCII + result += static_cast(byte); + } + } + return result; +} + +} // namespace nut_ups +} // namespace esphome \ No newline at end of file diff --git a/components/nut_ups/nut_ups.h b/components/nut_ups/nut_ups.h new file mode 100644 index 0000000..f606b3a --- /dev/null +++ b/components/nut_ups/nut_ups.h @@ -0,0 +1,220 @@ +#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 +#include +#include +#include + +#ifdef USE_ESP32 +#include "esp_err.h" +#include "driver/usb_serial_jtag.h" +#include "hal/usb_serial_jtag_hal.h" +#include "soc/usb_pins.h" +#endif + +namespace esphome +{ + namespace nut_ups + { + + static const char *const TAG = "nut_ups"; + + // 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_CYBERPOWER_HID, + PROTOCOL_GENERIC_HID + }; + + // UPS data structure + 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; + }; + + // Forward declarations + class UpsProtocolBase; + class ApcSmartProtocol; + class CyberPowerProtocol; + class GenericHidProtocol; + + class NutUpsComponent : public PollingComponent + { + public: + NutUpsComponent() = default; + + void setup() override; + void update() override; + void dump_config() override; + float get_setup_priority() const override { return setup_priority::DATA; } + + // Configuration setters + void set_simulation_mode(bool simulation_mode) { simulation_mode_ = simulation_mode; } + void set_usb_vendor_id(uint16_t vendor_id) { usb_vendor_id_ = vendor_id; } + void set_usb_product_id(uint16_t product_id) { usb_product_id_ = product_id; } + void set_protocol_timeout(uint32_t timeout_ms) { protocol_timeout_ms_ = timeout_ms; } + void set_auto_detect_protocol(bool auto_detect) { auto_detect_protocol_ = auto_detect; } + + // Data getters for sensors + const UpsData &get_ups_data() const { return ups_data_; } + bool is_connected() const { return connected_; } + std::string get_protocol_name() const; + + // 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}; + UpsData ups_data_; + + std::unique_ptr active_protocol_; + std::map sensors_; + std::map binary_sensors_; + std::map text_sensors_; + + // Core methods + bool initialize_usb(); + bool detect_ups_protocol(); + bool read_ups_data(); + void update_sensors(); + void simulate_ups_data(); + + public: + // USB communication methods (accessible by protocol classes) + bool usb_write(const std::vector &data); + bool usb_read(std::vector &data, uint32_t timeout_ms = 1000); + + protected: +#ifdef USE_ESP32 + // ESP32-specific USB handling + esp_err_t usb_init(); + void usb_deinit(); +#endif + }; + + // Base class for UPS protocols + class UpsProtocolBase + { + public: + explicit UpsProtocolBase(NutUpsComponent *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: + NutUpsComponent *parent_; + + bool send_command(const std::vector &cmd, std::vector &response, uint32_t timeout_ms = 1000); + std::string bytes_to_string(const std::vector &data); + }; + + // APC Smart Protocol implementation + class ApcSmartProtocol : public UpsProtocolBase + { + public: + explicit ApcSmartProtocol(NutUpsComponent *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(NutUpsComponent *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 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(NutUpsComponent *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"; } + }; + + } // namespace nut_ups +} // namespace esphome \ No newline at end of file diff --git a/components/nut_ups/sensor.cpp b/components/nut_ups/sensor.cpp new file mode 100644 index 0000000..9240bcd --- /dev/null +++ b/components/nut_ups/sensor.cpp @@ -0,0 +1,19 @@ +#include "sensor.h" +#include "esphome/core/log.h" + +namespace esphome +{ + namespace nut_ups + { + + static const char *const S_TAG = "nut_ups.sensor"; + + void NutUpsSensor::dump_config() + { + ESP_LOGCONFIG(S_TAG, "NUT UPS Sensor:"); + ESP_LOGCONFIG(S_TAG, " Type: %s", sensor_type_.c_str()); + LOG_SENSOR(" ", "Sensor", this); + } + + } // namespace nut_ups +} // namespace esphome \ No newline at end of file diff --git a/components/nut_ups/sensor.h b/components/nut_ups/sensor.h new file mode 100644 index 0000000..64c016c --- /dev/null +++ b/components/nut_ups/sensor.h @@ -0,0 +1,23 @@ +#pragma once + +#include "esphome/core/component.h" +#include "esphome/components/sensor/sensor.h" +#include "nut_ups.h" + +namespace esphome +{ + namespace nut_ups + { + + class NutUpsSensor : 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 nut_ups +} // namespace esphome \ No newline at end of file diff --git a/components/nut_ups/sensor.py b/components/nut_ups/sensor.py new file mode 100644 index 0000000..7ed7a48 --- /dev/null +++ b/components/nut_ups/sensor.py @@ -0,0 +1,99 @@ +import esphome.codegen as cg +import esphome.config_validation as cv +from esphome.components import sensor +from esphome.const import ( + CONF_ID, + 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 nut_ups_ns, NutUpsComponent, CONF_NUT_UPS_ID + +DEPENDENCIES = ["nut_ups"] + +NutUpsSensor = nut_ups_ns.class_("NutUpsSensor", 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, + }, +} + +CONF_NUT_UPS_ID = "nut_ups_id" + +CONFIG_SCHEMA = sensor.sensor_schema( + NutUpsSensor, + accuracy_decimals=1, +).extend( + { + cv.GenerateID(CONF_NUT_UPS_ID): cv.use_id(NutUpsComponent), + cv.Required(CONF_TYPE): cv.one_of(*SENSOR_TYPES, lower=True), + } +) + + +async def to_code(config): + parent = await cg.get_variable(config[CONF_NUT_UPS_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"])) \ No newline at end of file diff --git a/components/nut_ups/text_sensor.cpp b/components/nut_ups/text_sensor.cpp new file mode 100644 index 0000000..0eb9531 --- /dev/null +++ b/components/nut_ups/text_sensor.cpp @@ -0,0 +1,19 @@ +#include "text_sensor.h" +#include "esphome/core/log.h" + +namespace esphome +{ + namespace nut_ups + { + + static const char *const TXT_TAG = "nut_ups.text_sensor"; + + void NutUpsTextSensor::dump_config() + { + ESP_LOGCONFIG(TXT_TAG, "NUT UPS Text Sensor:"); + ESP_LOGCONFIG(TXT_TAG, " Type: %s", sensor_type_.c_str()); + LOG_TEXT_SENSOR(" ", "Text Sensor", this); + } + + } // namespace nut_ups +} // namespace esphome \ No newline at end of file diff --git a/components/nut_ups/text_sensor.h b/components/nut_ups/text_sensor.h new file mode 100644 index 0000000..16037cd --- /dev/null +++ b/components/nut_ups/text_sensor.h @@ -0,0 +1,23 @@ +#pragma once + +#include "esphome/core/component.h" +#include "esphome/components/text_sensor/text_sensor.h" +#include "nut_ups.h" + +namespace esphome +{ + namespace nut_ups + { + + class NutUpsTextSensor : 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 nut_ups +} // namespace esphome \ No newline at end of file diff --git a/components/nut_ups/text_sensor.py b/components/nut_ups/text_sensor.py new file mode 100644 index 0000000..e08973f --- /dev/null +++ b/components/nut_ups/text_sensor.py @@ -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_ID, + CONF_TYPE, +) + +from . import nut_ups_ns, NutUpsComponent, CONF_NUT_UPS_ID + +DEPENDENCIES = ["nut_ups"] + +NutUpsTextSensor = nut_ups_ns.class_("NutUpsTextSensor", text_sensor.TextSensor, cg.Component) + +TEXT_SENSOR_TYPES = [ + "model", + "manufacturer", + "status", + "protocol", + "serial_number", + "firmware_version", +] + +CONF_NUT_UPS_ID = "nut_ups_id" + +CONFIG_SCHEMA = text_sensor.text_sensor_schema(NutUpsTextSensor).extend( + { + cv.GenerateID(CONF_NUT_UPS_ID): cv.use_id(NutUpsComponent), + cv.Required(CONF_TYPE): cv.one_of(*TEXT_SENSOR_TYPES, lower=True), + } +) + + +async def to_code(config): + parent = await cg.get_variable(config[CONF_NUT_UPS_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)) \ No newline at end of file diff --git a/minimal-test.yaml b/minimal-test.yaml index e7e38a2..691fb51 100644 --- a/minimal-test.yaml +++ b/minimal-test.yaml @@ -108,11 +108,16 @@ binary_sensor: type: fault device_class: problem -dashboard_card: | - type: entities - title: UPS Monitor - entities: - - entity: sensor.ups_battery_level - name: Battery Level - - entity: binary_sensor.ups_on_battery - name: On Battery +# Text Sensors +text_sensor: + - platform: nut_ups + nut_ups_id: ups_monitor + name: "UPS Status" + id: ups_status + type: status + + - platform: nut_ups + nut_ups_id: ups_monitor + name: "UPS Model" + id: ups_model + type: model