Chapters

Practice: NFC Reader Simulation

rfid-nfc-uwb
apps
simulation
lab

This lab belongs to NFC Tag Programming

Start With the Story

This section: Start With the Story — Picture a phone tapping a label to open the correct equipment record.

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

This section: 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

This section: Quick Check: NFC Simulation

Simulation Scope

This section: Simulation Scope — An NFC simulation is useful when it is honest about its boundary.

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 Figure 1 and ask which NFC behaviors software can exercise without claiming evidence about the RF tap.

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.
Figure 1: 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 Figure 1 from the inputs to the saved result. The model polls, picks one tag, reads its memory, parses NDEF, and applies the app rule. It can show payloads, fault cases, reason codes, repeat reads, and policy choices. It cannot prove tap range, detuning, phone prompts, secure-element use, or the user’s hand motion. Those facts stay outside the model. The next plan must test typical tags, phones, cases, mount surfaces, and fault paths on real hardware.

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

This section: Reader State Model — Start with a small state machine.

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

This section: Minimal Scenario Record — Use a compact scenario record instead of a long copied code listing.

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

This section: Activation Loop Trace — Simulating an NFC reader means modelling a repeating loop, not a single read.

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.

Figure 2 divides a reader tap into states that can be logged separately.

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

Polling turns on the field and cycles the supported modes. Detection reports a nearby target, while anti-collision resolves a participant when more than one response appears. Selection and activation establish the exchange context before the reader decodes data; release ends that attempt. Record the state where a simulated run failed instead of writing only “read failed.” A detection without activation does not prove an NDEF message was available, and a decoded message does not authorize an application action. The software-only model prepares a trace to check later against a real reader and tag.

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

This section: Activation Sequence Details — Run it: Steps 3 and 4 are a command-then-response exchange — watch one play out in the card-emulation workbench below.

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. Click Show a common failure once for the out-of-range case, then again for No matching route: the workbench reports No route is registered for the selected AID. This was observed in the browser run and identifies a route failure before APDU exchange.

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.

Quick Check: Reject malformed TLV length

Folded Hands-On Pilot Notes

This section: Folded Hands-On Pilot Notes — Use the simulator for parser behavior, duplicate reads, anti-collision paths, malformed records, and policy denials.

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

This section: Folded Lab Evidence Record — This record is intentionally small.

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

This section: NDEF Trace Review — The simulation should teach byte-level reasoning without burying the learner in a thousand-line sketch.

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.

Figure 3 asks readers to decode the NDEF bytes before trusting a URI.

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.
Figure 3: 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.

The 03 TLV marks an NDEF message and its length field bounds the bytes that follow. The record header, type length, payload length, and 55 URI type identify how the URI payload should be read; FE terminates the TLV area. A container check must confirm those lengths fit before the application uses the resulting link. First compare the declared TLV length with the available NDEF bytes; only after that check passes should the record lengths and decoded host be checked. Compare the decoded URI with the approved host and path rule. A trace that merely contains readable characters does not prove a valid or allowed record, so keep both byte-level and policy results.

Parser Checks

This section: 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

This section: Interactive Scenario Runner — Use the runner to inspect a few common cases.

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

This section: Failure Injection Matrix — A useful lab does not only show the happy path.

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 Figure 4 and ask whether every injected failure has an expected reader response and a retained evidence field.

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.
Figure 4: 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 Figure 4 down the cases. A valid maintenance URI may reach authorization, while two visible tags require isolation or explicit selection. Malformed length must stop before policy receives a partial URI, and an unknown host must not be opened even when parsing succeeds. Locked-tag writes fail safely, while suspicious timing is recorded as a freshness and review signal rather than automatic attack proof. Each outcome retains inputs, reason codes, lock state, timing, and the resulting decision.

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

This section: 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.

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

This section: Quick Check: Anti-Collision

Worked Example: Maintenance Tag Review

This section: 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

This section: 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

Step 1: Set the reader scenario

  • Copy the maintenance-tag-valid scenario above into a lab record and identify its Type 2 tag and URI intent.
  • In the reader state model, mark polling, selection, memory access, parsing, policy, and evidence as separate stages.
  • The expected output is an asset reference, not permission to update an asset.
  • Label the supplied UID and bytes as scenario data; they are not a live RF capture.
  • Keep the approved host and maximum payload length beside the scenario before decoding.

Step 2: Trace activation and selection

  • Follow the activation loop above from field on through technology poll, one selected target, and release.
  • In the card-emulation workbench, compare the host app and secure-element routes and note the selected AID.
  • Click its common-failure control twice; the browser run reported Out of NFC coupling range. and then No route is registered for the selected AID.
  • Record a distinct reason for two candidates, selection failure, or mid-exchange field loss.
  • The software trace models state transitions; only a physical reader can test installed range and coupling.

Step 3: Decode the NDEF bytes

  • In a local Python terminal, decode the chapter’s 03 13 ... FE bytes as an NDEF TLV and URI record.
  • Check the TLV length against available bytes before reading the short-record payload length.
  • The local run returned ACCEPT reference=https://ops.example/A7 action=requires_app_authorization.
  • Confirm the URI prefix byte 04 supplies https:// and the remaining payload supplies the host and path.
  • Save both the input hex and decoded URI so a reviewer can detect byte-to-text mistakes.

Step 4: Reject damaged or untrusted records

  • Change one byte or length at a time, then rerun the same parser and record its first failed rule.
  • A TLV length of 0x40 on the short chapter buffer returned REJECT tlv_length_exceeds_buffer locally.
  • Changing the URI host in the fixture returned REJECT unknown_host.
  • Also document duplicate-read, multi-tag, oversized payload, and read-only-write cases in the matrix above.
  • Do not pass a partial URI to application policy when the container length is invalid.

Step 5: Apply application authority

  • For the accepted URI, check the authenticated technician session and work-order state in the application layer.
  • Record requires_app_authorization after parsing; this is the actual local fixture disposition.
  • Deny service-note creation when the session or object state is not approved, even if the tag parsed cleanly.
  • Keep parser acceptance, policy acceptance, and completed action as three different fields.
  • This boundary prevents a readable label from becoming an authorization credential.

Step 6: Prepare physical follow-up

  • Complete the evidence record above with raw bytes, decode, reason codes, and policy decision.
  • On your own hardware, test final label placement, phone models, cases, metal surfaces, and damaged tags.
  • Capture the actual reader or phone window and note the installed tap range; this was not run here.
  • Include read-back and lock-state evidence before approving any writable tag design.
  • Mark the release provisional until those field tests match the simulated record.

Checkpoint: Acceptance Evidence

This section: Checkpoint: 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

This section: 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

This section: Knowledge Check

Quick Check: Simulation Boundary

This section: Quick Check: Simulation Boundary

Matching Quiz: Lab Artifact To Purpose

This section: Matching Quiz: Lab Artifact To Purpose

Ordering Quiz: Run A Simulation Review

This section: Ordering Quiz: Run A Simulation Review

Checkpoint: Summary

This section: Checkpoint: 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

This section: 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.

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