Chapters

 Practice: NFC Reader Simulation

rfid-nfc-uwb
apps
simulation
lab

This lab belongs to NFC Tag Programming

Start With the Story

Reject One Bad Tap Before Adding Real Hardware

Picture a phone tapping a label to open the correct equipment record. A software exercise can show whether the reader accepts a wrong field or repeated message before radio details make the fault harder to see.

NFC means Near Field Communication, a short-range link used for deliberate taps. A payload means the useful record carried inside a message. A protocol means the shared rules for an exchange.

Run one known tag record through polling, selection, decoding, policy checks, and release. Change its length, host, type, and identifier; repeat it; then restart the reader. Record which step rejects the bad input and which claims still need a physical test.

This runway does not prove antenna range, phone behavior, or field timing. The deeper lab covers reader states, NDEF structure, validation, injected faults, evidence capture, and the hardware checks left open.

A simulation cannot prove the RF field, but it can make the NFC logic visible. Polling, anti-collision, NDEF parsing, policy checks, and failure cases become easier to inspect when the lab removes the hardware uncertainty.

Use this chapter as a dry run for reasoning. Treat each simulated trace as evidence about the protocol and policy path, then mark which claims still need hardware before anyone calls the result field-ready.

In 60 Seconds

This lab builds a software-only NFC reader simulation. The goal is not to emulate antenna tuning, phone operating-system behavior, or every timing detail of the 13.56 MHz radio link. The goal is to make the reader pipeline visible: polling, tag selection, NDEF decoding, payload validation, failure injection, and evidence capture for a real deployment review.

Learning Objectives

By the end of this chapter, you should be able to:

  • Define what an NFC reader simulation can and cannot prove.
  • Model the reader state sequence from polling through tag selection, NDEF parsing, policy validation, and release evidence.
  • Decode simple NDEF TLV and URI records well enough to spot length, type, and host-validation failures.
  • Simulate multi-tag, malformed-payload, cloned-static-data, and relay-risk scenarios without overclaiming physical accuracy.
  • Convert simulation output into a test record that can guide later hardware and field validation.

Quick Check: NFC Simulation

Simulation Scope

An NFC simulation is useful when it is honest about its boundary. A browser or microcontroller sketch can model bytes, state transitions, and policy checks. It cannot prove the final tap range, detuning, operating-system prompts, secure-element behavior, or user workflow until the target phones, tags, cases, and mounting surfaces are tested.

Inspect Outside model and one tag in Figure for simulation scope. While tracing simulation scope, anchor the review at Outside model and one tag in it. The conclusion depends on Plan real hardware validation.

NFC reader simulation boundary showing scenario inputs, reader state machine, anti-collision, tag memory, NDEF parser, app policy, and evidence output, with RF and antenna behavior outside the software-only model.
NFC reader simulation boundary showing scenario inputs, reader state machine, anti-collision, tag memory, NDEF parser, app policy, and evidence output, with the RF field and antenna behavior outside the software-only model.

Read Outside model with one tag in Figure for simulation scope. Read its ownership map with Outside model and one tag on distinct boundaries before Plan real hardware validation. A fault should remain attached to Outside model or one tag. Preserve the Plan real hardware validation condition in the handoff for simulation scope.

Good simulation target State transitions, NDEF payloads, parser behavior, error handling, duplicate reads, and application validation rules.
Bad simulation target Exact antenna field shape, phone-specific NFC controller behavior, secure-element internals, or installed read range.
Useful output A trace that explains what the reader selected, decoded, accepted, rejected, and recorded as evidence.
Required follow-up Physical testing with representative tags, phones, cases, mounting surfaces, and failure paths.

The mathematical gist. At 13.56 MHz, wavelength is 22.1 m and the near-field boundary is 3.52 m. With 2.5 cm and 1.5 cm coaxial single-turn loops, the approximation gives 14.2 nH at 1 cm but 2.64 nH at 4 cm: only 18.6% of the reference coupling remains, so induced voltage falls by the same ratio when frequency and reader current stay fixed.

Math Bridge · guided foundationsWhy does a few centimetres change an NFC tap?Let Eddie connect wavelength, near-field depth, loop geometry, mutual inductance, and induced voltage.

Reader State Model

Start with a small state machine. The simulation should make each transition explicit so a bad tag, ambiguous field, malformed record, or policy denial is visible rather than hidden behind a single “read failed” message.

Idle to polling. The reader waits, then sends a polling request for compatible tags in range.
Polling to selection. If more than one candidate responds, the anti-collision procedure selects one tag at a time.
Selection to memory access. The reader checks tag type, capacity, lock state, and whether the memory layout advertises NDEF data.
Memory access to parsing. The parser reads the TLV container, NDEF record header, type field, and payload bytes.
Parsing to policy. The application validates host, record type, payload length, schema version, duplicate-read rules, and credential risk signals.
Policy to evidence. The simulation stores the decision, trace, inputs, and reason codes for the lab report.

Minimal Scenario Record

Use a compact scenario record instead of a long copied code listing. The record should describe what the simulated reader sees, not pretend to be real RF data.

scenario_id: maintenance-tag-valid field: candidates: - uid: 04:A1:8C:22 tag_type: NFC Forum Type 2 memory_state: readable, locked ndef_tlv: "03 13 D1 01 0F 55 04 6F 70 73 2E 65 78 61 6D 70 6C 65 2F 41 37 FE" reader_policy: accepted_record_types: URI accepted_hosts: ops.example max_payload_bytes: 64 require_read_back_after_write: true expected_decision: accept asset reference, then require app authorization

Activation Loop Trace

Simulating an NFC reader means modelling a repeating loop, not a single read. The reader energizes the 13.56 MHz field, polls supported technologies such as NFC-A, NFC-B, NFC-F, and NFC-V, detects a response, resolves one target out of any crowd, activates it, exchanges data, and releases the target before polling again.

Inspect cycle modes and Resolve in Figure for activation loop trace. To challenge the claim in activation loop trace, compare cycle modes with Resolve in it. The comparison reaches Activate.

NFC reader activation flow from polling through detection, anti-collision, selection, activation, exchange, and release evidence.
NFC reader activation flow from polling through detection, anti-collision, selection, activation, exchange, and release evidence.

Read cycle modes with Resolve in Figure for activation loop trace. Set its cases by setting cycle modes against Resolve under Activate. Neither cycle modes nor Resolve wins without Activate. Return to activation loop trace with Resolve explicitly tested.

A useful simulator logs transitions instead of returning only “tag read” or “read failed.” For a maintenance tag, the trace might say: field on, Type 2 candidate detected, UID selected, NDEF TLV read, URI decoded, host accepted, app authorization still required. That trace lets a review distinguish a polling miss, collision-resolution issue, payload rejection, policy denial, or release-evidence outcome.

The simulation boundary should be explicit in the same report. A software-only lab can prove that the parser rejects a malformed TLV length, that policy rejects an unknown URI host, and that the application asks the user to isolate one label when two tags are in the field. It cannot prove antenna tuning, installed read range, phone operating-system prompts, secure-element behavior, or the effect of mounting a label on metal.

Use a simple release example. If the target deployment is a gateway tag carrying https://ops.example/A7, the simulation should accept that reference only after checking the NDEF record type, URI scheme, allowed host, payload length, and duplicate-read rule. It should still stop short of service action until an authenticated app session and backend work-order state allow it.

Activation Sequence Details

Model the activation sequence as distinct states so failure injection can name exactly where the workflow stopped:

  1. Field on and technology polling: the reader sends each technology’s poll command, such as REQA/WUPA for NFC-A or SENSF_REQ for NFC-F, and listens for a technology-specific response.
  2. Anti-collision: if more than one card answers, the reader resolves one UID or target identifier so it talks to exactly one device.
  3. Select and activate: the reader issues SELECT or the technology equivalent to put the resolved target into the active state.
  4. Protocol activation: for a Type 4 or ISO-DEP card, the reader runs RATS to learn card capabilities, then exchanges ISO 7816-4 APDUs such as application selection by AID and command/response pairs.
  5. Release: the card is deactivated and the polling loop resumes.

Run it: Steps 3 and 4 are a command-then-response exchange — watch one play out in the card-emulation workbench below. The terminal starts the conversation, the AID selects an app or secure element route, and each command draws a response until a security policy decides the result. Switch between the Host card emulation app and the Secure element route, then Show a common failure to trigger No matching route — the unknown-host case this lab injects — so you can name which activation state owns the failure.

This is where the lab earns its keep. You can inject a second card at the anti-collision step, drop the field mid-APDU, corrupt a TLV length, or delay a response and then ask which state owns the failure. The point is not to imitate every analog timing detail; it is to make the reader software obligations explicit enough that the review can separate parser, policy, and follow-up hardware risks.

A practical scenario table should include one clean tag and several negative cases. In the clean case, a Type 2 tag advertises an NDEF Message TLV, the parser finds a URI record, and policy accepts the host. In a malformed case, the TLV length claims more bytes than the buffer contains, so the parser must reject before policy sees a partial URI. In a multi-tag case, anti-collision selects one UID, but the application may still reject a maintenance write because two nearby labels create user ambiguity.

The byte trace can stay small. For example, 03 13 means an NDEF Message TLV with length 0x13, or 19 bytes, before the FE terminator. The record header D1 indicates a short well-known record with message-begin and message-end set. The URI record type 55 is followed by URI identifier code 04, which abbreviates the https:// prefix, and the remaining payload bytes spell the host and path.

