ESPHome 2026.1.3
Loading...
Searching...
No Matches
rc522.cpp
Go to the documentation of this file.
1#include "rc522.h"
3#include "esphome/core/log.h"
4
5// Based on:
6// - https://github.com/miguelbalboa/rfid
7
8namespace esphome {
9namespace rc522 {
10
11static const uint8_t WAIT_I_RQ = 0x30; // RxIRq and IdleIRq
12
13static const char *const TAG = "rc522";
14
15// Max UID size for RFID tags (4, 7, or 10 bytes)
16static constexpr size_t RC522_MAX_UID_SIZE = 10;
17
18static const uint8_t RESET_COUNT = 5;
19
21 state_ = STATE_SETUP;
22 // Pull device out of power down / reset state.
23
24 // First set the resetPowerDownPin as digital input, to check the MFRC522 power down mode.
25 if (reset_pin_ != nullptr) {
27
28 if (!reset_pin_->digital_read()) { // The MFRC522 chip is in power down mode.
29 ESP_LOGV(TAG, "Power down mode detected. Hard resetting");
30 reset_pin_->pin_mode(gpio::FLAG_OUTPUT); // Now set the resetPowerDownPin as digital output.
31 reset_pin_->digital_write(false); // Make sure we have a clean LOW state.
32 delayMicroseconds(2); // 8.8.1 Reset timing requirements says about 100ns. Let us be generous: 2μsl
33 reset_pin_->digital_write(true); // Exit power down mode. This triggers a hard reset.
34 // Section 8.8.2 in the datasheet says the oscillator start-up time is the start up time of the crystal + 37,74μs.
35 // Let us be generous: 50ms.
37 return;
38 }
39 }
40
41 // Setup a soft reset
42 reset_count_ = RESET_COUNT;
44}
45
47 // Per original code, wait 50 ms
48 if (millis() - reset_timeout_ < 50)
49 return;
50
51 // Reset baud rates
52 ESP_LOGV(TAG, "Initialize");
53
56 // Reset ModWidthReg
58
59 // When communicating with a PICC we need a timeout if something goes wrong.
60 // f_timer = 13.56 MHz / (2*TPreScaler+1) where TPreScaler = [TPrescaler_Hi:TPrescaler_Lo].
61 // TPrescaler_Hi are the four low bits in TModeReg. TPrescaler_Lo is TPrescalerReg.
62 pcd_write_register(T_MODE_REG, 0x80); // TAuto=1; timer starts automatically at the end of the transmission in all
63 // communication modes at all speeds
64
65 // TPreScaler = TModeReg[3..0]:TPrescalerReg, ie 0x0A9 = 169 => f_timer=40kHz, ie a timer period of 25μs.
67 pcd_write_register(T_RELOAD_REG_H, 0x03); // Reload timer with 0x3E8 = 1000, ie 25ms before timeout.
69
70 // Default 0x00. Force a 100 % ASK modulation independent of the ModGsPReg register setting
72 pcd_write_register(MODE_REG, 0x3D); // Default 0x3F. Set the preset value for the CRC coprocessor for the CalcCRC
73 // command to 0x6363 (ISO 14443-3 part 6.2.4)
74
75 state_ = STATE_INIT;
76}
77
79 ESP_LOGCONFIG(TAG, "RC522:");
80 switch (this->error_code_) {
81 case NONE:
82 break;
83 case RESET_FAILED:
84 ESP_LOGE(TAG, "Reset command failed");
85 break;
86 }
87
88 LOG_PIN(" RESET Pin: ", this->reset_pin_);
89
90 LOG_UPDATE_INTERVAL(this);
91
92 for (auto *child : this->binary_sensors_) {
93 LOG_BINARY_SENSOR(" ", "Tag", child);
94 }
95}
96
98 if (state_ == STATE_INIT) {
100 pcd_clear_register_bit_mask_(COLL_REG, 0x80); // ValuesAfterColl=1 => Bits received after collision are cleared.
103 state_ = STATE_PICC_REQUEST_A;
104 } else {
105 ESP_LOGW(TAG, "Communication takes longer than update interval: %d", state_);
106 }
107}
108
110 // First check reset is needed
111 if (reset_count_ > 0) {
112 pcd_reset_();
113 return;
114 }
115 if (state_ == STATE_SETUP) {
116 initialize_();
117 return;
118 }
119
120 StatusCode status = STATUS_ERROR; // For lint passing. TODO: refactor this
121 if (awaiting_comm_) {
122 if (state_ == STATE_SELECT_SERIAL_DONE) {
123 status = await_crc_();
124 } else {
126 }
127
128 if (status == STATUS_WAITING) {
129 return;
130 }
131 awaiting_comm_ = false;
132 ESP_LOGV(TAG, "finished communication status: %d, state: %d", status, state_);
133 }
134
135 switch (state_) {
137 if (status == STATUS_TIMEOUT) { // no tag present
138 for (auto *obj : this->binary_sensors_)
139 obj->on_scan_end(); // reset the binary sensors
140 ESP_LOGV(TAG, "CMD_REQA -> TIMEOUT (no tag present) %d", status);
141 state_ = STATE_DONE;
142 } else if (status != STATUS_OK) {
143 ESP_LOGW(TAG, "CMD_REQA -> Not OK %d", status);
144 state_ = STATE_DONE;
145 } else if (back_length_ != 2) { // || *valid_bits_ != 0) { // ATQA must be exactly 16 bits.
146 ESP_LOGW(TAG, "CMD_REQA -> OK, but unexpected back_length_ of %d", back_length_);
147 state_ = STATE_DONE;
148 } else {
149 state_ = STATE_READ_SERIAL;
150 }
151 if (state_ == STATE_DONE) {
152 // Don't wait another loop cycle
154 }
155 break;
156 }
157 case STATE_READ_SERIAL: {
158 ESP_LOGV(TAG, "STATE_READ_SERIAL (%d)", status);
159 switch (uid_idx_) {
160 case 0:
162 break;
163 case 3:
165 break;
166 case 6:
168 break;
169 default:
170 ESP_LOGE(TAG, "uid_idx_ invalid, uid_idx_ = %d", uid_idx_);
171 state_ = STATE_DONE;
172 }
173 buffer_[1] = 32;
175 state_ = STATE_SELECT_SERIAL;
176 break;
177 }
178 case STATE_SELECT_SERIAL: {
179 buffer_[1] = 0x70; // select
180 // todo: set CRC
181 buffer_[6] = buffer_[2] ^ buffer_[3] ^ buffer_[4] ^ buffer_[5];
184 break;
185 }
187 send_len_ = 6;
189 state_ = STATE_READ_SERIAL_DONE;
190 break;
191 }
193 if (status != STATUS_OK || back_length_ != 3) {
194 if (status == STATUS_TIMEOUT) {
195 ESP_LOGV(TAG, "STATE_READ_SERIAL_DONE -> TIMEOUT (no tag present) %d", status);
196 } else {
197 char hex_buf[format_hex_pretty_size(RC522_MAX_UID_SIZE)];
198 ESP_LOGW(TAG, "Unexpected response. Read status is %d. Read bytes: %d (%s)", status, back_length_,
200 }
201
202 state_ = STATE_DONE;
203 uid_idx_ = 0;
204
206 return;
207 }
208
209 // copy the uid
210 bool cascade = buffer_[2] == PICC_CMD_CT; // todo: should be determined based on select response (buffer[6])
211 for (uint8_t i = 2 + cascade; i < 6; i++)
213 ESP_LOGVV(TAG, "copied uid to idx %d last byte is 0x%x, cascade is %d", uid_idx_, uid_buffer_[uid_idx_ - 1],
214 cascade);
215
216 if (cascade) { // there is more bytes in the UID
217 state_ = STATE_READ_SERIAL;
218 return;
219 }
220
221 std::vector<uint8_t> rfid_uid(std::begin(uid_buffer_), std::begin(uid_buffer_) + uid_idx_);
222 uid_idx_ = 0;
223 // ESP_LOGD(TAG, "Processing '%s'", format_hex_pretty(rfid_uid, '-', false).c_str()); // NOLINT
225 state_ = STATE_INIT; // scan again on next update
226 bool report = true;
227
228 for (auto *tag : this->binary_sensors_) {
229 if (tag->process(rfid_uid)) {
230 report = false;
231 }
232 }
233
234 if (this->current_uid_ == rfid_uid) {
235 return;
236 }
237
238 this->current_uid_ = rfid_uid;
239
240 for (auto *trigger : this->triggers_ontag_)
241 trigger->process(rfid_uid);
242
243 if (report) {
244 char uid_buf[format_hex_pretty_size(RC522_MAX_UID_SIZE)];
245 ESP_LOGD(TAG, "Found new tag '%s'", format_hex_pretty_to(uid_buf, rfid_uid.data(), rfid_uid.size(), '-'));
246 }
247 break;
248 }
249 case STATE_DONE: {
250 if (!this->current_uid_.empty()) {
251#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
252 char uid_buf[format_hex_pretty_size(RC522_MAX_UID_SIZE)];
253 ESP_LOGV(TAG, "Tag '%s' removed",
254 format_hex_pretty_to(uid_buf, this->current_uid_.data(), this->current_uid_.size(), '-'));
255#endif
256 for (auto *trigger : this->triggers_ontagremoved_)
257 trigger->process(this->current_uid_);
258 }
259 this->current_uid_ = {};
260 state_ = STATE_INIT;
261 break;
262 }
263 default:
264 break;
265 }
266} // namespace rc522
267
272 // The datasheet does not mention how long the SoftRest command takes to complete.
273 // But the MFRC522 might have been in soft power-down mode (triggered by bit 4 of CommandReg)
274 // Section 8.8.2 in the datasheet says the oscillator start-up time is the start up time of the crystal + 37,74μs.
275 // Let us be generous: 50ms.
276
277 if (millis() - reset_timeout_ < 50)
278 return;
279
280 if (reset_count_ == RESET_COUNT) {
281 ESP_LOGI(TAG, "Soft reset");
282 // Issue the SoftReset command.
284 }
285
286 // Expect the PowerDown bit in CommandReg to be cleared (max 3x50ms)
287 if ((pcd_read_register(COMMAND_REG) & (1 << 4)) == 0) {
288 reset_count_ = 0;
289 ESP_LOGI(TAG, "Device online");
290 // Wait for initialize
292 return;
293 }
294
295 if (--reset_count_ == 0) {
296 ESP_LOGE(TAG, "Unable to reset");
297 this->error_code_ = RESET_FAILED;
298 mark_failed();
299 }
300}
301
307 uint8_t value = pcd_read_register(TX_CONTROL_REG);
308 if ((value & 0x03) != 0x03) {
309 pcd_write_register(TX_CONTROL_REG, value | 0x03);
310 }
311}
312
317 uint8_t value = pcd_read_register(TX_CONTROL_REG);
318 if ((value & 0x03) != 0x00) {
319 pcd_write_register(TX_CONTROL_REG, value & ~0x03);
320 }
321}
322
327 uint8_t mask
328) {
329 uint8_t tmp = pcd_read_register(reg);
330 pcd_write_register(reg, tmp | mask); // set bit mask
331}
332
337 uint8_t mask
338) {
339 uint8_t tmp = pcd_read_register(reg);
340 pcd_write_register(reg, tmp & (~mask)); // clear bit mask
341}
342
349void RC522::pcd_transceive_data_(uint8_t send_len) {
350#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
351 char hex_buf[format_hex_pretty_size(RC522_MAX_UID_SIZE)];
352 ESP_LOGV(TAG, "PCD TRANSCEIVE: RX: %s", format_hex_pretty_to(hex_buf, buffer_, send_len, '-'));
353#endif
354 delayMicroseconds(1000); // we need 1 ms delay between antenna on and those communication commands
355 send_len_ = send_len;
356 // Prepare values for BitFramingReg
357 // For REQA and WUPA we need the short frame format - transmit only 7 bits of the last (and only)
358 // uint8_t. TxLastBits = BitFramingReg[2..0]
359 uint8_t bit_framing = (buffer_[0] == PICC_CMD_REQA) ? 7 : 0;
360
361 pcd_write_register(COMMAND_REG, PCD_IDLE); // Stop any active command.
362 pcd_write_register(COM_IRQ_REG, 0x7F); // Clear all seven interrupt request bits
363 pcd_write_register(FIFO_LEVEL_REG, 0x80); // FlushBuffer = 1, FIFO initialization
364 pcd_write_register(FIFO_DATA_REG, send_len_, buffer_); // Write sendData to the FIFO
365 pcd_write_register(BIT_FRAMING_REG, bit_framing); // Bit adjustments
366 pcd_write_register(COMMAND_REG, PCD_TRANSCEIVE); // Execute the command
367 pcd_set_register_bit_mask_(BIT_FRAMING_REG, 0x80); // StartSend=1, transmission of data starts
368 awaiting_comm_ = true;
370}
371
373 if (millis() - awaiting_comm_time_ < 2) // wait at least 2 ms
374 return STATUS_WAITING;
375 uint8_t n = pcd_read_register(
376 COM_IRQ_REG); // ComIrqReg[7..0] bits are: Set1 TxIRq RxIRq IdleIRq HiAlertIRq LoAlertIRq ErrIRq TimerIRq
377 if (n & 0x01) { // Timer interrupt - nothing received in 25ms
378 back_length_ = 0;
379 error_counter_ = 0; // reset the error counter
380 return STATUS_TIMEOUT;
381 }
382 if (!(n & WAIT_I_RQ)) { // None of the interrupts that signal success has been set.
383 // Wait for the command to complete.
384 if (millis() - awaiting_comm_time_ < 40)
385 return STATUS_WAITING;
386 back_length_ = 0;
387 ESP_LOGW(TAG, "Communication with the MFRC522 might be down, reset in %d",
388 10 - error_counter_); // todo: trigger reset?
389 if (error_counter_++ >= 10) {
390 setup();
391 error_counter_ = 0; // reset the error counter
392 }
393
394 return STATUS_TIMEOUT;
395 }
396 // Stop now if any errors except collisions were detected.
397 uint8_t error_reg_value = pcd_read_register(
398 ERROR_REG); // ErrorReg[7..0] bits are: WrErr TempErr reserved BufferOvfl CollErr CRCErr ParityErr ProtocolErr
399 if (error_reg_value & 0x13) { // BufferOvfl ParityErr ProtocolErr
400 return STATUS_ERROR;
401 }
402 error_counter_ = 0; // reset the error counter
403
404 n = pcd_read_register(FIFO_LEVEL_REG); // Number of uint8_ts in the FIFO
405 if (n > sizeof(buffer_))
406 return STATUS_NO_ROOM;
407 if (n > sizeof(buffer_) - send_len_)
408 send_len_ = sizeof(buffer_) - n; // simply overwrite the sent values
409 back_length_ = n; // Number of uint8_ts returned
410 pcd_read_register(FIFO_DATA_REG, n, buffer_ + send_len_, rx_align_); // Get received data from FIFO
411 uint8_t valid_bits_local =
412 pcd_read_register(CONTROL_REG) & 0x07; // RxLastBits[2:0] indicates the number of valid bits in the last
413 // received uint8_t. If this value is 000b, the whole uint8_t is valid.
414
415 // Tell about collisions
416 if (error_reg_value & 0x08) { // CollErr
417 ESP_LOGW(TAG, "collision error, received %d bytes + %d bits (but anticollision not implemented)",
418 back_length_ - (valid_bits_local > 0), valid_bits_local);
419 return STATUS_COLLISION;
420 }
421 // Tell about collisions
422 if (valid_bits_local) {
423 ESP_LOGW(TAG, "only %d valid bits received, tag distance to high? Error code is 0x%x", valid_bits_local,
424 error_reg_value); // TODO: is this always due to collissions?
425 return STATUS_ERROR;
426 }
427#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
428 char hex_buf[format_hex_pretty_size(RC522_MAX_UID_SIZE)];
429 ESP_LOGV(TAG, "received %d bytes: %s", back_length_,
431#endif
432
433 return STATUS_OK;
434}
435
442void RC522::pcd_calculate_crc_(uint8_t *data,
443 uint8_t length
444) {
445 ESP_LOGVV(TAG, "pcd_calculate_crc_(..., %d, ...)", length);
446 pcd_write_register(COMMAND_REG, PCD_IDLE); // Stop any active command.
447 pcd_write_register(DIV_IRQ_REG, 0x04); // Clear the CRCIRq interrupt request bit
448 pcd_write_register(FIFO_LEVEL_REG, 0x80); // FlushBuffer = 1, FIFO initialization
449 pcd_write_register(FIFO_DATA_REG, length, data); // Write data to the FIFO
450 pcd_write_register(COMMAND_REG, PCD_CALC_CRC); // Start the calculation
451
452 awaiting_comm_ = true;
454}
455
457 if (millis() - awaiting_comm_time_ < 2) // wait at least 2 ms
458 return STATUS_WAITING;
459
460 // DivIrqReg[7..0] bits are: Set2 reserved reserved MfinActIRq reserved CRCIRq reserved reserved
461 uint8_t n = pcd_read_register(DIV_IRQ_REG);
462 if (n & 0x04) { // CRCIRq bit set - calculation done
463 pcd_write_register(COMMAND_REG, PCD_IDLE); // Stop calculating CRC for new content in the FIFO.
464 // Transfer the result from the registers to the result buffer
467
468 ESP_LOGVV(TAG, "pcd_calculate_crc_() STATUS_OK");
469 return STATUS_OK;
470 }
471 if (millis() - awaiting_comm_time_ < 89)
472 return STATUS_WAITING;
473
474 ESP_LOGD(TAG, "pcd_calculate_crc_() TIMEOUT");
475 // 89ms passed and nothing happened. Communication with the MFRC522 might be down.
476 return STATUS_TIMEOUT;
477}
478
479bool RC522BinarySensor::process(std::vector<uint8_t> &data) {
480 bool result = true;
481 if (data.size() != this->uid_.size()) {
482 result = false;
483 } else {
484 for (size_t i = 0; i < data.size(); i++) {
485 if (data[i] != this->uid_[i]) {
486 result = false;
487 break;
488 }
489 }
490 }
491 this->publish_state(result);
492 this->found_ = result;
493 return result;
494}
495void RC522Trigger::process(std::vector<uint8_t> &data) {
496 char uid_buf[format_hex_pretty_size(RC522_MAX_UID_SIZE)];
497 this->trigger(format_hex_pretty_to(uid_buf, data.data(), data.size(), '-'));
498}
499
500} // namespace rc522
501} // namespace esphome
uint8_t status
Definition bl0942.h:8
virtual void mark_failed()
Mark this component as failed.
virtual void pin_mode(gpio::Flags flags)=0
virtual void digital_write(bool value)=0
virtual bool digital_read()=0
void trigger(const Ts &...x)
Definition automation.h:238
void publish_state(bool new_state)
Publish a new state to the front-end.
bool process(std::vector< uint8_t > &data)
Definition rc522.cpp:479
std::vector< uint8_t > uid_
Definition rc522.h:269
std::vector< RC522Trigger * > triggers_ontagremoved_
Definition rc522.h:246
void dump_config() override
Definition rc522.cpp:78
virtual uint8_t pcd_read_register(PcdRegister reg)=0
GPIOPin * reset_pin_
Definition rc522.h:241
enum esphome::rc522::RC522::RC522Error NONE
void pcd_transceive_data_(uint8_t send_len)
Transfers data to the MFRC522 FIFO, executes a command, waits for completion and transfers data back ...
Definition rc522.cpp:349
std::vector< RC522Trigger * > triggers_ontag_
Definition rc522.h:245
void pcd_reset_()
Performs a soft reset on the MFRC522 chip and waits for it to be ready again.
Definition rc522.cpp:271
uint32_t awaiting_comm_time_
Definition rc522.h:227
std::vector< RC522BinarySensor * > binary_sensors_
Definition rc522.h:244
void pcd_antenna_off_()
Turns the antenna off by disabling pins TX1 and TX2.
Definition rc522.cpp:316
uint8_t back_length_
In: Max number of uint8_ts to write to *backData. Out: The number of uint8_ts returned.
Definition rc522.h:234
void update() override
Definition rc522.cpp:97
StatusCode await_crc_()
Definition rc522.cpp:456
uint8_t reset_count_
Definition rc522.h:242
uint32_t reset_timeout_
Definition rc522.h:243
void setup() override
Definition rc522.cpp:20
uint8_t error_counter_
Definition rc522.h:237
StatusCode await_transceive_()
Definition rc522.cpp:372
void pcd_antenna_on_()
Turns the antenna on by enabling pins TX1 and TX2.
Definition rc522.cpp:306
void pcd_set_register_bit_mask_(PcdRegister reg, uint8_t mask)
Sets the bits given in mask in register reg.
Definition rc522.cpp:326
void pcd_calculate_crc_(uint8_t *data, uint8_t length)
Use the CRC coprocessor in the MFRC522 to calculate a CRC_A.
Definition rc522.cpp:442
std::vector< uint8_t > current_uid_
Definition rc522.h:247
void pcd_clear_register_bit_mask_(PcdRegister reg, uint8_t mask)
Clears the bits given in mask from register reg.
Definition rc522.cpp:336
uint8_t uid_buffer_[10]
Definition rc522.h:235
uint8_t buffer_[9]
buffer for communication, the first bits [0..back_idx-1] are for tx , [back_idx..back_idx+back_len] f...
Definition rc522.h:231
void loop() override
Definition rc522.cpp:109
virtual void pcd_write_register(PcdRegister reg, uint8_t value)=0
void process(std::vector< uint8_t > &data)
Definition rc522.cpp:495
@ FLAG_OUTPUT
Definition gpio.h:28
@ FLAG_INPUT
Definition gpio.h:27
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
void IRAM_ATTR HOT delayMicroseconds(uint32_t us)
Definition core.cpp:28
char * format_hex_pretty_to(char *buffer, size_t buffer_size, const uint8_t *data, size_t length, char separator)
Format byte array as uppercase hex to buffer (base implementation).
Definition helpers.cpp:334
constexpr size_t format_hex_pretty_size(size_t byte_count)
Calculate buffer size needed for format_hex_pretty_to with separator: "XX:XX:...:XX\0".
Definition helpers.h:830
uint32_t IRAM_ATTR HOT millis()
Definition core.cpp:25
uint16_t length
Definition tt21100.cpp:0