ESPHome 2026.12.0-dev
Loading...
Searching...
No Matches
sx126x_radio.cpp
Go to the documentation of this file.
1#include "sx126x_radio.h"
2#include "esphome/core/log.h"
3#include <utility>
4
5namespace esphome::sx126x {
6
7// No ESP_LOG calls in this file: log listeners are user code, see sx126x_radio.h.
8
9static constexpr uint32_t RESET_DELAY_HIGH_US = 5000;
10static constexpr uint32_t RESET_DELAY_LOW_US = 2000;
11static constexpr uint32_t RECEIVE_RETRY_INTERVAL_MS = 200;
12
13RadioEffects SX126xRadio::comm_report(bool ok) {
14 RadioEffects effects;
15 effects.report = true;
16 effects.warning = ok ? nullptr : LOG_STR("Wait busy timeout");
17 return effects;
18}
19
20RadioEffects SX126xRadio::configure(const RadioProfile &requested, std::span<char, 16> version) {
21 ESPHOME_DEBUG_ASSERT(this->can_configure());
22 this->busy_ = true;
23 this->rx_retry_pending_ = false;
24 this->pending_irq_ = 0;
25 RadioEffects effects;
26 effects.report = true;
27 effects.warning = this->apply_configuration_(requested, version);
28 this->commit_(effects.warning == nullptr ? RadioState::RADIO_STATE_IDLE
30 return effects;
31}
32
33const LogString *SX126xRadio::apply_configuration_(const RadioProfile &requested, std::span<char, 16> version) {
34 if (!requested.sync_valid) {
35 return LOG_STR("Invalid sync value");
36 }
37 this->rst_pin_->digital_write(true);
38 delayMicroseconds(RESET_DELAY_HIGH_US);
39 pulse_pin(this->rst_pin_, false, RESET_DELAY_LOW_US);
40 delayMicroseconds(RESET_DELAY_HIGH_US);
41 this->bus().begin();
42 AppliedProfile applied;
43 switch (this->commands_.configure(requested, version, applied)) {
45 this->applied_ = applied;
46 return nullptr;
48 return LOG_STR("Unsupported chip version");
49 default:
50 return LOG_STR("Wait busy timeout");
51 }
52}
53
55 ESPHOME_DEBUG_ASSERT(this->can_change_mode());
56 this->busy_ = true;
57 this->bus().begin();
58 this->commands_.standby(STDBY_XOSC);
59 // A packet begun on the old frequency is abandoned, and its header or sync word flag would keep is_receiving() true.
60 // A packet already received stays flagged for loop().
62 this->commands_.set_frequency(frequency);
63 // A radio that sleeps keeps a received packet in standby, held, so that reading it puts the radio back to sleep
64 const bool hold = !this->applied_.rx_start && this->packet_waiting_();
65 if (this->applied_.rx_start) {
66 this->commands_.receive();
67 } else if (!hold) {
68 // A CRC error or timeout left flagged would keep DIO1 high, and reading it would wake the radio
69 this->commands_.clear_irqs();
70 this->pending_irq_ = 0;
71 this->commands_.sleep();
72 }
73 const bool ok = this->bus().ok();
74 if (ok) {
75 this->applied_.frequency = frequency;
76 }
80 return comm_report(ok);
81}
82
83bool SX126xRadio::packet_waiting_() {
84 const uint16_t irq = this->commands_.read_irq() | this->pending_irq_;
85 return (irq & IRQ_RX_DONE) && !(irq & IRQ_CRC_ERROR);
86}
87
89 ESPHOME_DEBUG_ASSERT(this->can_change_mode());
90 this->busy_ = true;
91 this->bus().begin();
92 switch (command) {
94 this->commands_.receive();
95 break;
97 this->commands_.transmit();
98 break;
100 this->commands_.standby(static_cast<SX126xStandbyMode>(arg));
101 break;
104 this->commands_.sleep(command == ModeCommand::MODE_COMMAND_COLD_SLEEP);
105 break;
107 this->commands_.calibrate_image(this->applied_.frequency);
108 break;
109 }
110 const bool ok = this->bus().ok();
111 // Cold sleep loses the configuration, and a failed command leaves the chip state unknown.
114 return comm_report(ok);
115}
116
118 uint32_t timeout_ms) {
119 RadioEffects effects;
122 return effects;
123 }
124 if (this->busy_ || this->state_ != RadioState::RADIO_STATE_IDLE) {
126 return effects;
127 }
128 const uint8_t fixed_length = this->applied_.payload_length;
129 if (data == nullptr || len == 0 || len > this->max_packet_size() || (fixed_length != 0 && len != fixed_length)) {
131 return effects;
132 }
133 this->busy_ = true;
134 this->bus().begin();
135 this->commands_.standby(STDBY_XOSC);
136 // RX cannot advance in standby. Keep a packet that completed before standby intact for
137 // poll(), before clearing IRQs or overwriting the shared FIFO. A failed read returns 0.
138 // A packet that failed its CRC is not delivered, so it does not hold up the send.
139 if (this->packet_waiting_()) {
142 return effects;
143 }
144 this->commands_.clear_irqs();
145 this->pending_irq_ = 0;
146 if (fixed_length == 0) {
147 this->commands_.set_packet_length(this->applied_, len);
148 }
149 this->commands_.write_fifo(data, len);
150 this->commands_.transmit(timeout_ms);
151 if (!this->bus().ok()) {
152 const bool restored = this->restore_();
154 effects = comm_report(restored);
156 return effects;
157 }
158 this->tx_ = {listener, millis(), timeout_ms};
160 // No status report on success, so no user code runs before the caller has the result.
161 // The completion reports status instead.
162 return effects;
163}
164
166 if (this->busy_ || !this->is_transmitting()) {
167 return {};
168 }
169 bool done = false;
171 if (this->dio1_pin_->digital_read()) {
172 this->busy_ = true;
173 this->bus().begin();
174 const uint16_t status = this->commands_.read_irq();
175 this->commands_.clear_irqs(status);
176 this->busy_ = false;
177 if (!this->bus().ok()) {
179 done = true;
180 } else if (status & IRQ_RX_TX_TIMEOUT) {
182 done = true;
183 } else if (status & IRQ_TX_DONE) {
184 done = true;
185 }
186 }
187 // A cached loop tick can precede admission; signed subtraction also handles wraparound.
188 if (!done && static_cast<int32_t>(now - this->tx_.started_ms) >= static_cast<int32_t>(this->tx_.timeout_ms)) {
190 done = true;
191 }
192 return done ? this->finish_transmit_(outcome) : RadioEffects{};
193}
194
196 if (this->busy_ || !this->is_transmitting() || listener == nullptr || listener != this->tx_.listener) {
197 return {};
198 }
199 return this->finish_transmit_(SX126xError::SX126X_ERROR_CANCELLED);
200}
201
202// The only place a send ends.
203RadioEffects SX126xRadio::finish_transmit_(SX126xError result) {
204 this->busy_ = true;
205 const bool restored = this->restore_();
207 RadioEffects effects = comm_report(restored);
209 effects.listener = std::exchange(this->tx_.listener, nullptr);
210 effects.finished = true;
211 return effects;
212}
213
214bool SX126xRadio::restore_() {
215 this->bus().begin();
216 this->commands_.standby(STDBY_XOSC);
217 this->commands_.clear_irqs();
218 if (this->applied_.payload_length == 0) {
219 this->commands_.set_packet_length(this->applied_, this->max_packet_size());
220 }
221 if (this->applied_.rx_start) {
222 this->commands_.receive();
223 } else {
224 this->commands_.sleep();
225 }
226 return this->bus().ok();
227}
228
230 if (this->state_ == RadioState::RADIO_STATE_HOLDING_RX) {
231 return true;
232 }
233 // A radio that sleeps after sending is not listening, and reading it would wake it
234 if (this->busy_ || this->state_ != RadioState::RADIO_STATE_IDLE || !this->applied_.rx_start) {
235 return false;
236 }
237 // DIO1 signals a received packet that loop() has not read yet
238 if (this->pending_irq_ != 0 || this->dio1_pin_->digital_read()) {
239 return true;
240 }
241 this->busy_ = true;
242 this->bus().begin();
243 const uint16_t status = this->commands_.read_irq();
244 this->busy_ = false;
245 // A failed read counts as receiving, so the link holds the send and warns if the radio stays unreadable
246 return !this->bus().ok() || (status & (IRQ_HEADER_VALID | IRQ_SYNCWORD_VALID)) != 0;
247}
248
249RadioEffects SX126xRadio::poll(uint32_t now, std::span<uint8_t, SX126X_MAX_PACKET_SIZE> packet) {
250 if (this->busy_) {
251 return {};
252 }
253 if (this->is_transmitting()) {
254 return this->poll_transmit(now);
255 }
256 RadioEffects effects;
258 effects.sleep_loop = true; // Polling cannot recover the radio; configure() can.
259 return effects;
260 }
261 if (this->rx_retry_pending_ && now - this->rx_retry_started_ms_ < RECEIVE_RETRY_INTERVAL_MS) {
262 return effects;
263 }
264 const bool holding = this->state_ == RadioState::RADIO_STATE_HOLDING_RX;
265 if (!holding && this->pending_irq_ == 0 && !this->dio1_pin_->digital_read()) {
266 effects.sleep_loop = this->dio1_pin_->is_internal(); // Its interrupt wakes the loop.
267 return effects;
268 }
269 return this->receive_(holding, now, packet);
270}
271
272RadioEffects SX126xRadio::receive_(bool holding, uint32_t now, std::span<uint8_t, SX126X_MAX_PACKET_SIZE> packet) {
273 this->busy_ = true;
274 this->bus().begin();
275 // A packet whose read failed has had its flags cleared, so they are kept until it is read.
276 const uint16_t status = this->commands_.read_irq() | this->pending_irq_;
277 const bool received = (status & IRQ_RX_DONE) && !(status & IRQ_CRC_ERROR);
278 if (!holding) {
279 // Cleared before the read, so a packet that completes during the read raises DIO1 again.
280 // A held packet keeps its IRQ until restoration.
281 this->commands_.clear_irqs(status);
282 }
283 float rssi = 0, snr = 0;
284 uint8_t length = 0;
285 if (received) {
286 this->commands_.read_packet(this->applied_.modulation, packet, length, rssi, snr);
287 }
288 const bool read = this->bus().ok();
289 this->pending_irq_ = read ? 0 : status;
290 // Do not spend a BUSY timeout on every loop while a read keeps failing.
291 this->rx_retry_pending_ = !read;
292 this->rx_retry_started_ms_ = now;
293 RadioState next = this->state_;
294 if (read && holding) {
296 }
297 this->commit_(next);
298 RadioEffects effects = comm_report(read && next != RadioState::RADIO_STATE_NEEDS_CONFIGURATION);
299 effects.received = read && received;
300 effects.rssi = rssi;
301 effects.snr = snr;
302 effects.packet_length = length;
303 return effects;
304}
305
306} // namespace esphome::sx126x
uint8_t status
Definition bl0942.h:8
uint16_le_t frequency
Definition bl0942.h:6
virtual void digital_write(bool value)=0
virtual bool is_internal()
Only the platform pin class behind the InternalGPIOPin alias may return true: callers static_cast to ...
Definition gpio_pin.h:87
virtual bool digital_read()=0
void transmit(uint32_t timeout_ms=0)
ConfigurationResult configure(const RadioProfile &profile, std::span< char, 16 > version, AppliedProfile &applied)
void standby(SX126xStandbyMode mode)
void set_frequency(uint32_t frequency)
void calibrate_image(uint32_t frequency)
void write_fifo(const uint8_t *data, size_t size)
void set_packet_length(AppliedProfile &applied, uint8_t length)
void read_packet(uint8_t modulation, std::span< uint8_t, SX126X_MAX_PACKET_SIZE > packet, uint8_t &length, float &rssi, float &snr)
void clear_irqs(uint16_t mask=0xFFFF)
RadioEffects configure(const RadioProfile &requested, std::span< char, 16 > version)
SX126xSpiDevice & bus()
RadioEffects retune(uint32_t frequency)
RadioEffects cancel_transmit(SX126xTransmitListener *listener)
RadioEffects poll(uint32_t now, std::span< uint8_t, SX126X_MAX_PACKET_SIZE > packet)
RadioEffects poll_transmit(uint32_t now)
RadioEffects change_mode(ModeCommand command, uint8_t arg)
RadioEffects start_transmit(SX126xTransmitListener *listener, const uint8_t *data, size_t len, uint32_t timeout_ms)
NameCopy * next
void pulse_pin(GPIOPin *pin, bool level, uint32_t width_us)
Drive pin to level for width_us microseconds, then to the opposite level.
Definition gpio.cpp:23
const void size_t len
Definition hal.h:68
void IRAM_ATTR HOT delayMicroseconds(uint32_t us)
Definition hal.cpp:48
uint32_t IRAM_ATTR HOT millis()
Definition hal.cpp:25
static void uint32_t
SX126xTransmitListener * listener
uint16_t length
Definition tt21100.cpp:0
esp_err_t result
SemaphoreHandle_t done