Folded Hands-On Pilot Notes

A useful NFC hands-on pilot separates tap intent, payload design, app policy, and field testing:

Pilot checkpointEvidence to capture
Tap intentWhat the user expects the tap to select, open, or hand off.
NDEF payloadRecord type, host, schema version, payload size, and unsupported-record behavior.
Application policySession requirement, role check, object-state check, fallback path, and audit event.
Field testFinal tag surface, phone models, cases, label overlay, tap-zone marking, and damaged-tag behavior.
Release recordOwner, app version, tag batch, replacement process, and failure reason codes.

Use the simulator for parser behavior, duplicate reads, anti-collision paths, malformed records, and policy denials. Then run a physical pilot before release, because software-only traces cannot prove installed read range, phone prompts, metal detuning, or user handling.

Folded Lab Evidence Record

When the lab uses a real tag, phone, USB reader, or supplied trace, finish with one evidence record that separates observation from authorization:

Evidence fieldWhat to record
Reader pathPhone app, USB reader, embedded reader, or supplied trace.
Raw evidenceSaved trace, tag type, UID if exposed, NDEF bytes, record order, and read timestamp.
Decode resultRecord type, payload length, URI prefix, host, text encoding, schema version, and terminator handling.
Validation resultApproved host, allowed record type, object reference exists, malformed length rejected, duplicate tap behavior.
Action boundaryWhich action may proceed after app policy, and which actions must never follow from read success alone.
Retest triggerPayload format, reader path, policy, tag replacement, mounting material, or installation change.

This record is intentionally small. It should prove that learners can plan a payload, read it, decode it, reject bad cases, and explain why “tag read” is not the same as “action allowed.”

NDEF Trace Review

The simulation should teach byte-level reasoning without burying the learner in a thousand-line sketch. The important question is whether the parser and application disagree with the raw bytes.

Inspect Trace the bytes before trusting the action and Container check in Figure for ndef trace review. Before carrying ndef trace review forward, anchor the review at Trace the bytes before trusting the action and Container check in it. authorize after parse marks the next check.

NDEF trace example showing TLV type, TLV length, record header, type length, payload length, URI identifier code, URI payload, terminator, parser checks, and application policy checks.
NDEF trace example showing TLV type, TLV length, record header, type length, payload length, URI identifier code, URI payload, terminator, parser checks, and application policy checks.

Read Trace the bytes before trusting the action with Container check in Figure for ndef trace review. Work through it from the Trace the bytes before trusting the action field to Container check, then the authorize after parse disposition. Keep authorize after parse separately reviewable. Preserve the authorize after parse condition in the handoff for ndef trace review.

Parser Checks

TLV type Confirm the data is an NDEF Message TLV before treating bytes as records.
Length agreement Check that the TLV length, record payload length, and actual bytes agree.
Record header Decode message begin, message end, short record, ID-length, and type-name-format bits.
Record type Accept only expected record types for the workflow, such as URI or a controlled MIME type.
Payload policy Validate host, scheme, schema version, size, and unsafe command fields before acting.
Failure reason Return a specific reason code so the lab output can drive a real fix.

Interactive Scenario Runner

Use the runner to inspect a few common cases. It intentionally models logical reader decisions and application policy only; final hardware behavior still needs field testing.

Reader Trace


Evidence Review

Failure Injection Matrix

A useful lab does not only show the happy path. It should include failure scenarios that force the reader and application to explain their decision.

Inspect Failure injection turns a demo into evidence and Expected reader behavior in Figure for failure injection matrix. For the evidence behind failure injection matrix, use it to distinguish Failure injection turns a demo into evidence from Expected reader behavior. The conclusion depends on known host, small URI.

NFC simulation failure-injection matrix comparing valid tag, two tags, malformed NDEF, unknown host, locked tag, and relay-risk timing against reader behavior and required evidence.
NFC simulation failure-injection matrix comparing valid tag, two tags, malformed NDEF, unknown host, locked tag, and relay-risk timing against the reader behavior and required evidence.

Read Failure injection turns a demo into evidence with Expected reader behavior in Figure for failure injection matrix. Apply its criteria around the contrast between Failure injection turns a demo into evidence and Expected reader behavior, then check known host, small URI. known host, small URI decides the category. For failure injection matrix, attach the next action to known host, small URI.

Malformed payload. Confirm that parser errors stop action and produce a readable reason code.
Unknown host. Confirm that an otherwise valid URI is rejected when the application does not recognize the destination.
Multiple tags. Confirm that the reader either selects one predictable tag or asks the user to isolate the target.
Locked or read-only tag. Confirm that write operations fail safely and that release evidence records the intended lock state.
Relay-risk timing. Confirm that credential flows record challenge freshness, timing bucket, and policy decision without claiming timing alone proves an attack.

