From 1b585ff74631de6fe07bfb50a992d7ecd18d4669 Mon Sep 17 00:00:00 2001 From: bullshit Date: Tue, 2 Sep 2025 23:01:49 +0200 Subject: [PATCH] chore: organize new protocol development process Signed-off-by: bullshit --- .../ISSUE_TEMPLATE/new-protocol-request.yml | 224 +++++++++++++++++ CONTRIBUTING.md | 136 ++++++++++ tools/README.md | 31 +++ tools/collect-protocol-debug.sh | 238 ++++++++++++++++++ 4 files changed, 629 insertions(+) create mode 100644 .github/ISSUE_TEMPLATE/new-protocol-request.yml create mode 100644 CONTRIBUTING.md create mode 100755 tools/collect-protocol-debug.sh diff --git a/.github/ISSUE_TEMPLATE/new-protocol-request.yml b/.github/ISSUE_TEMPLATE/new-protocol-request.yml new file mode 100644 index 0000000..1d28806 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/new-protocol-request.yml @@ -0,0 +1,224 @@ +name: New UPS Protocol Request +description: Request support for a new UPS device protocol +title: "[Protocol Request] " +labels: ["enhancement", "new-protocol"] +body: + - type: markdown + attributes: + value: | + ## Thank you for requesting a new UPS protocol! + This form collects all necessary debug information to implement support for your UPS device. + Please ensure you have NUT (Network UPS Tools) installed and your device is connected via USB. + + - type: input + id: manufacturer + attributes: + label: Manufacturer + description: UPS manufacturer name + placeholder: "e.g., APC, CyberPower, Eaton" + validations: + required: true + + - type: input + id: model + attributes: + label: Model + description: Complete model number + placeholder: "e.g., Back-UPS ES 700, CP1500EPFCLCD" + validations: + required: true + + - type: input + id: usb_ids + attributes: + label: USB IDs + description: "Vendor ID and Product ID (run: lsusb | grep -i ups)" + placeholder: "Vendor: 0x051d, Product: 0x0002" + validations: + required: true + + - type: textarea + id: lsusb_verbose + attributes: + label: USB Device Details + description: "Output of: lsusb -v -d :" + placeholder: "Paste the complete lsusb -v output here" + render: shell + validations: + required: true + + - type: textarea + id: nut_initial + attributes: + label: NUT Initial Discovery + description: | + Run: sudo /lib/nut/usbhid-ups -DD -a 2>&1 | head -500 + This shows HID descriptor parsing and initial device setup + placeholder: "Paste NUT debug output during initial connection" + render: shell + validations: + required: true + + - type: textarea + id: nut_online + attributes: + label: NUT Debug - Online State (AC Power) + description: | + Run: sudo /lib/nut/usbhid-ups -DD -a 2>&1 | grep -A2 -B2 "Report" + Capture for ~30 seconds while UPS is connected to AC power + placeholder: "Paste NUT debug output showing HID reports during normal operation" + render: shell + validations: + required: true + + - type: textarea + id: nut_battery + attributes: + label: NUT Debug - On Battery State + description: | + Run: sudo /lib/nut/usbhid-ups -DD -a 2>&1 | grep -A2 -B2 "Report" + Capture for ~30 seconds after unplugging AC power + placeholder: "Paste NUT debug output showing HID reports while on battery" + render: shell + validations: + required: true + + - type: textarea + id: nut_charging + attributes: + label: NUT Debug - Charging State + description: | + Run: sudo /lib/nut/usbhid-ups -DD -a 2>&1 | grep -A2 -B2 "Report" + Capture for ~30 seconds after reconnecting AC power (battery charging) + placeholder: "Paste NUT debug output showing HID reports during charging" + render: shell + validations: + required: true + + - type: textarea + id: hid_paths + attributes: + label: HID Path Mappings + description: | + Run: sudo /lib/nut/usbhid-ups -DD -a 2>&1 | grep "Path:" + Shows all HID paths discovered by NUT + placeholder: "Paste all HID path mappings" + render: shell + validations: + required: true + + - type: textarea + id: upsc_full + attributes: + label: UPS Variables (upsc output) + description: | + Run: upsc + Complete list of all UPS variables + placeholder: "Paste complete upsc output" + render: shell + validations: + required: true + + - type: textarea + id: state_transitions + attributes: + label: Variable Changes During State Transitions + description: | + Document how key variables change between states: + 1. Run: upsc | grep -E "battery|status|input" (on AC power) + 2. Unplug UPS, wait 10 seconds, run command again + 3. Plug UPS back in, wait 10 seconds, run command again + placeholder: | + === On AC Power === + battery.charge: 100 + battery.runtime: 3825 + ups.status: OL + + === On Battery === + battery.charge: 99 + battery.runtime: 3700 + ups.status: OB DISCHRG + + === Charging === + battery.charge: 99 + battery.runtime: 3750 + ups.status: OL CHRG + render: shell + validations: + required: true + + - type: textarea + id: report_analysis + attributes: + label: HID Report Analysis + description: | + Based on debug output, identify report IDs and their purpose. + Include example hex data for each report type. + placeholder: | + Report 0x0C (7 bytes): Power Summary + Example: [0C 64 00 58 02 00 00] + - Byte 1: Battery percentage (0x64 = 100%) + - Bytes 2-3: Runtime in seconds (little-endian) + + Report 0x16 (5 bytes): Present Status + Example: [16 01 00 00 00] + - Byte 1, Bit 0: AC present (1=yes) + - Byte 1, Bit 1: Discharging (1=yes) + render: text + validations: + required: true + + - type: textarea + id: upscmd_output + attributes: + label: Supported Commands + description: | + Run: upscmd -l + List of commands the UPS supports + placeholder: "Paste upscmd -l output, or write 'No commands supported'" + render: shell + + - type: checkboxes + id: features + attributes: + label: Device Features + description: Check all features your UPS supports + options: + - label: Battery test commands (test.battery.start) + - label: Beeper control (beeper.enable/disable) + - label: Reports nominal values (voltage.nominal, power.nominal) + - label: Configuration changes (shutdown.delay, etc.) + - label: LCD/LED panel test capability + - label: Multiple battery information + - label: Temperature monitoring + - label: Frequency monitoring + + - type: textarea + id: additional_debug + attributes: + label: Additional Debug Information + description: | + Optional but helpful: + Run: sudo /lib/nut/usbhid-ups -DD -a -x explore 2>&1 | head -1000 + placeholder: "Paste additional HID exploration data if available" + render: shell + + - type: textarea + id: notes + attributes: + label: Implementation Notes + description: Any device-specific quirks, observations, or additional context + placeholder: | + - Device only has IN endpoint (no OUT endpoint for commands) + - Beeper control requires special sequence + - Runtime calculation seems to be off by factor of 60 + + - type: textarea + id: priority + attributes: + label: Priority Information + description: Help us understand the impact of this implementation + placeholder: | + - This is a popular budget UPS model sold worldwide + - Would also support models X, Y, Z from same manufacturer + - Currently affects 10+ users in our community \ No newline at end of file diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..0a5e948 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,136 @@ +# Contributing to ESPHome Components + +Thank you for your interest in contributing to this project! This guide will help you get started. + +## Reporting Issues + +### New UPS Protocol Support + +If you have a UPS device that isn't currently supported, please use our **New UPS Protocol Request** issue template. This template guides you through collecting all necessary debug information. + +#### Quick Start: Automated Debug Collection + +We provide a tool to automatically collect all required debug information: + +```bash +# 1. Configure your UPS in /etc/nut/ups.conf +sudo nano /etc/nut/ups.conf +# Add: +# [myups] +# driver = usbhid-ups +# port = auto + +# 2. Run the collection script +./tools/collect-protocol-debug.sh myups + +# 3. Follow the interactive prompts +# 4. Review the generated debug output +# 5. Create an issue with the collected data +``` + +The script will: +- Detect your UPS USB IDs +- Capture HID communication during different power states +- Extract all UPS variables and supported commands +- Generate a summary report for your issue + +#### Manual Debug Collection + +If you prefer manual collection, the issue template provides detailed instructions for: +- Capturing NUT driver debug output +- Documenting state transitions (AC → Battery → Charging) +- Identifying HID report structures +- Mapping UPS variables + +### Required Information for Protocol Requests + +**Essential data needed:** +1. **USB IDs**: Vendor and Product IDs from `lsusb` +2. **HID Reports**: Debug output showing report IDs and data during: + - Normal operation (on AC power) + - Battery operation (unplugged) + - Charging state (plugged back in) +3. **UPS Variables**: Complete `upsc` output +4. **HID Paths**: All discovered HID paths from NUT debug + +**Why this matters**: This debug data allows developers (including AI assistants) to: +- Understand the HID report structure +- Map data bytes to UPS variables +- Identify status bits and their meanings +- Implement accurate protocol support + +## Development Setup + +### Prerequisites + +- ESP32-S3 with USB OTG support +- ESPHome development environment +- VS Code with devcontainer support (recommended) +- UPS device for testing + +### Quick Start + +1. Clone the repository +2. Open in VS Code with devcontainer +3. Test with: `esphome compile configs/testing/simulation_test.yaml` + +## Code Contributions + +### Adding New Protocols + +1. **Study existing protocols**: Review `apc_hid_protocol.cpp` or `cyberpower_protocol.cpp` +2. **Use the protocol base class**: Inherit from `UpsProtocolBase` +3. **Register your protocol**: Use the `REGISTER_UPS_PROTOCOL_FOR_VENDOR` macro +4. **Follow patterns**: Match existing code style and error handling +5. **Add constants properly**: Use `ups_constants.h` for shared values + +### Code Quality Standards + +- **No exceptions**: ESPHome disables C++ exceptions +- **Thread safety**: Use mutexes for shared data access +- **Logging**: Use appropriate ESP_LOG levels +- **Constants**: No magic numbers - use named constants +- **Testing**: Provide simulation mode for testing without hardware + +### Testing Your Changes + +1. **Compile test**: `esphome compile configs/testing/simulation_test.yaml` +2. **Upload to device**: Use VS Code task or `esphome upload` +3. **Monitor logs**: `esphome logs configs/testing/simulation_test.yaml` +4. **Test all states**: Verify online, battery, and charging states +5. **Check memory**: Monitor heap usage and task stack sizes + +## Documentation + +### Component Documentation + +Update the component README (`components/ups_hid/README.md`) when: +- Adding new features +- Changing configuration options +- Adding protocol support +- Fixing significant bugs + +### Code Comments + +- Document complex algorithms +- Explain protocol-specific quirks +- Reference NUT source files when applicable +- NO unnecessary comments for obvious code + +## Pull Request Process + +1. **Create focused PRs**: One feature/fix per PR +2. **Test thoroughly**: Include test results in PR description +3. **Update documentation**: README and configuration examples +4. **Follow commit conventions**: Clear, descriptive commit messages +5. **Be responsive**: Address review feedback promptly + +## Getting Help + +- **GitHub Issues**: For bugs and feature requests +- **Discussions**: For questions and general help +- **Debug logs**: Always include when reporting issues + +## License + +By contributing, you agree that your contributions will be licensed under the same license as the project. \ No newline at end of file diff --git a/tools/README.md b/tools/README.md index e5e2f95..ba0a168 100644 --- a/tools/README.md +++ b/tools/README.md @@ -2,6 +2,37 @@ This folder contains development tools for ESP32 ESPHome component development and debugging utilities. +## Protocol Debug Collection + +### collect-protocol-debug.sh + +Automated collection of debug information for new UPS protocol support requests. This tool gathers all necessary data for implementing new UPS protocols. + +**Usage:** +```bash +./tools/collect-protocol-debug.sh +``` + +**Features:** +- Collects USB device information and descriptors +- Captures NUT driver debug output for different states (online, battery, charging) +- Extracts HID paths and report IDs automatically +- Documents UPS variables and supported commands +- Creates organized output directory with all debug files +- Generates markdown-formatted summary ready for GitHub issues + +**Requirements:** +- NUT (Network UPS Tools) installed +- UPS configured in `/etc/nut/ups.conf` +- sudo access for USB device access + +**Output:** +Creates a timestamped directory containing: +- USB device descriptors and IDs +- HID report captures for each power state +- Complete UPS variable listings +- Summary report for issue creation + ## USB Device Management ### scan-usb.sh diff --git a/tools/collect-protocol-debug.sh b/tools/collect-protocol-debug.sh new file mode 100755 index 0000000..e283cff --- /dev/null +++ b/tools/collect-protocol-debug.sh @@ -0,0 +1,238 @@ +#!/bin/bash +# Script to collect debug information for new UPS protocol requests +# Usage: ./collect-protocol-debug.sh + +set -e + +# Colors for output +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +NC='\033[0m' # No Color + +# Check if UPS name is provided +if [ $# -eq 0 ]; then + echo -e "${RED}Error: UPS name required${NC}" + echo "Usage: $0 " + echo "Example: $0 myups" + echo "" + echo "First configure your UPS in /etc/nut/ups.conf:" + echo "[myups]" + echo " driver = usbhid-ups" + echo " port = auto" + echo " vendorid = 051d" + echo " productid = 0002" + exit 1 +fi + +UPS_NAME=$1 +OUTPUT_DIR="ups-protocol-debug-$(date +%Y%m%d-%H%M%S)" +OUTPUT_FILE="$OUTPUT_DIR/debug-output.md" + +# Create output directory +mkdir -p "$OUTPUT_DIR" + +echo -e "${GREEN}=== UPS Protocol Debug Collection Tool ===${NC}" +echo -e "Collecting debug information for: ${YELLOW}$UPS_NAME${NC}" +echo "Output directory: $OUTPUT_DIR" +echo "" + +# Function to run command and save output +run_and_save() { + local description=$1 + local command=$2 + local output_file=$3 + + echo -e "${YELLOW}Running: $description${NC}" + echo "## $description" >> "$OUTPUT_FILE" + echo '```bash' >> "$OUTPUT_FILE" + echo "# Command: $command" >> "$OUTPUT_FILE" + + if eval "$command" > "$output_file" 2>&1; then + cat "$output_file" >> "$OUTPUT_FILE" + echo -e "${GREEN}✓ Success${NC}" + else + echo "Error running command" >> "$OUTPUT_FILE" + echo -e "${RED}✗ Failed${NC}" + fi + + echo '```' >> "$OUTPUT_FILE" + echo "" >> "$OUTPUT_FILE" +} + +# Start collecting information +echo "# UPS Protocol Debug Information" > "$OUTPUT_FILE" +echo "Date: $(date)" >> "$OUTPUT_FILE" +echo "UPS Name: $UPS_NAME" >> "$OUTPUT_FILE" +echo "" >> "$OUTPUT_FILE" + +# 1. USB Device Information +echo -e "\n${GREEN}Step 1: USB Device Information${NC}" +run_and_save "USB Device List" "lsusb | grep -i ups || lsusb | grep -iE 'apc|cyber|eaton|tripplite'" "$OUTPUT_DIR/lsusb.txt" + +# Get vendor and product ID +VENDOR_PRODUCT=$(lsusb | grep -i ups | head -1 | sed -n 's/.*ID \([0-9a-f]*:[0-9a-f]*\).*/\1/p') +if [ -n "$VENDOR_PRODUCT" ]; then + echo "Detected USB ID: $VENDOR_PRODUCT" + run_and_save "USB Device Details" "lsusb -v -d $VENDOR_PRODUCT" "$OUTPUT_DIR/lsusb-verbose.txt" +fi + +# 2. Test UPS driver connection +echo -e "\n${GREEN}Step 2: Testing UPS Driver Connection${NC}" +run_and_save "Driver Test" "sudo timeout 10 /lib/nut/usbhid-ups -DD -a $UPS_NAME 2>&1 | head -500" "$OUTPUT_DIR/driver-test.txt" + +# 3. Collect HID paths +echo -e "\n${GREEN}Step 3: Collecting HID Paths${NC}" +run_and_save "HID Path Discovery" "sudo timeout 10 /lib/nut/usbhid-ups -DD -a $UPS_NAME 2>&1 | grep 'Path:' | sort -u" "$OUTPUT_DIR/hid-paths.txt" + +# 4. Start NUT driver if not running +echo -e "\n${GREEN}Step 4: Starting NUT Driver${NC}" +sudo upsdrvctl stop $UPS_NAME 2>/dev/null || true +sleep 2 +sudo upsdrvctl start $UPS_NAME +sleep 3 + +# 5. Collect upsc output +echo -e "\n${GREEN}Step 5: Collecting UPS Variables${NC}" +run_and_save "UPS Variables (upsc)" "upsc $UPS_NAME" "$OUTPUT_DIR/upsc-full.txt" + +# 6. Collect supported commands +echo -e "\n${GREEN}Step 6: Checking Supported Commands${NC}" +run_and_save "UPS Commands" "upscmd -l $UPS_NAME" "$OUTPUT_DIR/upscmd.txt" + +# 7. Collect state-specific debug output +echo -e "\n${GREEN}Step 7: Collecting State-Specific Debug Output${NC}" +echo -e "${YELLOW}This section requires manual intervention...${NC}" +echo "" + +# Function for interactive debug collection +collect_state_debug() { + local state_name=$1 + local instruction=$2 + local wait_time=${3:-30} + + echo -e "${YELLOW}$instruction${NC}" + echo -e "Press ${GREEN}ENTER${NC} when ready to start capturing $state_name state..." + read + + echo "Capturing $state_name state for $wait_time seconds..." + + # Start background capture + sudo timeout $wait_time /lib/nut/usbhid-ups -DD -a $UPS_NAME 2>&1 | grep -A2 -B2 "Report" > "$OUTPUT_DIR/$state_name-reports.txt" & + PID=$! + + # Show progress + for i in $(seq $wait_time -1 1); do + echo -ne "\rTime remaining: $i seconds " + sleep 1 + done + echo -e "\n${GREEN}✓ $state_name capture complete${NC}" + + # Also capture upsc output for this state + upsc $UPS_NAME > "$OUTPUT_DIR/$state_name-upsc.txt" + + # Add to main output file + echo "## Debug Output - $state_name State" >> "$OUTPUT_FILE" + echo '```bash' >> "$OUTPUT_FILE" + cat "$OUTPUT_DIR/$state_name-reports.txt" | head -100 >> "$OUTPUT_FILE" + echo '```' >> "$OUTPUT_FILE" + echo "" >> "$OUTPUT_FILE" + + echo "## UPS Variables - $state_name State" >> "$OUTPUT_FILE" + echo '```bash' >> "$OUTPUT_FILE" + cat "$OUTPUT_DIR/$state_name-upsc.txt" >> "$OUTPUT_FILE" + echo '```' >> "$OUTPUT_FILE" + echo "" >> "$OUTPUT_FILE" +} + +# Collect different states +echo -e "${GREEN}We'll now collect debug data for different UPS states.${NC}" +echo -e "${YELLOW}IMPORTANT: Only proceed if it's safe to disconnect AC power!${NC}" +echo "" + +collect_state_debug "online" "Ensure UPS is connected to AC power (normal operation)" 30 +collect_state_debug "battery" "Now UNPLUG the UPS from AC power (running on battery)" 30 +collect_state_debug "charging" "Now PLUG the UPS back into AC power (charging mode)" 30 + +# 8. Optional: Low battery test +echo -e "\n${YELLOW}Optional: Low Battery Test${NC}" +echo "Would you like to test low battery state? This requires running on battery until low battery warning." +echo -n "This may take a long time and is optional. Continue? (y/N): " +read -r response +if [[ "$response" =~ ^[Yy]$ ]]; then + collect_state_debug "lowbatt" "Keep UPS on battery until low battery warning appears" 60 +fi + +# 9. Analyze collected data +echo -e "\n${GREEN}Step 8: Analyzing Collected Data${NC}" +echo "## Report ID Analysis" >> "$OUTPUT_FILE" +echo "" >> "$OUTPUT_FILE" + +# Extract unique report IDs +echo "### Discovered Report IDs" >> "$OUTPUT_FILE" +echo '```' >> "$OUTPUT_FILE" +grep -h "Report" "$OUTPUT_DIR"/*-reports.txt 2>/dev/null | \ + sed -n 's/.*Report \([0-9a-fA-F]*\).*/0x\1/p' | \ + sort -u | while read report_id; do + echo "Report ID: $report_id" + # Find example data for this report + grep -h "Report ${report_id#0x}" "$OUTPUT_DIR"/*-reports.txt 2>/dev/null | head -1 +done >> "$OUTPUT_FILE" +echo '```' >> "$OUTPUT_FILE" + +# 10. Create summary +echo -e "\n${GREEN}Step 9: Creating Summary${NC}" +cat > "$OUTPUT_DIR/SUMMARY.md" << EOF +# UPS Protocol Debug Summary + +## Device Information +- UPS Name: $UPS_NAME +- USB ID: $VENDOR_PRODUCT +- Date: $(date) + +## Quick Status +$(upsc $UPS_NAME 2>/dev/null | grep -E "device.mfr|device.model|device.serial|ups.status" || echo "Could not retrieve device info") + +## Files Collected +- lsusb.txt - USB device listing +- lsusb-verbose.txt - Detailed USB descriptor +- driver-test.txt - Initial driver connection test +- hid-paths.txt - All HID paths discovered +- upsc-full.txt - Complete UPS variables +- upscmd.txt - Supported commands +- online-reports.txt - HID reports during AC power +- battery-reports.txt - HID reports on battery +- charging-reports.txt - HID reports while charging +- *-upsc.txt - UPS variables for each state + +## Next Steps +1. Review the collected data in $OUTPUT_DIR/ +2. Create a new issue at: https://github.com/oleander/esphome-components/issues +3. Use the "New UPS Protocol Request" template +4. Attach or paste the relevant debug outputs + +## Key Information for Issue Report +\`\`\`bash +# USB IDs +$VENDOR_PRODUCT + +# Key Variables +$(upsc $UPS_NAME 2>/dev/null | grep -E "battery.charge|battery.runtime|ups.status|input.voltage" || echo "N/A") +\`\`\` +EOF + +echo -e "\n${GREEN}=== Collection Complete ===${NC}" +echo "" +echo "Debug data saved to: $OUTPUT_DIR/" +echo "Summary available at: $OUTPUT_DIR/SUMMARY.md" +echo "Main output file: $OUTPUT_FILE" +echo "" +echo -e "${YELLOW}Next steps:${NC}" +echo "1. Review the collected data" +echo "2. Create an issue at: https://github.com/oleander/esphome-components/issues" +echo "3. Use the 'New UPS Protocol Request' template" +echo "4. Paste relevant sections from $OUTPUT_FILE" +echo "" +echo -e "${GREEN}Thank you for helping improve UPS support!${NC}" + +exit 0