ESPHome  2022.6.3
rc522.h
Go to the documentation of this file.
1 #pragma once
2 
4 #include "esphome/core/hal.h"
7 
8 namespace esphome {
9 namespace rc522 {
10 
11 class RC522BinarySensor;
12 class RC522Trigger;
13 class RC522 : public PollingComponent {
14  public:
15  void setup() override;
16 
17  void dump_config() override;
18 
19  void update() override;
20  float get_setup_priority() const override { return setup_priority::DATA; };
21 
22  void loop() override;
23 
24  void register_tag(RC522BinarySensor *tag) { this->binary_sensors_.push_back(tag); }
25  void register_trigger(RC522Trigger *trig) { this->triggers_.push_back(trig); }
26 
27  void set_reset_pin(GPIOPin *reset) { this->reset_pin_ = reset; }
28 
29  protected:
30  // Return codes from the functions in this class. Remember to update GetStatusCodeName() if you add more.
31  // last value set to 0xff, then compiler uses less ram, it seems some optimisations are triggered
32  enum StatusCode : uint8_t {
33  STATUS_OK, // Success
34  STATUS_WAITING, // Waiting result from RC522 chip
35  STATUS_ERROR, // Error in communication
36  STATUS_COLLISION, // Collision detected
37  STATUS_TIMEOUT, // Timeout in communication.
38  STATUS_NO_ROOM, // A buffer is not big enough.
39  STATUS_INTERNAL_ERROR, // Internal error in the code. Should not happen ;-)
40  STATUS_INVALID, // Invalid argument.
41  STATUS_CRC_WRONG, // The CRC_A does not match
42  STATUS_MIFARE_NACK = 0xff // A MIFARE PICC responded with NAK.
43  };
44 
45  enum State {
55  } state_{STATE_NONE};
56 
57  enum PcdRegister : uint8_t {
58  // Page 0: Command and status
59  // 0x00 // reserved for future use
60  COMMAND_REG = 0x01 << 1, // starts and stops command execution
61  COM_I_EN_REG = 0x02 << 1, // enable and disable interrupt request control bits
62  DIV_I_EN_REG = 0x03 << 1, // enable and disable interrupt request control bits
63  COM_IRQ_REG = 0x04 << 1, // interrupt request bits
64  DIV_IRQ_REG = 0x05 << 1, // interrupt request bits
65  ERROR_REG = 0x06 << 1, // error bits showing the error status of the last command executed
66  STATUS1_REG = 0x07 << 1, // communication status bits
67  STATUS2_REG = 0x08 << 1, // receiver and transmitter status bits
68  FIFO_DATA_REG = 0x09 << 1, // input and output of 64 uint8_t FIFO buffer
69  FIFO_LEVEL_REG = 0x0A << 1, // number of uint8_ts stored in the FIFO buffer
70  WATER_LEVEL_REG = 0x0B << 1, // level for FIFO underflow and overflow warning
71  CONTROL_REG = 0x0C << 1, // miscellaneous control registers
72  BIT_FRAMING_REG = 0x0D << 1, // adjustments for bit-oriented frames
73  COLL_REG = 0x0E << 1, // bit position of the first bit-collision detected on the RF interface
74  // 0x0F // reserved for future use
75 
76  // Page 1: Command
77  // 0x10 // reserved for future use
78  MODE_REG = 0x11 << 1, // defines general modes for transmitting and receiving
79  TX_MODE_REG = 0x12 << 1, // defines transmission data rate and framing
80  RX_MODE_REG = 0x13 << 1, // defines reception data rate and framing
81  TX_CONTROL_REG = 0x14 << 1, // controls the logical behavior of the antenna driver pins TX1 and TX2
82  TX_ASK_REG = 0x15 << 1, // controls the setting of the transmission modulation
83  TX_SEL_REG = 0x16 << 1, // selects the internal sources for the antenna driver
84  RX_SEL_REG = 0x17 << 1, // selects internal receiver settings
85  RX_THRESHOLD_REG = 0x18 << 1, // selects thresholds for the bit decoder
86  DEMOD_REG = 0x19 << 1, // defines demodulator settings
87  // 0x1A // reserved for future use
88  // 0x1B // reserved for future use
89  MF_TX_REG = 0x1C << 1, // controls some MIFARE communication transmit parameters
90  MF_RX_REG = 0x1D << 1, // controls some MIFARE communication receive parameters
91  // 0x1E // reserved for future use
92  SERIAL_SPEED_REG = 0x1F << 1, // selects the speed of the serial UART interface
93 
94  // Page 2: Configuration
95  // 0x20 // reserved for future use
96  CRC_RESULT_REG_H = 0x21 << 1, // shows the MSB and LSB values of the CRC calculation
97  CRC_RESULT_REG_L = 0x22 << 1,
98  // 0x23 // reserved for future use
99  MOD_WIDTH_REG = 0x24 << 1, // controls the ModWidth setting?
100  // 0x25 // reserved for future use
101  RF_CFG_REG = 0x26 << 1, // configures the receiver gain
102  GS_N_REG = 0x27 << 1, // selects the conductance of the antenna driver pins TX1 and TX2 for modulation
103  CW_GS_P_REG = 0x28 << 1, // defines the conductance of the p-driver output during periods of no modulation
104  MOD_GS_P_REG = 0x29 << 1, // defines the conductance of the p-driver output during periods of modulation
105  T_MODE_REG = 0x2A << 1, // defines settings for the internal timer
106  T_PRESCALER_REG = 0x2B << 1, // the lower 8 bits of the TPrescaler value. The 4 high bits are in TModeReg.
107  T_RELOAD_REG_H = 0x2C << 1, // defines the 16-bit timer reload value
108  T_RELOAD_REG_L = 0x2D << 1,
109  T_COUNTER_VALUE_REG_H = 0x2E << 1, // shows the 16-bit timer value
111 
112  // Page 3: Test Registers
113  // 0x30 // reserved for future use
114  TEST_SEL1_REG = 0x31 << 1, // general test signal configuration
115  TEST_SEL2_REG = 0x32 << 1, // general test signal configuration
116  TEST_PIN_EN_REG = 0x33 << 1, // enables pin output driver on pins D1 to D7
117  TEST_PIN_VALUE_REG = 0x34 << 1, // defines the values for D1 to D7 when it is used as an I/O bus
118  TEST_BUS_REG = 0x35 << 1, // shows the status of the internal test bus
119  AUTO_TEST_REG = 0x36 << 1, // controls the digital self-test
120  VERSION_REG = 0x37 << 1, // shows the software version
121  ANALOG_TEST_REG = 0x38 << 1, // controls the pins AUX1 and AUX2
122  TEST_DA_C1_REG = 0x39 << 1, // defines the test value for TestDAC1
123  TEST_DA_C2_REG = 0x3A << 1, // defines the test value for TestDAC2
124  TEST_ADC_REG = 0x3B << 1 // shows the value of ADC I and Q channels
125  // 0x3C // reserved for production tests
126  // 0x3D // reserved for production tests
127  // 0x3E // reserved for production tests
128  // 0x3F // reserved for production tests
129  };
130 
131  // MFRC522 commands. Described in chapter 10 of the datasheet.
132  enum PcdCommand : uint8_t {
133  PCD_IDLE = 0x00, // no action, cancels current command execution
134  PCD_MEM = 0x01, // stores 25 uint8_ts into the internal buffer
135  PCD_GENERATE_RANDOM_ID = 0x02, // generates a 10-uint8_t random ID number
136  PCD_CALC_CRC = 0x03, // activates the CRC coprocessor or performs a self-test
137  PCD_TRANSMIT = 0x04, // transmits data from the FIFO buffer
138  PCD_NO_CMD_CHANGE = 0x07, // no command change, can be used to modify the CommandReg register bits without
139  // affecting the command, for example, the PowerDown bit
140  PCD_RECEIVE = 0x08, // activates the receiver circuits
142  0x0C, // transmits data from FIFO buffer to antenna and automatically activates the receiver after transmission
143  PCD_MF_AUTHENT = 0x0E, // performs the MIFARE standard authentication as a reader
144  PCD_SOFT_RESET = 0x0F // resets the MFRC522
145  };
146 
147  // Commands sent to the PICC.
148  enum PiccCommand : uint8_t {
149  // The commands used by the PCD to manage communication with several PICCs (ISO 14443-3, Type A, section 6.4)
150  PICC_CMD_REQA = 0x26, // REQuest command, Type A. Invites PICCs in state IDLE to go to READY and prepare for
151  // anticollision or selection. 7 bit frame.
152  PICC_CMD_WUPA = 0x52, // Wake-UP command, Type A. Invites PICCs in state IDLE and HALT to go to READY(*) and
153  // prepare for anticollision or selection. 7 bit frame.
154  PICC_CMD_CT = 0x88, // Cascade Tag. Not really a command, but used during anti collision.
155  PICC_CMD_SEL_CL1 = 0x93, // Anti collision/Select, Cascade Level 1
156  PICC_CMD_SEL_CL2 = 0x95, // Anti collision/Select, Cascade Level 2
157  PICC_CMD_SEL_CL3 = 0x97, // Anti collision/Select, Cascade Level 3
158  PICC_CMD_HLTA = 0x50, // HaLT command, Type A. Instructs an ACTIVE PICC to go to state HALT.
159  PICC_CMD_RATS = 0xE0, // Request command for Answer To Reset.
160  // The commands used for MIFARE Classic (from http://www.mouser.com/ds/2/302/MF1S503x-89574.pdf, Section 9)
161  // Use PCD_MFAuthent to authenticate access to a sector, then use these commands to read/write/modify the blocks on
162  // the sector.
163  // The read/write commands can also be used for MIFARE Ultralight.
164  PICC_CMD_MF_AUTH_KEY_A = 0x60, // Perform authentication with Key A
165  PICC_CMD_MF_AUTH_KEY_B = 0x61, // Perform authentication with Key B
167  0x30, // Reads one 16 uint8_t block from the authenticated sector of the PICC. Also used for MIFARE Ultralight.
168  PICC_CMD_MF_WRITE = 0xA0, // Writes one 16 uint8_t block to the authenticated sector of the PICC. Called
169  // "COMPATIBILITY WRITE" for MIFARE Ultralight.
171  0xC0, // Decrements the contents of a block and stores the result in the internal data register.
173  0xC1, // Increments the contents of a block and stores the result in the internal data register.
174  PICC_CMD_MF_RESTORE = 0xC2, // Reads the contents of a block into the internal data register.
175  PICC_CMD_MF_TRANSFER = 0xB0, // Writes the contents of the internal data register to a block.
176  // The commands used for MIFARE Ultralight (from http://www.nxp.com/documents/data_sheet/MF0ICU1.pdf, Section 8.6)
177  // The PICC_CMD_MF_READ and PICC_CMD_MF_WRITE can also be used for MIFARE Ultralight.
178  PICC_CMD_UL_WRITE = 0xA2 // Writes one 4 uint8_t page to the PICC.
179  };
180 
181  void pcd_reset_();
182  void initialize_();
183  void pcd_antenna_on_();
184  void pcd_antenna_off_();
185 
186  virtual uint8_t pcd_read_register(PcdRegister reg
187  ) = 0;
188 
193  virtual void pcd_read_register(PcdRegister reg,
194  uint8_t count,
195  uint8_t *values,
196  uint8_t rx_align
197  ) = 0;
198  virtual void pcd_write_register(PcdRegister reg,
199  uint8_t value
200  ) = 0;
201 
206  virtual void pcd_write_register(PcdRegister reg,
207  uint8_t count,
208  uint8_t *values
209  ) = 0;
210 
212  uint8_t mask
213  );
215  uint8_t mask
216  );
217 
218  void pcd_transceive_data_(uint8_t send_len);
219 
220  void pcd_calculate_crc_(uint8_t *data,
221  uint8_t length
222  );
223 
228 
229  uint8_t buffer_[9];
230  uint8_t send_len_; // index of first byte for RX
232  uint8_t back_length_;
233  uint8_t uid_buffer_[10]; // buffer to construct the uid (for 7 and 10 bit uids)
234  uint8_t uid_idx_ = 0; // number of read uid bytes e.g. index of the next available position in uid_buffer
235  uint8_t error_counter_ = 0; // to reset if unresponsive
236  uint8_t rx_align_;
237  uint8_t *valid_bits_;
238 
239  GPIOPin *reset_pin_{nullptr};
240  uint8_t reset_count_{0};
241  uint32_t reset_timeout_{0};
242  std::vector<RC522BinarySensor *> binary_sensors_;
243  std::vector<RC522Trigger *> triggers_;
244  std::vector<uint8_t> current_uid_;
245 
246  enum RC522Error {
247  NONE = 0,
249  } error_code_{NONE};
250 };
251 
253  public:
254  void set_uid(const std::vector<uint8_t> &uid) { uid_ = uid; }
255 
256  bool process(std::vector<uint8_t> &data);
257 
258  void on_scan_end() {
259  if (!this->found_) {
260  this->publish_state(false);
261  }
262  this->found_ = false;
263  }
264 
265  protected:
266  std::vector<uint8_t> uid_;
267  bool found_{false};
268 };
269 
270 class RC522Trigger : public Trigger<std::string> {
271  public:
272  void process(std::vector<uint8_t> &data);
273 };
274 
275 } // namespace rc522
276 } // namespace esphome
uint8_t rx_align_
Definition: rc522.h:236
void pcd_reset_()
Performs a soft reset on the MFRC522 chip and waits for it to be ready again.
Definition: rc522.cpp:280
void pcd_set_register_bit_mask_(PcdRegister reg, uint8_t mask)
Sets the bits given in mask in register reg.
Definition: rc522.cpp:335
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:229
float get_setup_priority() const override
Definition: rc522.h:20
const float DATA
For components that import data from directly connected sensors like DHT.
Definition: component.cpp:18
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:358
void update() override
Definition: rc522.cpp:117
virtual void pcd_write_register(PcdRegister reg, uint8_t value)=0
void set_reset_pin(GPIOPin *reset)
Definition: rc522.h:27
void dump_config() override
Definition: rc522.cpp:98
This class simplifies creating components that periodically check a state.
Definition: component.h:266
uint8_t back_length_
In: Max number of uint8_ts to write to *backData. Out: The number of uint8_ts returned.
Definition: rc522.h:232
StatusCode await_crc_()
Definition: rc522.cpp:456
uint8_t uid_buffer_[10]
Definition: rc522.h:233
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
void setup() override
Definition: rc522.cpp:40
void register_trigger(RC522Trigger *trig)
Definition: rc522.h:25
uint8_t * valid_bits_
Definition: rc522.h:237
std::vector< RC522Trigger * > triggers_
Definition: rc522.h:243
uint32_t awaiting_comm_time_
Definition: rc522.h:225
uint8_t reset_count_
Definition: rc522.h:240
std::vector< uint8_t > uid_
Definition: rc522.h:266
GPIOPin * reset_pin_
Definition: rc522.h:239
uint8_t send_len_
Definition: rc522.h:231
enum esphome::rc522::RC522::RC522Error NONE
uint8_t error_counter_
Definition: rc522.h:235
void pcd_antenna_off_()
Turns the antenna off by disabling pins TX1 and TX2.
Definition: rc522.cpp:325
uint32_t reset_timeout_
Definition: rc522.h:241
enum esphome::rc522::RC522::State STATE_NONE
Definition: a4988.cpp:4
std::vector< uint8_t > current_uid_
Definition: rc522.h:244
Base class for all binary_sensor-type classes.
Definition: binary_sensor.h:26
StatusCode await_transceive_()
Definition: rc522.cpp:378
virtual uint8_t pcd_read_register(PcdRegister reg)=0
void register_tag(RC522BinarySensor *tag)
Definition: rc522.h:24
void pcd_antenna_on_()
Turns the antenna on by enabling pins TX1 and TX2.
Definition: rc522.cpp:315
uint8_t uid_idx_
Definition: rc522.h:234
void loop() override
Definition: rc522.cpp:129
void pcd_clear_register_bit_mask_(PcdRegister reg, uint8_t mask)
Clears the bits given in mask from register reg.
Definition: rc522.cpp:345
void set_uid(const std::vector< uint8_t > &uid)
Definition: rc522.h:254
std::vector< RC522BinarySensor * > binary_sensors_
Definition: rc522.h:242