Skip to content

chore: merge pn532 upstream changes#61

Merged
rednblkx merged 2 commits into
mainfrom
upstream/pn532
Apr 24, 2026
Merged

chore: merge pn532 upstream changes#61
rednblkx merged 2 commits into
mainfrom
upstream/pn532

Conversation

@rednblkx
Copy link
Copy Markdown
Owner

@rednblkx rednblkx commented Apr 10, 2026

Summary by CodeRabbit

  • Refactor

    • Modernized write-completion handling to callback-based automations for more reliable NFC write workflows.
    • Improved read-timeout tracking for NFC readers to reduce spurious timeouts and improve stability.
  • Bug Fixes

    • Strengthened SPI NFC packet validation and ensured device is properly disabled on invalid reads to avoid corrupted exchanges.
    • Tightened MIFARE Ultralight NDEF bounds and byte-layout handling for more reliable tag read/write operations.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 10, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 8693ab16-d7f8-4053-956d-71fa846c79c7

📥 Commits

Reviewing files that changed from the base of the PR and between ddbc8ba and 84c0d46.

📒 Files selected for processing (1)
  • components/homekit/lock.cpp
📜 Recent review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: build
🧰 Additional context used
📓 Path-based instructions (1)
**/*

⚙️ CodeRabbit configuration file

assess the relevance of the changes to the purpose of the PR and do not mention anything if they are relevant.

Files:

  • components/homekit/lock.cpp
🧠 Learnings (1)
📓 Common learnings
Learnt from: chbmuc
Repo: rednblkx/HAP-ESPHome PR: 30
File: components/pn532_uart/pn532_uart.cpp:111-120
Timestamp: 2025-01-26T16:21:43.438Z
Learning: The checksum calculation in PN532 implementations (both SPI and UART) follows the same approach using uint8_t type, maintaining consistency across different interface implementations.
🔇 Additional comments (1)
components/homekit/lock.cpp (1)

414-421: LGTM — version-gated lambda signature aligns with ESPHome 2026.4.0 lock API.

The new lambda correctly accepts lock::LockState to match the updated add_on_state_callback signature in ESPHome ≥ 2026.4.0, while the #else branch preserves the parameterless callback for older versions. Ignoring the passed-in state and re-reading ptrToLock->state inside on_lock_update keeps behavior identical across both branches.


Walkthrough

Removed PN532 write-completion trigger and replaced trigger handling with callback-based automations; switched PN532 read-timing from a sentinel uint32_t to an optional; adjusted MIFARE Ultralight NDEF indexing and extended-length encoding layout; tightened PN532 SPI response validation and added disable-on-failure paths.

Changes

Cohort / File(s) Summary
Callback automation & API
components/pn532/__init__.py, components/pn532/pn532.h, components/pn532/pn532.cpp
Removed PN532OnFinishedWriteTrigger and its export; added _CALLBACK_AUTOMATIONS and switched to automation.build_callback_automations; changed add_on_finished_write_callback to a templated forwarding overload.
Optional read-timing state
components/pn532/pn532.h, components/pn532/pn532.cpp
Replaced sentinel uint32_t rd_start_time_{0} with optional<uint32_t> rd_start_time_ and updated readiness timeout logic to use reset()/has_value()/dereference.
MIFARE Ultralight NDEF handling
components/pn532/pn532_mifare_ultralight.cpp
Increased bounds check from p4_offset + 5p4_offset + 6 for second NDEF marker location; adjusted insertion index for extended-length message_length from position 2 → 3.
SPI response validation & error handling
components/pn532_spi/pn532_spi.cpp
Changed preamble check to fail if any expected byte mismatches, added this->disable() on early-fail returns, added full_len < 2 payload guard and removed prior full_len == 0 special-case handling.
HomeKit lambda typing (minor)
components/homekit/lock.cpp
Explicitly typed HomeKit lock callback lambda parameter as lock::LockState (no behavioral change).

Poem

🐰 A tiny rabbit hops and grins,
I swapped the trigger for callback spins,
Optional clocks now wake on cue,
Bounds and SPI checks tightened too,
Code nibbles cleaner — hop, hop, woo!

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title 'chore: merge pn532 upstream changes' is a generic, vague description that does not convey the specific nature of the changes (refactoring callback automations, improving error handling, fixing bounds checking, etc.). Consider a more specific title that highlights key changes, such as 'refactor: convert PN532 on_finished_write to callback automation' or 'chore: merge pn532 upstream changes (callbacks, error handling, bounds fixes)'.
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch upstream/pn532

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 718ac64b-faad-43f1-b0ee-d2a1c818fc67

📥 Commits

Reviewing files that changed from the base of the PR and between 0c47244 and ddbc8ba.

📒 Files selected for processing (1)
  • components/pn532_spi/pn532_spi.cpp
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: build
🧰 Additional context used
📓 Path-based instructions (1)
**/*

⚙️ CodeRabbit configuration file

assess the relevance of the changes to the purpose of the PR and do not mention anything if they are relevant.

Files:

  • components/pn532_spi/pn532_spi.cpp
🔇 Additional comments (1)
components/pn532_spi/pn532_spi.cpp (1)

91-95: Correct preamble validation and cleanup.

The || check now rejects any malformed start sequence, and the added disable() calls keep the SPI transaction balanced on both early-return paths.

Also applies to: 108-110

Comment on lines +114 to +120
// full length of message, including command response (minimum 2: TFI + command response)
uint16_t full_len = header[3];
if (full_len < 2) {
ESP_LOGV(TAG, "read data has no payload");
this->disable();
return false;
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

Validate the decoded extended-frame length before using it.

full_len is checked before the extended-frame branch overwrites it. If a malformed extended frame decodes to 0 or 1, Line 134 still executes with an invalid length, which can turn into a 65535-byte read or an invalid data[len - 1] access. Move the < 2 guard after the extended-length decode so both frame formats are covered.

🐛 Proposed fix
-  // full length of message, including command response (minimum 2: TFI + command response)
-  uint16_t full_len = header[3];
-  if (full_len < 2) {
-    ESP_LOGV(TAG, "read data has no payload");
-    this->disable();
-    return false;
-  }
+  // full length of message, including command response (minimum 2: TFI + command response)
+  uint16_t full_len = header[3];
   if (extended_frame) {
     ESP_LOGV(TAG, "Abnormal length and checksum, possible Extended Frame");
     header.resize(10);
     this->read_array(header.data() + 7, 3);
     ESP_LOGV(TAG, "EF: Header data: %s", format_hex_pretty(header).c_str());
     if ((uint8_t)(header[5] + header[6] + header[7]) != 0) {
       ESP_LOGV(TAG, "EF: read data invalid header!");
       this->disable();
       return false;
     }
     full_len = ((((uint16_t)header[5]) << 8) | header[6]);
   }
+  if (full_len < 2) {
+    ESP_LOGV(TAG, "read data has no payload");
+    this->disable();
+    return false;
+  }

Also applies to: 121-132

@rednblkx rednblkx merged commit 018b356 into main Apr 24, 2026
4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant