ESPHome 2026.12.0-dev
Loading...
Searching...
No Matches
cc1101.cpp
Go to the documentation of this file.
1#include "cc1101.h"
2#include "cc1101pa.h"
5#include "esphome/core/log.h"
7#include <algorithm>
8#include <cmath>
9#include <cstring>
10
11#ifdef USE_ESP32
12#include <esp_memory_utils.h>
13#endif
14
15namespace esphome::cc1101 {
16
17ESPHOME_LOG_TAG(TAG, "cc1101");
18static constexpr size_t TX_FIFO_SIZE = 64;
19static constexpr size_t RX_FIFO_SIZE = 64;
20// RX FIFO threshold for FIFO_THR = 7 in long packet mode
21static constexpr uint8_t RX_FIFO_THRESHOLD = 32;
22// The crystal takes about 150 us to start after CSn goes low
23static constexpr uint32_t WAKEUP_DELAY_US = 200;
24
25static float freq_offset_hz(uint8_t freqest) { return static_cast<int8_t>(freqest) * (XTAL_FREQUENCY / (1 << 14)); }
26static float rssi_dbm(int8_t rssi) { return (rssi * RSSI_STEP) - RSSI_OFFSET; }
27
28// MDMCFG2 MOD_FORMAT values
29PROGMEM_STRING_TABLE(ModulationStrings, "2-FSK", "GFSK", "UNUSED", "ASK/OOK", "4-FSK", "UNUSED", "UNUSED", "MSK");
30
31static void split_float(float value, int mbits, uint8_t &e, uint32_t &m) {
32 int e_tmp;
33 float m_tmp = std::frexp(value, &e_tmp);
34 if (e_tmp <= mbits) {
35 e = 0;
36 m = 0;
37 return;
38 }
39 e = static_cast<uint8_t>(e_tmp - mbits - 1);
40 m = static_cast<uint32_t>(((m_tmp * 2 - 1) * (1 << (mbits + 1))) + 1) >> 1;
41 if (m == (1UL << mbits)) {
42 e = e + 1;
43 m = 0;
44 }
45}
46
48 // Datasheet defaults
49 memset(&this->state_, 0, sizeof(this->state_));
50 this->state_.GDO2_CFG = 0x0D; // Serial Data (for RX on GDO2)
51 this->state_.GDO1_CFG = 0x2E;
52 this->state_.GDO0_CFG = 0x0D; // Serial Data (for RX on GDO0 / TX Input)
53 this->state_.FIFO_THR = 7;
54 this->state_.SYNC1 = 0xD3;
55 this->state_.SYNC0 = 0x91;
56 this->state_.PKTLEN = 0xFF;
57 this->state_.APPEND_STATUS = 1;
58 this->state_.LENGTH_CONFIG = 1;
59 this->state_.CRC_EN = 1;
60 this->state_.WHITE_DATA = 1;
61 this->state_.FREQ_IF = 0x0F;
62 this->state_.FREQ2 = 0x1E;
63 this->state_.FREQ1 = 0xC4;
64 this->state_.FREQ0 = 0xEC;
65 this->state_.DRATE_E = 0x0C;
66 this->state_.CHANBW_E = 0x02;
67 this->state_.DRATE_M = 0x22;
68 this->state_.SYNC_MODE = 2;
69 this->state_.CHANSPC_E = 2;
70 this->state_.NUM_PREAMBLE = 2;
71 this->state_.CHANSPC_M = 0xF8;
72 this->state_.DEVIATION_M = 7;
73 this->state_.DEVIATION_E = 4;
74 this->state_.RX_TIME = 7;
75 this->state_.CCA_MODE = 3;
76 this->state_.PO_TIMEOUT = 1;
77 this->state_.FOC_LIMIT = 2;
78 this->state_.FOC_POST_K = 1;
79 this->state_.FOC_PRE_K = 2;
80 this->state_.FOC_BS_CS_GATE = 1;
81 this->state_.BS_POST_KP = 1;
82 this->state_.BS_POST_KI = 1;
83 this->state_.BS_PRE_KP = 2;
84 this->state_.BS_PRE_KI = 1;
85 this->state_.MAGN_TARGET = 3;
86 this->state_.AGC_LNA_PRIORITY = 1;
87 this->state_.FILTER_LENGTH = 1;
88 this->state_.WAIT_TIME = 1;
89 this->state_.HYST_LEVEL = 2;
90 this->state_.WOREVT1 = 0x87;
91 this->state_.WOREVT0 = 0x6B;
92 this->state_.RC_CAL = 1;
93 this->state_.EVENT1 = 7;
94 this->state_.RC_PD = 1;
95 this->state_.MIX_CURRENT = 2;
96 this->state_.LODIV_BUF_CURRENT_RX = 1;
97 this->state_.LNA2MIX_CURRENT = 1;
98 this->state_.LNA_CURRENT = 1;
99 this->state_.LODIV_BUF_CURRENT_TX = 1;
100 this->state_.FSCAL3_LO = 9;
101 this->state_.CHP_CURR_CAL_EN = 2;
102 this->state_.FSCAL3_HI = 2;
103 this->state_.FSCAL2 = 0x0A;
104 this->state_.FSCAL1 = 0x20;
105 this->state_.FSCAL0 = 0x0D;
106 this->state_.RCCTRL1 = 0x41;
107 this->state_.FSTEST = 0x59;
108 this->state_.PTEST = 0x7F;
109 this->state_.AGCTEST = 0x3F;
110 this->state_.TEST2 = 0x88;
111 this->state_.TEST1 = 0x31;
112 this->state_.TEST0_LO = 1;
113 this->state_.VCO_SEL_CAL_EN = 1;
114 this->state_.TEST0_HI = 2;
115
116 // PKTCTRL0
117 this->state_.PKT_FORMAT = 3;
118 this->state_.LENGTH_CONFIG = 2;
119 this->state_.FS_AUTOCAL = 1;
120
121 // CRITICAL: Initialize PA Table to avoid transmitting 0 power (Silence)
122 memset(this->pa_table_, 0, sizeof(this->pa_table_));
123}
124
126 this->spi_setup();
127
128 if (this->gdo0_pin_ != nullptr) {
129 this->gdo0_pin_->setup();
130 }
131
132 this->configure();
133 if (this->is_failed()) {
134 return;
135 }
136
137 // Defer pin mode setup until after all components have completed setup()
138 // This handles the case where remote_transmitter runs after CC1101 and changes pin mode
139 if (this->gdo0_pin_ != nullptr) {
140 this->defer([this]() {
142 if (this->state_.PKT_FORMAT == static_cast<uint8_t>(PacketFormat::PACKET_FORMAT_FIFO)) {
144 }
145 });
146 }
147}
148
150 // Manual reset sequence per CC1101 datasheet section 19.1.2
151 this->cs_->digital_write(true);
153 this->cs_->digital_write(false);
155 this->cs_->digital_write(true);
157 this->cs_->digital_write(false);
158 delay(5);
159
160 this->strobe_(Command::RES);
161 delay(5);
162
165 this->chip_id_ = encode_uint16(this->state_.PARTNUM, this->state_.VERSION);
166 ESP_LOGD(TAG, "CC1101 found! Chip ID: 0x%04X", this->chip_id_);
167 if (this->state_.VERSION == 0 || this->state_.PARTNUM == 0xFF) {
168 ESP_LOGE(TAG, "Failed to verify CC1101.");
169 this->mark_failed();
170 return;
171 }
172
173 this->initialized_ = true;
174 this->sleeping_ = false;
175
176 this->write_registers_();
178
179 if (!this->enter_rx_()) {
180 this->mark_failed();
181 return;
182 }
183}
184
186 for (uint8_t i = 0; i <= static_cast<uint8_t>(Register::TEST0); i++) {
187 if (i == static_cast<uint8_t>(Register::FSTEST) || i == static_cast<uint8_t>(Register::AGCTEST)) {
188 continue;
189 }
190 this->write_(static_cast<Register>(i));
191 }
192 this->registers_dirty_ = false;
193}
194
195void CC1101Component::call_listeners_(const std::vector<uint8_t> &packet, float freq_offset, float rssi, uint8_t lqi) {
196 for (auto &listener : this->listeners_) {
197 listener->on_packet(packet, freq_offset, rssi, lqi);
198 }
199 this->packet_trigger_.trigger(packet, freq_offset, rssi, lqi);
200}
201
203 return (((256.0f + this->state_.DRATE_M) * (1 << this->state_.DRATE_E)) / (1 << 28)) * XTAL_FREQUENCY;
204}
205
206#ifdef USE_CC1101_LONG_PACKET
208 return this->packet_mode_ && (this->packet_length_ > RX_FIFO_SIZE || this->packet_length_func_ != nullptr);
209}
210
212 // Over 255 bytes or unknown starts in infinite mode (datasheet section 15.2.2). PKTLEN must not be 0, so a
213 // multiple of 256 stays in infinite mode and ends on the MCU byte count alone.
215 this->state_.LENGTH_CONFIG = static_cast<uint8_t>(length > 0 && length < 256 ? LengthConfig::LENGTH_CONFIG_FIXED
217 this->state_.PKTLEN = length % 256 == 0 ? 0xFF : static_cast<uint8_t>(length % 256);
218}
219
221 this->packet_.clear();
222 this->packet_last_byte_ms_ = 0;
223 this->high_freq_.stop();
224 this->arm_length_(this->packet_length_func_ != nullptr ? 0 : this->packet_length_);
225}
226
228 this->enter_idle_();
229 this->enter_rx_();
230 this->disable_loop();
231}
232
234 const uint16_t expected = this->packet_expected_length_;
235 if (this->state_.LENGTH_CONFIG == static_cast<uint8_t>(LengthConfig::LENGTH_CONFIG_FIXED) || expected == 0 ||
236 expected % 256 == 0) {
237 return;
238 }
239 const uint16_t received = this->packet_.size();
240 if (expected - received >= 256) {
241 return;
242 }
243 // PKTLEN keeps the (length % 256) set at the start, as in TI Design Note DN500 section 2.3
244 this->state_.LENGTH_CONFIG = static_cast<uint8_t>(LengthConfig::LENGTH_CONFIG_FIXED);
246 ESP_LOGVV(TAG, "Switched long packet RX to fixed mode: received=%u expected=%u pktlen=%u", received, expected,
247 this->state_.PKTLEN);
248}
249
251 this->packet_.resize(this->packet_expected_length_);
253 this->read_(Register::LQI);
254 const float freq_offset = freq_offset_hz(this->state_.FREQEST);
255 const uint8_t lqi = this->state_.LQI & STATUS_LQI_MASK;
256 // No CRC check: crc_enable is rejected for long packets, CRC_OK is only set after the last payload byte.
257 // Restart RX before dispatching so a callback may change settings; swapping back keeps the reserved capacity
258 // unless a callback reserved a larger buffer.
259 std::vector<uint8_t> packet;
260 packet.swap(this->packet_);
262 this->call_listeners_(packet, freq_offset, rssi_dbm(this->long_packet_rssi_), lqi);
263 if (packet.capacity() > this->packet_.capacity()) {
264 packet.clear();
265 this->packet_.swap(packet);
266 }
267}
268
270 // Leave one byte in the FIFO unless it holds the rest of the packet (datasheet section 20)
271 uint16_t to_read = rx_bytes > 0 ? rx_bytes - 1 : 0;
272 if (this->packet_expected_length_ > 0) {
273 const uint16_t remaining = this->packet_expected_length_ - this->packet_.size();
274 if (remaining <= rx_bytes) {
275 to_read = remaining;
276 }
277 }
278
279 if (to_read == 0) {
280 if (this->packet_.empty()) {
281 return;
282 }
283 // Discard a packet when no byte arrived for the air time of PACKET_IDLE_TIMEOUT_BYTES
284 const uint32_t timeout_ms =
285 std::max(static_cast<uint32_t>(std::ceil((8.0f * PACKET_IDLE_TIMEOUT_BYTES * 1000.0f) / this->symbol_rate_())),
286 PACKET_IDLE_TIMEOUT_MIN_MS);
287 if (App.get_loop_component_start_time() - this->packet_last_byte_ms_ > timeout_ms) {
288 ESP_LOGW(TAG, "Packet receive timeout, discarding packet: received=%u expected=%u fifo=%u",
289 static_cast<uint16_t>(this->packet_.size()), this->packet_expected_length_, rx_bytes);
291 }
292 return;
293 }
294
295 const size_t old_size = this->packet_.size();
296 if (old_size == 0) {
297 // The RSSI register follows the live signal; sample it while the packet is still on air
298 this->read_(Register::RSSI);
299 this->long_packet_rssi_ = this->state_.RSSI;
300 // The FIFO threshold signal does not fire for the bytes after the last threshold crossing; poll until done
301 this->high_freq_.start();
302 }
303 // Read through an aligned buffer: for an unaligned target the ESP32 SPI driver allocates a bounce buffer
304 alignas(4) uint8_t staged[RX_FIFO_SIZE];
305 this->read_(Register::FIFO, staged, to_read);
306 this->packet_.resize(old_size + to_read);
307 std::memcpy(this->packet_.data() + old_size, staged, to_read);
309 ESP_LOGVV(TAG, "Drained RX FIFO: read=%u received=%u expected=%u fifo=%u", to_read,
310 static_cast<uint16_t>(this->packet_.size()), this->packet_expected_length_, rx_bytes);
311
312 if (this->packet_expected_length_ == 0 && this->packet_length_func_ != nullptr) {
313 const int32_t length = this->packet_length_func_(this->packet_);
314 if (length < 0) {
315 ESP_LOGVV(TAG, "Packet length lambda discarded packet: received=%u", static_cast<uint16_t>(this->packet_.size()));
317 return;
318 }
319 if (length > MAX_PACKET_LENGTH) {
320 ESP_LOGW(TAG, "Packet length exceeds maximum, discarding packet: length=%" PRId32 " max=%u", length,
321 MAX_PACKET_LENGTH);
323 return;
324 }
325 if (length > 0) {
326 this->arm_length_(static_cast<uint16_t>(length));
327 // A packet shorter than the first FIFO drain is already complete; finish_long_packet_() truncates it
329 this->finish_long_packet_();
330 return;
331 }
334 ESP_LOGVV(TAG, "Resolved packet length: received=%u expected=%u pktlen=%u",
335 static_cast<uint16_t>(this->packet_.size()), this->packet_expected_length_, this->state_.PKTLEN);
336 }
337 }
338
339 // Only reachable while the length is still unknown; a known length caps every read
340 if (this->packet_.size() > MAX_PACKET_LENGTH) {
341 ESP_LOGW(TAG, "Packet length exceeds maximum, discarding packet: length=%u max=%u",
342 static_cast<uint16_t>(this->packet_.size()), MAX_PACKET_LENGTH);
344 return;
345 }
346
348
349 if (this->packet_expected_length_ > 0 && this->packet_.size() >= this->packet_expected_length_) {
350 this->finish_long_packet_();
351 }
352}
353
355 if (this->sleeping_ || this->state_.PKT_FORMAT != static_cast<uint8_t>(PacketFormat::PACKET_FORMAT_FIFO) ||
356 this->gdo0_pin_ == nullptr) {
357 this->high_freq_.stop();
358 this->disable_loop();
359 return;
360 }
361 // While GDO0 (RX FIFO threshold) is high, the FIFO holds at least RX_FIFO_THRESHOLD bytes, so drain without
362 // reading RXBYTES. At high data rates RXBYTES changes between two reads, so waiting for two reads that agree
363 // and retrying on the next loop pass lets the FIFO overflow. MARCSTATE does not change during RX.
364 for (uint8_t i = 0; i < RX_FIFO_SIZE / RX_FIFO_THRESHOLD + 2 && this->gdo0_pin_->digital_read(); i++) {
366 if (static_cast<State>(this->state_.MARC_STATE) == State::RXFIFO_OVERFLOW) {
367 ESP_LOGW(TAG, "RX FIFO overflow, discarding packet: received=%u expected=%u",
368 static_cast<uint16_t>(this->packet_.size()), this->packet_expected_length_);
370 return;
371 }
372 this->handle_long_packet_(RX_FIFO_THRESHOLD);
373 if (this->packet_.empty()) {
374 return; // finished or discarded
375 }
376 }
377 // Below the threshold the next crossing raises GDO0 again, and after the packet the count no longer changes,
378 // so retrying on the next loop pass is safe here. RXBYTES can be misread while bytes arrive (TI SWRZ020), so
379 // only trust two consecutive reads that agree.
381 uint8_t rx_bytes = this->state_.RXBYTES;
382 bool stable = false;
383 for (uint8_t retries = RXBYTES_STABLE_RETRIES; retries > 0 && !stable; retries--) {
384 const uint8_t previous = rx_bytes;
386 rx_bytes = this->state_.RXBYTES;
387 stable = rx_bytes == previous;
388 }
389 if (!stable) {
390 return;
391 }
392 rx_bytes = this->state_.NUM_RXBYTES;
393 // More than the FIFO holds can only be a misread; the staged drain buffer is FIFO sized
394 if (this->state_.RXFIFO_OVERFLOW || rx_bytes > RX_FIFO_SIZE) {
395 ESP_LOGW(TAG, "RX FIFO overflow, discarding packet: received=%u expected=%u fifo=%u",
396 static_cast<uint16_t>(this->packet_.size()), this->packet_expected_length_, rx_bytes);
398 return;
399 }
400 if (rx_bytes == 0 && this->packet_.empty() && !this->gdo0_pin_->digital_read()) {
401 this->disable_loop();
402 return;
403 }
404 this->handle_long_packet_(rx_bytes);
405}
406#endif
407
409#ifdef USE_CC1101_LONG_PACKET
410 if (this->is_long_packet_mode_()) {
411 this->loop_long_packet_();
412 return;
413 }
414#endif
415
416 this->disable_loop();
417 if (this->sleeping_ || this->state_.PKT_FORMAT != static_cast<uint8_t>(PacketFormat::PACKET_FORMAT_FIFO) ||
418 this->gdo0_pin_ == nullptr || !this->gdo0_pin_->digital_read()) {
419 return;
420 }
421
422 // Read state
424 uint8_t rx_bytes = this->state_.NUM_RXBYTES;
425 bool overflow = this->state_.RXFIFO_OVERFLOW;
426 if (overflow || rx_bytes == 0) {
427 ESP_LOGW(TAG, "RX FIFO overflow, flushing");
428 this->enter_idle_();
429 this->strobe_(Command::FRX);
430 this->enter_rx_();
431 return;
432 }
433 // GDO0 also rises when the FIFO fills, which for a 64 byte packet is before the CRC has arrived
434 if (rx_bytes == RX_FIFO_SIZE) {
436 if (static_cast<State>(this->state_.MARC_STATE) == State::RX) {
437 this->enable_loop();
438 return;
439 }
440 }
441
442 // Read packet
443 uint8_t payload_length, expected_rx;
444 if (this->state_.LENGTH_CONFIG == static_cast<uint8_t>(LengthConfig::LENGTH_CONFIG_VARIABLE)) {
445 this->read_(Register::FIFO, &payload_length, 1);
446 expected_rx = payload_length + 1;
447 } else {
448 payload_length = this->state_.PKTLEN;
449 expected_rx = payload_length;
450 }
451 if (payload_length == 0 || payload_length > RX_FIFO_SIZE || rx_bytes != expected_rx) {
452 ESP_LOGW(TAG, "Invalid packet: rx_bytes %u, payload_length %u", rx_bytes, payload_length);
453 this->enter_idle_();
454 this->strobe_(Command::FRX);
455 this->enter_rx_();
456 return;
457 }
458 this->packet_.resize(payload_length);
459 this->read_(Register::FIFO, this->packet_.data(), payload_length);
460
461 // Read status from registers (more reliable than FIFO status bytes due to timing issues)
463 this->read_(Register::RSSI);
464 this->read_(Register::LQI);
465 float freq_offset = freq_offset_hz(this->state_.FREQEST);
466 float rssi = rssi_dbm(this->state_.RSSI);
467 bool crc_ok = (this->state_.LQI & STATUS_CRC_OK_MASK) != 0;
468 uint8_t lqi = this->state_.LQI & STATUS_LQI_MASK;
469 if (this->state_.CRC_EN == 0 || crc_ok) {
470 this->call_listeners_(this->packet_, freq_offset, rssi, lqi);
471 }
472 // A listener may have powered the radio down
473 if (this->sleeping_) {
474 return;
475 }
476
477 // Return to rx
478 this->enter_idle_();
479 this->strobe_(Command::FRX);
480 this->enter_rx_();
481}
482
484 int32_t freq = static_cast<int32_t>(this->state_.FREQ2 << 16 | this->state_.FREQ1 << 8 | this->state_.FREQ0) *
485 XTAL_FREQUENCY / (1 << 16);
486 float symbol_rate = this->symbol_rate_();
487 float bw = XTAL_FREQUENCY / (8.0f * (4 + this->state_.CHANBW_M) * (1 << this->state_.CHANBW_E));
488 ESP_LOGCONFIG(TAG,
489 "CC1101:\n"
490 " Chip ID: 0x%04X\n"
491 " Frequency: %" PRId32 " Hz\n"
492 " Channel: %u\n"
493 " Modulation: %s\n"
494 " Symbol Rate: %.0f baud\n"
495 " Filter Bandwidth: %.1f Hz\n"
496 " Output Power: %.1f dBm",
497 this->chip_id_, freq, this->state_.CHANNR,
498 LOG_STR_ARG(ModulationStrings::get_log_str(this->state_.MOD_FORMAT & 0x07, 0)), symbol_rate, bw,
499 this->output_power_effective_);
500 LOG_PIN(" CS Pin: ", this->cs_);
501 LOG_PIN(" GDO0 Pin: ", this->gdo0_pin_);
502
503 if (this->packet_mode_) {
504#ifdef USE_CC1101_LONG_PACKET
505 if (this->packet_length_func_ != nullptr) {
506 ESP_LOGCONFIG(TAG, " Packet Length: lambda");
507 } else
508#endif
509 if (this->packet_length_ == 0) {
510 ESP_LOGCONFIG(TAG, " Packet Length: variable");
511 } else {
512 ESP_LOGCONFIG(TAG, " Packet Length: %u", this->packet_length_);
513 }
514 }
515}
516
518 if (this->state_.PKT_FORMAT == static_cast<uint8_t>(PacketFormat::PACKET_FORMAT_FIFO)) {
519 ESP_LOGW(TAG, "begin_tx is for async serial mode; use send_packet in packet mode");
520 return;
521 }
522 ESP_LOGV(TAG, "Beginning TX sequence");
523 if (this->gdo0_pin_ != nullptr) {
525 }
526 // Transition through IDLE to bypass CCA (Clear Channel Assessment) which can
527 // block TX entry when strobing from RX, and to ensure FS_AUTOCAL calibration
528 this->enter_idle_();
529 if (!this->enter_tx_()) {
530 ESP_LOGW(TAG, "Failed to enter TX state!");
531 }
532}
533
535 ESP_LOGV(TAG, "Beginning RX sequence");
536 if (this->gdo0_pin_ != nullptr) {
538 }
539 // Transition through IDLE to ensure FS_AUTOCAL calibration occurs
540 this->enter_idle_();
541 if (!this->enter_rx_()) {
542 ESP_LOGW(TAG, "Failed to enter RX state!");
543 }
544}
545
547 this->strobe_(Command::RES);
548 this->configure();
549}
550
552 ESP_LOGV(TAG, "Setting IDLE state");
553 this->enter_idle_();
554#ifdef USE_CC1101_LONG_PACKET
555 if (this->is_long_packet_mode_()) {
556 // Drop a partial packet so a pending loop pass cannot finish it and re-enter RX
557 this->strobe_(Command::FRX);
558 this->reset_long_packet_rx_();
559 this->disable_loop();
560 }
561#endif
562}
563
565 if (this->sleeping_) {
566 return;
567 }
568 this->enter_idle_();
569 ESP_LOGV(TAG, "Entering SLEEP state");
570 this->strobe_(Command::PWD);
571 this->sleeping_ = true;
572}
573
575 if (!this->sleeping_) {
576 return;
577 }
578 this->sleeping_ = false;
579 ESP_LOGV(TAG, "Waking up from SLEEP");
580 this->enable();
581 delayMicroseconds(WAKEUP_DELAY_US);
582 this->disable();
583 this->enter_idle_();
584 // sync register writes that were skipped while asleep
585 // TEST2 to TEST0 and PATABLE entries 1-7 are always lost
586 if (this->registers_dirty_) {
587 this->write_registers_();
588 } else {
589 this->write_(Register::TEST2);
590 this->write_(Register::TEST1);
591 this->write_(Register::TEST0);
592 }
593 this->write_(Register::PATABLE, this->pa_table_, sizeof(this->pa_table_));
594}
595
596bool CC1101Component::wait_for_state_(State target_state, uint32_t timeout_ms) {
597 uint32_t start = millis();
598 while (millis() - start < timeout_ms) {
600 State s = static_cast<State>(this->state_.MARC_STATE);
601 if (s == target_state) {
602 return true;
603 }
605 }
606 return false;
607}
608
610 // The PLL must be recalibrated until PLL lock is achieved
611 for (uint8_t retries = PLL_LOCK_RETRIES; retries > 0; retries--) {
612 this->strobe_(cmd);
613 if (!this->wait_for_state_(target_state)) {
614 return false;
615 }
616 this->read_(Register::FSCAL1);
617 if (this->state_.FSCAL1 != FSCAL1_PLL_NOT_LOCKED) {
618 return true;
619 }
620 ESP_LOGW(TAG, "PLL lock failed, retrying calibration");
621 this->enter_idle_();
622 }
623 ESP_LOGE(TAG, "PLL lock failed after retries");
624 return false;
625}
626
628 if (this->sleeping_) {
629 // wake_up() ends in IDLE
630 this->wake_up();
631 return;
632 }
633 this->strobe_(Command::IDLE);
634 if (!this->wait_for_state_(State::IDLE)) {
635 ESP_LOGW(TAG, "Failed to enter IDLE state");
636 }
637}
638
640#ifdef USE_CC1101_LONG_PACKET
641 if (this->is_long_packet_mode_()) {
642 // Every RX entry starts a fresh long packet; callers leave the chip in IDLE, where SFRX is allowed
643 this->strobe_(Command::FRX);
644 this->reset_long_packet_rx_();
647 }
648#endif
650}
651
653
655 uint8_t index = static_cast<uint8_t>(cmd);
656 if (cmd < Command::RES || cmd > Command::NOP) {
657 return 0xFF;
658 }
659 this->enable();
660 uint8_t status_byte = this->transfer_byte(index);
661 this->disable();
662 return status_byte;
663}
664
666 if (this->sleeping_) {
667 this->registers_dirty_ = true;
668 return; // wake_up() writes state_ to the chip
669 }
670 uint8_t index = static_cast<uint8_t>(reg);
671 this->write_register(index, this->state_.regs()[index]);
672}
673
675 uint8_t index = static_cast<uint8_t>(reg);
676 this->state_.regs()[index] = value;
677 this->write_(reg);
678}
679
680void CC1101Component::write_(Register reg, const uint8_t *buffer, size_t length) {
681 if (this->sleeping_) {
682 this->registers_dirty_ = true;
683 return;
684 }
685 uint8_t index = static_cast<uint8_t>(reg);
686 this->write_registers(index | BUS_WRITE | BUS_BURST, buffer, length);
687}
688
690 uint8_t index = static_cast<uint8_t>(reg);
691 this->state_.regs()[index] = this->read_register(index | BUS_READ | BUS_BURST);
692}
693
694void CC1101Component::read_(Register reg, uint8_t *buffer, size_t length) {
695 uint8_t index = static_cast<uint8_t>(reg);
696 this->read_registers(index | BUS_READ | BUS_BURST, buffer, length);
697}
698
700 if (this->state_.PKT_FORMAT != static_cast<uint8_t>(PacketFormat::PACKET_FORMAT_FIFO)) {
701 ESP_LOGW(TAG, "Cannot transmit packet: packet mode is not FIFO");
702 return CC1101Error::PARAMS;
703 }
704#ifdef USE_CC1101_LONG_PACKET
705 // Long packet TX needs chunked FIFO refills and is not implemented
706 if (this->is_long_packet_mode_()) {
707 ESP_LOGW(TAG, "Cannot transmit packet: long packet mode is RX-only");
708 return CC1101Error::PARAMS;
709 }
710#endif
711 const bool variable = this->state_.LENGTH_CONFIG == static_cast<uint8_t>(LengthConfig::LENGTH_CONFIG_VARIABLE);
712 // In variable length mode the FIFO also holds the length byte
713 if (len + (variable ? 1 : 0) > TX_FIFO_SIZE) {
714 ESP_LOGW(TAG,
715 "Cannot transmit packet: long packet TX is not implemented, payload length %u exceeds TX FIFO limit %u",
716 static_cast<unsigned>(len), static_cast<unsigned>(TX_FIFO_SIZE));
717 return CC1101Error::PARAMS;
718 }
719
720 // Write packet
721 this->enter_idle_();
722 this->strobe_(Command::FTX);
723 if (variable) {
724 this->write_(Register::FIFO, static_cast<uint8_t>(len));
725 }
726#ifdef USE_ESP32
727 // SPI DMA cannot read flash or unaligned buffers; stage them here so the driver does not allocate a copy
728 alignas(4) uint8_t staged[TX_FIFO_SIZE];
729 if (len != 0 && (!esp_ptr_dma_capable(data) || (reinterpret_cast<uintptr_t>(data) & 3) != 0)) {
730 std::memcpy(staged, data, len);
731 data = staged;
732 }
733#endif
734 this->write_(Register::FIFO, data, len);
735
736 // Calibrate PLL
738 ESP_LOGW(TAG, "PLL lock failed during TX");
739 this->enter_idle_();
740 this->enter_rx_();
742 }
743
744 // Transmit packet
745 this->strobe_(Command::TX);
746 if (!this->wait_for_state_(State::IDLE, 1000)) {
747 ESP_LOGW(TAG, "TX timeout");
748 this->enter_idle_();
749 this->enter_rx_();
751 }
752
753 // Return to rx
754 this->enter_rx_();
755 return CC1101Error::NONE;
756}
757
758// Setters
761 int32_t freq = static_cast<int32_t>(this->state_.FREQ2 << 16 | this->state_.FREQ1 << 8 | this->state_.FREQ0) *
762 XTAL_FREQUENCY / (1 << 16);
763 uint8_t a = 0xC0;
764 if (freq >= 300000000 && freq <= 348000000) {
765 a = PowerTableItem::find(PA_TABLE_315, sizeof(PA_TABLE_315) / sizeof(PA_TABLE_315[0]), value);
766 } else if (freq >= 378000000 && freq <= 464000000) {
767 a = PowerTableItem::find(PA_TABLE_433, sizeof(PA_TABLE_433) / sizeof(PA_TABLE_433[0]), value);
768 } else if (freq >= 779000000 && freq < 900000000) {
769 a = PowerTableItem::find(PA_TABLE_868, sizeof(PA_TABLE_868) / sizeof(PA_TABLE_868[0]), value);
770 } else if (freq >= 900000000 && freq <= 928000000) {
771 a = PowerTableItem::find(PA_TABLE_915, sizeof(PA_TABLE_915) / sizeof(PA_TABLE_915[0]), value);
772 }
773
774 if (static_cast<Modulation>(this->state_.MOD_FORMAT) == Modulation::MODULATION_ASK_OOK) {
775 this->pa_table_[0] = 0;
776 this->pa_table_[1] = a;
777 } else {
778 this->pa_table_[0] = a;
779 this->pa_table_[1] = 0;
780 }
782 if (this->initialized_) {
783 this->write_(Register::PATABLE, this->pa_table_, sizeof(this->pa_table_));
784 }
785}
786
788 this->state_.CLOSE_IN_RX = static_cast<uint8_t>(value);
789 if (this->initialized_) {
791 }
792}
793
795 this->state_.DEM_DCFILT_OFF = value ? 0 : 1;
796 if (this->initialized_) {
798 }
799}
800
802 int32_t freq = static_cast<int32_t>(value * (1 << 16) / XTAL_FREQUENCY);
803 this->state_.FREQ2 = static_cast<uint8_t>(freq >> 16);
804 this->state_.FREQ1 = static_cast<uint8_t>(freq >> 8);
805 this->state_.FREQ0 = static_cast<uint8_t>(freq);
806 if (this->initialized_) {
807 // While asleep the writes wait for wake_up() and the radio stays asleep
808 const bool awake = !this->sleeping_;
809 if (awake)
810 this->enter_idle_();
811 this->write_(Register::FREQ2);
812 this->write_(Register::FREQ1);
813 this->write_(Register::FREQ0);
814 if (awake)
815 this->enter_rx_();
816 }
817}
818
820 this->state_.FREQ_IF = value * (1 << 10) / XTAL_FREQUENCY;
821 if (this->initialized_) {
823 }
824}
825
827 uint8_t e;
828 uint32_t m;
829 split_float(XTAL_FREQUENCY / (value * 8), 2, e, m);
830 this->state_.CHANBW_E = e;
831 this->state_.CHANBW_M = static_cast<uint8_t>(m);
832 if (this->initialized_) {
834 }
835}
836
838 this->state_.CHANNR = value;
839 if (this->initialized_) {
840 const bool awake = !this->sleeping_;
841 if (awake)
842 this->enter_idle_();
844 if (awake)
845 this->enter_rx_();
846 }
847}
848
850 uint8_t e;
851 uint32_t m;
852 split_float(value * (1 << 18) / XTAL_FREQUENCY, 8, e, m);
853 this->state_.CHANSPC_E = e;
854 this->state_.CHANSPC_M = static_cast<uint8_t>(m);
855 if (this->initialized_) {
858 }
859}
860
862 uint8_t e;
863 uint32_t m;
864 split_float(value * (1 << 17) / XTAL_FREQUENCY, 3, e, m);
865 this->state_.DEVIATION_E = e;
866 this->state_.DEVIATION_M = static_cast<uint8_t>(m);
867 if (this->initialized_) {
869 }
870}
871
873 this->state_.DEVIATION_E = 0;
874 this->state_.DEVIATION_M = value - 1;
875 if (this->initialized_) {
877 }
878}
879
881 uint8_t e;
882 uint32_t m;
883 split_float(value * (1 << 28) / XTAL_FREQUENCY, 8, e, m);
884 this->state_.DRATE_E = e;
885 this->state_.DRATE_M = static_cast<uint8_t>(m);
886 if (this->initialized_) {
889 }
890}
891
893 this->state_.SYNC_MODE = static_cast<uint8_t>(value);
894 if (this->initialized_) {
896 }
897}
898
900 this->state_.CARRIER_SENSE_ABOVE_THRESHOLD = value ? 1 : 0;
901 if (this->initialized_) {
903 }
904}
905
907 this->state_.MOD_FORMAT = static_cast<uint8_t>(value);
908 this->state_.PA_POWER = value == Modulation::MODULATION_ASK_OOK ? 1 : 0;
909 if (this->initialized_) {
910 const bool awake = !this->sleeping_;
911 if (awake)
912 this->enter_idle_();
916 if (awake)
917 this->enter_rx_();
918 }
919}
920
922 this->state_.MANCHESTER_EN = value ? 1 : 0;
923 if (this->initialized_) {
925 }
926}
927
929 this->state_.NUM_PREAMBLE = value;
930 if (this->initialized_) {
932 }
933}
934
936 this->state_.SYNC1 = value;
937 if (this->initialized_) {
938 this->write_(Register::SYNC1);
939 }
940}
941
943 this->state_.SYNC0 = value;
944 if (this->initialized_) {
945 this->write_(Register::SYNC0);
946 }
947}
948
950 this->state_.MAGN_TARGET = static_cast<uint8_t>(value);
951 if (this->initialized_) {
953 }
954}
955
957 this->state_.MAX_LNA_GAIN = static_cast<uint8_t>(value);
958 if (this->initialized_) {
960 }
961}
962
964 this->state_.MAX_DVGA_GAIN = static_cast<uint8_t>(value);
965 if (this->initialized_) {
967 }
968}
969
971 this->state_.CARRIER_SENSE_ABS_THR = static_cast<uint8_t>(value & 0b1111);
972 if (this->initialized_) {
974 }
975}
976
978 this->state_.CARRIER_SENSE_REL_THR = static_cast<uint8_t>(value);
979 if (this->initialized_) {
981 }
982}
983
985 this->state_.AGC_LNA_PRIORITY = value ? 1 : 0;
986 if (this->initialized_) {
988 }
989}
990
992 this->state_.FILTER_LENGTH = static_cast<uint8_t>(value);
993 if (this->initialized_) {
995 }
996}
997
999 this->state_.FILTER_LENGTH = static_cast<uint8_t>(value);
1000 if (this->initialized_) {
1002 }
1003}
1004
1006 this->state_.AGC_FREEZE = static_cast<uint8_t>(value);
1007 if (this->initialized_) {
1009 }
1010}
1011
1013 this->state_.WAIT_TIME = static_cast<uint8_t>(value);
1014 if (this->initialized_) {
1016 }
1017}
1018
1020 this->state_.HYST_LEVEL = static_cast<uint8_t>(value);
1021 if (this->initialized_) {
1023 }
1024}
1025
1027 this->state_.FOC_BS_CS_GATE = value ? 1 : 0;
1028 if (this->initialized_) {
1029 this->write_(Register::FOCCFG);
1030 }
1031}
1032
1034 this->state_.FOC_LIMIT = static_cast<uint8_t>(value);
1035 if (this->initialized_) {
1036 this->write_(Register::FOCCFG);
1037 }
1038}
1039
1041 this->state_.FOC_PRE_K = static_cast<uint8_t>(value);
1042 if (this->initialized_) {
1043 this->write_(Register::FOCCFG);
1044 }
1045}
1046
1048 this->state_.FOC_POST_K = static_cast<uint8_t>(value);
1049 if (this->initialized_) {
1050 this->write_(Register::FOCCFG);
1051 }
1052}
1053
1055 this->state_.BS_LIMIT = static_cast<uint8_t>(value);
1056 if (this->initialized_) {
1057 this->write_(Register::BSCFG);
1058 }
1059}
1060
1062 this->state_.BS_PRE_KI = static_cast<uint8_t>(value);
1063 if (this->initialized_) {
1064 this->write_(Register::BSCFG);
1065 }
1066}
1067
1069 this->state_.BS_PRE_KP = static_cast<uint8_t>(value);
1070 if (this->initialized_) {
1071 this->write_(Register::BSCFG);
1072 }
1073}
1074
1076 this->state_.BS_POST_KI = static_cast<uint8_t>(value);
1077 if (this->initialized_) {
1078 this->write_(Register::BSCFG);
1079 }
1080}
1081
1083 this->state_.BS_POST_KP = static_cast<uint8_t>(value);
1084 if (this->initialized_) {
1085 this->write_(Register::BSCFG);
1086 }
1087}
1088
1090#ifdef USE_CC1101_LONG_PACKET
1091 // Ends a long reception in progress, also when switching to a short packet mode
1092 this->high_freq_.stop();
1093 this->packet_.clear();
1094#endif
1095 if (!this->packet_mode_) {
1096 this->state_.PKT_FORMAT = static_cast<uint8_t>(PacketFormat::PACKET_FORMAT_ASYNC_SERIAL);
1097 this->state_.GDO0_CFG = 0x0D;
1098 } else {
1099 this->state_.PKT_FORMAT = static_cast<uint8_t>(PacketFormat::PACKET_FORMAT_FIFO);
1100 this->state_.APPEND_STATUS = 0;
1101#ifdef USE_CC1101_LONG_PACKET
1102 if (this->is_long_packet_mode_()) {
1103 // Threshold-only signal, reasserts after each partial FIFO drain
1104 this->state_.GDO0_CFG = 0x00;
1105 this->state_.FIFO_THR = 7;
1106 // Reserve once so receiving never allocates; a lambda may read one FIFO drain past MAX_PACKET_LENGTH
1107 this->packet_.reserve(this->packet_length_func_ != nullptr ? MAX_PACKET_LENGTH + RX_FIFO_SIZE
1108 : this->packet_length_);
1109 this->reset_long_packet_rx_();
1110 } else
1111#endif
1112 {
1113 this->state_.GDO0_CFG = 0x01;
1114 this->state_.FIFO_THR = 15;
1115 if (this->packet_length_ == 0) {
1116 this->state_.LENGTH_CONFIG = static_cast<uint8_t>(LengthConfig::LENGTH_CONFIG_VARIABLE);
1117 } else {
1118 this->state_.LENGTH_CONFIG = static_cast<uint8_t>(LengthConfig::LENGTH_CONFIG_FIXED);
1119 this->state_.PKTLEN = static_cast<uint8_t>(this->packet_length_);
1120 }
1121 }
1122 }
1123
1124 if (this->initialized_) {
1127 this->write_(Register::PKTLEN);
1128 this->write_(Register::IOCFG0);
1130 }
1131}
1132
1134 this->packet_mode_ = value;
1135#ifdef USE_CC1101_LONG_PACKET
1136 // Long packet RX must drop the FIFO along with a partial packet, so go through IDLE and restart RX
1137 if (this->initialized_ && this->is_long_packet_mode_()) {
1139 } else
1140#endif
1141 {
1142 this->configure_packet_mode_();
1143 }
1144 if (this->initialized_) {
1145 if (this->gdo0_pin_ != nullptr) {
1146 if (value) {
1148 } else {
1149 this->gdo0_pin_->detach_interrupt();
1150 }
1151 }
1152 }
1153}
1154
1156#ifndef USE_CC1101_LONG_PACKET
1157 if (value > RX_FIFO_SIZE) {
1158 ESP_LOGW(TAG, "Packet length %u needs a configured packet_length above %u", value,
1159 static_cast<unsigned>(RX_FIFO_SIZE));
1160 return;
1161 }
1162#else
1163 this->packet_length_func_ = nullptr;
1164#endif
1165 this->packet_length_ = value;
1167}
1168
1169#ifdef USE_CC1101_LONG_PACKET
1174#endif
1175
1177 // While asleep the writes wait for wake_up() and the radio stays asleep, like set_frequency()
1178 if (!this->initialized_ || this->sleeping_) {
1179 this->configure_packet_mode_();
1180 return;
1181 }
1182 // Like the other runtime setters: go through IDLE, and flush bytes of a reception in progress
1183 this->enter_idle_();
1184 this->strobe_(Command::FRX);
1185 this->configure_packet_mode_();
1186 this->enter_rx_();
1187}
1188
1190 this->state_.CRC_EN = value ? 1 : 0;
1191 if (this->initialized_) {
1193 }
1194}
1195
1197 this->state_.WHITE_DATA = value ? 1 : 0;
1198 if (this->initialized_) {
1200 }
1201}
1202
1203} // namespace esphome::cc1101
uint8_t m
Definition bl0906.h:1
uint32_t IRAM_ATTR HOT get_loop_component_start_time() const
Get the cached time in milliseconds from when the current component started its loop execution.
void mark_failed()
Mark this component as failed.
bool is_failed() const
Definition component.h:288
void defer(const char *name, SchedulerCallback &&f)
Defer a callback to the next loop() call with a const char* name.
void enable_loop()
Enable this component's loop.
Definition component.h:262
void disable_loop()
Disable this component's loop.
virtual void digital_write(bool value)=0
void stop()
Stop running the loop continuously.
Definition helpers.h:2608
void start()
Start running the loop continuously.
Definition helpers.h:2606
void trigger(const Ts &...x) ESPHOME_ALWAYS_INLINE
Inform the parent automation that the event has triggered.
Definition automation.h:588
void set_bs_post_kp(BsPostKp value)
Definition cc1101.cpp:1082
void set_packet_mode(bool value)
Definition cc1101.cpp:1133
void set_max_dvga_gain(MaxDvgaGain value)
Definition cc1101.cpp:963
void set_carrier_sense_above_threshold(bool value)
Definition cc1101.cpp:899
void write_(Register reg)
Definition cc1101.cpp:665
void set_sync0(uint8_t value)
Definition cc1101.cpp:942
void set_freeze(Freeze value)
Definition cc1101.cpp:1005
packet_length_func_t packet_length_func_
Definition cc1101.h:141
void call_listeners_(const std::vector< uint8_t > &packet, float freq_offset, float rssi, uint8_t lqi)
Definition cc1101.cpp:195
void set_rx_attenuation(RxAttenuation value)
Definition cc1101.cpp:787
InternalGPIOPin * gdo0_pin_
Definition cc1101.h:120
void set_symbol_rate(float value)
Definition cc1101.cpp:880
void set_packet_length_lambda(packet_length_func_t func)
Definition cc1101.cpp:1170
void set_bs_pre_ki(BsPreKi value)
Definition cc1101.cpp:1061
uint8_t strobe_(Command cmd)
Definition cc1101.cpp:654
void set_sync_mode(SyncMode value)
Definition cc1101.cpp:892
void set_fsk_deviation(float value)
Definition cc1101.cpp:861
void set_bs_pre_kp(BsPreKp value)
Definition cc1101.cpp:1068
void handle_long_packet_(uint8_t rx_bytes)
Definition cc1101.cpp:269
void set_msk_deviation(uint8_t value)
Definition cc1101.cpp:872
void set_carrier_sense_rel_thr(CarrierSenseRelThr value)
Definition cc1101.cpp:977
uint8_t pa_table_[PA_TABLE_SIZE]
Definition cc1101.h:115
void set_lna_priority(bool value)
Definition cc1101.cpp:984
void set_foc_bs_cs_gate(bool value)
Definition cc1101.cpp:1026
void set_foc_pre_k(FocPreK value)
Definition cc1101.cpp:1040
void set_output_power(float value)
Definition cc1101.cpp:759
void arm_length_(uint16_t length)
Definition cc1101.cpp:211
void set_modulation_type(Modulation value)
Definition cc1101.cpp:906
void set_if_frequency(float value)
Definition cc1101.cpp:819
void set_packet_length(uint16_t value)
Definition cc1101.cpp:1155
void set_frequency(float value)
Definition cc1101.cpp:801
void set_num_preamble(uint8_t value)
Definition cc1101.cpp:928
void set_hyst_level(HystLevel value)
Definition cc1101.cpp:1019
void set_filter_bandwidth(float value)
Definition cc1101.cpp:826
void set_filter_length_fsk_msk(FilterLengthFskMsk value)
Definition cc1101.cpp:991
void set_crc_enable(bool value)
Definition cc1101.cpp:1189
void set_carrier_sense_abs_thr(int8_t value)
Definition cc1101.cpp:970
void set_bs_post_ki(BsPostKi value)
Definition cc1101.cpp:1075
bool enter_calibrated_(State target_state, Command cmd)
Definition cc1101.cpp:609
void set_magn_target(MagnTarget value)
Definition cc1101.cpp:949
void set_channel_spacing(float value)
Definition cc1101.cpp:849
CC1101Error transmit_packet(const std::vector< uint8_t > &packet)
Definition cc1101.h:99
void set_wait_time(WaitTime value)
Definition cc1101.cpp:1012
std::vector< CC1101Listener * > listeners_
Definition cc1101.h:139
void set_dc_blocking_filter(bool value)
Definition cc1101.cpp:794
void set_manchester(bool value)
Definition cc1101.cpp:921
std::vector< uint8_t > packet_
Definition cc1101.h:138
void set_channel(uint8_t value)
Definition cc1101.cpp:837
void set_foc_limit(FocLimit value)
Definition cc1101.cpp:1033
void set_filter_length_ask_ook(FilterLengthAskOok value)
Definition cc1101.cpp:998
void set_max_lna_gain(MaxLnaGain value)
Definition cc1101.cpp:956
void set_sync1(uint8_t value)
Definition cc1101.cpp:935
bool wait_for_state_(State target_state, uint32_t timeout_ms=100)
Definition cc1101.cpp:596
HighFrequencyLoopRequester high_freq_
Definition cc1101.h:148
void set_bs_limit(BsLimit value)
Definition cc1101.cpp:1054
void set_foc_post_k(FocPostK value)
Definition cc1101.cpp:1047
Trigger< std::vector< uint8_t >, float, float, uint8_t > packet_trigger_
Definition cc1101.h:137
void pin_mode(gpio::Flags flags) override
Definition gpio.cpp:172
uint32_t buffer
Definition gif.cpp:50
int32_t(*)(const std::vector< uint8_t > &) packet_length_func_t
Definition cc1101.h:14
PROGMEM_STRING_TABLE(ModulationStrings, "2-FSK", "GFSK", "UNUSED", "ASK/OOK", "4-FSK", "UNUSED", "UNUSED", "MSK")
ESPHOME_LOG_TAG(TAG, "cc1101")
@ INTERRUPT_RISING_EDGE
Definition gpio_pin.h:52
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
void attach_wake_interrupt(InternalGPIOPin *pin, Component *component, gpio::InterruptType type)
Wake component's loop() from pin's interrupt, through one ISR shared by every caller.
Definition gpio.h:54
constexpr uint16_t encode_uint16(uint8_t msb, uint8_t lsb)
Encode a 16-bit value given the most and least significant byte.
Definition helpers.h:1227
void HOT delay(uint32_t ms)
Definition hal.cpp:78
uint32_t IRAM_ATTR HOT millis()
Definition hal.cpp:25
Application App
Global storage of Application pointer - only one Application can exist.
static void uint32_t
static uint8_t find(const PowerTableItem *items, size_t count, float &dbm_target)
Definition cc1101pa.h:15
uint16_t length
Definition tt21100.cpp:0