Added NFC implementation into refactored structure

This commit is contained in:
2026-08-02 16:26:13 +02:00
parent 5f76802f92
commit 78765ce595
4 changed files with 145 additions and 1 deletions
+118 -1
View File
@@ -1 +1,118 @@
// Drivers nfc_pn532 module
use core::convert::Infallible;
use esp_hal::gpio::interconnect::{PeripheralInput, PeripheralOutput};
use esp_hal::i2c::master::{Config as I2cConfig, I2c};
use esp_hal::peripherals::I2C0;
use esp_hal::time::{Duration, Instant, Rate};
use log::{error, info};
use pn532::i2c::I2CInterface;
use pn532::requests::SAMMode;
use pn532::{nb, Pn532, Request};
/// Timer implementation required by `pn532::CountDown`.
pub struct TimerWrapper {
start: Instant,
duration: Duration,
counter: u32,
}
impl TimerWrapper {
pub fn new() -> Self {
Self {
start: Instant::now(),
duration: Duration::ZERO,
counter: 0,
}
}
}
impl Default for TimerWrapper {
fn default() -> Self {
Self::new()
}
}
impl pn532::CountDown for TimerWrapper {
type Time = Duration;
fn start<T>(&mut self, timeout: T)
where
T: Into<Self::Time>,
{
// without this debug log, it works worse: stuck in NFC card search without ever returning.
self.start = esp_println::dbg!(Instant::now());
self.duration = timeout.into();
self.counter = 0;
}
fn wait(&mut self) -> nb::Result<(), Infallible> {
let elapsed = self.start.elapsed();
self.counter += 1;
if self.counter.is_multiple_of(1) {
info!("Elapsed: {elapsed}");
}
if elapsed >= self.duration {
Ok(())
} else {
Err(nb::Error::WouldBlock)
}
}
}
pub type Pn532Device<'a> = Pn532<I2CInterface<I2c<'a, esp_hal::Blocking>>, TimerWrapper, 32>;
/// PN532 NFC reader driver.
pub struct NfcPn532Driver<'a> {
pn532: Pn532Device<'a>,
}
impl<'a> NfcPn532Driver<'a> {
pub fn new<SDA, SCL>(i2c0: I2C0<'static>, sda: SDA, scl: SCL) -> Self
where
SDA: PeripheralInput<'static> + PeripheralOutput<'static>,
SCL: PeripheralInput<'static> + PeripheralOutput<'static>,
{
let config = I2cConfig::default().with_frequency(Rate::from_khz(100));
let i2c = I2c::new(i2c0, config)
.expect("Failed to init I2C")
.with_sda(sda)
.with_scl(scl);
let pn532 = Pn532::new(I2CInterface { i2c }, TimerWrapper::new());
Self { pn532 }
}
pub fn configure_sam(&mut self, timeout: Duration) -> Result<(), ()> {
if let Err(e) = self.pn532.process(
&Request::sam_configuration(SAMMode::Normal, false),
0,
timeout,
) {
error!("Could not initialize PN532: {e:?}");
Err(())
} else {
info!("Successfully init'ed PN532");
Ok(())
}
}
pub fn read_card(&mut self, timeout: Duration) -> Option<[u8; 4]> {
if let Ok(uid) = self.pn532.process(&Request::INLIST_ONE_ISO_A_TARGET, 7, timeout) {
info!("uid = {uid:?}");
if let Ok(result) = self.pn532.process(&Request::ntag_read(10), 17, timeout) {
info!("page 10: {:?}", &result[1..5]);
let mut data = [0u8; 4];
data.copy_from_slice(&result[1..5]);
Some(data)
} else {
None
}
} else {
info!("No NFC card found.");
None
}
}
pub fn device_mut(&mut self) -> &mut Pn532Device<'a> {
&mut self.pn532
}
}