UID Anti-Collision and Cascade Levels

The step that surprises people is anti-collision, because NFC has to single out one card from several sharing the field with no central schedule. For NFC-A, ISO/IEC 14443-3 Type A uses bit-oriented anti-collision over the card UID. Cards reply with UID bits; when two disagree at a bit position, the reader detects the collision, fixes the prefix, and asks again. That binary walk continues until one card is uniquely identified.

Because UIDs can be 4, 7, or 10 bytes, this happens in cascade levels: CL1, CL2, and CL3. Each level resolves part of the UID, and a cascade tag byte signals that more UID bytes follow. Once the full UID is known, SELECT activates that one card. NFC-B uses a different time-slotted anti-collision process, so a simulator should not pretend all technologies resolve collisions the same way.

The simulator should expose the difference between reader capability and application safety. The reader may correctly resolve one Type A card from two candidates, but a maintenance workflow may still reject the action because two nearby labels create user ambiguity. For a read-only lookup, selecting one card may be acceptable. For a write, lock, or credential action, policy may require one visible target in the field before proceeding.

Cascade-level logging also protects the model from treating every UID as an opaque string. A 4-byte UID can be resolved in one cascade level, while longer UIDs require later levels after the cascade tag indicates that more bytes follow. If the model never records those steps, it cannot test partial UID handling, duplicate prefixes, or mistaken selection after a collision.

Finally, keep relay-risk modelling honest. A software scenario can simulate stale challenge identifiers, delayed responses, duplicate credential observations, and policy decisions that deny high-value actions. It cannot prove that a real relay attack was prevented by timing alone. The right output is a trace and a reason code: challenge freshness checked, response outside expected bucket, action denied or escalated, audit row recorded, physical or credential review required.

Quick Check: Anti-Collision

Worked Example: Maintenance Tag Review

Scenario

A facilities team wants tags on gateways and air handlers. A tap should open the correct maintenance record and allow a technician to create a service note. The team wants a simulation before buying production labels.

Simulation Design

workflow: maintenance lookup tag_payload: URI record with asset reference reader_model: polling, single-tag selection, TLV parse, URI parse application_policy: approved_hosts: ops.example allowed_record_types: URI max_payload_bytes: 64 action_authority: authenticated technician session failure_cases: - malformed TLV length - unknown host - two nearby labels - duplicate static asset reference - read-only tag during attempted update

Acceptance Evidence

The simulation is ready for field testing only when it produces evidence for both accepted and rejected paths:

  • Accepted tag opens the asset record only after the app session is valid.
  • Unknown host, malformed NDEF, and oversized payload are rejected with clear reason codes.
  • Multi-tag behavior is documented so label spacing can be checked in the physical layout.
  • Write tests include read-back validation and expected lock state.
  • The report states what the simulation does not prove: tap range, antenna detuning, case effects, and phone operating-system prompts.

Common Pitfalls

  • Using a new-project simulator as evidence. A generic board page does not validate an NFC workflow unless the scenario, parser, policy, and failure cases are explicit.
  • Confusing parsed data with trusted data. Valid NDEF syntax only means the bytes decoded. The application still needs host, type, length, schema, and authorization checks.
  • Overclaiming relay detection. Timing signals can inform risk, but credential flows need challenge freshness, policy, audit, and fallback decisions.
  • Skipping negative tests. A lab that only shows a valid URI does not prepare the deployment for replaced tags, partial writes, nearby labels, or corrupted data.
  • Forgetting physical validation. A software lab cannot replace installed tests with real tags, readers, phones, cases, and mounting surfaces.

Knowledge Check

Quick Check: Simulation Boundary

Matching Quiz: Lab Artifact To Purpose

Ordering Quiz: Run A Simulation Review

Summary

  • A useful NFC simulation is a logic and evidence tool, not a substitute for RF, phone, and installation testing.
  • Model the reader path explicitly: polling, anti-collision, memory access, NDEF parsing, application policy, and evidence.
  • Valid NDEF syntax does not mean the payload is trusted or authorized.
  • Failure injection is part of the lab, especially malformed records, unexpected hosts, nearby tags, lock-state errors, and relay-risk signals.
  • The final lab output should say what passed, what failed, what remains unproven, and what must be tested with real hardware.

Key Takeaway

NFC labs should prove the read, write, validation, error, and security path that a real user or device will experience at the tap point.

What’s Next

NFC Security and Alternatives Compare NFC risks and controls against RFID, QR, Bluetooth LE, and UWB.
NFC Real-World Applications Apply simulation evidence to payment, product, access, and automation workflows.
How NFC Taps Work Return to the NFC section map and choose the next review topic.