ESPHome 2026.12.0-dev
Loading...
Searching...
No Matches
sx1231.cpp
Go to the documentation of this file.
1#include "sx1231.h"
3#include "esphome/core/hal.h"
5#include "esphome/core/log.h"
7#include <cmath>
8
9namespace esphome::sx1231 {
10
11ESPHOME_LOG_TAG(TAG, "sx1231");
12static constexpr uint32_t FXOSC = 32000000u;
13static constexpr uint8_t CHIP_VERSION = 0x24;
14static constexpr uint32_t TRANSMIT_TIMEOUT_MS = 4000;
15static constexpr uint32_t MODE_TIMEOUT_MS = 50;
16static constexpr uint32_t RECONFIGURE_INTERVAL_ID = 0;
17static constexpr uint32_t RECONFIGURE_INTERVAL_MS = 1000;
18static constexpr uint32_t RX_STALL_CHECK_INTERVAL_MS = 1000;
19// In units of 16 bit times from signal detection: 510 byte times, more than a packet with a 435 byte preamble takes
20static constexpr uint8_t RX_STALL_TIMEOUT = 0xFF;
21
22// Indexed by SX1231Error
23PROGMEM_STRING_TABLE(SX1231ErrorStrings, "none", "timeout", "invalid parameters", "radio not ready", "radio busy");
24
25static const LogString *set_mode_failure() { return LOG_STR("Set mode failure"); }
26static constexpr uint16_t RAMP[16] PROGMEM = {3400, 2000, 1000, 500, 250, 125, 100, 62, 50, 40, 31, 25, 20, 15, 12, 10};
27// FSK width of a RegRxBw code: RxBwMant (16, 20 or 24) in bits 4:3 and RxBwExp in bits 2:0
28static uint32_t bandwidth_hz(uint8_t rx_bw) { return FXOSC / ((16 + 4 * (rx_bw >> 3)) << ((rx_bw & 0x07) + 2)); }
29
30// Indexed by the shaping code, plus 4 for OOK
31PROGMEM_STRING_TABLE(ShapingStrings, "NONE", "GAUSSIAN_BT_1_0", "GAUSSIAN_BT_0_5", "GAUSSIAN_BT_0_3", "NONE",
32 "CUTOFF_BR_X_1", "CUTOFF_BR_X_2");
33
34uint8_t SX1231::read_register_(uint8_t reg) { return this->read_register(reg); }
35
36void SX1231::write_register_(uint8_t reg, uint8_t value) { this->write_register(reg | 0x80, value); }
37
38// Burst write: the radio moves to the next register after each byte
39void SX1231::write_registers_(uint8_t reg, const uint8_t *data, size_t len) {
40 this->write_registers(reg | 0x80, data, len);
41}
42
43void SX1231::write_fifo_(const uint8_t *data, size_t len) {
44 this->enable();
45 this->write_byte(REG_FIFO | 0x80);
46 // Not write_array(): in a multi-byte write the FIFO sometimes stores a byte with its last bit cleared
47 for (size_t i = 0; i < len; i++) {
48 this->write_byte(data[i]);
49 }
50 this->disable();
51}
52
53void SX1231::write_register16_(uint8_t msb_reg, uint16_t value) {
54 uint8_t bytes[2];
55 put_be16(bytes, value);
56 this->write_registers_(msb_reg, bytes, sizeof(bytes));
57}
58
60 setup_output_pin(this->rst_pin_, false);
61 this->spi_setup();
62
63 const LogString *reason = this->configure_radio_();
64 if (reason != nullptr) {
65 this->mark_failed(reason);
66 return;
67 }
68 // After the radio is known to work: core keeps a loop request from a failed component pending for good
71 this->set_interval(RX_STALL_CHECK_INTERVAL_MS, [this]() { this->restart_stalled_rx_(); });
72}
73
75 // Nothing to configure before setup() or after a failed setup
76 if (!this->is_ready()) {
77 return;
78 }
79 const LogString *reason = this->configure_radio_();
80 if (reason != nullptr) {
81 this->fail_(reason);
82 return;
83 }
85 if (this->reconfigure_pending_) {
86 this->reconfigure_pending_ = false;
87 this->cancel_interval(RECONFIGURE_INTERVAL_ID);
88 }
90 this->enable_loop();
91}
92
93void SX1231::fail_(const LogString *reason) {
95 // Nothing else configures the radio again
96 if (!this->reconfigure_pending_) {
97 this->reconfigure_pending_ = true;
98 this->set_interval(RECONFIGURE_INTERVAL_ID, RECONFIGURE_INTERVAL_MS, [this]() { this->configure(); });
99 }
100 // Last: a log listener may call configure(), which cancels the retry
101 this->status_set_warning(reason);
102}
103
104const LogString *SX1231::configure_radio_() {
105 // Until this succeeds
107 // Codes from 0x18 are reserved, and OOK uses the next exponent down, which a code with exponent 0 does not have
108 if (this->bandwidth_ >= 0x18 || (this->modulation_ == MOD_OOK && (this->bandwidth_ & 0x07) == 0)) {
109 return LOG_STR("Invalid bandwidth");
110 }
111 // The same range as the YAML option; the divider is 16 bits and 0 would divide by zero
112 if (this->bitrate_ < 500 || this->bitrate_ > 300000) {
113 return LOG_STR("Invalid bitrate");
114 }
115 // A longer fixed length would make the receive path read past its buffer
116 if (this->payload_length_ > SX1231_MAX_PACKET_SIZE) {
117 return LOG_STR("Invalid payload length");
118 }
119 const bool boost = this->pa_pin_ == PA_PIN_BOOST;
120 const int8_t pa_power = clamp<int8_t>(this->pa_power_, boost ? -2 : -18, boost ? 20 : 13);
121 if (pa_power != this->pa_power_) {
122 ESP_LOGW(TAG, "PA power %d dBm is out of range for the PA pin, using %d dBm", this->pa_power_, pa_power);
123 this->pa_power_ = pa_power;
124 }
125 const bool high_power = this->pa_power_ > 17;
126 this->applied_ = {this->payload_length_, this->packet_mode_, high_power, this->rx_start_};
127
128 // Reset is active high
129 if (this->rst_pin_ != nullptr) {
130 pulse_pin(this->rst_pin_, true, 1000);
131 delayMicroseconds(10000);
132 }
133
134 const uint8_t version = this->read_register_(REG_VERSION);
135 if (version != CHIP_VERSION) {
136 ESP_LOGE(TAG, "Chip version 0x%02X, expected 0x%02X", version, CHIP_VERSION);
137 return LOG_STR("Unsupported chip version");
138 }
139
140 if (!this->set_mode_(MODE_STDBY)) {
141 return set_mode_failure();
142 }
143
144 uint8_t data_modul = this->modulation_ | this->shaping_;
145 if (!this->packet_mode_) {
147 }
148 this->write_register_(REG_DATA_MODUL, data_modul);
149 uint16_t bitrate = (FXOSC + this->bitrate_ / 2) / this->bitrate_; // rounded to nearest
150 this->write_register16_(REG_BITRATE_MSB, bitrate);
151 // Rounded to nearest, so that the lowest deviation allowed is not programmed as less
152 uint16_t fdev = clamp_at_most((this->deviation_ * 4096 + 125000) / 250000, uint32_t{0x3FFF});
153 this->write_register16_(REG_FDEV_MSB, fdev);
154
155 uint64_t frf = ((uint64_t) this->frequency_ << 19) / FXOSC;
156 uint8_t frf_bytes[3];
157 put_be24(frf_bytes, static_cast<uint32_t>(frf));
158 this->write_registers_(REG_FRF_MSB, frf_bytes, sizeof(frf_bytes));
159
160 uint8_t pa_level = this->pa_pin_ | (this->pa_power_ + 18);
161 if (this->pa_power_ > 13) {
162 // Both BOOST amplifiers; the +20 dBm settings add another 3 dB
163 pa_level = PA_PIN_BOOST | PA_BOOST_COMBINED | (this->pa_power_ + (high_power ? 11 : 14));
164 }
165 this->write_register_(REG_PA_LEVEL, pa_level);
167 this->write_register_(REG_OCP, high_power ? OCP_OFF : OCP_ON_95MA);
168 // set_mode_() switches these only when the +20 dBm settings are used
171
172 uint8_t rx_bw = this->bandwidth_;
173 if (this->modulation_ == MOD_OOK) {
174 // Each code is half as wide in OOK, so use the next exponent down
175 rx_bw--;
176 }
179 this->write_register_(REG_RSSI_THRESH, std::abs(int(this->rx_floor_ * 2.0f)));
180 this->write_register_(REG_RX_TIMEOUT2, RX_STALL_TIMEOUT);
183
185 if (!this->sync_value_.empty()) {
186 uint8_t size = (this->sync_value_.size() - 1) << SYNC_SIZE_SHIFT;
188 this->write_registers_(REG_SYNC_VALUE1, this->sync_value_.data(), this->sync_value_.size());
189 } else {
190 this->write_register_(REG_SYNC_CONFIG, 0x00);
191 }
192
193 uint8_t crc_mode = this->crc_enable_ ? CRC_ON : CRC_OFF;
194 if (this->payload_length_ > 0) {
197 } else {
198 this->write_register_(REG_PAYLOAD_LENGTH, SX1231_MAX_PACKET_SIZE);
200 }
203 // Writing this flag empties the FIFO
205
206 if (!this->restore_()) {
207 return set_mode_failure();
208 }
209 return nullptr;
210}
211
213 if (this->applied_.payload_length > 0) {
214 return this->applied_.payload_length;
215 }
216 return SX1231_MAX_PACKET_SIZE;
217}
218
219SX1231Error SX1231::transmit_packet(const uint8_t *data, size_t len) {
220 SX1231Error result = this->start_transmit_(data, len);
222 const uint32_t start = millis();
223 // DIO0 is PacketSent while transmitting
224 while (!this->dio0_pin_->digital_read()) {
225 if (millis() - start >= TRANSMIT_TIMEOUT_MS) {
227 break;
228 }
229 App.feed_wdt();
230 }
231 if (!this->restore_()) {
232 this->fail_(set_mode_failure());
233 }
234 }
236 ESP_LOGW(TAG, "Packet send failed: %s", LOG_STR_ARG(SX1231ErrorStrings::get_log_str(result)));
237 }
238 return result;
239}
240
241SX1231Error SX1231::start_transmit_(const uint8_t *data, size_t len) {
242 // Callers such as a template number's on_value can run before setup() or after a failed setup
245 }
246 if (!this->applied_.packet_mode || data == nullptr || len == 0 || len > this->get_max_packet_size() ||
247 (this->applied_.payload_length > 0 && this->applied_.payload_length != len)) {
249 }
250 if (this->dio0_pin_ == nullptr) {
251 ESP_LOGE(TAG, "DIO0 pin not configured, cannot wait for transmit completion");
253 }
254
255 // Checked in receive mode, as the chip clears this flag on leaving it; the packet stays in the FIFO for loop()
256 if (this->packet_waiting_()) {
258 }
259 if (!this->set_mode_(MODE_STDBY)) {
260 this->fail_(set_mode_failure());
262 }
263 // Drop any part of a packet that was still arriving
265 if (this->applied_.payload_length == 0) {
266 const uint8_t length = len;
267 this->write_fifo_(&length, 1);
268 }
269 this->write_fifo_(data, len);
270 if (!this->set_mode_(MODE_TX)) {
271 this->fail_(set_mode_failure());
273 }
275}
276
278 // Via standby, which ends a send and clears PacketSent
279 if (!this->set_mode_(MODE_STDBY)) {
280 return false;
281 }
282 return this->set_mode_(this->applied_.rx_start ? MODE_RX : MODE_SLEEP);
283}
284
287 return false;
288 }
289 // Set from the sync word until the packet has been read, and cleared on leaving receive mode
291 return true;
292 }
293 // Without a sync word, only a received packet that loop() has not read yet shows
294 return this->packet_waiting_();
295}
296
300
301#ifdef SX1231_LISTENER_COUNT
303 if (this->listeners_.size() == SX1231_LISTENER_COUNT) {
304 ESP_LOGE(TAG, "Listener list full; call sx1231.request_listener_slot(radio_id) from the component's to_code");
305 return;
306 }
307 this->listeners_.push_back(listener);
308}
309#endif
310
311void SX1231::call_listeners_(std::span<const uint8_t> packet, float rssi, float snr) {
312#ifdef SX1231_LISTENER_COUNT
313 for (auto &listener : this->listeners_) {
314 listener->on_packet(packet, rssi, snr);
315 }
316#endif
317 this->packet_callback_.call(ByteView(packet.data(), packet.size()), rssi, snr);
318}
319
321 // DIO0's interrupt and configure() wake the loop
322 this->disable_loop();
323 if (this->state_ == RadioState::RADIO_STATE_IDLE && this->dio0_pin_ != nullptr && this->dio0_pin_->digital_read()) {
324 this->receive_();
325 }
326}
327
329 if (!this->packet_waiting_()) {
330 return;
331 }
332 // Read first: emptying the FIFO restarts the receiver, which then measures again
333 const float rssi = this->read_register_(REG_RSSI_VALUE) / -2.0f;
334 uint8_t payload_length = this->applied_.payload_length;
335 if (payload_length == 0) {
336 payload_length = this->read_register_(REG_FIFO);
337 }
338 if (payload_length == 0 || payload_length > SX1231_MAX_PACKET_SIZE) {
339 ESP_LOGW(TAG, "Dropping packet with invalid length %u", payload_length);
340 // Empties the FIFO, which restarts the receiver
342 return;
343 }
344 uint8_t packet[SX1231_MAX_PACKET_SIZE];
345 this->read_registers(REG_FIFO, packet, payload_length);
346 this->call_listeners_(std::span<const uint8_t>(packet, payload_length), rssi, NAN);
347}
348
349// A signal above the RX floor that no sync word follows leaves the receiver waiting, with its gain set for that
350// signal, so weaker packets are then missed. The chip flags this but does not recover from it.
353 return;
354 }
355 const uint8_t flags = this->read_register_(REG_IRQ_FLAGS1);
356 if ((flags & TIMEOUT) != 0 && (flags & SYNC_ADDRESS_MATCH) == 0) {
357 ESP_LOGV(TAG, "Restarting stalled receiver");
359 }
360}
361
362bool SX1231::set_mode_(uint8_t mode) {
363 // DIO0 is PayloadReady while receiving and PacketSent while transmitting
364 if (mode == MODE_RX) {
366 } else if (mode == MODE_TX) {
368 }
369 // The +20 dBm settings must be off except while sending
370 if (this->applied_.high_power) {
371 const bool tx = mode == MODE_TX;
374 }
375 uint32_t start = millis();
376 this->write_register_(REG_OP_MODE, mode);
377 while ((this->read_register_(REG_IRQ_FLAGS1) & MODE_READY) == 0) {
378 if (millis() - start > MODE_TIMEOUT_MS) {
379 return false;
380 }
381 }
382 return true;
383}
384
387 ESP_LOGW(TAG, "Radio unavailable, mode change ignored");
388 return;
389 }
390 if (!this->set_mode_(mode)) {
391 this->fail_(set_mode_failure());
392 }
393}
394
396
398
400
402
404 ESP_LOGCONFIG(TAG, "SX1231:");
405 LOG_PIN(" CS Pin: ", this->cs_);
406 LOG_PIN(" RST Pin: ", this->rst_pin_);
407 LOG_PIN(" DIO0 Pin: ", this->dio0_pin_);
408 ESP_LOGCONFIG(TAG,
409 " Frequency: %" PRIu32 " Hz\n"
410 " Bandwidth: %" PRIu32 " Hz\n"
411 " PA Pin: %s\n"
412 " PA Power: %" PRId8 " dBm\n"
413 " PA Ramp: %" PRIu16 " us\n"
414 " Shaping: %s",
415 this->frequency_, bandwidth_hz(this->bandwidth_),
416 this->pa_pin_ == PA_PIN_BOOST ? LOG_STR_LITERAL("BOOST") : LOG_STR_LITERAL("RFO"), this->pa_power_,
417 progmem_read_uint16(&RAMP[this->pa_ramp_]),
418 LOG_STR_ARG(ShapingStrings::get_log_str(this->shaping_ + (this->modulation_ == MOD_OOK ? 4 : 0))));
419 if (this->modulation_ == MOD_FSK) {
420 ESP_LOGCONFIG(TAG, " Deviation: %" PRIu32 " Hz", this->deviation_);
421 }
422 ESP_LOGCONFIG(TAG,
423 " Modulation: %s\n"
424 " Bitrate: %" PRIu32 "b/s\n"
425 " Bitsync: %s\n"
426 " Rx Start: %s\n"
427 " Rx Floor: %.1f dBm\n"
428 " Packet Mode: %s",
429 this->modulation_ == MOD_FSK ? LOG_STR_LITERAL("FSK") : LOG_STR_LITERAL("OOK"), this->bitrate_,
430 TRUEFALSE(this->packet_mode_ || this->bitsync_), TRUEFALSE(this->rx_start_), this->rx_floor_,
431 TRUEFALSE(this->packet_mode_));
432 if (this->packet_mode_) {
433 ESP_LOGCONFIG(TAG, " CRC Enable: %s", TRUEFALSE(this->crc_enable_));
434 }
435 if (this->payload_length_ > 0) {
436 ESP_LOGCONFIG(TAG, " Payload Length: %" PRIu8, this->payload_length_);
437 }
438 if (!this->sync_value_.empty()) {
439 char hex_buf[SX1231_MAX_SYNC_SIZE * 2 + 1];
440 ESP_LOGCONFIG(TAG, " Sync Value: 0x%s",
441 format_hex_to(hex_buf, this->sync_value_.data(), this->sync_value_.size()));
442 }
443 if (this->preamble_size_ > 0) {
444 ESP_LOGCONFIG(TAG, " Preamble Size: %" PRIu16, this->preamble_size_);
445 }
446}
447
448} // namespace esphome::sx1231
BedjetMode mode
BedJet operating mode.
void feed_wdt()
Feed the task watchdog.
Read-only view of bytes in a buffer owned elsewhere, valid only until that buffer is written again.
Definition helpers.h:149
void mark_failed()
Mark this component as failed.
bool cancel_interval(const char *name)
Cancel an interval function.
Definition component.cpp:92
bool is_ready() const
void enable_loop()
Enable this component's loop.
Definition component.h:262
void disable_loop()
Disable this component's loop.
void status_clear_warning()
Definition component.h:318
void set_interval(const char *name, uint32_t interval, SchedulerCallback &&f)
Set an interval function with a const char* name.
Definition component.cpp:88
size_t size() const
Definition helpers.h:404
bool empty() const
Definition helpers.h:406
void change_mode_(uint8_t mode)
Definition sx1231.cpp:385
SX1231Error start_transmit_(const uint8_t *data, size_t len)
Definition sx1231.cpp:241
void fail_(const LogString *reason)
Definition sx1231.cpp:93
void write_fifo_(const uint8_t *data, size_t len)
Definition sx1231.cpp:43
SX1231Error transmit_packet(const uint8_t *data, size_t len)
Definition sx1231.cpp:219
void dump_config() override
Definition sx1231.cpp:403
uint8_t read_register_(uint8_t reg)
Definition sx1231.cpp:34
void call_listeners_(std::span< const uint8_t > packet, float rssi, float snr)
Definition sx1231.cpp:311
uint16_t preamble_size_
Definition sx1231.h:128
void write_register_(uint8_t reg, uint8_t value)
Definition sx1231.cpp:36
StaticVector< SX1231Listener *, SX1231_LISTENER_COUNT > listeners_
Definition sx1231.h:119
size_t get_max_packet_size()
Definition sx1231.cpp:212
void setup() override
Definition sx1231.cpp:59
const LogString * configure_radio_()
Definition sx1231.cpp:104
LazyCallbackManager< void(ByteView, float, float)> packet_callback_
Definition sx1231.h:117
void loop() override
Definition sx1231.cpp:320
StaticVector< uint8_t, SX1231_MAX_SYNC_SIZE > sync_value_
Definition sx1231.h:127
void register_listener(SX1231Listener *listener)
Listeners must request a slot from their to_code: sx1231.request_listener_slot(radio_id).
Definition sx1231.cpp:302
void write_register16_(uint8_t msb_reg, uint16_t value)
Definition sx1231.cpp:53
void write_registers_(uint8_t reg, const uint8_t *data, size_t len)
Definition sx1231.cpp:39
InternalGPIOPin * dio0_pin_
Definition sx1231.h:121
AppliedSettings applied_
Definition sx1231.h:129
bool set_mode_(uint8_t mode)
Definition sx1231.cpp:362
uint16_t flags
@ INTERRUPT_RISING_EDGE
Definition gpio_pin.h:52
ESPHOME_LOG_TAG(TAG, "sx1231")
PROGMEM_STRING_TABLE(SX1231ErrorStrings, "none", "timeout", "invalid parameters", "radio not ready", "radio busy")
T clamp_at_most(T value, U max)
Definition helpers.h:2859
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
uint32_t value
Definition hal.cpp:59
const void size_t len
Definition hal.h:68
void IRAM_ATTR HOT delayMicroseconds(uint32_t us)
Definition hal.cpp:48
uint16_t size
Definition helpers.cpp:44
uint16_t progmem_read_uint16(const uint16_t *addr)
Definition hal.h:53
constexpr uint8_t * put_be16(uint8_t *dst, uint16_t value)
Write the low 16, 24 or 32 bits of value to dst, most significant byte first (be) or least significan...
Definition helpers.h:1296
constexpr uint8_t * put_be24(uint8_t *dst, uint32_t value)
Definition helpers.h:1301
void setup_output_pin(GPIOPin *pin, bool level)
Set up pin and drive it to level. Does nothing when pin is null, so an optional pin needs no check.
Definition gpio.cpp:44
bool setup_wake_interrupt(GPIOPin *pin, Component *component, gpio::InterruptType type)
Set up pin and attach the wake interrupt when it is a GPIO of the chip itself.
Definition gpio.h:60
uint32_t IRAM_ATTR HOT millis()
Definition hal.cpp:25
char * format_hex_to(char *buffer, size_t buffer_size, const uint8_t *data, size_t length)
Format byte array as lowercase hex to buffer (base implementation).
Definition helpers.cpp:459
Application App
Global storage of Application pointer - only one Application can exist.
static void uint32_t
esp_err_t result