ESPHome 2026.3.0-dev
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 {
13namespace pn532 {
14
15static const char *const TAG = "pn532";
16
18 // Get version data
19 if (!this->write_command_({PN532_COMMAND_VERSION_DATA})) {
20 ESP_LOGW(TAG, "Error sending version command, trying again");
21 if (!this->write_command_({PN532_COMMAND_VERSION_DATA})) {
22 ESP_LOGE(TAG, "Error sending version command");
23 this->mark_failed();
24 return;
25 }
26 }
27
28 std::vector<uint8_t> version_data;
29 if (!this->read_response(PN532_COMMAND_VERSION_DATA, version_data)) {
30 ESP_LOGE(TAG, "Error getting version");
31 this->mark_failed();
32 return;
33 }
34 ESP_LOGD(TAG, "Found chip PN5%02X, Firmware v%d.%d", version_data[0], version_data[1], version_data[2]);
35
36 if (!this->write_command_({
37 PN532_COMMAND_SAMCONFIGURATION,
38 0x01, // normal mode
39 0x14, // zero timeout (not in virtual card mode)
40 0x01,
41 })) {
42 ESP_LOGE(TAG, "No wakeup ack");
43 this->mark_failed();
44 return;
45 }
46
47 std::vector<uint8_t> wakeup_result;
48 if (!this->read_response(PN532_COMMAND_SAMCONFIGURATION, wakeup_result)) {
49 this->error_code_ = WAKEUP_FAILED;
50 this->mark_failed();
51 return;
52 }
53
54 // Set up SAM (secure access module)
55 uint8_t sam_timeout = std::min<uint8_t>(255u, this->update_interval_ / 50);
56 if (!this->write_command_({
57 PN532_COMMAND_SAMCONFIGURATION,
58 0x01, // normal mode
59 sam_timeout, // timeout as multiple of 50ms (actually only for virtual card mode, but shouldn't matter)
60 0x01, // Enable IRQ
61 })) {
62 this->error_code_ = SAM_COMMAND_FAILED;
63 this->mark_failed();
64 return;
65 }
66
67 std::vector<uint8_t> sam_result;
68 if (!this->read_response(PN532_COMMAND_SAMCONFIGURATION, sam_result)) {
69 ESP_LOGV(TAG, "Invalid SAM result: (%u)", sam_result.size()); // NOLINT
70 for (uint8_t dat : sam_result) {
71 ESP_LOGV(TAG, " 0x%02X", dat);
72 }
73 this->error_code_ = SAM_COMMAND_FAILED;
74 this->mark_failed();
75 return;
76 }
77
78 this->turn_off_rf_();
79}
80
82 updates_enabled_ = false;
83 requested_read_ = false;
84 ESP_LOGI(TAG, "Powering down PN532");
85 if (!this->write_command_({PN532_COMMAND_POWERDOWN, 0b10100000})) { // enable i2c,spi wakeup
86 ESP_LOGE(TAG, "Error writing powerdown command to PN532");
87 return false;
88 }
89 std::vector<uint8_t> response;
90 if (!this->read_response(PN532_COMMAND_POWERDOWN, response)) {
91 ESP_LOGE(TAG, "Error reading PN532 powerdown response");
92 return false;
93 }
94 if (response[0] != 0x00) {
95 ESP_LOGE(TAG, "Error on PN532 powerdown: %02x", response[0]);
96 return false;
97 }
98 ESP_LOGV(TAG, "Powerdown successful");
99 delay(1);
100 return true;
101}
102
104 if (!updates_enabled_)
105 return;
106
107 for (auto *obj : this->binary_sensors_)
108 obj->on_scan_end();
109
110 if (!this->write_command_({
111 PN532_COMMAND_INLISTPASSIVETARGET,
112 0x01, // max 1 card
113 0x00, // baud rate ISO14443A (106 kbit/s)
114 })) {
115 ESP_LOGW(TAG, "Requesting tag read failed!");
116 this->status_set_warning();
117 return;
118 }
119 this->status_clear_warning();
120 this->requested_read_ = true;
121}
122
124 if (!this->requested_read_)
125 return;
126
127 auto ready = this->read_ready_(false);
128 if (ready == WOULDBLOCK)
129 return;
130
131 bool success = false;
132 std::vector<uint8_t> read;
133
134 if (ready == READY) {
135 success = this->read_response(PN532_COMMAND_INLISTPASSIVETARGET, read);
136 } else {
137 this->send_ack_(); // abort still running InListPassiveTarget
138 }
139
140 this->requested_read_ = false;
141
142 if (!success) {
143 // Something failed
144 if (!this->current_uid_.empty()) {
145 auto tag = make_unique<nfc::NfcTag>(this->current_uid_);
146 for (auto *trigger : this->triggers_ontagremoved_)
147 trigger->process(tag);
148 }
149 this->current_uid_ = {};
150 this->turn_off_rf_();
151 return;
152 }
153
154 uint8_t num_targets = read[0];
155 if (num_targets != 1) {
156 // no tags found or too many
157 if (!this->current_uid_.empty()) {
158 auto tag = make_unique<nfc::NfcTag>(this->current_uid_);
159 for (auto *trigger : this->triggers_ontagremoved_)
160 trigger->process(tag);
161 }
162 this->current_uid_ = {};
163 this->turn_off_rf_();
164 return;
165 }
166
167 uint8_t nfcid_length = read[5];
168 if (nfcid_length > nfc::NFC_UID_MAX_LENGTH || read.size() < 6U + nfcid_length) {
169 // oops, pn532 returned invalid data
170 return;
171 }
172 nfc::NfcTagUid nfcid(read.begin() + 6, read.begin() + 6 + nfcid_length);
173
174 bool report = true;
175 for (auto *bin_sens : this->binary_sensors_) {
176 if (bin_sens->process(nfcid)) {
177 report = false;
178 }
179 }
180
181 if (nfcid.size() == this->current_uid_.size()) {
182 bool same_uid = true;
183 for (size_t i = 0; i < nfcid.size(); i++)
184 same_uid &= nfcid[i] == this->current_uid_[i];
185 if (same_uid)
186 return;
187 }
188
189 this->current_uid_ = nfcid;
190
191 if (next_task_ == READ) {
192 auto tag = this->read_tag_(nfcid);
193 for (auto *trigger : this->triggers_ontag_)
194 trigger->process(tag);
195
196 if (report) {
197 char uid_buf[nfc::FORMAT_UID_BUFFER_SIZE];
198 ESP_LOGD(TAG, "Found new tag '%s'", nfc::format_uid_to(uid_buf, nfcid));
199 if (tag->has_ndef_message()) {
200 const auto &message = tag->get_ndef_message();
201 const auto &records = message->get_records();
202 ESP_LOGD(TAG, " NDEF formatted records:");
203 for (const auto &record : records) {
204 ESP_LOGD(TAG, " %s - %s", record->get_type().c_str(), record->get_payload().c_str());
205 }
206 }
207 }
208 } else if (next_task_ == CLEAN) {
209 ESP_LOGD(TAG, " Tag cleaning");
210 if (!this->clean_tag_(nfcid)) {
211 ESP_LOGE(TAG, " Tag was not fully cleaned successfully");
212 }
213 ESP_LOGD(TAG, " Tag cleaned!");
214 } else if (next_task_ == FORMAT) {
215 ESP_LOGD(TAG, " Tag formatting");
216 if (!this->format_tag_(nfcid)) {
217 ESP_LOGE(TAG, "Error formatting tag as NDEF");
218 }
219 ESP_LOGD(TAG, " Tag formatted!");
220 } else if (next_task_ == WRITE) {
221 if (this->next_task_message_to_write_ != nullptr) {
222 ESP_LOGD(TAG, " Tag writing");
223 ESP_LOGD(TAG, " Tag formatting");
224 if (!this->format_tag_(nfcid)) {
225 ESP_LOGE(TAG, " Tag could not be formatted for writing");
226 } else {
227 ESP_LOGD(TAG, " Writing NDEF data");
228 if (!this->write_tag_(nfcid, this->next_task_message_to_write_)) {
229 ESP_LOGE(TAG, " Failed to write message to tag");
230 }
231 ESP_LOGD(TAG, " Finished writing NDEF data");
232 delete this->next_task_message_to_write_;
233 this->next_task_message_to_write_ = nullptr;
234 this->on_finished_write_callback_.call();
235 }
236 }
237 }
238
239 this->read_mode();
240
241 this->turn_off_rf_();
242}
243
244bool PN532::write_command_(const std::vector<uint8_t> &data) {
245 std::vector<uint8_t> write_data;
246 // Preamble
247 write_data.push_back(0x00);
248
249 // Start code
250 write_data.push_back(0x00);
251 write_data.push_back(0xFF);
252
253 // Length of message, TFI + data bytes
254 const uint8_t real_length = data.size() + 1;
255 // LEN
256 write_data.push_back(real_length);
257 // LCS (Length checksum)
258 write_data.push_back(~real_length + 1);
259
260 // TFI (Frame Identifier, 0xD4 means to PN532, 0xD5 means from PN532)
261 write_data.push_back(0xD4);
262 // calculate checksum, TFI is part of checksum
263 uint8_t checksum = 0xD4;
264
265 // DATA
266 for (uint8_t dat : data) {
267 write_data.push_back(dat);
268 checksum += dat;
269 }
270
271 // DCS (Data checksum)
272 write_data.push_back(~checksum + 1);
273 // Postamble
274 write_data.push_back(0x00);
275
276 this->write_data(write_data);
277
278 return this->read_ack_();
279}
280
282 ESP_LOGV(TAG, "Reading ACK");
283
284 std::vector<uint8_t> data;
285 if (!this->read_data(data, 6)) {
286 return false;
287 }
288
289 bool matches = (data[1] == 0x00 && // preamble
290 data[2] == 0x00 && // start of packet
291 data[3] == 0xFF && data[4] == 0x00 && // ACK packet code
292 data[5] == 0xFF && data[6] == 0x00); // postamble
293 ESP_LOGV(TAG, "ACK valid: %s", YESNO(matches));
294 return matches;
295}
296
298 ESP_LOGV(TAG, "Sending ACK for abort");
299 this->write_data({0x00, 0x00, 0xFF, 0x00, 0xFF, 0x00});
300 delay(10);
301}
303 ESP_LOGV(TAG, "Sending NACK for retransmit");
304 this->write_data({0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00});
305 delay(10);
306}
307
309 if (this->rd_ready_ == READY) {
310 if (block) {
311 this->rd_start_time_.reset();
312 this->rd_ready_ = WOULDBLOCK;
313 }
314 return READY;
315 }
316
317 if (!this->rd_start_time_.has_value()) {
318 this->rd_start_time_ = millis();
319 }
320
321 while (true) {
322 if (this->is_read_ready()) {
323 this->rd_ready_ = READY;
324 break;
325 }
326
327 if (millis() - *this->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 pn532
461} // namespace esphome
uint8_t checksum
Definition bl0906.h:3
void mark_failed()
Mark this component as failed.
void status_set_warning(const char *message=nullptr)
void status_clear_warning()
size_t size() const
Definition helpers.h:269
bool empty() const
Definition helpers.h:270
void publish_state(bool new_state)
Publish a new state to the front-end.
bool has_value() const
Definition optional.h:92
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:100
enum PN532ReadReady read_ready_(bool block)
Definition pn532.cpp:308
virtual bool is_read_ready()=0
optional< uint32_t > rd_start_time_
Definition pn532.h:102
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:97
bool format_mifare_classic_ndef_(nfc::NfcTagUid &uid)
void dump_config() override
Definition pn532.cpp:426
void setup() override
Definition pn532.cpp:17
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:99
CallbackManager< void()> on_finished_write_callback_
Definition pn532.h:115
void write_mode(nfc::NdefMessage *message)
Definition pn532.cpp:387
void update() override
Definition pn532.cpp:103
std::vector< nfc::NfcOnTagTrigger * > triggers_ontag_
Definition pn532.h:98
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:244
bool format_tag_(nfc::NfcTagUid &uid)
Definition pn532.cpp:404
nfc::NdefMessage * next_task_message_to_write_
Definition pn532.h:101
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:123
const char * message
Definition component.cpp:38
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:11
uint8_t guess_tag_type(uint8_t uid_length)
Definition nfc.cpp:30
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
void HOT yield()
Definition core.cpp:24
void HOT delay(uint32_t ms)
Definition core.cpp:27
uint32_t IRAM_ATTR HOT millis()
Definition core.cpp:25