ESPHome 2026.5.0b1
Loading...
Searching...
No Matches
pn532.cpp
Go to the documentation of this file.
1#include "pn532.h"
2
3#include <memory>
4#include "esphome/core/log.h"
5#include "esphome/core/hal.h"
6
7// Based on:
8// - https://cdn-shop.adafruit.com/datasheets/PN532C106_Application+Note_v1.2.pdf
9// - https://www.nxp.com/docs/en/nxp/application-notes/AN133910.pdf
10// - https://www.nxp.com/docs/en/nxp/application-notes/153710.pdf
11
12namespace esphome::pn532 {
13
14static const char *const TAG = "pn532";
15
17 // Get version data
18 if (!this->write_command_({PN532_COMMAND_VERSION_DATA})) {
19 ESP_LOGW(TAG, "Error sending version command, trying again");
20 if (!this->write_command_({PN532_COMMAND_VERSION_DATA})) {
21 ESP_LOGE(TAG, "Error sending version command");
22 this->mark_failed();
23 return;
24 }
25 }
26
27 std::vector<uint8_t> version_data;
28 if (!this->read_response(PN532_COMMAND_VERSION_DATA, version_data)) {
29 ESP_LOGE(TAG, "Error getting version");
30 this->mark_failed();
31 return;
32 }
33 ESP_LOGD(TAG, "Found chip PN5%02X, Firmware v%d.%d", version_data[0], version_data[1], version_data[2]);
34
35 if (!this->write_command_({
36 PN532_COMMAND_SAMCONFIGURATION,
37 0x01, // normal mode
38 0x14, // zero timeout (not in virtual card mode)
39 0x01,
40 })) {
41 ESP_LOGE(TAG, "No wakeup ack");
42 this->mark_failed();
43 return;
44 }
45
46 std::vector<uint8_t> wakeup_result;
47 if (!this->read_response(PN532_COMMAND_SAMCONFIGURATION, wakeup_result)) {
48 this->error_code_ = WAKEUP_FAILED;
49 this->mark_failed();
50 return;
51 }
52
53 // Set up SAM (secure access module)
54 uint8_t sam_timeout = std::min<uint8_t>(255u, this->update_interval_ / 50);
55 if (!this->write_command_({
56 PN532_COMMAND_SAMCONFIGURATION,
57 0x01, // normal mode
58 sam_timeout, // timeout as multiple of 50ms (actually only for virtual card mode, but shouldn't matter)
59 0x01, // Enable IRQ
60 })) {
61 this->error_code_ = SAM_COMMAND_FAILED;
62 this->mark_failed();
63 return;
64 }
65
66 std::vector<uint8_t> sam_result;
67 if (!this->read_response(PN532_COMMAND_SAMCONFIGURATION, sam_result)) {
68 ESP_LOGV(TAG, "Invalid SAM result: (%u)", sam_result.size()); // NOLINT
69 for (uint8_t dat : sam_result) {
70 ESP_LOGV(TAG, " 0x%02X", dat);
71 }
72 this->error_code_ = SAM_COMMAND_FAILED;
73 this->mark_failed();
74 return;
75 }
76
77 this->turn_off_rf_();
78}
79
81 updates_enabled_ = false;
82 requested_read_ = false;
83 ESP_LOGI(TAG, "Powering down PN532");
84 if (!this->write_command_({PN532_COMMAND_POWERDOWN, 0b10100000})) { // enable i2c,spi wakeup
85 ESP_LOGE(TAG, "Error writing powerdown command to PN532");
86 return false;
87 }
88 std::vector<uint8_t> response;
89 if (!this->read_response(PN532_COMMAND_POWERDOWN, response)) {
90 ESP_LOGE(TAG, "Error reading PN532 powerdown response");
91 return false;
92 }
93 if (response[0] != 0x00) {
94 ESP_LOGE(TAG, "Error on PN532 powerdown: %02x", response[0]);
95 return false;
96 }
97 ESP_LOGV(TAG, "Powerdown successful");
98 delay(1);
99 return true;
100}
101
103 if (!updates_enabled_)
104 return;
105
106 for (auto *obj : this->binary_sensors_)
107 obj->on_scan_end();
108
109 if (!this->write_command_({
110 PN532_COMMAND_INLISTPASSIVETARGET,
111 0x01, // max 1 card
112 0x00, // baud rate ISO14443A (106 kbit/s)
113 })) {
114 ESP_LOGW(TAG, "Requesting tag read failed!");
115 this->status_set_warning();
116 return;
117 }
118 this->status_clear_warning();
119 this->requested_read_ = true;
120}
121
123 if (!this->requested_read_)
124 return;
125
126 auto ready = this->read_ready_(false);
127 if (ready == WOULDBLOCK)
128 return;
129
130 bool success = false;
131 std::vector<uint8_t> read;
132
133 if (ready == READY) {
134 success = this->read_response(PN532_COMMAND_INLISTPASSIVETARGET, read);
135 } else {
136 this->send_ack_(); // abort still running InListPassiveTarget
137 }
138
139 this->requested_read_ = false;
140
141 if (!success) {
142 // Something failed
143 if (!this->current_uid_.empty()) {
144 auto tag = make_unique<nfc::NfcTag>(this->current_uid_);
145 for (auto *trigger : this->triggers_ontagremoved_)
146 trigger->process(tag);
147 }
148 this->current_uid_ = {};
149 this->turn_off_rf_();
150 return;
151 }
152
153 uint8_t num_targets = read[0];
154 if (num_targets != 1) {
155 // no tags found or too many
156 if (!this->current_uid_.empty()) {
157 auto tag = make_unique<nfc::NfcTag>(this->current_uid_);
158 for (auto *trigger : this->triggers_ontagremoved_)
159 trigger->process(tag);
160 }
161 this->current_uid_ = {};
162 this->turn_off_rf_();
163 return;
164 }
165
166 uint8_t nfcid_length = read[5];
167 if (nfcid_length > nfc::NFC_UID_MAX_LENGTH || read.size() < 6U + nfcid_length) {
168 // oops, pn532 returned invalid data
169 return;
170 }
171 nfc::NfcTagUid nfcid(read.begin() + 6, read.begin() + 6 + nfcid_length);
172
173 bool report = true;
174 for (auto *bin_sens : this->binary_sensors_) {
175 if (bin_sens->process(nfcid)) {
176 report = false;
177 }
178 }
179
180 if (nfcid.size() == this->current_uid_.size()) {
181 bool same_uid = true;
182 for (size_t i = 0; i < nfcid.size(); i++)
183 same_uid &= nfcid[i] == this->current_uid_[i];
184 if (same_uid)
185 return;
186 }
187
188 this->current_uid_ = nfcid;
189
190 if (next_task_ == READ) {
191 auto tag = this->read_tag_(nfcid);
192 for (auto *trigger : this->triggers_ontag_)
193 trigger->process(tag);
194
195 if (report) {
196 char uid_buf[nfc::FORMAT_UID_BUFFER_SIZE];
197 ESP_LOGD(TAG, "Found new tag '%s'", nfc::format_uid_to(uid_buf, nfcid));
198 if (tag->has_ndef_message()) {
199 const auto &message = tag->get_ndef_message();
200 const auto &records = message->get_records();
201 ESP_LOGD(TAG, " NDEF formatted records:");
202 for (const auto &record : records) {
203 ESP_LOGD(TAG, " %s - %s", record->get_type().c_str(), record->get_payload().c_str());
204 }
205 }
206 }
207 } else if (next_task_ == CLEAN) {
208 ESP_LOGD(TAG, " Tag cleaning");
209 if (!this->clean_tag_(nfcid)) {
210 ESP_LOGE(TAG, " Tag was not fully cleaned successfully");
211 }
212 ESP_LOGD(TAG, " Tag cleaned!");
213 } else if (next_task_ == FORMAT) {
214 ESP_LOGD(TAG, " Tag formatting");
215 if (!this->format_tag_(nfcid)) {
216 ESP_LOGE(TAG, "Error formatting tag as NDEF");
217 }
218 ESP_LOGD(TAG, " Tag formatted!");
219 } else if (next_task_ == WRITE) {
220 if (this->next_task_message_to_write_ != nullptr) {
221 ESP_LOGD(TAG, " Tag writing");
222 ESP_LOGD(TAG, " Tag formatting");
223 if (!this->format_tag_(nfcid)) {
224 ESP_LOGE(TAG, " Tag could not be formatted for writing");
225 } else {
226 ESP_LOGD(TAG, " Writing NDEF data");
227 if (!this->write_tag_(nfcid, this->next_task_message_to_write_)) {
228 ESP_LOGE(TAG, " Failed to write message to tag");
229 }
230 ESP_LOGD(TAG, " Finished writing NDEF data");
231 delete this->next_task_message_to_write_;
232 this->next_task_message_to_write_ = nullptr;
233 this->on_finished_write_callback_.call();
234 }
235 }
236 }
237
238 this->read_mode();
239
240 this->turn_off_rf_();
241}
242
243bool PN532::write_command_(const std::vector<uint8_t> &data) {
244 std::vector<uint8_t> write_data;
245 // Preamble
246 write_data.push_back(0x00);
247
248 // Start code
249 write_data.push_back(0x00);
250 write_data.push_back(0xFF);
251
252 // Length of message, TFI + data bytes
253 const uint8_t real_length = data.size() + 1;
254 // LEN
255 write_data.push_back(real_length);
256 // LCS (Length checksum)
257 write_data.push_back(~real_length + 1);
258
259 // TFI (Frame Identifier, 0xD4 means to PN532, 0xD5 means from PN532)
260 write_data.push_back(0xD4);
261 // calculate checksum, TFI is part of checksum
262 uint8_t checksum = 0xD4;
263
264 // DATA
265 for (uint8_t dat : data) {
266 write_data.push_back(dat);
267 checksum += dat;
268 }
269
270 // DCS (Data checksum)
271 write_data.push_back(~checksum + 1);
272 // Postamble
273 write_data.push_back(0x00);
274
275 this->write_data(write_data);
276
277 return this->read_ack_();
278}
279
281 ESP_LOGV(TAG, "Reading ACK");
282
283 std::vector<uint8_t> data;
284 if (!this->read_data(data, 6)) {
285 return false;
286 }
287
288 bool matches = (data[1] == 0x00 && // preamble
289 data[2] == 0x00 && // start of packet
290 data[3] == 0xFF && data[4] == 0x00 && // ACK packet code
291 data[5] == 0xFF && data[6] == 0x00); // postamble
292 ESP_LOGV(TAG, "ACK valid: %s", YESNO(matches));
293 return matches;
294}
295
297 ESP_LOGV(TAG, "Sending ACK for abort");
298 this->write_data({0x00, 0x00, 0xFF, 0x00, 0xFF, 0x00});
299 delay(10);
300}
302 ESP_LOGV(TAG, "Sending NACK for retransmit");
303 this->write_data({0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00});
304 delay(10);
305}
306
308 if (this->rd_ready_ == READY) {
309 if (block) {
310 this->rd_start_time_.reset();
311 this->rd_ready_ = WOULDBLOCK;
312 }
313 return READY;
314 }
315
316 if (!this->rd_start_time_.has_value()) {
317 this->rd_start_time_ = millis();
318 }
319 const uint32_t rd_start_time = *this->rd_start_time_;
320
321 while (true) {
322 if (this->is_read_ready()) {
323 this->rd_ready_ = READY;
324 break;
325 }
326
327 if (millis() - rd_start_time > 100) {
328 ESP_LOGV(TAG, "Timed out waiting for readiness from PN532!");
329 this->rd_ready_ = TIMEOUT;
330 break;
331 }
332
333 if (!block) {
334 this->rd_ready_ = WOULDBLOCK;
335 break;
336 }
337
338 yield();
339 }
340
341 auto rdy = this->rd_ready_;
342 if (block || rdy == TIMEOUT) {
343 this->rd_start_time_.reset();
344 this->rd_ready_ = WOULDBLOCK;
345 }
346 return rdy;
347}
348
350 ESP_LOGV(TAG, "Turning RF field OFF");
351 this->write_command_({
352 PN532_COMMAND_RFCONFIGURATION,
353 0x01, // RF Field
354 0x00, // Off
355 });
356}
357
358std::unique_ptr<nfc::NfcTag> PN532::read_tag_(nfc::NfcTagUid &uid) {
359 uint8_t type = nfc::guess_tag_type(uid.size());
360
361 if (type == nfc::TAG_TYPE_MIFARE_CLASSIC) {
362 ESP_LOGD(TAG, "Mifare classic");
363 return this->read_mifare_classic_tag_(uid);
364 } else if (type == nfc::TAG_TYPE_2) {
365 ESP_LOGD(TAG, "Mifare ultralight");
366 return this->read_mifare_ultralight_tag_(uid);
367 } else if (type == nfc::TAG_TYPE_UNKNOWN) {
368 ESP_LOGV(TAG, "Cannot determine tag type");
369 return make_unique<nfc::NfcTag>(uid);
370 } else {
371 return make_unique<nfc::NfcTag>(uid);
372 }
373}
374
376 this->next_task_ = READ;
377 ESP_LOGD(TAG, "Waiting to read next tag");
378}
380 this->next_task_ = CLEAN;
381 ESP_LOGD(TAG, "Waiting to clean next tag");
382}
384 this->next_task_ = FORMAT;
385 ESP_LOGD(TAG, "Waiting to format next tag");
386}
388 this->next_task_ = WRITE;
390 ESP_LOGD(TAG, "Waiting to write next tag");
391}
392
394 uint8_t type = nfc::guess_tag_type(uid.size());
395 if (type == nfc::TAG_TYPE_MIFARE_CLASSIC) {
396 return this->format_mifare_classic_mifare_(uid);
397 } else if (type == nfc::TAG_TYPE_2) {
398 return this->clean_mifare_ultralight_();
399 }
400 ESP_LOGE(TAG, "Unsupported Tag for formatting");
401 return false;
402}
403
405 uint8_t type = nfc::guess_tag_type(uid.size());
406 if (type == nfc::TAG_TYPE_MIFARE_CLASSIC) {
407 return this->format_mifare_classic_ndef_(uid);
408 } else if (type == nfc::TAG_TYPE_2) {
409 return this->clean_mifare_ultralight_();
410 }
411 ESP_LOGE(TAG, "Unsupported Tag for formatting");
412 return false;
413}
414
416 uint8_t type = nfc::guess_tag_type(uid.size());
417 if (type == nfc::TAG_TYPE_MIFARE_CLASSIC) {
418 return this->write_mifare_classic_tag_(uid, message);
419 } else if (type == nfc::TAG_TYPE_2) {
420 return this->write_mifare_ultralight_tag_(uid, message);
421 }
422 ESP_LOGE(TAG, "Unsupported Tag for formatting");
423 return false;
424}
425
427 ESP_LOGCONFIG(TAG, "PN532:");
428 switch (this->error_code_) {
429 case NONE:
430 break;
431 case WAKEUP_FAILED:
432 ESP_LOGE(TAG, "Wake Up command failed!");
433 break;
435 ESP_LOGE(TAG, "SAM command failed!");
436 break;
437 }
438
439 LOG_UPDATE_INTERVAL(this);
440
441 for (auto *child : this->binary_sensors_) {
442 LOG_BINARY_SENSOR(" ", "Tag", child);
443 }
444}
445
447 if (data.size() != this->uid_.size())
448 return false;
449
450 for (size_t i = 0; i < data.size(); i++) {
451 if (data[i] != this->uid_[i])
452 return false;
453 }
454
455 this->publish_state(true);
456 this->found_ = true;
457 return true;
458}
459
460} // namespace esphome::pn532
uint8_t checksum
Definition bl0906.h:3
void mark_failed()
Mark this component as failed.
void status_clear_warning()
Definition component.h:306
size_t size() const
Definition helpers.h:277
bool empty() const
Definition helpers.h:278
void publish_state(bool new_state)
Publish a new state to the front-end.
bool process(const nfc::NfcTagUid &data)
Definition pn532.cpp:446
virtual bool write_data(const std::vector< uint8_t > &data)=0
nfc::NfcTagUid current_uid_
Definition pn532.h:99
enum PN532ReadReady read_ready_(bool block)
Definition pn532.cpp:307
virtual bool is_read_ready()=0
optional< uint32_t > rd_start_time_
Definition pn532.h:101
bool format_mifare_classic_mifare_(nfc::NfcTagUid &uid)
std::unique_ptr< nfc::NfcTag > read_mifare_ultralight_tag_(nfc::NfcTagUid &uid)
virtual bool read_response(uint8_t command, std::vector< uint8_t > &data)=0
virtual bool read_data(std::vector< uint8_t > &data, uint8_t len)=0
std::vector< PN532BinarySensor * > binary_sensors_
Definition pn532.h:96
bool format_mifare_classic_ndef_(nfc::NfcTagUid &uid)
void dump_config() override
Definition pn532.cpp:426
void setup() override
Definition pn532.cpp:16
bool write_mifare_classic_tag_(nfc::NfcTagUid &uid, nfc::NdefMessage *message)
std::unique_ptr< nfc::NfcTag > read_mifare_classic_tag_(nfc::NfcTagUid &uid)
enum esphome::pn532::PN532::NfcTask READ
std::vector< nfc::NfcOnTagTrigger * > triggers_ontagremoved_
Definition pn532.h:98
CallbackManager< void()> on_finished_write_callback_
Definition pn532.h:114
void write_mode(nfc::NdefMessage *message)
Definition pn532.cpp:387
void update() override
Definition pn532.cpp:102
std::vector< nfc::NfcOnTagTrigger * > triggers_ontag_
Definition pn532.h:97
bool write_mifare_ultralight_tag_(nfc::NfcTagUid &uid, nfc::NdefMessage *message)
enum esphome::pn532::PN532::PN532Error NONE
bool clean_tag_(nfc::NfcTagUid &uid)
Definition pn532.cpp:393
bool write_command_(const std::vector< uint8_t > &data)
Definition pn532.cpp:243
bool format_tag_(nfc::NfcTagUid &uid)
Definition pn532.cpp:404
nfc::NdefMessage * next_task_message_to_write_
Definition pn532.h:100
bool write_tag_(nfc::NfcTagUid &uid, nfc::NdefMessage *message)
Definition pn532.cpp:415
std::unique_ptr< nfc::NfcTag > read_tag_(nfc::NfcTagUid &uid)
Definition pn532.cpp:358
void loop() override
Definition pn532.cpp:122
const char * message
Definition component.cpp:35
void yield(void)
uint16_t type
char * format_uid_to(char *buffer, std::span< const uint8_t > uid)
Format UID to buffer with '-' separator (e.g., "04-11-22-33"). Returns buffer for inline use.
Definition nfc.cpp:10
uint8_t guess_tag_type(uint8_t uid_length)
Definition nfc.cpp:29
const char * tag
Definition log.h:74
void HOT delay(uint32_t ms)
Definition hal.cpp:82
uint32_t IRAM_ATTR HOT millis()
Definition hal.cpp:28
static void uint32_t