Skip to content

feat: impl simple gpio pin allocator#288

Open
rednblkx wants to merge 4 commits into
mainfrom
gpio-allocator
Open

feat: impl simple gpio pin allocator#288
rednblkx wants to merge 4 commits into
mainfrom
gpio-allocator

Conversation

@rednblkx

@rednblkx rednblkx commented Jul 10, 2026

Copy link
Copy Markdown
Owner

GPIOAllocator is to be in charge of allocating leases for GPIO Pins to any components that needs controlling any of the pins, at the same time maintaining a central repository of who owns what pin to help avoid conflicts and henceforth becomes critical that anytime a pin is assigned, it should be first of all acquired from the allocator.

LIfecycle:

  1. pin acquired from GPIOAllocator and ownership maintained by the returned GPIOLease
  2. Until GPIOLease's is destroyed, the pin is owned
  3. GPIOLease is destructed, pin gets reset and removed from the owners array, releasing the pin for use

Summary by CodeRabbit

  • New Features
    • Added centralized GPIO allocation with ownership tracking using runtime “pin leases” to prevent conflicts.
    • Updated GPIO-controlled hardware (including NFC, TAG, NeoPixel, and locking) to drive pins via managed leases.
    • Enhanced configuration saving and validation: pin fields are now rejected when already owned, with clear error details.
    • Improved Ethernet and NFC startup by automatically acquiring required GPIO resources and handling conflicts; NFC is initialized more consistently.
    • Added a debug command to query which component currently owns a given GPIO pin.

GPIOAllocator is to become in charge of allocating leases for GPIO Pins
to any components that needs it
@coderabbitai

coderabbitai Bot commented Jul 10, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

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: a3ac063e-d15c-43ad-844e-9e34eca5eda7

📥 Commits

Reviewing files that changed from the base of the PR and between 16bbcec and df086dd.

📒 Files selected for processing (3)
  • main/HardwareManager.cpp
  • main/HomeKitLock.cpp
  • main/include/GPIOAllocator.hpp
🚧 Files skipped from review as they are similar to previous changes (3)
  • main/HomeKitLock.cpp
  • main/HardwareManager.cpp
  • main/include/GPIOAllocator.hpp

Walkthrough

The PR adds a centralized RAII GPIO allocator with ownership tracking, integrates leases into NFC, Ethernet, and hardware control, validates pin conflicts in web configuration, and removes duplicated Ethernet–NFC pin intersection handling.

Changes

GPIO leasing integration

Layer / File(s) Summary
GPIO allocator contract and implementation
main/include/GPIOAllocator.hpp, main/GPIOAllocator.cpp, main/CMakeLists.txt
Defines move-only GPIO leases, allocation errors, ownership lookup, synchronized storage, and component registration.
NFC and Ethernet pin allocation
main/include/NfcManager.hpp, main/NfcManager.cpp, main/HomeKitLock.cpp, main/main.cpp
NFC acquires SPI and optional control pins; Ethernet validates SPI configuration, allocates required pins, checks SPI2 sharing, and initializes through preset or custom paths.
HardwareManager leased GPIO control
main/include/HardwareManager.hpp, main/HardwareManager.cpp
Tracks leases by pin function, updates allocations on configuration changes, and drives lock, indicator, alternate-action, and tag-event GPIOs through leases.
Web configuration ownership validation
main/WebServerManager.cpp
Extends pin-change event handling and rejects submitted GPIOs already owned by another component.

Sequence Diagram(s)

sequenceDiagram
  participant main
  participant NfcManager
  participant HomeKitLock
  participant GPIOAllocator
  participant Ethernet

  main->>NfcManager: construct with NFC pin configuration
  NfcManager->>GPIOAllocator: acquire NFC pins
  GPIOAllocator-->>NfcManager: return leases or errors
  main->>HomeKitLock: initializeETH()
  HomeKitLock->>GPIOAllocator: acquire Ethernet pins
  GPIOAllocator-->>HomeKitLock: return leases or errors
  HomeKitLock->>Ethernet: initialize Ethernet
Loading

Possibly related PRs

Poem

I hop through pins where currents flow,
A lease for each, so none collide below.
NFC and Ethernet share the chart,
Hardware lights now play their part.
GPIO owners proudly show—
Squeak, allocate, and safely go!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 4.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly matches the main change: introducing a simple GPIO pin allocator and lease-based ownership tracking.
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.
✨ 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 gpio-allocator

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 5

🧹 Nitpick comments (1)
main/HomeKitLock.cpp (1)

493-499: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Redundant value_or and no output on miss.

Inside if(s.has_value()), s.value_or("Not allocated") can never yield the fallback; and when the pin is unowned nothing is logged, so the command silently does nothing.

♻️ Optional cleanup
     new SpanUserCommand('G', "Who owns this GPIO Pin?", [](const char* c) {
       uint8_t i = atoi(c+1);
       auto s = GPIOAllocator::instance().owner_of(i);
-      if(s.has_value()){
-          ESP_LOGI(TAG, "Owner: %s", s.value_or("Not allocated").c_str());
-      }
+      ESP_LOGI(TAG, "Owner: %s", s.has_value() ? s->c_str() : "Not allocated");
     });

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: c4286c5c-2a01-4a97-987e-276584e840c6

📥 Commits

Reviewing files that changed from the base of the PR and between 33f704f and 16bbcec.

📒 Files selected for processing (10)
  • main/CMakeLists.txt
  • main/GPIOAllocator.cpp
  • main/HardwareManager.cpp
  • main/HomeKitLock.cpp
  • main/NfcManager.cpp
  • main/WebServerManager.cpp
  • main/include/GPIOAllocator.hpp
  • main/include/HardwareManager.hpp
  • main/include/NfcManager.hpp
  • main/main.cpp
📜 Review details
🧰 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:

  • main/CMakeLists.txt
  • main/GPIOAllocator.cpp
  • main/NfcManager.cpp
  • main/include/HardwareManager.hpp
  • main/include/NfcManager.hpp
  • main/include/GPIOAllocator.hpp
  • main/WebServerManager.cpp
  • main/HomeKitLock.cpp
  • main/main.cpp
  • main/HardwareManager.cpp
🔇 Additional comments (12)
main/include/GPIOAllocator.hpp (1)

25-65: LGTM!

main/GPIOAllocator.cpp (1)

1-3: LGTM!

main/CMakeLists.txt (1)

4-4: LGTM!

main/include/NfcManager.hpp (1)

98-107: LGTM!

main/NfcManager.cpp (1)

230-237: LGTM!

main/HomeKitLock.cpp (1)

130-302: LGTM!

main/main.cpp (1)

133-142: LGTM!

main/WebServerManager.cpp (3)

5-5: LGTM!


885-894: LGTM!


1098-1109: 🎯 Functional Correctness

This rejection doesn’t affect the normal config save flow. The UI posts diff(...) payloads for /config/save, so unchanged/self-owned pins are omitted and won’t reach this owner_of(...) check. If there’s another caller sending full objects to this endpoint, that would be a separate case.

			> Likely an incorrect or invalid review comment.
main/include/HardwareManager.hpp (1)

8-10: LGTM!

Also applies to: 145-157

main/HardwareManager.cpp (1)

5-9: LGTM!

Also applies to: 36-56, 208-227, 393-416, 466-466, 530-532, 580-614

Comment thread main/HardwareManager.cpp
Comment on lines +145 to +155
if (meta->func == PinFunctions::ALT_ACTION_INIT) {
new_lease.value().set_pullup(true);
gpio_set_intr_type(gpio_num_t(s.newValue), GPIO_INTR_NEGEDGE);
gpio_isr_handler_add(gpio_num_t(s.newValue), initiator_isr_handler, (void*)this);
}

alloc_entry = std::move(new_lease);
ESP_LOGI(TAG, "Acquired pin %d for %s", s.newValue, meta->tag);
} else {
ESP_LOGE(TAG, "Failed to acquire pin %d, error: %d", s.newValue, new_lease.error());
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Inspect initiator ISR handler + queue usage and any ISR-service install outside begin()
fd -t f 'HardwareManager.cpp' main | xargs -I{} sed -n '1,240p;450,480p' {}
rg -nP 'gpio_install_isr_service|initiator_isr_handler|m_initiatorQueue' main/HardwareManager.cpp

Repository: rednblkx/HomeKey-ESP32

Length of output: 12815


Install the ISR service before dynamically adding ALT_ACTION_INIT

main/HardwareManager.cpp:145-155 can call gpio_isr_handler_add(...) during HW_CONFIG_CHANGED even when begin() never installed the ISR service or created m_initiatorQueue/initiator_task (for example, if hkAltActionInitPin was 255 at boot). Lazily initialize that setup here, or guard the dynamic-add path until it exists.

Comment thread main/HardwareManager.cpp Outdated
Comment thread main/HomeKitLock.cpp
Comment thread main/include/GPIOAllocator.hpp Outdated
Comment thread main/include/GPIOAllocator.hpp
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