Clean-up get_button_from_position

This commit is contained in:
Edward Firmo
2024-12-21 23:32:15 +01:00
parent 8c610a406a
commit 65bbd901b1

View File

@@ -59,18 +59,22 @@ namespace esphome {
} }
uint8_t TxUltimateEasy::get_button_from_position(const uint8_t position) { uint8_t TxUltimateEasy::get_button_from_position(const uint8_t position) {
if (position > TOUCH_MAX_POSITION) // Invalid position // Validate position bounds
if (position > TOUCH_MAX_POSITION)
return 0; return 0;
if (this->gang_count_ == 1) // For 1 Gang model, any position is button 1
// Special case for single gang (only one button exists)
if (this->gang_count_ == 1)
return 1; return 1;
if (this->gang_count_ < 1 or this->gang_count_ > 4) // Invalid gang count
return 0; // Calculate button number
const uint8_t width = TOUCH_MAX_POSITION / this->gang_count_; // Width of each button region const uint8_t width = (TOUCH_MAX_POSITION + 1) / this->gang_count_; // Width of each button region
if (width < 1 or width > this->gang_count_) // Invalid width - and prevents division by zero if (width < 1 or width > this->gang_count_) // Invalid width - and prevents division by zero
return 0; return 0;
uint8_t button = (position / width) + 1; // Determine button region const uint8_t button = std::min(
if (button > this->gang_count_) static_cast<uint8_t>((position / width) + 1), // Convert position to button index
button = this->gang_count_; // Clamp to max button count this->gang_count_ // Clamp to max gang count
);
return button; return button;
} }