From 4707e1bbc98a63215ccaf7c9353f798861827558 Mon Sep 17 00:00:00 2001 From: Adam Jones Date: Mon, 16 Sep 2024 21:07:33 +0100 Subject: [PATCH] NEC IR protocol: add padding bytes --- esphome/components/remote_base/nec_protocol.cpp | 17 +++++++++++++---- .../remote_transmitter/common-buttons.yaml | 6 ++++++ 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/esphome/components/remote_base/nec_protocol.cpp b/esphome/components/remote_base/nec_protocol.cpp index 6ea9a8583c..a43dbce34c 100644 --- a/esphome/components/remote_base/nec_protocol.cpp +++ b/esphome/components/remote_base/nec_protocol.cpp @@ -13,8 +13,17 @@ static const uint32_t BIT_ONE_LOW_US = 1690; static const uint32_t BIT_ZERO_LOW_US = 560; void NECProtocol::encode(RemoteTransmitData *dst, const NECData &data) { - ESP_LOGD(TAG, "Sending NEC: address=0x%04X, command=0x%04X command_repeats=%d", data.address, data.command, - data.command_repeats); + // If the address or command is <= 0xFF the user has only supplied one byte + // We need to generate parity bits to pad the value to 2 bytes + // The NEC protocol requires us to prepend the inverse byte, e.g. 0x21 -> 0xDE21 + uint16_t address = data.address <= 0xFF + ? data.address | ((uint16_t)(~data.address) << 8) + : data.address; + uint16_t command = data.command <= 0xFF + ? data.command | ((uint16_t)(~data.command) << 8) + : data.command; + + ESP_LOGD(TAG, "Sending NEC: address=0x%04X, command=0x%04X command_repeats=%d", address, command, data.command_repeats); dst->reserve(2 + 32 + 32 * data.command_repeats + 2); dst->set_carrier_frequency(38000); @@ -22,7 +31,7 @@ void NECProtocol::encode(RemoteTransmitData *dst, const NECData &data) { dst->item(HEADER_HIGH_US, HEADER_LOW_US); for (uint16_t mask = 1; mask; mask <<= 1) { - if (data.address & mask) { + if (address & mask) { dst->item(BIT_HIGH_US, BIT_ONE_LOW_US); } else { dst->item(BIT_HIGH_US, BIT_ZERO_LOW_US); @@ -31,7 +40,7 @@ void NECProtocol::encode(RemoteTransmitData *dst, const NECData &data) { for (uint16_t repeats = 0; repeats < data.command_repeats; repeats++) { for (uint16_t mask = 1; mask; mask <<= 1) { - if (data.command & mask) { + if (command & mask) { dst->item(BIT_HIGH_US, BIT_ONE_LOW_US); } else { dst->item(BIT_HIGH_US, BIT_ZERO_LOW_US); diff --git a/tests/components/remote_transmitter/common-buttons.yaml b/tests/components/remote_transmitter/common-buttons.yaml index c6a2453b20..6e42eaa765 100644 --- a/tests/components/remote_transmitter/common-buttons.yaml +++ b/tests/components/remote_transmitter/common-buttons.yaml @@ -17,6 +17,12 @@ button: remote_transmitter.transmit_nec: address: 0x4242 command: 0x8484 + - platform: template + name: NEC short + on_press: + remote_transmitter.transmit_nec: + address: 0x32 + command: 0x02 - platform: template name: LG on_press: