The ChainGate Device Agent is an Arduino-based access control system that uses NFC card reading for user authentication. The system has been refactored into a modular architecture for better maintainability, testability, and scalability.
┌─────────────────┐
│ AccessControl │ ← Main orchestrator
└─────────┬───────┘
│
┌─────▼─────┬─────────┬─────────────┬──────────────┐
│ │ │ │ │
┌───▼───┐ ┌─────▼──┐ ┌────▼────┐ ┌──────▼─────┐ ┌─────▼──────┐
│ LED │ │ WiFi │ │ NFC │ │ Server │ │ Config │
│Control│ │Manager │ │ Reader │ │ Comm │ │ │
└───────┘ └────────┘ └─────────┘ └────────────┘ └────────────┘
- ESP32 Development Board
- PN532 NFC Reader Module
- Power Supply (5V/2A)
- 2x LEDs (Green and Red)
- 2x Current-limiting resistors (220Ω recommended)
- Breadboard and jumper wires
- Relay module for electric lock control
#define SDA_PIN 8 // I2C Data pin for NFC
#define SCL_PIN 9 // I2C Clock pin for NFC
#define PN532_IRQ 2 // NFC interrupt pin
#define PN532_RESET 3 // NFC reset pin
#define GREEN_LED_PIN 5 // Access granted indicator
#define RED_LED_PIN 6 // Access denied indicatorESP32 PN532
----- -----
3.3V ─────── VCC
GND ─────── GND
Pin 8 ─────── SDA
Pin 9 ─────── SCL
Pin 2 ─────── IRQ
Pin 3 ─────── RST
ESP32 LEDs
----- ----
Pin 5 ──[220Ω]── Green LED ── GND
Pin 6 ──[220Ω]── Red LED ── GND
Purpose: Centralized configuration management
Key Features:
- Pin definitions
- Network credentials
- System constants
- Easy configuration updates
Usage:
#include "core/config.h"
// All pin definitions and constants are availablePurpose: Manages LED status indicators
Key Features:
- Non-blocking LED control
- Timed LED activation
- Startup and status animations
- State management
Public Methods:
void init(); // Initialize pins
void update(); // Update LED states (call in loop)
void activate(int pin, unsigned long duration); // Activate LED for duration
void startupAnimation(); // System startup indication
void wifiConnectedAnimation(); // WiFi connection indication
bool isActive() const; // Check if any LED is activePurpose: Handles WiFi connectivity
Key Features:
- Connection establishment
- Connection monitoring
- Automatic reconnection
- Status reporting
Public Methods:
bool connect(); // Connect to WiFi
bool isConnected() const; // Check connection status
String getStatusString(); // Get readable status
bool reconnect(); // Reconnect if neededPurpose: NFC card reading and data processing
Key Features:
- PN532 chip initialization
- Card detection and reading
- UID processing and formatting
- Error handling
Data Structure:
struct NFCData {
String uidHex; // Hex representation of UID
uint32_t reversedUID; // Reversed UID for server
uint8_t uidLength; // Length of UID
bool valid; // Whether read was successful
};Public Methods:
bool init(); // Initialize NFC reader
NFCData readCard(unsigned int timeout); // Read card with timeout
bool isReady() const; // Check if reader is readyPurpose: Handles all server communication
Key Features:
- HTTP POST requests
- JSON payload construction
- Response parsing
- Error handling
Data Structures:
struct ServerResponse {
bool success; // Request successful
bool userFound; // User authorized
String userName; // User's name
String message; // Response message
int httpCode; // HTTP response code
};Public Methods:
ServerResponse sendAccessRequest(const NFCData& nfcData); // Send access request
bool isServerReachable(); // Check server statusPurpose: Main system orchestration
Key Features:
- Component initialization
- Main processing loop
- Decision making
- Error handling and recovery
Public Methods:
bool init(); // Initialize all components
void update(); // Main processing loop
void processCardScan(); // Handle NFC card detection-
System Startup
- Initialize serial communication
- Display system information
- Initialize LED controller
- Perform startup animation
-
Network Setup
- Connect to WiFi
- Display connection status
- Perform WiFi connected animation
-
Hardware Initialization
- Initialize NFC reader
- Verify PN532 connectivity
- Configure for card detection
-
LED State Management
- Update active LED timers
- Turn off expired LEDs
-
Card Detection
- Scan for NFC cards (if not blocked by active red LED)
- Process card data when detected
-
Server Communication
- Send access request to server
- Parse server response
-
Access Decision
- Grant access (Green LED) if user authorized
- Deny access (Red LED) if user not authorized
- Handle errors appropriately
-
Connection Monitoring
- Check WiFi connection status
- Attempt reconnection if needed
| LED Color | Duration | Meaning |
|---|---|---|
| Green | 3 seconds | Access Granted |
| Red | 3 seconds | Access Denied |
| Red (blinking) | Continuous | NFC Reader Error |
| Both (alternating) | Startup | System Initialization |
| Green (3 blinks) | Startup | WiFi Connected |
Edit core/config.cpp:
const char* ssid = "YourWiFiNetwork";
const char* password = "YourPassword";
const char* serverUrl = "http://your-server.com/api/access/";const unsigned long GREEN_LED_DURATION = 3000; // 3 seconds
const unsigned long RED_LED_DURATION = 3000; // 3 seconds- Automatic reconnection attempts
- Status logging
- Red LED indication for extended failures
- Initialization validation
- Continuous red LED blinking for hardware failures
- Graceful degradation
- Timeout handling
- Network error detection
- Offline operation consideration
Use Arduino IDE or PlatformIO with ESP32 board support.
This project depends on several excellent open-source libraries:
- Author: Adafruit Industries
- Purpose: NFC/RFID communication with PN532 chip
- License: MIT License
- Repository: https://github.com/adafruit/Adafruit_PN532
- Credit: "Written by Limor Fried/Ladyada for Adafruit Industries"
- Author: Benoit Blanchon
- Purpose: JSON parsing and serialization
- License: MIT License
- Repository: https://github.com/bblanchon/ArduinoJson
- Version: 7.x compatible
- Credit: "The most efficient JSON library for embedded C++"
- Author: Espressif Systems
- Purpose: WiFi connectivity management
- License: Apache License 2.0
- Repository: Part of ESP32 Arduino Core
- Credit: Built-in library for ESP32 Arduino framework
- Author: Espressif Systems / Arduino Community
- Purpose: HTTP/HTTPS client functionality
- License: LGPL-2.1
- Repository: Part of ESP32 Arduino Core
- Credit: Based on ESP-IDF HTTP client
- Author: Arduino Team
- Purpose: I2C communication protocol
- License: LGPL
- Repository: Part of Arduino Core
- Credit: Standard Arduino I2C library
# In Arduino IDE Library Manager, search and install:
# - "Adafruit PN532" by Adafruit
# - "ArduinoJson" by Benoit Blanchon
# WiFi, HTTPClient, and Wire are included with ESP32 core- Serial output for all major operations
- Component status reporting
- Error message logging
-
NFC Not Reading Cards
- Check wiring connections
- Verify power supply
- Test with different cards
-
WiFi Connection Problems
- Verify credentials
- Check signal strength
- Review network configuration
-
Server Communication Failures
- Verify server endpoint
- Check network connectivity
- Review API format## Acknowledgments