ESPHome 2026.12.0-dev
Loading...
Searching...
No Matches
pn71xx.cpp
Go to the documentation of this file.
1#include <algorithm>
2#include <utility>
3
4#include "pn71xx.h"
5
7#include "esphome/core/hal.h"
9#include "esphome/core/log.h"
10
11namespace esphome::pn71xx {
12
13ESPHOME_LOG_TAG(TAG, "pn71xx");
14
15// Builds a message with a URI record and, optionally, the Home Assistant Android app record
16static std::unique_ptr<nfc::NdefMessage> build_uri_message(const std::string &uri,
17 const bool include_android_app_record) {
18 auto ndef_message = make_unique<nfc::NdefMessage>();
19
20 ndef_message->add_uri_record(uri);
21
22 if (include_android_app_record) {
23 auto ext_record = make_unique<nfc::NdefRecord>();
24 ext_record->set_tnf(nfc::TNF_EXTERNAL_TYPE);
25 ext_record->set_type(nfc::HA_TAG_ID_EXT_RECORD_TYPE);
26 ext_record->set_payload(nfc::HA_TAG_ID_EXT_RECORD_PAYLOAD);
27 ndef_message->add_record(std::move(ext_record));
28 }
29 return ndef_message;
30}
31
33 this->irq_pin_->setup();
34 this->ven_pin_->setup();
35
36 this->nci_fsm_transition_(); // kick off reset & init processes
37}
38
40 LOG_PIN(" IRQ pin: ", this->irq_pin_);
41 LOG_PIN(" VEN pin: ", this->ven_pin_);
42}
43
45 this->nci_fsm_transition_();
46 this->purge_old_tags_();
47}
48
49void PN71xx::set_tag_emulation_message(const std::shared_ptr<nfc::NdefMessage> &message) {
50 if (message == nullptr) {
51 return;
52 }
53 // encoded once here so it is validated up front and not re-encoded for every read from the reader
54 auto encoded = message->encode();
55 if (encoded.size() > CARD_EMU_T4T_MAX_NDEF_SIZE) {
56 ESP_LOGE(TAG, "Tag emulation message too long: %zu > %u bytes", encoded.size(), CARD_EMU_T4T_MAX_NDEF_SIZE);
57 return;
58 }
59 this->card_emulation_ndef_.init(encoded.size());
60 for (const uint8_t byte : encoded) {
62 }
63 ESP_LOGD(TAG, "Tag emulation message set");
64}
65
66void PN71xx::set_tag_emulation_message(const std::string &message, const bool include_android_app_record) {
67 this->set_tag_emulation_message(build_uri_message(message, include_android_app_record));
68}
69
70void PN71xx::set_tag_emulation_message(const char *message, const bool include_android_app_record) {
71 this->set_tag_emulation_message(std::string(message), include_android_app_record);
72}
73
75 if (this->listening_enabled_) {
76 this->listening_enabled_ = false;
77 this->config_refresh_pending_ = true;
78 }
79 ESP_LOGD(TAG, "Tag emulation disabled");
80}
81
83 if (this->card_emulation_ndef_.empty()) {
84 ESP_LOGE(TAG, "No NDEF message is set; tag emulation cannot be enabled");
85 return;
86 }
87 if (!this->listening_enabled_) {
88 this->listening_enabled_ = true;
89 this->config_refresh_pending_ = true;
90 }
91 ESP_LOGD(TAG, "Tag emulation enabled");
92}
93
95 if (this->polling_enabled_) {
96 this->polling_enabled_ = false;
97 this->config_refresh_pending_ = true;
98 }
99 ESP_LOGD(TAG, "Tag polling disabled");
100}
101
103 if (!this->polling_enabled_) {
104 this->polling_enabled_ = true;
105 this->config_refresh_pending_ = true;
106 }
107 ESP_LOGD(TAG, "Tag polling enabled");
108}
109
111 this->next_task_ = EP_READ;
112 ESP_LOGD(TAG, "Waiting to read next tag");
113}
114
116 this->next_task_ = EP_CLEAN;
117 ESP_LOGD(TAG, "Waiting to clean next tag");
118}
119
121 this->next_task_ = EP_FORMAT;
122 ESP_LOGD(TAG, "Waiting to format next tag");
123}
124
126 if (this->next_task_message_to_write_ == nullptr) {
127 ESP_LOGW(TAG, "Message to write must be set before setting write mode");
128 return;
129 }
130
131 this->next_task_ = EP_WRITE;
132 ESP_LOGD(TAG, "Waiting to write next tag");
133}
134
135void PN71xx::set_tag_write_message(std::shared_ptr<nfc::NdefMessage> message) {
136 this->next_task_message_to_write_ = std::move(message);
137 ESP_LOGD(TAG, "Message to write has been set");
138}
139
140void PN71xx::set_tag_write_message(const std::string &message, const bool include_android_app_record) {
141 this->set_tag_write_message(build_uri_message(message, include_android_app_record));
142}
143
144uint8_t PN71xx::set_test_mode(const TestMode test_mode, const std::vector<uint8_t> &data,
145 std::vector<uint8_t> &result) {
146 auto test_oid = TEST_PRBS_OID;
147
148 switch (test_mode) {
150 // test_oid = TEST_PRBS_OID;
151 break;
152
154 test_oid = TEST_ANTENNA_OID;
155 break;
156
158 test_oid = TEST_GET_REGISTER_OID;
159 break;
160
162 default:
163 ESP_LOGD(TAG, "Exiting test mode");
165 return nfc::STATUS_OK;
166 }
167
168 if (this->reset_core_(true, true) != nfc::STATUS_OK) {
169 ESP_LOGE(TAG, "Failed to reset NCI core");
171 result.clear();
172 return nfc::STATUS_FAILED;
173 } else {
175 }
176 if (this->init_core_() != nfc::STATUS_OK) {
177 ESP_LOGE(TAG, "Failed to initialise NCI core");
179 result.clear();
180 return nfc::STATUS_FAILED;
181 } else {
183 }
184
186 nfc::NciMessage tx(nfc::NCI_PKT_MT_CTRL_COMMAND, nfc::NCI_PROPRIETARY_GID, test_oid, data);
187
188 ESP_LOGW(TAG, "Starting test mode, OID 0x%02X", test_oid);
189 auto status = this->transceive_(tx, rx, NFCC_INIT_TIMEOUT);
190
191 if (status != nfc::STATUS_OK) {
192 ESP_LOGE(TAG, "Failed to start test mode, OID 0x%02X", test_oid);
194 result.clear();
195 } else {
196 // the payload after the status byte, if the NFCC sent one
197 const auto payload = rx.get_payload();
198 result.assign(payload.begin() + std::min<size_t>(1, payload.size()), payload.end());
199 if (!result.empty()) {
200 char buf[nfc::FORMAT_BYTES_BUFFER_SIZE];
201 ESP_LOGW(TAG, "Test results: %s", nfc::format_bytes_to(buf, result));
202 }
203 }
204 return status;
205}
206
207uint8_t PN71xx::reset_core_(const bool reset_config, const bool power) {
208 this->prepare_reset();
209
210 if (power) {
211 pulse_reset(this->ven_pin_,
212 {.high_before_ms = NFCC_RESET_DELAY, .low_ms = NFCC_RESET_DELAY, .high_after_ms = NFCC_INIT_TIMEOUT});
213 }
214
216 nfc::NciMessage tx(nfc::NCI_PKT_MT_CTRL_COMMAND, nfc::NCI_CORE_GID, nfc::NCI_CORE_RESET_OID,
217 {(uint8_t) reset_config});
218
219 if (this->transceive_(tx, rx, NFCC_INIT_TIMEOUT) != nfc::STATUS_OK) {
220 ESP_LOGE(TAG, "Error sending reset command");
221 return nfc::STATUS_FAILED;
222 }
223
224 if (!rx.simple_status_response_is(nfc::STATUS_OK)) {
225 char buf[nfc::FORMAT_BYTES_BUFFER_SIZE];
226 ESP_LOGE(TAG, "Invalid reset response: %s", nfc::format_bytes_to(buf, rx.get_message()));
227 return rx.get_simple_status_response();
228 }
229 return this->verify_reset(rx, reset_config);
230}
231
234 nfc::NciMessage tx(nfc::NCI_PKT_MT_CTRL_COMMAND, nfc::NCI_CORE_GID, nfc::NCI_CORE_INIT_OID);
235
236 if (this->transceive_(tx, rx) != nfc::STATUS_OK) {
237 ESP_LOGE(TAG, "Error sending initialise command");
238 return nfc::STATUS_FAILED;
239 }
240
241 if (!rx.simple_status_response_is(nfc::STATUS_OK)) {
242 char buf[nfc::FORMAT_BYTES_BUFFER_SIZE];
243 ESP_LOGE(TAG, "Invalid initialise response: %s", nfc::format_bytes_to(buf, rx.get_message()));
244 return nfc::STATUS_FAILED;
245 }
246
247 return this->process_init_response(rx);
248}
249
252 nfc::NciMessage tx(nfc::NCI_PKT_MT_CTRL_COMMAND, nfc::NCI_PROPRIETARY_GID, nfc::NCI_CORE_SET_CONFIG_OID);
253
254 if (this->transceive_(tx, rx) != nfc::STATUS_OK) {
255 ESP_LOGE(TAG, "Error enabling proprietary extensions");
256 return nfc::STATUS_FAILED;
257 }
258
259 tx.set_message(nfc::NCI_PKT_MT_CTRL_COMMAND, nfc::NCI_CORE_GID, nfc::NCI_CORE_SET_CONFIG_OID, this->pmu_config());
260
261 if (this->transceive_(tx, rx) != nfc::STATUS_OK) {
262 ESP_LOGE(TAG, "Error sending PMU config");
263 return nfc::STATUS_FAILED;
264 }
265
266 return this->send_core_config_();
267}
268
270 std::span<const uint8_t> core_config = CORE_CONFIG_SOLO;
271 this->core_config_is_solo_ = true;
272
273 if (this->listening_enabled_ && this->polling_enabled_) {
274 core_config = CORE_CONFIG_RW_CE;
275 this->core_config_is_solo_ = false;
276 }
277
279 nfc::NciMessage tx(nfc::NCI_PKT_MT_CTRL_COMMAND, nfc::NCI_CORE_GID, nfc::NCI_CORE_SET_CONFIG_OID, core_config);
280
281 if (this->transceive_(tx, rx) != nfc::STATUS_OK) {
282 ESP_LOGW(TAG, "Error sending core config");
283 return nfc::STATUS_FAILED;
284 }
285
286 return nfc::STATUS_OK;
287}
288
290 bool core_config_should_be_solo = !(this->listening_enabled_ && this->polling_enabled_);
291
293 if (this->stop_discovery_() != nfc::STATUS_OK) {
295 return nfc::STATUS_FAILED;
296 }
298 }
299
300 if (this->core_config_is_solo_ != core_config_should_be_solo) {
301 if (this->send_core_config_() != nfc::STATUS_OK) {
302 ESP_LOGV(TAG, "Failed to refresh core config");
303 return nfc::STATUS_FAILED;
304 }
305 }
306 this->config_refresh_pending_ = false;
307 return nfc::STATUS_OK;
308}
309
312 nfc::NciMessage tx(nfc::NCI_PKT_MT_CTRL_COMMAND, nfc::RF_GID, nfc::RF_DISCOVER_MAP_OID,
313 {sizeof(RF_DISCOVER_MAP_CONFIG) / 3});
314 tx.append(RF_DISCOVER_MAP_CONFIG);
315
316 if (this->transceive_(tx, rx, NFCC_INIT_TIMEOUT) != nfc::STATUS_OK) {
317 ESP_LOGE(TAG, "Error sending discover map poll config");
318 return nfc::STATUS_FAILED;
319 }
320 return nfc::STATUS_OK;
321}
322
325 nfc::NciMessage tx(nfc::NCI_PKT_MT_CTRL_COMMAND, nfc::RF_GID, nfc::RF_SET_LISTEN_MODE_ROUTING_OID,
327
328 if (this->transceive_(tx, rx, NFCC_INIT_TIMEOUT) != nfc::STATUS_OK) {
329 ESP_LOGE(TAG, "Error setting listen mode routing config");
330 return nfc::STATUS_FAILED;
331 }
332 return nfc::STATUS_OK;
333}
334
336 std::span<const uint8_t> rf_discovery_config = RF_DISCOVERY_CONFIG;
337
338 if (!this->listening_enabled_) {
339 rf_discovery_config = RF_DISCOVERY_POLL_CONFIG;
340 } else if (!this->polling_enabled_) {
341 rf_discovery_config = RF_DISCOVERY_LISTEN_CONFIG;
342 }
343
345 nfc::NciMessage tx(nfc::NCI_PKT_MT_CTRL_COMMAND, nfc::RF_GID, nfc::RF_DISCOVER_OID,
346 {static_cast<uint8_t>(rf_discovery_config.size())});
347 for (const uint8_t mode_tech : rf_discovery_config) {
348 tx.append({mode_tech, 0x01}); // RF Technology and Mode will be executed in every discovery period
349 }
350
351 if (this->transceive_(tx, rx) != nfc::STATUS_OK) {
352 switch (rx.get_simple_status_response()) {
353 // in any of these cases, we are either already in or will remain in discovery, which satisfies the function call
354 case nfc::STATUS_OK:
355 case nfc::DISCOVERY_ALREADY_STARTED:
356 case nfc::DISCOVERY_TARGET_ACTIVATION_FAILED:
357 case nfc::DISCOVERY_TEAR_DOWN:
358 return nfc::STATUS_OK;
359
360 default:
361 ESP_LOGE(TAG, "Error starting discovery");
362 return nfc::STATUS_FAILED;
363 }
364 }
365
366 return nfc::STATUS_OK;
367}
368
369uint8_t PN71xx::stop_discovery_() { return this->deactivate_(nfc::DEACTIVATION_TYPE_IDLE, NFCC_TAG_WRITE_TIMEOUT); }
370
371uint8_t PN71xx::deactivate_(const uint8_t type, const uint16_t timeout) {
373 nfc::NciMessage tx(nfc::NCI_PKT_MT_CTRL_COMMAND, nfc::RF_GID, nfc::RF_DEACTIVATE_OID, {type});
374
375 auto status = this->transceive_(tx, rx, timeout);
376 // if (status != nfc::STATUS_OK) {
377 // ESP_LOGE(TAG, "Error sending deactivate type %u", type);
378 // return nfc::STATUS_FAILED;
379 // }
380 return status;
381}
382
384 if (this->discovered_endpoint_.empty()) {
385 ESP_LOGW(TAG, "No cached tags to select");
386 this->stop_discovery_();
388 return;
389 }
390 this->selecting_endpoint_ = 0;
391 for (size_t i = 0; i < this->discovered_endpoint_.size(); i++) {
392 if (!this->discovered_endpoint_[i].trig_called) {
393 this->selecting_endpoint_ = i;
394 break;
395 }
396 }
397 const auto &endpoint = this->discovered_endpoint_[this->selecting_endpoint_];
398 // the RF interface must match the one set for this protocol in RF_DISCOVER_MAP_CONFIG
399 uint8_t interface = nfc::INTF_FRAME;
400 if (endpoint.protocol == nfc::PROT_ISODEP) {
401 interface = nfc::INTF_ISODEP;
402 } else if (endpoint.protocol == nfc::PROT_MIFARE) {
403 interface = nfc::INTF_TAGCMD;
404 }
406 nfc::NciMessage tx(nfc::NCI_PKT_MT_CTRL_COMMAND, nfc::RF_GID, nfc::RF_DISCOVER_SELECT_OID,
407 {endpoint.id, endpoint.protocol, interface});
408
409 if (this->transceive_(tx, rx) != nfc::STATUS_OK) {
410 ESP_LOGE(TAG, "Error selecting endpoint");
411 } else {
413 }
414}
415
416uint8_t PN71xx::read_endpoint_data_(const uint8_t protocol, nfc::NfcTag &tag) {
417 switch (protocol) {
418 case nfc::PROT_MIFARE:
419 ESP_LOGV(TAG, "Reading Mifare classic");
420 return this->read_mifare_classic_tag_(tag);
421
422 case nfc::PROT_T2T:
423 ESP_LOGV(TAG, "Reading Mifare ultralight");
424 return this->read_mifare_ultralight_tag_(tag);
425
426 default:
427 ESP_LOGV(TAG, "Reading protocol 0x%02X is not supported", protocol);
428 break;
429 }
430 return nfc::STATUS_FAILED;
431}
432
433uint8_t PN71xx::clean_endpoint_(const uint8_t protocol) {
434 switch (protocol) {
435 case nfc::PROT_MIFARE:
436 return this->format_mifare_classic_mifare_();
437
438 case nfc::PROT_T2T:
439 return this->clean_mifare_ultralight_();
440
441 default:
442 ESP_LOGE(TAG, "Unsupported tag for cleaning");
443 break;
444 }
445 return nfc::STATUS_FAILED;
446}
447
448uint8_t PN71xx::format_endpoint_(const uint8_t protocol) {
449 switch (protocol) {
450 case nfc::PROT_MIFARE:
451 return this->format_mifare_classic_ndef_();
452
453 case nfc::PROT_T2T:
454 return this->clean_mifare_ultralight_();
455
456 default:
457 ESP_LOGE(TAG, "Unsupported tag for formatting");
458 break;
459 }
460 return nfc::STATUS_FAILED;
461}
462
463uint8_t PN71xx::write_endpoint_(const uint8_t protocol, nfc::NfcTagUid &uid,
464 std::shared_ptr<nfc::NdefMessage> &message) {
465 switch (protocol) {
466 case nfc::PROT_MIFARE:
467 return this->write_mifare_classic_tag_(message);
468
469 case nfc::PROT_T2T:
470 return this->write_mifare_ultralight_tag_(uid, message);
471
472 default:
473 ESP_LOGE(TAG, "Unsupported tag for writing");
474 break;
475 }
476 return nfc::STATUS_FAILED;
477}
478
479bool PN71xx::parse_uid_(const uint8_t mode_tech, const std::span<const uint8_t> rf_tech_params, nfc::NfcTagUid &uid) {
480 if (mode_tech != (nfc::MODE_POLL | nfc::TECH_PASSIVE_NFCA)) {
481 return false;
482 }
483 // RF technology parameters: SENS_RES (2 bytes), NFCID1 length, NFCID1, ...
484 if (rf_tech_params.size() < 3) {
485 ESP_LOGE(TAG, "NFC-A parameters too short");
486 return false;
487 }
488 const uint8_t uid_length = rf_tech_params[2];
489 if (uid_length == 0 || uid_length > nfc::NFC_UID_MAX_LENGTH || rf_tech_params.size() < 3u + uid_length) {
490 ESP_LOGE(TAG, "Invalid UID length: %u", uid_length);
491 return false;
492 }
493 uid.assign(rf_tech_params.begin() + 3, rf_tech_params.begin() + 3 + uid_length);
494 return true;
495}
496
497std::unique_ptr<nfc::NfcTag> PN71xx::build_tag_(const uint8_t protocol, const nfc::NfcTagUid &uid) {
498 if (protocol == nfc::PROT_MIFARE) {
499 return make_unique<nfc::NfcTag>(uid, nfc::MIFARE_CLASSIC);
500 }
501 if (protocol == nfc::PROT_T2T) {
502 return make_unique<nfc::NfcTag>(uid, nfc::NFC_FORUM_TYPE_2);
503 }
504 return make_unique<nfc::NfcTag>(uid);
505}
506
507size_t PN71xx::find_or_add_tag_(const uint8_t protocol, const nfc::NfcTagUid &uid) {
508 const auto tag_loc = this->find_tag_uid_(uid);
509 if (tag_loc.has_value()) {
510 ESP_LOGVV(TAG, "Tag cache updated");
511 return tag_loc.value();
512 }
513 if (this->discovered_endpoint_.size() >= MAX_DISCOVERED_ENDPOINTS) {
514 size_t oldest = 0;
515 for (size_t i = 1; i < this->discovered_endpoint_.size(); i++) {
516 if (this->discovered_endpoint_[i].last_seen < this->discovered_endpoint_[oldest].last_seen) {
517 oldest = i;
518 }
519 }
520 ESP_LOGW(TAG, "Tag cache full; dropping the tag seen longest ago");
521 this->erase_tag_(oldest);
522 }
523 this->discovered_endpoint_.emplace_next() = DiscoveredEndpoint{.last_seen = App.get_loop_component_start_time(),
524 .tag = this->build_tag_(protocol, uid),
525 .id = 0,
526 .protocol = protocol,
527 .trig_called = false};
528 ESP_LOGVV(TAG, "Tag added to cache");
529 return this->discovered_endpoint_.size() - 1;
530}
531
532optional<size_t> PN71xx::find_tag_uid_(const nfc::NfcTagUid &uid) {
533 if (!this->discovered_endpoint_.empty()) {
534 for (size_t i = 0; i < this->discovered_endpoint_.size(); i++) {
535 auto existing_tag_uid = this->discovered_endpoint_[i].tag->get_uid();
536 bool uid_match = (uid.size() == existing_tag_uid.size());
537
538 if (uid_match) {
539 for (size_t i = 0; i < uid.size(); i++) {
540 uid_match &= (uid[i] == existing_tag_uid[i]);
541 }
542 if (uid_match) {
543 return i;
544 }
545 }
546 }
547 }
548 return nullopt;
549}
550
552 // millis(), not the loop start time: last_seen is stamped after tag operations that may block for seconds
553 const uint32_t now = millis();
554 for (size_t i = this->discovered_endpoint_.size(); i > 0; i--) {
555 if (now - this->discovered_endpoint_[i - 1].last_seen > this->tag_ttl_) {
556 this->erase_tag_(i - 1);
557 }
558 }
559}
560
561void PN71xx::erase_tag_(const uint8_t tag_index) {
562 if (tag_index < this->discovered_endpoint_.size()) {
563 for (auto *trigger : this->triggers_ontagremoved_) {
564 trigger->process(this->discovered_endpoint_[tag_index].tag);
565 }
566#ifdef NFC_TAG_LISTENER_COUNT
567 for (auto *listener : this->tag_listeners_) {
568 listener->tag_off(*this->discovered_endpoint_[tag_index].tag);
569 }
570#endif
571 char uid_buf[nfc::FORMAT_UID_BUFFER_SIZE];
572 ESP_LOGI(TAG, "Tag %s removed", nfc::format_uid_to(uid_buf, this->discovered_endpoint_[tag_index].tag->get_uid()));
573 // keep the remaining entries in order; selecting_endpoint_ indexes into this list
574 for (size_t i = tag_index; i + 1 < this->discovered_endpoint_.size(); i++) {
575 this->discovered_endpoint_[i] = std::move(this->discovered_endpoint_[i + 1]);
576 }
577 // StaticVector::resize() does not destroy the dropped slot; free its tag now, not when the slot is reused
578 this->discovered_endpoint_[this->discovered_endpoint_.size() - 1].tag.reset();
579 this->discovered_endpoint_.resize(this->discovered_endpoint_.size() - 1);
580 }
581}
582
584 switch (this->nci_state_) {
586 if (this->reset_core_(true, true) != nfc::STATUS_OK) {
587 ESP_LOGE(TAG, "Failed to reset NCI core");
589 return;
590 } else {
592 }
593 [[fallthrough]];
594
596 if (this->init_core_() != nfc::STATUS_OK) {
597 ESP_LOGE(TAG, "Failed to initialise NCI core");
599 return;
600 } else {
602 }
603 [[fallthrough]];
604
606 if (this->send_init_config_() != nfc::STATUS_OK) {
607 ESP_LOGE(TAG, "Failed to send initial config");
609 return;
610 } else {
611 this->config_refresh_pending_ = false;
613 }
614 [[fallthrough]];
615
617 if (this->set_discover_map_() != nfc::STATUS_OK) {
618 ESP_LOGE(TAG, "Failed to set discover map");
620 return;
621 } else {
623 }
624 [[fallthrough]];
625
627 if (this->set_listen_mode_routing_() != nfc::STATUS_OK) {
628 ESP_LOGE(TAG, "Failed to set listen mode routing");
630 return;
631 } else {
633 }
634 [[fallthrough]];
635
638 this->stop_discovery_();
639 }
640
641 if (this->config_refresh_pending_) {
642 this->refresh_core_config_();
643 }
644
645 if (!this->listening_enabled_ && !this->polling_enabled_) {
646 return;
647 }
648
649 if (this->start_discovery_() != nfc::STATUS_OK) {
650 ESP_LOGV(TAG, "Failed to start discovery");
652 } else {
654 }
655 return;
656
659 [[fallthrough]];
660
661 // All cases below are waiting for NOTIFICATION messages
663 if (this->config_refresh_pending_) {
664 this->refresh_core_config_();
665 }
666 [[fallthrough]];
667
673 // only a notification from the NFCC ends the EP_ states; if it was lost, recover rather than wait forever.
674 // millis(), not the loop start time: the state is stamped after tag operations that may block for seconds.
676 !this->irq_pin_->digital_read() && millis() - this->last_nci_state_change_ > NFCC_STATE_TIMEOUT) {
677 ESP_LOGW(TAG, "Timed out waiting for notification in state %u; resetting NFCC", (uint8_t) this->nci_state_);
679 return;
680 }
681 if (this->irq_pin_->digital_read()) {
682 this->process_message_();
683 }
684 break;
685
686 case NCIState::TEST:
687 case NCIState::FAILED:
688 case NCIState::NONE:
689 default:
690 return;
691 }
692}
693
695 ESP_LOGVV(TAG, "nci_fsm_set_state_(%u)", (uint8_t) new_state);
696 this->nci_state_ = new_state;
698 this->error_count_ = 0;
700}
701
703 ESP_LOGVV(TAG, "nci_fsm_set_error_state_(%u); error_count_ = %u", (uint8_t) new_state, this->error_count_);
704 this->nci_state_error_ = new_state;
705 if (this->error_count_++ > NFCC_MAX_ERROR_COUNT) {
708 ESP_LOGE(TAG, "Too many initialization failures -- check device connections");
709 this->mark_failed();
711 } else {
712 ESP_LOGW(TAG, "Too many errors transitioning to state %u; resetting NFCC", (uint8_t) this->nci_state_error_);
714 }
715 }
716 return this->error_count_ > NFCC_MAX_ERROR_COUNT;
717}
718
721 if (this->read_nfcc(rx, NFCC_DEFAULT_TIMEOUT) != nfc::STATUS_OK) {
722 return; // No data
723 }
724
725 switch (rx.get_message_type()) {
726 case nfc::NCI_PKT_MT_CTRL_NOTIFICATION:
727 if (rx.get_gid() == nfc::RF_GID) {
728 switch (rx.get_oid()) {
729 case nfc::RF_INTF_ACTIVATED_OID:
730 ESP_LOGVV(TAG, "RF_INTF_ACTIVATED_OID");
732 return;
733
734 case nfc::RF_DISCOVER_OID:
735 ESP_LOGVV(TAG, "RF_DISCOVER_OID");
736 this->process_rf_discover_oid_(rx);
737 return;
738
739 case nfc::RF_DEACTIVATE_OID:
740 ESP_LOGVV(TAG, "RF_DEACTIVATE_OID: type: 0x%02X, reason: 0x%02X", rx.get_message()[3], rx.get_message()[4]);
742 return;
743
744 default:
745 ESP_LOGV(TAG, "Unimplemented RF OID received: 0x%02X", rx.get_oid());
746 }
747 } else if (rx.get_gid() == nfc::NCI_CORE_GID) {
748 switch (rx.get_oid()) {
749 case nfc::NCI_CORE_GENERIC_ERROR_OID:
750 ESP_LOGV(TAG, "NCI_CORE_GENERIC_ERROR_OID:");
751 switch (rx.get_simple_status_response()) {
752 case nfc::DISCOVERY_ALREADY_STARTED:
753 ESP_LOGV(TAG, " DISCOVERY_ALREADY_STARTED");
754 break;
755
756 case nfc::DISCOVERY_TARGET_ACTIVATION_FAILED:
757 // Tag removed too soon
758 ESP_LOGV(TAG, " DISCOVERY_TARGET_ACTIVATION_FAILED");
759 if (this->nci_state_ == NCIState::EP_SELECTING) {
761 if (!this->discovered_endpoint_.empty()) {
762 this->erase_tag_(this->selecting_endpoint_);
763 }
764 } else {
765 this->stop_discovery_();
767 }
768 break;
769
770 case nfc::DISCOVERY_TEAR_DOWN:
771 ESP_LOGV(TAG, " DISCOVERY_TEAR_DOWN");
772 break;
773
774 default:
775 ESP_LOGW(TAG, "Unknown error: 0x%02X", rx.get_simple_status_response());
776 break;
777 }
778 break;
779
780 default:
781 ESP_LOGV(TAG, "Unimplemented NCI Core OID received: 0x%02X", rx.get_oid());
782 }
783 } else {
784 char buf[nfc::FORMAT_BYTES_BUFFER_SIZE];
785 ESP_LOGV(TAG, "Unimplemented notification: %s", nfc::format_bytes_to(buf, rx.get_message()));
786 }
787 break;
788
789 case nfc::NCI_PKT_MT_CTRL_RESPONSE: {
790 char buf[nfc::FORMAT_BYTES_BUFFER_SIZE];
791 ESP_LOGV(TAG, "Unimplemented GID: 0x%02X OID: 0x%02X Full response: %s", rx.get_gid(), rx.get_oid(),
793 break;
794 }
795
796 case nfc::NCI_PKT_MT_CTRL_COMMAND: {
797 char buf[nfc::FORMAT_BYTES_BUFFER_SIZE];
798 ESP_LOGV(TAG, "Unimplemented command: %s", nfc::format_bytes_to(buf, rx.get_message()));
799 break;
800 }
801
802 case nfc::NCI_PKT_MT_DATA:
803 this->process_data_message_(rx);
804 break;
805
806 default: {
807 char buf[nfc::FORMAT_BYTES_BUFFER_SIZE];
808 ESP_LOGV(TAG, "Unimplemented message type: %s", nfc::format_bytes_to(buf, rx.get_message()));
809 break;
810 }
811 }
812}
813
814void PN71xx::process_rf_intf_activated_oid_(nfc::NciMessage &rx) { // an endpoint was activated
815 uint8_t discovery_id = rx.get_message_byte(nfc::RF_INTF_ACTIVATED_NTF_DISCOVERY_ID);
816 uint8_t interface = rx.get_message_byte(nfc::RF_INTF_ACTIVATED_NTF_INTERFACE);
817 uint8_t protocol = rx.get_message_byte(nfc::RF_INTF_ACTIVATED_NTF_PROTOCOL);
818 uint8_t mode_tech = rx.get_message_byte(nfc::RF_INTF_ACTIVATED_NTF_MODE_TECH);
819 uint8_t max_size = rx.get_message_byte(nfc::RF_INTF_ACTIVATED_NTF_MAX_SIZE);
820
821 ESP_LOGVV(TAG, "Endpoint activated -- interface: 0x%02X, protocol: 0x%02X, mode&tech: 0x%02X, max payload: %u",
822 interface, protocol, mode_tech, max_size);
823
824 if (mode_tech & nfc::MODE_LISTEN_MASK) {
825 ESP_LOGVV(TAG, "Tag activated in listen mode");
826 this->nci_fsm_set_state_(NCIState::RFST_LISTEN_ACTIVE);
827 return;
828 }
829
831 if (rx.get_message().size() < nfc::RF_INTF_ACTIVATED_NTF_RF_TECH_PARAMS) {
832 ESP_LOGE(TAG, "RF_INTF_ACTIVATED_NTF too short");
833 this->stop_discovery_();
835 return;
836 }
837 nfc::NfcTagUid uid;
838 if (!this->parse_uid_(mode_tech,
839 std::span<const uint8_t>(rx.get_message()).subspan(nfc::RF_INTF_ACTIVATED_NTF_RF_TECH_PARAMS),
840 uid)) {
841 ESP_LOGE(TAG, "Could not build tag");
842 } else {
843 auto &working_endpoint = this->discovered_endpoint_[this->find_or_add_tag_(protocol, uid)];
844 working_endpoint.id = discovery_id;
845 working_endpoint.protocol = protocol;
846 working_endpoint.last_seen = App.get_loop_component_start_time();
847
848 switch (this->next_task_) {
849 case EP_CLEAN:
850 ESP_LOGD(TAG, " Tag cleaning");
851 if (this->clean_endpoint_(working_endpoint.protocol) != nfc::STATUS_OK) {
852 ESP_LOGE(TAG, " Tag cleaning incomplete");
853 }
854 ESP_LOGD(TAG, " Tag cleaned!");
855 break;
856
857 case EP_FORMAT:
858 ESP_LOGD(TAG, " Tag formatting");
859 if (this->format_endpoint_(working_endpoint.protocol) != nfc::STATUS_OK) {
860 ESP_LOGE(TAG, "Error formatting tag as NDEF");
861 }
862 ESP_LOGD(TAG, " Tag formatted!");
863 break;
864
865 case EP_WRITE:
866 if (this->next_task_message_to_write_ != nullptr) {
867 ESP_LOGD(TAG, " Tag writing\n"
868 " Tag formatting");
869 if (this->format_endpoint_(working_endpoint.protocol) != nfc::STATUS_OK) {
870 ESP_LOGE(TAG, " Tag could not be formatted for writing");
871 } else {
872 ESP_LOGD(TAG, " Writing NDEF data");
873 if (this->write_endpoint_(working_endpoint.protocol, working_endpoint.tag->get_uid(),
874 this->next_task_message_to_write_) != nfc::STATUS_OK) {
875 ESP_LOGE(TAG, " Failed to write message to tag");
876 }
877 ESP_LOGD(TAG, " Finished writing NDEF data");
878 this->next_task_message_to_write_ = nullptr;
879 this->on_finished_write_callback_.call();
880 }
881 }
882 break;
883
884 case EP_READ:
885 default:
886 if (!working_endpoint.trig_called) {
887 char uid_buf[nfc::FORMAT_UID_BUFFER_SIZE];
888 ESP_LOGI(TAG, "Read tag type %s with UID %s", working_endpoint.tag->get_tag_type().c_str(),
889 nfc::format_uid_to(uid_buf, working_endpoint.tag->get_uid()));
890 if (this->read_endpoint_data_(working_endpoint.protocol, *working_endpoint.tag) != nfc::STATUS_OK) {
891 ESP_LOGW(TAG, " Unable to read NDEF record(s)");
892 } else if (working_endpoint.tag->has_ndef_message()) {
893 const auto &message = working_endpoint.tag->get_ndef_message();
894 const auto &records = message->get_records();
895 ESP_LOGD(TAG, " NDEF record(s):");
896 for (const auto &record : records) {
897 ESP_LOGD(TAG, " %s - %s", record->get_type().c_str(), record->get_payload().c_str());
898 }
899 } else {
900 ESP_LOGW(TAG, " No NDEF records found");
901 }
902 for (auto *trigger : this->triggers_ontag_) {
903 trigger->process(working_endpoint.tag);
904 }
905#ifdef NFC_TAG_LISTENER_COUNT
906 for (auto *listener : this->tag_listeners_) {
907 listener->tag_on(*working_endpoint.tag);
908 }
909#endif
910 working_endpoint.trig_called = true;
911 break;
912 }
913 }
914 // the tag was present for the whole operation, which may have taken longer than tag_ttl
915 working_endpoint.last_seen = millis();
916 if (working_endpoint.protocol == nfc::PROT_MIFARE) {
918 }
919 }
920 if (this->next_task_ != EP_READ) {
921 this->read_mode();
922 }
923
924 this->stop_discovery_();
926}
927
929 if (rx.get_message().size() < nfc::RF_DISCOVER_NTF_RF_TECH_PARAMS) {
930 ESP_LOGE(TAG, "RF_DISCOVER_NTF too short");
931 return;
932 }
933 const uint8_t protocol = rx.get_message_byte(nfc::RF_DISCOVER_NTF_PROTOCOL);
934 nfc::NfcTagUid uid;
935 if (!this->parse_uid_(rx.get_message_byte(nfc::RF_DISCOVER_NTF_MODE_TECH),
936 std::span<const uint8_t>(rx.get_message()).subspan(nfc::RF_DISCOVER_NTF_RF_TECH_PARAMS), uid)) {
937 ESP_LOGE(TAG, "Could not build tag!");
938 } else {
939 auto &endpoint = this->discovered_endpoint_[this->find_or_add_tag_(protocol, uid)];
940 endpoint.id = rx.get_message_byte(nfc::RF_DISCOVER_NTF_DISCOVERY_ID);
941 endpoint.protocol = protocol;
942 endpoint.last_seen = App.get_loop_component_start_time();
943 }
944
945 const auto &ntf = rx.get_message();
946 if (ntf[ntf.size() - 1] != nfc::RF_DISCOVER_NTF_NT_MORE) {
948 ESP_LOGVV(TAG, "Discovered %zu endpoints", this->discovered_endpoint_.size());
949 }
950}
951
954
955 switch (rx.get_simple_status_response()) {
956 case nfc::DEACTIVATION_TYPE_DISCOVERY:
958 break;
959
960 case nfc::DEACTIVATION_TYPE_IDLE:
962 break;
963
964 case nfc::DEACTIVATION_TYPE_SLEEP:
965 case nfc::DEACTIVATION_TYPE_SLEEP_AF:
968 } else if (this->nci_state_ == NCIState::RFST_POLL_ACTIVE) {
970 } else {
972 }
973 break;
974
975 default:
976 break;
977 }
978}
979
981 char buf[nfc::FORMAT_BYTES_BUFFER_SIZE];
982 ESP_LOGVV(TAG, "Received data message: %s", nfc::format_bytes_to(buf, rx.get_message()));
983
984 CardEmuResponse ndef_response;
985 this->card_emu_t4t_get_response_(rx.get_message(), ndef_response);
986
987 if (ndef_response.empty()) {
988 return; // no message returned, we cannot respond
989 }
990
991 nfc::NciMessage tx(nfc::NCI_PKT_MT_DATA, ndef_response);
992 ESP_LOGVV(TAG, "Sending data message: %s", nfc::format_bytes_to(buf, tx.get_message()));
993 if (this->transceive_(tx, rx, NFCC_DEFAULT_TIMEOUT, false) != nfc::STATUS_OK) {
994 ESP_LOGE(TAG, "Sending reply for card emulation failed");
995 }
996}
997
998bool PN71xx::card_emu_t4t_read_ndef_(const uint16_t offset, const uint8_t length, CardEmuResponse &ndef_response) {
999 const auto &ndef_message = this->card_emulation_ndef_;
1000 // the NDEF file is a two-byte big-endian length (NLEN) followed by the message
1001 const uint16_t ndef_msg_size = ndef_message.size();
1002 const uint32_t file_size = ndef_msg_size + 2;
1003 // the reply must also hold the two status bytes; the CC's MLe keeps well-behaved readers below this
1004 if (offset + static_cast<uint32_t>(length) > file_size ||
1005 length + sizeof(CARD_EMU_T4T_OK) > CardEmuResponse::capacity()) {
1006 return false;
1007 }
1008 for (uint32_t i = offset; i < offset + static_cast<uint32_t>(length); i++) {
1009 if (i == 0) {
1010 ndef_response.push_back(ndef_msg_size >> 8);
1011 } else if (i == 1) {
1012 ndef_response.push_back(ndef_msg_size & 0xFF);
1013 } else {
1014 ndef_response.push_back(ndef_message[i - 2]);
1015 }
1016 }
1017 if (offset + static_cast<uint32_t>(length) == file_size) {
1018 ESP_LOGD(TAG, "NDEF message sent");
1019 this->on_emulated_tag_scan_callback_.call();
1020 }
1021 return true;
1022}
1023
1024void PN71xx::card_emu_t4t_get_response_(const std::span<const uint8_t> response, CardEmuResponse &ndef_response) {
1025 ndef_response.clear();
1026 if (this->card_emulation_ndef_.empty()) {
1027 ESP_LOGE(TAG, "No NDEF message is set; tag emulation not possible");
1028 return;
1029 }
1030 if (response.size() < nfc::NCI_PKT_HEADER_SIZE) {
1031 return;
1032 }
1033
1034 const auto apdu_begin = response.begin() + nfc::NCI_PKT_HEADER_SIZE;
1035 const size_t apdu_size = response.size() - nfc::NCI_PKT_HEADER_SIZE;
1036 auto apdu_is = [&](const uint8_t *cmd, size_t cmd_size) {
1037 return apdu_size == cmd_size && std::equal(apdu_begin, response.end(), cmd);
1038 };
1039 auto apdu_starts_with = [&](const uint8_t *cmd, size_t cmd_size) {
1040 return apdu_size >= cmd_size && std::equal(cmd, cmd + cmd_size, apdu_begin);
1041 };
1042 auto append = [&](std::span<const uint8_t> bytes) {
1043 for (const uint8_t byte : bytes) {
1044 ndef_response.push_back(byte);
1045 }
1046 };
1047 bool ok = false;
1048
1049 if (apdu_is(CARD_EMU_T4T_APP_SELECT, sizeof(CARD_EMU_T4T_APP_SELECT)) ||
1050 apdu_is(CARD_EMU_T4T_APP_SELECT, sizeof(CARD_EMU_T4T_APP_SELECT) - 1)) { // Le is optional
1051 ESP_LOGVV(TAG, "CARD_EMU_NDEF_APP_SELECTED");
1053 ok = true;
1054 } else if (apdu_is(CARD_EMU_T4T_CC_SELECT, sizeof(CARD_EMU_T4T_CC_SELECT))) {
1056 ESP_LOGVV(TAG, "CARD_EMU_CC_SELECTED");
1058 ok = true;
1059 }
1060 } else if (apdu_is(CARD_EMU_T4T_NDEF_SELECT, sizeof(CARD_EMU_T4T_NDEF_SELECT))) {
1061 ESP_LOGVV(TAG, "CARD_EMU_NDEF_SELECTED");
1063 ok = true;
1064 } else if (apdu_starts_with(CARD_EMU_T4T_READ, sizeof(CARD_EMU_T4T_READ)) && apdu_size == 5) {
1065 // READ BINARY: CLA INS P1 P2 Le, where P1-P2 is the offset
1066 const uint16_t offset = encode_uint16(apdu_begin[2], apdu_begin[3]);
1067 const uint8_t length = apdu_begin[4];
1069 ESP_LOGVV(TAG, "CARD_EMU_T4T_READ with CARD_EMU_CC_SELECTED");
1070 if (offset + static_cast<uint32_t>(length) <= sizeof(CARD_EMU_T4T_CC)) {
1071 append(std::span<const uint8_t>(CARD_EMU_T4T_CC).subspan(offset, length));
1072 ok = true;
1073 }
1075 ESP_LOGVV(TAG, "CARD_EMU_T4T_READ with CARD_EMU_NDEF_SELECTED");
1076 ok = this->card_emu_t4t_read_ndef_(offset, length, ndef_response);
1077 }
1078 } else if (apdu_starts_with(CARD_EMU_T4T_WRITE, sizeof(CARD_EMU_T4T_WRITE)) && apdu_size >= 5) {
1079 // UPDATE BINARY: CLA INS P1 P2 Lc data
1080 const uint8_t length = apdu_begin[4];
1081 if (this->ce_state_ == CardEmulationState::CARD_EMU_NDEF_SELECTED && apdu_size >= 5u + length) {
1082 ESP_LOGVV(TAG, "CARD_EMU_T4T_WRITE");
1083 char write_buf[nfc::FORMAT_BYTES_BUFFER_SIZE];
1084 ESP_LOGD(TAG, "Received %u-byte NDEF message: %s", length,
1085 nfc::format_bytes_to(write_buf, response.subspan(nfc::NCI_PKT_HEADER_SIZE + 5, length)));
1086 ok = true;
1087 }
1088 }
1089
1090 if (ok) {
1091 append(CARD_EMU_T4T_OK);
1092 } else {
1093 ndef_response.clear();
1094 append(CARD_EMU_T4T_NOK);
1096 }
1097}
1098
1099uint8_t PN71xx::transceive_(nfc::NciMessage &tx, nfc::NciMessage &rx, const uint16_t timeout,
1100 const bool expect_notification) {
1101 char buf[nfc::FORMAT_BYTES_BUFFER_SIZE];
1102
1103 // The NFCC may refuse a frame while it wakes from standby; the whole frame must then be sent again.
1104 // A command must never be re-sent once it was accepted, as the NFCC will answer it (NCI 1.0, 3.2.1).
1105 uint8_t attempts = 0;
1106 while (this->write_nfcc(tx) != nfc::STATUS_OK) {
1107 if (++attempts >= NFCC_MAX_COMM_FAILS) {
1108 ESP_LOGE(TAG, "Error sending message");
1109 return nfc::STATUS_FAILED;
1110 }
1111 delay(NFCC_WRITE_RETRY_DELAY);
1112 }
1113 ESP_LOGVV(TAG, "Wrote: %s", nfc::format_bytes_to(buf, tx.get_message()));
1114
1115 if (!tx.message_type_is(nfc::NCI_PKT_MT_DATA)) {
1116 // Notifications may already be queued ahead of the response; skip them. They carry the same GID and OID
1117 // as some responses (e.g. RF_DEACTIVATE_NTF), so the message type must be checked. A response to an earlier
1118 // command whose read timed out (a tag leaving the field delays RF_DEACTIVATE_RSP) is skipped the same way.
1119 for (uint8_t i = 0; i < NFCC_MAX_COMM_FAILS; i++) {
1120 if (this->read_nfcc(rx, timeout) != nfc::STATUS_OK) {
1121 ESP_LOGW(TAG, "Error receiving response");
1122 return nfc::STATUS_FAILED;
1123 }
1124 ESP_LOGVV(TAG, "Read: %s", nfc::format_bytes_to(buf, rx.get_message()));
1125 if (rx.message_type_is(nfc::NCI_PKT_MT_CTRL_RESPONSE) && rx.get_gid() == tx.get_gid() &&
1126 rx.get_oid() == tx.get_oid()) {
1127 break;
1128 }
1129 ESP_LOGW(TAG, "Discarding message received while waiting for response: %s",
1131 }
1132 // for commands, the GID and OID should match and the status should be OK
1133 if (!rx.message_type_is(nfc::NCI_PKT_MT_CTRL_RESPONSE) || (rx.get_gid() != tx.get_gid()) ||
1134 (rx.get_oid() != tx.get_oid())) {
1135 ESP_LOGE(TAG, "Incorrect response to command: %s", nfc::format_bytes_to(buf, rx.get_message()));
1136 return nfc::STATUS_FAILED;
1137 }
1138
1139 if (!rx.simple_status_response_is(nfc::STATUS_OK)) {
1140 ESP_LOGE(TAG, "Error in response to command: %s", nfc::format_bytes_to(buf, rx.get_message()));
1141 }
1142 return rx.get_simple_status_response();
1143 }
1144
1145 // when sending data to the endpoint, the first message is the credit notification from the NFCC
1146 if (this->read_nfcc(rx, timeout) != nfc::STATUS_OK) {
1147 ESP_LOGW(TAG, "Error receiving credit notification");
1148 return nfc::STATUS_FAILED;
1149 }
1150 ESP_LOGVV(TAG, "Read: %s", nfc::format_bytes_to(buf, rx.get_message()));
1151 if ((!rx.message_type_is(nfc::NCI_PKT_MT_CTRL_NOTIFICATION)) || (!rx.gid_is(nfc::NCI_CORE_GID)) ||
1152 (!rx.oid_is(nfc::NCI_CORE_CONN_CREDITS_OID)) || (!rx.message_length_is(3))) {
1153 ESP_LOGE(TAG, "Incorrect response to data message: %s", nfc::format_bytes_to(buf, rx.get_message()));
1154 return nfc::STATUS_FAILED;
1155 }
1156
1157 if (expect_notification) {
1158 // the endpoint's answer follows in a data message
1159 if (this->read_nfcc(rx, timeout) != nfc::STATUS_OK) {
1160 ESP_LOGE(TAG, "Error receiving data from endpoint");
1161 return nfc::STATUS_FAILED;
1162 }
1163 ESP_LOGVV(TAG, "Read: %s", nfc::format_bytes_to(buf, rx.get_message()));
1164 }
1165
1166 return nfc::STATUS_OK;
1167}
1168
1169uint8_t PN71xx::wait_for_irq_(uint16_t timeout, bool pin_state) {
1170 auto start_time = millis();
1171
1172 while (millis() - start_time < timeout) {
1173 if (this->irq_pin_->digital_read() == pin_state) {
1174 return nfc::STATUS_OK;
1175 }
1176 }
1177 return nfc::STATUS_FAILED;
1178}
1179
1180} // namespace esphome::pn71xx
uint8_t status
Definition bl0942.h:8
uint32_t IRAM_ATTR HOT get_loop_component_start_time() const
Get the cached time in milliseconds from when the current component started its loop execution.
void mark_failed()
Mark this component as failed.
bool empty() const
Definition helpers.h:946
size_t size() const
Definition helpers.h:945
void push_back(const T &value)
Add element without bounds checking Caller must ensure sufficient capacity was allocated via init() S...
Definition helpers.h:896
void init(size_t n)
Definition helpers.h:859
virtual void setup()=0
virtual bool digital_read()=0
size_t size() const
Definition helpers.h:404
void push_back(const T &value)
Definition helpers.h:374
bool empty() const
Definition helpers.h:406
static constexpr size_t capacity()
Definition helpers.h:405
void assign(InputIt first, InputIt last)
Definition helpers.h:387
One NCI packet, held in a fixed buffer so building and reading messages never allocates.
Definition nci_message.h:16
bool message_type_is(uint8_t message_type) const
uint8_t get_oid() const
bool simple_status_response_is(uint8_t response) const
uint8_t get_message_byte(uint8_t offset) const
bool gid_is(uint8_t gid) const
bool message_length_is(uint8_t message_length, bool recompute=false)
std::span< const uint8_t > get_payload() const
The payload bytes that follow the header.
void set_message(uint8_t message_type, std::span< const uint8_t > payload)
uint8_t get_gid() const
uint8_t get_simple_status_response() const
bool oid_is(uint8_t oid) const
uint8_t get_message_type() const
void append(std::span< const uint8_t > data)
Appends bytes to the payload; bytes that do not fit are dropped.
StaticVector< NfcTagListener *, NFC_TAG_LISTENER_COUNT > tag_listeners_
Definition nfc.h:90
void loop() override
Definition pn71xx.cpp:44
uint8_t write_mifare_classic_tag_(const std::shared_ptr< nfc::NdefMessage > &message)
StaticVector< DiscoveredEndpoint, MAX_DISCOVERED_ENDPOINTS > discovered_endpoint_
Definition pn71xx.h:298
uint8_t set_test_mode(TestMode test_mode, const std::vector< uint8_t > &data, std::vector< uint8_t > &result)
Definition pn71xx.cpp:144
uint8_t wait_for_irq_(uint16_t timeout=NFCC_DEFAULT_TIMEOUT, bool pin_state=true)
Definition pn71xx.cpp:1169
virtual void prepare_reset()
Chip hooks Called before the NFCC is reset, e.g.
Definition pn71xx.h:206
uint32_t last_nci_state_change_
Definition pn71xx.h:305
uint8_t write_mifare_ultralight_tag_(nfc::NfcTagUid &uid, const std::shared_ptr< nfc::NdefMessage > &message)
uint8_t send_core_config_()
Definition pn71xx.cpp:269
uint8_t stop_discovery_()
Definition pn71xx.cpp:369
void process_message_()
parse & process incoming messages from the NFCC
Definition pn71xx.cpp:719
size_t find_or_add_tag_(uint8_t protocol, const nfc::NfcTagUid &uid)
Finds a cached endpoint by UID, or caches a new one, evicting the entry seen longest ago if the cache...
Definition pn71xx.cpp:507
uint8_t transceive_(nfc::NciMessage &tx, nfc::NciMessage &rx, uint16_t timeout=NFCC_DEFAULT_TIMEOUT, bool expect_notification=true)
Definition pn71xx.cpp:1099
std::unique_ptr< nfc::NfcTag > build_tag_(uint8_t protocol, const nfc::NfcTagUid &uid)
Definition pn71xx.cpp:497
uint8_t deactivate_(uint8_t type, uint16_t timeout=NFCC_DEFAULT_TIMEOUT)
Definition pn71xx.cpp:371
void set_tag_emulation_message(const std::shared_ptr< nfc::NdefMessage > &message)
Definition pn71xx.cpp:49
uint8_t set_discover_map_()
Definition pn71xx.cpp:310
void nci_fsm_set_state_(NCIState new_state)
set new controller state
Definition pn71xx.cpp:694
void nci_fsm_transition_()
advance controller state as required
Definition pn71xx.cpp:583
optional< size_t > find_tag_uid_(const nfc::NfcTagUid &uid)
Definition pn71xx.cpp:532
uint8_t send_init_config_()
Definition pn71xx.cpp:250
uint8_t refresh_core_config_()
Definition pn71xx.cpp:289
uint8_t read_mifare_classic_tag_(nfc::NfcTag &tag)
bool card_emu_t4t_read_ndef_(uint16_t offset, uint8_t length, CardEmuResponse &ndef_response)
Definition pn71xx.cpp:998
uint8_t format_endpoint_(uint8_t protocol)
Definition pn71xx.cpp:448
void process_rf_deactivate_oid_(nfc::NciMessage &rx)
Definition pn71xx.cpp:952
virtual uint8_t verify_reset(nfc::NciMessage &rx, bool reset_config)=0
Validates what follows a successful CORE_RESET_RSP (in rx); may read more messages from the NFCC.
uint8_t read_endpoint_data_(uint8_t protocol, nfc::NfcTag &tag)
Definition pn71xx.cpp:416
virtual std::span< const uint8_t > listen_mode_routing_config() const =0
Payload of the RF_SET_LISTEN_MODE_ROUTING_CMD.
void set_tag_write_message(std::shared_ptr< nfc::NdefMessage > message)
Definition pn71xx.cpp:135
uint8_t clean_endpoint_(uint8_t protocol)
Definition pn71xx.cpp:433
void process_data_message_(nfc::NciMessage &rx)
Definition pn71xx.cpp:980
std::shared_ptr< nfc::NdefMessage > next_task_message_to_write_
Definition pn71xx.h:300
LazyCallbackManager< void()> on_emulated_tag_scan_callback_
Definition pn71xx.h:295
virtual uint8_t process_init_response(nfc::NciMessage &rx)=0
Logs chip information from a successful CORE_INIT_RSP.
virtual std::span< const uint8_t > pmu_config() const =0
Parameters for the CORE_SET_CONFIG_CMD that configures the power management unit.
void process_rf_discover_oid_(nfc::NciMessage &rx)
Definition pn71xx.cpp:928
uint8_t reset_core_(bool reset_config, bool power)
Definition pn71xx.cpp:207
uint8_t write_endpoint_(uint8_t protocol, nfc::NfcTagUid &uid, std::shared_ptr< nfc::NdefMessage > &message)
Definition pn71xx.cpp:463
uint8_t set_listen_mode_routing_()
Definition pn71xx.cpp:323
void dump_config() override
Definition pn71xx.cpp:39
LazyCallbackManager< void()> on_finished_write_callback_
Definition pn71xx.h:296
uint8_t read_mifare_ultralight_tag_(nfc::NfcTag &tag)
void process_rf_intf_activated_oid_(nfc::NciMessage &rx)
Definition pn71xx.cpp:814
FixedVector< uint8_t > card_emulation_ndef_
Definition pn71xx.h:299
virtual uint8_t write_nfcc(nfc::NciMessage &tx)=0
bool nci_fsm_set_error_state_(NCIState new_state)
setting controller to this state caused an error; returns true if too many errors/failures
Definition pn71xx.cpp:702
uint8_t selecting_endpoint_
Definition pn71xx.h:313
virtual uint8_t read_nfcc(nfc::NciMessage &rx, uint16_t timeout)=0
CardEmulationState ce_state_
Definition pn71xx.h:309
void card_emu_t4t_get_response_(std::span< const uint8_t > response, CardEmuResponse &ndef_response)
Definition pn71xx.cpp:1024
uint8_t start_discovery_()
Definition pn71xx.cpp:335
void setup() override
Definition pn71xx.cpp:32
void erase_tag_(uint8_t tag_index)
Definition pn71xx.cpp:561
bool parse_uid_(uint8_t mode_tech, std::span< const uint8_t > rf_tech_params, nfc::NfcTagUid &uid)
Reads the UID from the RF technology parameters of a discovery or activation notification.
Definition pn71xx.cpp:479
NCIState nci_state_error_
Definition pn71xx.h:311
const LogString * message
Definition component.cpp:35
uint8_t type
char * format_bytes_to(char *buffer, std::span< const uint8_t > bytes)
Format bytes to buffer with ' ' separator (e.g., "04 11 22 33"). Returns buffer for inline use.
Definition nfc.cpp:14
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
ESPHOME_LOG_TAG(TAG, "pn71xx")
if(written< 0)
Definition helpers.h:1539
constexpr uint16_t encode_uint16(uint8_t msb, uint8_t lsb)
Encode a 16-bit value given the most and least significant byte.
Definition helpers.h:1227
void HOT delay(uint32_t ms)
Definition hal.cpp:78
uint32_t IRAM_ATTR HOT millis()
Definition hal.cpp:25
Application App
Global storage of Application pointer - only one Application can exist.
void const char * tag
Definition log.h:110
ESPHOME_ALWAYS_INLINE void pulse_reset(GPIOPin *pin, ResetPulse pulse)
Set up an active-low reset pin and drive it through pulse.
Definition gpio_pin.h:214
static void uint32_t
uint16_t length
Definition tt21100.cpp:0
esp_err_t result