Skip to content

feat(readers): forward go-pn532 debug output to Core log - #1107

Merged
wizzomafizzo merged 5 commits into
mainfrom
investigate/nfc-write-1098-1106
Jul 25, 2026
Merged

feat(readers): forward go-pn532 debug output to Core log#1107
wizzomafizzo merged 5 commits into
mainfrom
investigate/nfc-write-1098-1106

Conversation

@wizzomafizzo

@wizzomafizzo wizzomafizzo commented Jul 16, 2026

Copy link
Copy Markdown
Member

Why

App-written NTAG213 tags don't launch on Core (#1098, #1106). Across the attached logs the failing
scans show a validly-formatted NTAG213 (valid Capability Container → variant=NTAG213,
hasNDEF=true) whose NDEF message is empty: messageNil=false with zero records, which is emitted
only when the NDEF TLV has a length byte of 0 (03 00). The record the app intended to write is not
where Core reads it.

go-pn532 already prints the exact bytes it reads from a tag (readNDEFHeader: user data = [...]) via
Debugf, but Core never wired that output anywhere, so the decisive bytes are absent from every log.
This PR captures them.

What

  • New pkg/readers/pn532/debug.go: a zerologDebugWriter that forwards each go-pn532 debug line to
    log.Debug().Str("src","pn532"), installed once via sync.Once.
  • pkg/readers/pn532/pn532.go: Open installs it when the existing debug_logging config is
    enabled. No new config key.
  • go.mod: go-pn532 v0.22.1v0.23.0, which adds the SetDebugWriter(io.Writer) hook this
    calls (feat: add embeddable debug writer go-pn532#96).

With debug_logging on, a failing app-written tag and a working Core-written tag can be scanned and
their byte dumps diffed to decide write-side vs read-side.

The branch previously built against a local sibling ../go-pn532 checkout via a replace directive
and a matching bind-mount in scripts/tasks/docker.yml. Both are gone now that SetDebugWriter is
released.

Scope

This adds the capture path only — it changes no read or write behaviour, and with debug_logging
off it costs nothing (the writer is never installed). It does not itself fix #1098 or #1106.

Diagnosing those still needs an on-device scan: a physically app-written failing tag read on the
MiSTer with debug_logging on. If the captured bytes show a genuine empty NDEF (03 00), the fix is
app-side (write read-back verification); if they show a valid record Core misreads, a read-side fix
lands in go-pn532.

Summary by CodeRabbit

  • New Features

    • Added optional PN532 diagnostic logging when debug logging is enabled.
    • PN532 communication details are now forwarded to application logs to help diagnose tag-reading issues.
  • Bug Fixes

    • Improved handling of PN532 debug output, including multiline messages and carriage returns.
  • Tests

    • Added coverage for diagnostic log formatting and ensuring logging is configured only once.

App-written NTAG213 tags (#1098, #1106) read on Core as a validly-formatted
tag with an empty NDEF message (messageNil=false, zero records = an NDEF TLV
of length 0). go-pn532 already prints the raw bytes it reads from the tag via
Debugf, but Core never captured that output, so the decisive bytes never
reached the log.

Add a zerolog adapter in the PN532 reader that forwards go-pn532's debug lines
to log.Debug(), installed once when the existing debug_logging config is on.
Pairs with go-pn532's new SetDebugWriter hook.

Includes temporary local wiring to build against a sibling go-pn532 checkout
(go.mod replace + docker mount); see PR description for removal.
@coderabbitai

coderabbitai Bot commented Jul 16, 2026

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 788b2059-9487-47e9-9266-69ef3392fb4a

📥 Commits

Reviewing files that changed from the base of the PR and between d2a0ad5 and 05f62b6.

📒 Files selected for processing (2)
  • pkg/readers/pn532/debug.go
  • pkg/readers/pn532/debug_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • pkg/readers/pn532/debug.go

📝 Walkthrough

Walkthrough

The PN532 dependency is updated to v0.23.0. Reader initialization conditionally routes PN532 debug output through Core’s zerolog logger, installing the writer once and testing line handling and repeated installation behavior.

Changes

PN532 debug logging

Layer / File(s) Summary
Configure PN532 debug logging
go.mod, pkg/readers/pn532/debug.go, pkg/readers/pn532/pn532.go
Updates go-pn532 to v0.23.0 and connects configuration-enabled Reader.Open calls to a once-installed writer that forwards PN532 debug lines to zerolog with src="pn532".
Validate PN532 debug logging
pkg/readers/pn532/debug_test.go
Tests line splitting, blank-line skipping, carriage-return trimming, unterminated writes, structured log fields, and once-only writer installation.

Estimated code review effort: 2 (Simple) | ~10 minutes

Possibly related PRs

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly describes the main change: forwarding go-pn532 debug output into Core logs.
Linked Issues check ✅ Passed The PR adds the requested debug logging path and enables full PN532 dumps when debug_logging is on.
Out of Scope Changes check ✅ Passed All changes are tied to PN532 debug logging and the dependency needed to support it.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch investigate/nfc-write-1098-1106

Comment @coderabbitai help to get the list of available commands.

Drops the local ../go-pn532 replace directive and the sibling-checkout
mount in the Docker build task, both of which existed only because
SetDebugWriter was unreleased.
@wizzomafizzo
wizzomafizzo marked this pull request as ready for review July 25, 2026 12:06
@wizzomafizzo wizzomafizzo changed the title investigate: capture raw NDEF bytes for app-written tags (#1098, #1106) feat(readers): forward go-pn532 debug output to Core log Jul 25, 2026
@wizzomafizzo

Copy link
Copy Markdown
Member Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 25, 2026

Copy link
Copy Markdown
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@pkg/readers/pn532/debug.go`:
- Around line 22-58: Add tests for zerologDebugWriter.Write covering newline
splitting, blank-line filtering, CRLF trimming, and fragmented writes while
verifying each non-empty line is logged at debug level with the pn532 source.
Add a test for enablePN532DebugLogging confirming pn532.SetDebugWriter is
installed only once, using isolated sync.Once state or equivalent test setup.
- Around line 40-48: Update zerologDebugWriter.Write to buffer trailing partial
PN532 debug lines across calls, emitting only complete newline-terminated lines
while preserving the existing trimming, empty-line filtering, and return values.
Add a test covering a message split across multiple Write calls and verify it
logs as one complete line.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 1e782c8e-6fef-4799-8316-73fb9bcb1dd0

📥 Commits

Reviewing files that changed from the base of the PR and between 3cd017b and d2a0ad5.

⛔ Files ignored due to path filters (1)
  • go.sum is excluded by !**/*.sum
📒 Files selected for processing (3)
  • go.mod
  • pkg/readers/pn532/debug.go
  • pkg/readers/pn532/pn532.go

Comment on lines +22 to +58
import (
"strings"
"sync"

pn532 "github.com/ZaparooProject/go-pn532"
"github.com/rs/zerolog/log"
)

// debugWriterOnce ensures the go-pn532 debug writer is only installed once,
// even if multiple PN532 readers are opened.
var debugWriterOnce sync.Once

// zerologDebugWriter forwards go-pn532's always-on debug output into Core's
// zerolog logger at debug level. go-pn532 writes the exact bytes it reads from
// tags (e.g. "NTAG readNDEFHeader: user data = [...]") through this path, which
// is otherwise never captured because Core creates no session log file.
type zerologDebugWriter struct{}

func (zerologDebugWriter) Write(p []byte) (int, error) {
for line := range strings.Lines(string(p)) {
line = strings.TrimRight(line, "\r\n")
if line == "" {
continue
}
log.Debug().Str("src", "pn532").Msg(line)
}
return len(p), nil
}

// enablePN532DebugLogging routes go-pn532 debug output into Core's logger when
// debug logging is enabled in the config. This is how raw NDEF/TLV byte dumps
// reach Core's log for diagnosing tag read failures.
func enablePN532DebugLogging() {
debugWriterOnce.Do(func() {
pn532.SetDebugWriter(zerologDebugWriter{})
})
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

Add tests for the new PN532 logging code.

Cover line splitting, blank-line filtering, CRLF handling, fragmented writes, and the once-only installation behavior. As per coding guidelines, **/*.go: Write tests for all new code — see TESTING.md and pkg/testing/README.md.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pkg/readers/pn532/debug.go` around lines 22 - 58, Add tests for
zerologDebugWriter.Write covering newline splitting, blank-line filtering, CRLF
trimming, and fragmented writes while verifying each non-empty line is logged at
debug level with the pn532 source. Add a test for enablePN532DebugLogging
confirming pn532.SetDebugWriter is installed only once, using isolated sync.Once
state or equivalent test setup.

Source: Coding guidelines

Comment on lines +40 to +48
func (zerologDebugWriter) Write(p []byte) (int, error) {
for line := range strings.Lines(string(p)) {
line = strings.TrimRight(line, "\r\n")
if line == "" {
continue
}
log.Debug().Str("src", "pn532").Msg(line)
}
return len(p), nil

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '\n== target file ==\n'
git ls-files 'pkg/readers/pn532/*'
printf '\n== outline/debug.go ==\n'
ast-grep outline pkg/readers/pn532/debug.go --view expanded || true
printf '\n== show debug.go ==\n'
cat -n pkg/readers/pn532/debug.go

printf '\n== search pn532 tests/references ==\n'
rg -n --hidden --glob '!**/node_modules/**' --glob '!**/dist/**' --glob '!**/build/**' 'pn532|strings\.Lines|enablePN532DebugLogging|zerologDebugWriter' .

printf '\n== go version hints ==\n'
rg -n --hidden --glob 'go.mod' '^go [0-9]+\.[0-9]+' .

Repository: ZaparooProject/zaparoo-core

Length of output: 37788


Buffer partial PN532 debug lines. Write can receive fragments of one logical message, so this will log truncated lines when a dump is split across calls. Keep the trailing partial line until the next write/newline, and add a split-write test.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pkg/readers/pn532/debug.go` around lines 40 - 48, Update
zerologDebugWriter.Write to buffer trailing partial PN532 debug lines across
calls, emitting only complete newline-terminated lines while preserving the
existing trimming, empty-line filtering, and return values. Add a test covering
a message split across multiple Write calls and verify it logs as one complete
line.

@codecov

codecov Bot commented Jul 25, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 84.61538% with 2 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
pkg/readers/pn532/pn532.go 0.00% 1 Missing and 1 partial ⚠️

📢 Thoughts on this report? Let us know!

Tests line splitting, blank-line filtering, CRLF trimming, unterminated
chunks, and the io.Writer return contract, plus that repeat calls to
enablePN532DebugLogging do not reinstall the writer.

Also records why Write does not buffer across calls: go-pn532 emits each
message in one Fprintf, so a partial line never arrives.
@wizzomafizzo
wizzomafizzo merged commit 1814c4f into main Jul 25, 2026
15 checks passed
@wizzomafizzo
wizzomafizzo deleted the investigate/nfc-write-1098-1106 branch July 25, 2026 12:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Zaparoo phone app written tags do not work on Mister device until re-written by script.

1 participant