From ed69a7a5eaaf7cd54a156376f833886e7dfa47a9 Mon Sep 17 00:00:00 2001 From: Andreas Neuhaus Date: Sun, 1 Sep 2024 01:32:07 +0200 Subject: [PATCH] Refactor pn532 process function with timeout --- firmware/src/nfc.rs | 8 +------- firmware/src/pn532.rs | 16 +++++++++++++++- 2 files changed, 16 insertions(+), 8 deletions(-) diff --git a/firmware/src/nfc.rs b/firmware/src/nfc.rs index 38b50b5..7e175a3 100644 --- a/firmware/src/nfc.rs +++ b/firmware/src/nfc.rs @@ -9,9 +9,6 @@ use embedded_hal_async::i2c::I2c; use log::{debug, info, warn}; use pn532::{Error as Pn532Error, I2CInterfaceWithIrq, Pn532, Request, SAMMode}; -/// NFC reader default command timeout -const COMMAND_TIMEOUT: Duration = Duration::from_millis(50); - /// NFC reader read loop timeout const READ_TIMEOUT: Duration = Duration::from_millis(100); @@ -66,7 +63,6 @@ impl> Nfc { // SAMConfiguration request (PN532 §7.2.10) &Request::sam_configuration(SAMMode::Normal, true), 0, - COMMAND_TIMEOUT, ) .await?; @@ -76,7 +72,6 @@ impl> Nfc { // GetFirmwareVersion request (PN532 §7.2.2) &Request::GET_FIRMWARE_VERSION, 4, - COMMAND_TIMEOUT, ) .await?; // GetFirmwareVersion response (PN532 §7.2.2) @@ -108,7 +103,7 @@ impl> Nfc { // Detect any ISO/IEC14443 Type A target in passive mode let list_response = match self .driver - .process( + .process_timeout( // InListPassiveTarget request (PN532 §7.3.5) &Request::INLIST_ONE_ISO_A_TARGET, pn532::BUFFER_SIZE - 9, // max response length @@ -167,7 +162,6 @@ impl> Nfc { // InRelease request (PN532 §7.3.11) &Request::RELEASE_TAG_1, 1, - COMMAND_TIMEOUT, ) .await { diff --git a/firmware/src/pn532.rs b/firmware/src/pn532.rs index 3ec6f2d..d3a95a7 100644 --- a/firmware/src/pn532.rs +++ b/firmware/src/pn532.rs @@ -15,6 +15,9 @@ pub const BUFFER_SIZE: usize = 32; /// Command ACK timeout const ACK_TIMEOUT: Duration = Duration::from_millis(50); +/// Command response timeout +const RESPONSE_TIMEOUT: Duration = Duration::from_millis(50); + const PREAMBLE: [u8; 3] = [0x00, 0x00, 0xFF]; const POSTAMBLE: u8 = 0x00; const ACK: [u8; 6] = [0x00, 0x00, 0xFF, 0x00, 0xFF, 0x00]; @@ -163,11 +166,22 @@ impl Pn532 { } /// Send PN532 request and wait for ack and response. - /// Like `pn532::Pn532::process`, but fully asynchronous and with timeout + /// Like `pn532::Pn532::process`, but fully asynchronous pub async fn process<'a>( &mut self, request: impl Into>, response_len: usize, + ) -> Result<&[u8], Error> { + self.process_timeout(request, response_len, RESPONSE_TIMEOUT) + .await + } + + /// Send PN532 request and wait for ack and response. + /// Like `pn532::Pn532::process`, but fully asynchronous and with timeout + pub async fn process_timeout<'a>( + &mut self, + request: impl Into>, + response_len: usize, timeout: Duration, ) -> Result<&[u8], Error> { let request = request.into();