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