Documentation
¶
Overview ¶
Package pn532 provides a pure Go library for interfacing with PN532 NFC/RFID controllers.
The PN532 is a highly integrated transceiver module for contactless communication at 13.56 MHz, supporting various protocols including ISO14443A/B and FeliCa. This library provides a clean, idiomatic Go interface for working with PN532 devices across multiple transport layers.
Features:
- Multiple transport support: UART, I2C, SPI
- Support for NTAG21x and MIFARE Classic tags
- NDEF (NFC Data Exchange Format) message reading and writing
- Cross-platform compatibility (Linux, Windows, macOS)
- Automatic tag detection and identification
- Retry logic with configurable backoff
- Comprehensive error handling
Basic Usage:
import (
"github.com/ZaparooProject/go-pn532"
"github.com/ZaparooProject/go-pn532/transport/uart"
)
// Create a UART transport
transport, err := uart.New("/dev/ttyUSB0")
if err != nil {
log.Fatal(err)
}
defer transport.Close()
// Create and initialize the PN532 device
device, err := pn532.New(transport)
if err != nil {
return err
}
if err := device.Init(); err != nil {
log.Fatal(err)
}
// Or create with custom options
device = pn532.New(transport,
pn532.WithTimeout(2*time.Second),
pn532.WithMaxRetries(5),
)
// Detect a tag
tag, err := device.DetectTag()
if err != nil {
log.Fatal(err)
}
if tag != nil {
fmt.Printf("Tag detected: %s\n", tag.UID())
// Create appropriate tag handler
nfcTag, err := device.CreateTag(tag)
if err != nil {
log.Fatal(err)
}
// Read NDEF message
msg, err := nfcTag.ReadNDEF()
if err != nil {
log.Fatal(err)
}
fmt.Printf("NDEF Content: %s\n", msg.Records[0].Text)
}
Transport Selection:
The library supports multiple transport layers:
- UART: Most common, works with USB-to-serial adapters
- I2C: For embedded systems with I2C bus
- SPI: High-speed communication for embedded systems
Tag Support:
Currently supported tag types:
- NTAG213/215/216 (NFC Forum Type 2)
- MIFARE Classic 1K/4K (with NDEF format)
NDEF Support:
The library includes comprehensive NDEF support:
- Text records
- URI records
- WiFi credential records
- vCard contact records
- Smart poster records
Error Handling:
All operations return meaningful errors that can be inspected:
if errors.Is(err, pn532.ErrTimeout) {
// Handle timeout
}
Thread Safety:
Device operations are not thread-safe. If you need concurrent access, implement appropriate synchronization in your application.
Index ¶
- Constants
- Variables
- func BuildNDEFMessage(text string) ([]byte, error)
- func BuildNDEFMessageEx(records []NDEFRecord) ([]byte, error)
- func BuildTextMessage(text string) ([]byte, error)
- func BuildURIMessage(uri string) ([]byte, error)
- func BuildVCardMessage(name, phone, email string) ([]byte, error)
- func BuildVCardRecord(contact *VCardContact) (*ndef.Record, error)
- func BuildWiFiMessage(ssid, password string, authType, encType uint16) ([]byte, error)
- func BuildWiFiRecord(cred WiFiCredential) (*ndef.Record, error)
- func ExponentialBackoff(attempt int, initial time.Duration, maxDuration time.Duration, ...) time.Duration
- func IsDebugEnabled() bool
- func IsRetryable(err error) bool
- func IsValidNDEFMessage(data []byte) bool
- func IsValidNDEFPayload(payload []byte) bool
- func Retry(ctx context.Context, fn RetryableFunc) error
- func RetryWithConfig(ctx context.Context, config *RetryConfig, retryFunc RetryableFunc) error
- func SetDebugEnabled(enabled bool)
- func ValidateNDEFMessage(data []byte) error
- func ValidateNDEFPayload(payload []byte) error
- type AccessControlConfig
- type Address
- type AutoPollResult
- type AutoPollTarget
- type BaseTag
- func (t *BaseTag) DebugInfo() string
- func (t *BaseTag) DebugInfoWithNDEF(ndefReader interface{ ... }) string
- func (t *BaseTag) IsMIFARE4K() bool
- func (*BaseTag) ReadBlock(_ uint8) ([]byte, error)
- func (*BaseTag) ReadNDEF() (*NDEFMessage, error)
- func (t *BaseTag) ReadText() (string, error)
- func (t *BaseTag) Summary() string
- func (t *BaseTag) Type() TagType
- func (t *BaseTag) UID() string
- func (t *BaseTag) UIDBytes() []byte
- func (*BaseTag) WriteBlock(_ uint8, _ []byte) error
- func (*BaseTag) WriteNDEF(_ *NDEFMessage) error
- func (t *BaseTag) WriteText(text string) error
- type ConnectOption
- func WithAutoDetection() ConnectOption
- func WithConnectTimeout(timeout time.Duration) ConnectOption
- func WithDeviceOptions(opts ...Option) ConnectOption
- func WithTransportFactory(factory TransportFactory) ConnectOption
- func WithTransportFromDeviceFactory(factory TransportFromDeviceFactory) ConnectOption
- func WithValidation(config *ValidationConfig) ConnectOption
- type ContinuousPollConfig
- type DetectedTag
- type Device
- func (d *Device) Close() error
- func (d *Device) CreateTag(detected *DetectedTag) (Tag, error)
- func (d *Device) DetectTag() (*DetectedTag, error)
- func (d *Device) DetectTagContext(ctx context.Context) (*DetectedTag, error)
- func (d *Device) DetectTags(maxTags, baudRate byte) ([]*DetectedTag, error)
- func (d *Device) DetectTagsContext(ctx context.Context, maxTags, baudRate byte) ([]*DetectedTag, error)
- func (d *Device) Diagnose(testNumber byte, data []byte) (*DiagnoseResult, error)
- func (d *Device) DiagnoseContext(ctx context.Context, testNumber byte, data []byte) (*DiagnoseResult, error)
- func (d *Device) GetCurrentPollStrategy() PollStrategy
- func (d *Device) GetFirmwareVersion() (*FirmwareVersion, error)
- func (d *Device) GetFirmwareVersionContext(ctx context.Context) (*FirmwareVersion, error)
- func (d *Device) GetGeneralStatus() (*GeneralStatus, error)
- func (d *Device) GetGeneralStatusContext(ctx context.Context) (*GeneralStatus, error)
- func (d *Device) GetPollConfig() *ContinuousPollConfig
- func (d *Device) InAutoPoll(pollCount, pollPeriod byte, targetTypes []AutoPollTarget) ([]AutoPollResult, error)
- func (d *Device) InAutoPollContext(ctx context.Context, pollCount, pollPeriod byte, targetTypes []AutoPollTarget) ([]AutoPollResult, error)
- func (d *Device) InListPassiveTargetContext(ctx context.Context, maxTg, brTy byte) ([]*DetectedTag, error)
- func (d *Device) InRelease(targetNumber byte) error
- func (d *Device) InReleaseContext(ctx context.Context, targetNumber byte) error
- func (d *Device) InSelect(targetNumber byte) error
- func (d *Device) InSelectContext(ctx context.Context, targetNumber byte) error
- func (d *Device) Init() error
- func (d *Device) InitContext(ctx context.Context) error
- func (d *Device) InitiatorListPassiveTargets(maxTags int, tagType TagType, uid []byte) ([]*DetectedTag, error)
- func (d *Device) IsAutoPollSupported() bool
- func (d *Device) PollForTag(ctx context.Context, pollInterval time.Duration) (*DetectedTag, error)
- func (d *Device) PowerDown(wakeupEnable, irqEnable byte) error
- func (d *Device) PowerDownContext(ctx context.Context, wakeupEnable, irqEnable byte) error
- func (d *Device) SAMConfiguration(mode SAMMode, timeout, irq byte) error
- func (d *Device) SAMConfigurationContext(ctx context.Context, mode SAMMode, timeout, irq byte) error
- func (d *Device) SendDataExchange(data []byte) ([]byte, error)
- func (d *Device) SendDataExchangeContext(ctx context.Context, data []byte) ([]byte, error)
- func (d *Device) SendRawCommand(data []byte) ([]byte, error)
- func (d *Device) SendRawCommandContext(ctx context.Context, data []byte) ([]byte, error)
- func (d *Device) SetPollConfig(config *ContinuousPollConfig) error
- func (d *Device) SetRetryConfig(config *RetryConfig)
- func (d *Device) SetTimeout(timeout time.Duration) error
- func (d *Device) Transport() Transport
- func (d *Device) WaitForTag(ctx context.Context) (*DetectedTag, error)
- type DeviceConfig
- type DiagnoseResult
- type ErrorType
- type FeliCaTag
- func (f *FeliCaTag) DebugInfo() string
- func (f *FeliCaTag) GetIDm() []byte
- func (f *FeliCaTag) GetPMm() []byte
- func (f *FeliCaTag) GetServiceCode() uint16
- func (f *FeliCaTag) GetSystemCode() uint16
- func (f *FeliCaTag) Polling(systemCode uint16) error
- func (f *FeliCaTag) ReadBlock(block uint8) ([]byte, error)
- func (f *FeliCaTag) ReadBlockExtended(block uint16) ([]byte, error)
- func (f *FeliCaTag) ReadNDEF() (*NDEFMessage, error)
- func (f *FeliCaTag) RequestService(serviceCodes []uint16) ([]byte, error)
- func (f *FeliCaTag) SetServiceCode(serviceCode uint16)
- func (f *FeliCaTag) SetSystemCode(systemCode uint16)
- func (f *FeliCaTag) WriteBlock(block uint8, data []byte) error
- func (f *FeliCaTag) WriteBlockExtended(block uint16, data []byte) error
- func (f *FeliCaTag) WriteNDEF(message *NDEFMessage) error
- func (f *FeliCaTag) WriteText(text string) error
- type FirmwareVersion
- type GeneralStatus
- type MIFARETag
- func (*MIFARETag) AnalyzeLastError(err error) string
- func (t *MIFARETag) Authenticate(sector uint8, keyType byte, key []byte) error
- func (t *MIFARETag) AuthenticateRobust(sector uint8, keyType byte, key []byte) error
- func (t *MIFARETag) DebugInfo() string
- func (t *MIFARETag) GetDevice() *Device
- func (t *MIFARETag) GetTimingVariance() time.Duration
- func (t *MIFARETag) IsTimingUnstable() bool
- func (t *MIFARETag) ReadBlock(block uint8) ([]byte, error)
- func (t *MIFARETag) ReadBlockAuto(block uint8) ([]byte, error)
- func (t *MIFARETag) ReadBlockDirect(block uint8) ([]byte, error)
- func (t *MIFARETag) ReadNDEF() (*NDEFMessage, error)
- func (t *MIFARETag) ResetAuthState() error
- func (t *MIFARETag) WriteBlock(block uint8, data []byte) error
- func (t *MIFARETag) WriteBlockAuto(block uint8, data []byte) error
- func (t *MIFARETag) WriteBlockDirect(block uint8, data []byte) error
- func (t *MIFARETag) WriteNDEF(message *NDEFMessage) error
- func (t *MIFARETag) WriteText(text string) error
- type NDEFMessage
- type NDEFRecord
- type NDEFRecordType
- type NTAGTag
- func (t *NTAGTag) DebugInfo() string
- func (t *NTAGTag) DetectType() error
- func (t *NTAGTag) DisablePasswordProtection() error
- func (t *NTAGTag) FastRead(startAddr, endAddr uint8) ([]byte, error)
- func (t *NTAGTag) GetConfigPage() uint8
- func (t *NTAGTag) GetPasswordPage() uint8
- func (t *NTAGTag) GetTotalPages() uint8
- func (t *NTAGTag) GetUserMemoryRange() (start, end uint8)
- func (t *NTAGTag) GetVersion() (*NTAGVersion, error)
- func (t *NTAGTag) LockPage(page uint8) error
- func (t *NTAGTag) PwdAuth(password []byte) ([]byte, error)
- func (t *NTAGTag) ReadBlock(block uint8) ([]byte, error)
- func (t *NTAGTag) ReadNDEF() (*NDEFMessage, error)
- func (t *NTAGTag) SetAccessControl(config AccessControlConfig) error
- func (t *NTAGTag) SetPasswordProtection(password, pack []byte, auth0 uint8) error
- func (t *NTAGTag) WriteBlock(block uint8, data []byte) error
- func (t *NTAGTag) WriteNDEF(message *NDEFMessage) error
- func (t *NTAGTag) WriteText(text string) error
- type NTAGType
- type NTAGVersion
- type OptimizedPollParams
- type Option
- type PollStrategy
- type RetryConfig
- type RetryableFunc
- type SAMMode
- type Tag
- type TagContext
- type TagType
- type Transport
- type TransportCapability
- type TransportCapabilityChecker
- type TransportContext
- type TransportError
- func NewChecksumMismatchError(op, port string) *TransportError
- func NewDataTooLargeError(op, port string) *TransportError
- func NewFrameCorruptedError(op, port string) *TransportError
- func NewInvalidResponseError(op, port string) *TransportError
- func NewNACKReceivedError(op, port string) *TransportError
- func NewNoACKError(op, port string) *TransportError
- func NewTimeoutError(op, port string) *TransportError
- func NewTransportError(op, port string, err error, errType ErrorType) *TransportError
- func NewTransportNotReadyError(op, port string) *TransportError
- func NewTransportReadError(op, port string) *TransportError
- func NewTransportWriteError(op, port string) *TransportError
- type TransportFactory
- type TransportFromDeviceFactory
- type TransportOptimizer
- type TransportType
- type TransportWithRetry
- func (t *TransportWithRetry) Close() error
- func (t *TransportWithRetry) HasCapability(capability TransportCapability) bool
- func (t *TransportWithRetry) IsConnected() bool
- func (t *TransportWithRetry) SendCommand(cmd byte, args []byte) ([]byte, error)
- func (t *TransportWithRetry) SetRetryConfig(config *RetryConfig)
- func (t *TransportWithRetry) SetTimeout(timeout time.Duration) error
- func (t *TransportWithRetry) Type() TransportType
- type VCardContact
- type ValidatedDevice
- type ValidatedMIFARETag
- func (t *ValidatedMIFARETag) ReadBlockValidated(block uint8) ([]byte, error)
- func (t *ValidatedMIFARETag) ReadNDEFValidated() (*NDEFMessage, error)
- func (t *ValidatedMIFARETag) ReadTextValidated() (string, error)
- func (t *ValidatedMIFARETag) WriteBlockValidated(block uint8, data []byte) error
- func (t *ValidatedMIFARETag) WriteNDEFValidated(message *NDEFMessage) error
- func (t *ValidatedMIFARETag) WriteTextValidated(text string) error
- type ValidatedNTAGTag
- func (t *ValidatedNTAGTag) ReadBlockValidated(block uint8) ([]byte, error)
- func (t *ValidatedNTAGTag) ReadNDEFValidated() (*NDEFMessage, error)
- func (t *ValidatedNTAGTag) ReadTextValidated() (string, error)
- func (t *ValidatedNTAGTag) WriteBlockValidated(block uint8, data []byte) error
- func (t *ValidatedNTAGTag) WriteNDEFValidated(message *NDEFMessage) error
- func (t *ValidatedNTAGTag) WriteTextValidated(text string) error
- type ValidatedTag
- type ValidationConfig
- type ValidationMetrics
- type ValidationResult
- type WiFiCredential
Constants ¶
const ( WakeupHSU byte = 0x01 // Wake-up by High Speed UART WakeupSPI byte = 0x02 // Wake-up by SPI WakeupI2C byte = 0x04 // Wake-up by I2C WakeupGPIOP32 byte = 0x08 // Wake-up by GPIO P32 WakeupGPIOP34 byte = 0x10 // Wake-up by GPIO P34 WakeupRF byte = 0x20 // Wake-up by RF field WakeupINT1 byte = 0x80 // Wake-up by GPIO P72/INT1 )
PowerDownWakeupFlags provides constants for PowerDown wake-up sources
const ( DiagnoseCommunicationTest = 0x00 DiagnoseROMTest = 0x01 DiagnoseRAMTest = 0x02 // 0x03 is not used DiagnosePollingTest = 0x04 DiagnoseEchoBackTest = 0x05 DiagnoseAttentionTest = 0x06 DiagnoseSelfAntennaTest = 0x07 )
DiagnoseTestNumber constants
const ( MIFAREKeyA = 0x00 MIFAREKeyB = 0x01 )
Key types
const ( AuthTypeOpen = 0x0001 AuthTypeWPA = 0x0002 AuthTypeWPAPSK = 0x0004 AuthTypeWPA2 = 0x0008 AuthTypeWPA2PSK = 0x0020 EncryptTypeNone = 0x0001 EncryptTypeWEP = 0x0002 EncryptTypeTKIP = 0x0004 EncryptTypeAES = 0x0008 )
WiFi authentication and encryption types
const ( TNFEmpty = 0x00 TNFWellKnown = 0x01 TNFMediaType = 0x02 TNFAbsoluteURI = 0x03 TNFExternalType = 0x04 TNFUnknown = 0x05 TNFUnchanged = 0x06 TNFReserved = 0x07 )
TNF (Type Name Format) values
Variables ¶
var ( ErrNoTagDetected = errors.New("no tag detected") ErrTimeout = errors.New("operation timeout") ErrInvalidTag = errors.New("invalid tag type") ErrNotImplemented = errors.New("not implemented") )
Device errors
var ( // Transport errors - potentially retryable ErrTransportTimeout = errors.New("transport timeout") ErrTransportWrite = errors.New("transport write failed") ErrTransportRead = errors.New("transport read failed") ErrTransportClosed = errors.New("transport is closed") ErrTransportNotReady = errors.New("transport not ready") // Communication errors - potentially retryable ErrCommunicationFailed = errors.New("communication failed") ErrNoACK = errors.New("no ACK received") ErrNACKReceived = errors.New("NACK received") ErrFrameCorrupted = errors.New("frame corrupted") ErrChecksumMismatch = errors.New("checksum mismatch") // Device errors - generally not retryable ErrDeviceNotFound = errors.New("device not found") ErrDeviceNotSupported = errors.New("device not supported") ErrCommandFailed = errors.New("command execution failed") ErrInvalidResponse = errors.New("invalid response format") // Tag errors - generally not retryable ErrTagNotFound = errors.New("tag not found") ErrTagAuthFailed = errors.New("tag authentication failed") ErrTagReadFailed = errors.New("tag read failed") ErrTagWriteFailed = errors.New("tag write failed") ErrTagUnsupported = errors.New("tag type not supported") // Data errors - not retryable ErrInvalidParameter = errors.New("invalid parameter") ErrDataTooLarge = errors.New("data too large") ErrInvalidFormat = errors.New("invalid data format") )
Error categories for better error handling and retry logic
var ( // Security constants for memory protection MaxNDEFMessageSize = 8192 // Maximum NDEF message size (8KB) MaxNDEFRecordCount = 255 // Maximum records per message MaxNDEFPayloadSize = 4096 // Maximum payload size per record MaxNDEFTypeLength = 255 // Maximum type field length MaxNDEFIDLength = 255 // Maximum ID field length // Error for security violations ErrSecurityViolation = errors.New("security violation: data exceeds safety limits") // ErrNoNDEF is returned when no NDEF record is found. ErrNoNDEF = errors.New("no NDEF record found") // ErrInvalidNDEF is returned when the NDEF format is invalid. ErrInvalidNDEF = errors.New("invalid NDEF format") )
var ( ErrInvalidTLV = errors.New("invalid TLV structure") ErrInvalidRecordHeader = errors.New("invalid NDEF record header") ErrInvalidTNF = errors.New("invalid TNF value") ErrInvalidTypeLength = errors.New("invalid TYPE length") ErrInvalidPayloadLength = errors.New("invalid PAYLOAD length") ErrInvalidIDLength = errors.New("invalid ID length") ErrIncompleteRecord = errors.New("incomplete NDEF record") ErrInvalidMBME = errors.New("invalid MB/ME flags") ErrInvalidChunking = errors.New("invalid chunking") ErrTooManyRecords = errors.New("too many NDEF records") )
NDEF validation errors
Functions ¶
func BuildNDEFMessage ¶
BuildNDEFMessage creates NDEF data from text Deprecated: Use BuildTextMessage or BuildNDEFMessageEx for more flexibility
func BuildNDEFMessageEx ¶
func BuildNDEFMessageEx(records []NDEFRecord) ([]byte, error)
BuildNDEFMessageEx creates NDEF data from multiple records
func BuildTextMessage ¶
BuildTextMessage creates an NDEF message with a single text record
func BuildURIMessage ¶
BuildURIMessage creates an NDEF message with a single URI record
func BuildVCardMessage ¶
BuildVCardMessage creates an NDEF message with contact information
func BuildVCardRecord ¶
func BuildVCardRecord(contact *VCardContact) (*ndef.Record, error)
BuildVCardRecord creates an NDEF record with vCard data
func BuildWiFiMessage ¶
BuildWiFiMessage creates an NDEF message with WiFi credentials
func BuildWiFiRecord ¶
func BuildWiFiRecord(cred WiFiCredential) (*ndef.Record, error)
BuildWiFiRecord creates an NDEF record with WiFi credentials
func ExponentialBackoff ¶
func ExponentialBackoff( attempt int, initial time.Duration, maxDuration time.Duration, multiplier float64, ) time.Duration
ExponentialBackoff calculates exponential backoff duration
func IsDebugEnabled ¶
func IsDebugEnabled() bool
IsDebugEnabled returns the current debug logging state
func IsRetryable ¶
IsRetryable returns true if the error is potentially retryable
func IsValidNDEFMessage ¶
IsValidNDEFMessage checks if data contains a valid NDEF message
func IsValidNDEFPayload ¶
IsValidNDEFPayload checks if payload is a valid NDEF structure
func Retry ¶
func Retry(ctx context.Context, fn RetryableFunc) error
Retry executes a function with default retry configuration
func RetryWithConfig ¶
func RetryWithConfig(ctx context.Context, config *RetryConfig, retryFunc RetryableFunc) error
RetryWithConfig executes a function with retry logic
func SetDebugEnabled ¶
func SetDebugEnabled(enabled bool)
SetDebugEnabled allows programmatic control of debug logging Useful for testing or application-controlled debug modes
func ValidateNDEFMessage ¶
ValidateNDEFMessage validates a complete NDEF message including TLV wrapper
func ValidateNDEFPayload ¶
ValidateNDEFPayload validates just the NDEF payload without TLV wrapper
Types ¶
type AccessControlConfig ¶
type AccessControlConfig struct {
Protection bool // false = write protection, true = read/write protection
ConfigLock bool // lock configuration pages
AuthFailureLimit uint8 // limit failed authentication attempts (0 = disabled, 1-7 = limit)
}
AccessControlConfig holds the access control settings for NTAG tags
type AutoPollResult ¶
type AutoPollResult struct {
TargetData []byte
Type AutoPollTarget
}
AutoPollResult contains the result of an InAutoPoll operation.
func (*AutoPollResult) ToDetectedTag ¶
func (a *AutoPollResult) ToDetectedTag() *DetectedTag
ToDetectedTag converts an AutoPollResult to a DetectedTag with proper configuration for InAutoPoll results. This method automatically sets FromInAutoPoll=true and handles UID extraction and tag type mapping.
type AutoPollTarget ¶
type AutoPollTarget byte
AutoPollTarget defines the target type for InAutoPoll.
const ( // AutoPollGeneric106kbps is the generic passive mode for ISO14443-4A, Mifare, DEP. AutoPollGeneric106kbps AutoPollTarget = 0x00 // AutoPollGeneric212kbps is the generic passive mode for FeliCa, DEP. AutoPollGeneric212kbps AutoPollTarget = 0x01 // AutoPollGeneric424kbps is the generic passive mode for FeliCa, DEP. AutoPollGeneric424kbps AutoPollTarget = 0x02 // AutoPollISO14443B is for ISO14443-4B specific passive mode. AutoPollISO14443B AutoPollTarget = 0x03 // AutoPollJewel is for Innovision Jewel tags. AutoPollJewel AutoPollTarget = 0x04 // AutoPollMifare is for Mifare tags. AutoPollMifare AutoPollTarget = 0x10 // AutoPollFeliCa212 is for FeliCa at 212 kbps. AutoPollFeliCa212 AutoPollTarget = 0x11 // AutoPollFeliCa424 is for FeliCa at 424 kbps. AutoPollFeliCa424 AutoPollTarget = 0x12 // AutoPollISO14443A is for ISO14443-4A. AutoPollISO14443A AutoPollTarget = 0x20 // AutoPollISO14443B4 is for ISO14443-4B. AutoPollISO14443B4 AutoPollTarget = 0x23 )
type BaseTag ¶
type BaseTag struct {
// contains filtered or unexported fields
}
BaseTag provides common tag functionality
func (*BaseTag) DebugInfoWithNDEF ¶
func (t *BaseTag) DebugInfoWithNDEF(ndefReader interface{ ReadNDEF() (*NDEFMessage, error) }) string
DebugInfoWithNDEF returns detailed debug information about the tag with NDEF support
func (*BaseTag) IsMIFARE4K ¶
IsMIFARE4K returns true if this is a MIFARE Classic 4K card
func (*BaseTag) ReadBlock ¶
ReadBlock provides a default implementation that returns an error Specific tag types should override this method
func (*BaseTag) ReadNDEF ¶
func (*BaseTag) ReadNDEF() (*NDEFMessage, error)
ReadNDEF provides a default implementation that returns an error Specific tag types should override this method
func (*BaseTag) ReadText ¶
ReadText reads the first text record from the tag's NDEF data This is a convenience method that handles the common case of reading simple text
func (*BaseTag) WriteBlock ¶
WriteBlock provides a default implementation that returns an error Specific tag types should override this method
func (*BaseTag) WriteNDEF ¶
func (*BaseTag) WriteNDEF(_ *NDEFMessage) error
WriteNDEF provides a default implementation that returns an error Specific tag types should override this method
type ConnectOption ¶
type ConnectOption func(*connectConfig) error
ConnectOption represents a functional option for ConnectDevice
func WithAutoDetection ¶
func WithAutoDetection() ConnectOption
WithAutoDetection enables automatic device detection instead of using a specific path
func WithConnectTimeout ¶
func WithConnectTimeout(timeout time.Duration) ConnectOption
WithConnectTimeout sets the device connection timeout
func WithDeviceOptions ¶
func WithDeviceOptions(opts ...Option) ConnectOption
WithDeviceOptions adds device-level options
func WithTransportFactory ¶
func WithTransportFactory(factory TransportFactory) ConnectOption
WithTransportFactory sets the transport factory function
func WithTransportFromDeviceFactory ¶
func WithTransportFromDeviceFactory(factory TransportFromDeviceFactory) ConnectOption
WithTransportFromDeviceFactory sets the transport from device factory function
func WithValidation ¶
func WithValidation(config *ValidationConfig) ConnectOption
WithValidation enables validation with the given configuration
type ContinuousPollConfig ¶
type ContinuousPollConfig struct {
Strategy PollStrategy
TargetTypes []AutoPollTarget
RetryDelay time.Duration
MaxRetries int
PollCount byte
PollPeriod byte
RetryOnFailure bool
CompatibilityMode bool
}
ContinuousPollConfig contains configuration for continuous polling operations
func DefaultContinuousPollConfig ¶
func DefaultContinuousPollConfig() *ContinuousPollConfig
DefaultContinuousPollConfig returns a default continuous polling configuration
func (*ContinuousPollConfig) Clone ¶
func (c *ContinuousPollConfig) Clone() *ContinuousPollConfig
Clone creates a deep copy of the configuration
func (*ContinuousPollConfig) Validate ¶
func (c *ContinuousPollConfig) Validate() error
Validate checks if the configuration is valid
type DetectedTag ¶
type DetectedTag struct {
// 8-byte aligned fields first (largest to smallest)
DetectedAt time.Time // 24 bytes (time.Time contains wall, ext, loc)
UID string // 16 bytes (string header: pointer + length)
Type TagType // 16 bytes (string header: pointer + length)
UIDBytes []byte // 24 bytes (slice header: pointer + len + cap)
ATQ []byte // 24 bytes (slice header: pointer + len + cap)
TargetData []byte // 24 bytes (slice header: pointer + len + cap) - Full target response data (needed for FeliCa)
// 1-byte fields grouped together to minimize padding
SAK byte // 1 byte
TargetNumber byte // 1 byte
FromInAutoPoll bool // 1 byte - indicates this tag was detected via InAutoPoll (skip InSelect)
}
DetectedTag represents a tag that was detected by the reader Field ordering optimized for memory alignment to reduce struct size from 120 to 112 bytes
type Device ¶
type Device struct {
// contains filtered or unexported fields
}
Device represents a PN532 NFC reader device
Thread Safety: Device is NOT thread-safe. All methods must be called from a single goroutine or protected with external synchronization. The underlying transport may have its own concurrency limitations. For concurrent access, wrap the Device with a mutex or use separate Device instances with separate transports.
func ConnectDevice ¶
func ConnectDevice(path string, opts ...ConnectOption) (*Device, error)
func NewWithOptions ¶
NewWithOptions creates a new PN532 device with the given transport and options
func (*Device) CreateTag ¶
func (d *Device) CreateTag(detected *DetectedTag) (Tag, error)
CreateTag creates a Tag instance based on the detected tag
func (*Device) DetectTag ¶
func (d *Device) DetectTag() (*DetectedTag, error)
DetectTag detects a single tag in the field For multiple tag detection, use DetectTags()
func (*Device) DetectTagContext ¶
func (d *Device) DetectTagContext(ctx context.Context) (*DetectedTag, error)
DetectTagContext detects a single tag in the field with context support
func (*Device) DetectTags ¶
func (d *Device) DetectTags(maxTags, baudRate byte) ([]*DetectedTag, error)
DetectTags detects multiple tags in the field maxTags: maximum number of tags to detect (1-2) baudRate: baud rate and modulation type:
- 0x00: 106 kbps type A (ISO/IEC14443 Type A)
- 0x01: 212 kbps (FeliCa polling)
- 0x02: 424 kbps (FeliCa polling)
- 0x03: 106 kbps type B (ISO/IEC14443-3B)
- 0x04: 106 kbps Innovision Jewel tag
func (*Device) DetectTagsContext ¶
func (d *Device) DetectTagsContext(ctx context.Context, maxTags, baudRate byte) ([]*DetectedTag, error)
DetectTagsContext detects multiple tags in the field with context support Uses polling strategy system to choose between InAutoPoll and InListPassiveTarget
func (*Device) Diagnose ¶
func (d *Device) Diagnose(testNumber byte, data []byte) (*DiagnoseResult, error)
Diagnose performs a self-diagnosis test
func (*Device) DiagnoseContext ¶
func (d *Device) DiagnoseContext(ctx context.Context, testNumber byte, data []byte) (*DiagnoseResult, error)
DiagnoseContext performs a self-diagnosis test with context support
func (*Device) GetCurrentPollStrategy ¶
func (d *Device) GetCurrentPollStrategy() PollStrategy
GetCurrentPollStrategy returns the currently active polling strategy
func (*Device) GetFirmwareVersion ¶
func (d *Device) GetFirmwareVersion() (*FirmwareVersion, error)
GetFirmwareVersion returns the PN532 firmware version
func (*Device) GetFirmwareVersionContext ¶
func (d *Device) GetFirmwareVersionContext(ctx context.Context) (*FirmwareVersion, error)
GetFirmwareVersionContext returns the PN532 firmware version with context support
func (*Device) GetGeneralStatus ¶
func (d *Device) GetGeneralStatus() (*GeneralStatus, error)
GetGeneralStatus returns the PN532 general status
func (*Device) GetGeneralStatusContext ¶
func (d *Device) GetGeneralStatusContext(ctx context.Context) (*GeneralStatus, error)
GetGeneralStatusContext returns the PN532 general status with context support
func (*Device) GetPollConfig ¶
func (d *Device) GetPollConfig() *ContinuousPollConfig
GetPollConfig returns the current polling configuration
func (*Device) InAutoPoll ¶
func (d *Device) InAutoPoll(pollCount, pollPeriod byte, targetTypes []AutoPollTarget) ([]AutoPollResult, error)
InAutoPoll polls for targets of specified types pollCount: number of polling cycles (0xFF for endless) pollPeriod: polling period in units of 150ms (1-15) targetTypes: types of targets to poll for Based on PN532 manual section 7.3.13
func (*Device) InAutoPollContext ¶
func (d *Device) InAutoPollContext( ctx context.Context, pollCount, pollPeriod byte, targetTypes []AutoPollTarget, ) ([]AutoPollResult, error)
InAutoPollContext polls for targets with context support
func (*Device) InListPassiveTargetContext ¶
func (d *Device) InListPassiveTargetContext(ctx context.Context, maxTg, brTy byte) ([]*DetectedTag, error)
InListPassiveTargetContext detects passive targets using InListPassiveTarget command
func (*Device) InRelease ¶
InRelease releases the selected target(s) targetNumber: logical number of the target to release (0x00 for all targets) Based on PN532 manual section 7.3.11
func (*Device) InReleaseContext ¶
InReleaseContext releases the selected target(s) with context support
func (*Device) InSelect ¶
InSelect selects the specified target targetNumber: logical number of the target to select Based on PN532 manual section 7.3.12
func (*Device) InSelectContext ¶
InSelectContext selects the specified target with context support
func (*Device) InitContext ¶
InitContext initializes the PN532 device with context support
func (*Device) InitiatorListPassiveTargets ¶
func (d *Device) InitiatorListPassiveTargets(maxTags int, tagType TagType, uid []byte) ([]*DetectedTag, error)
InitiatorListPassiveTargets detects passive targets with optional filtering This is a compatibility method for the PN532 InListPassiveTarget command
func (*Device) IsAutoPollSupported ¶
IsAutoPollSupported returns true if the transport supports native InAutoPoll
func (*Device) PollForTag ¶
PollForTag continuously polls for a tag until one is detected or context is cancelled Returns nil, nil if context is cancelled before a tag is detected
func (*Device) PowerDown ¶
PowerDown puts the PN532 into power down mode to save power consumption wakeupEnable: Wake-up enable parameters (bit field):
- bit 0: Enable wake-up by HSU (High Speed UART)
- bit 1: Enable wake-up by SPI
- bit 2: Enable wake-up by I2C
- bit 3: Enable wake-up by GPIO (P32)
- bit 4: Enable wake-up by GPIO (P34)
- bit 5: Enable wake-up by RF field
- bit 6: Reserved
- bit 7: Enable wake-up by GPIO (P72/INT1)
irqEnable: if 0x01, generates an IRQ when waking up Based on PN532 manual section 7.2.11
func (*Device) PowerDownContext ¶
PowerDownContext puts the PN532 into power down mode with context support
func (*Device) SAMConfiguration ¶
SAMConfiguration configures the SAM with advanced modes mode: Configuration mode (Normal, VirtualCard, WiredCard, DualCard) timeout: Timeout value (0x00-0xFF) - time to wait for tag irq: IRQ settings (0x00 = no IRQ, 0x01 = IRQ enabled) Based on PN532 manual section 7.2.10
func (*Device) SAMConfigurationContext ¶
func (d *Device) SAMConfigurationContext(ctx context.Context, mode SAMMode, timeout, irq byte) error
SAMConfigurationContext configures the SAM with context support
func (*Device) SendDataExchange ¶
SendDataExchange sends a data exchange command to the selected tag
func (*Device) SendDataExchangeContext ¶
SendDataExchangeContext sends a data exchange command with context support
func (*Device) SendRawCommand ¶
SendRawCommand sends a raw command to the selected tag using InCommunicateThru This is used for commands that don't work with InDataExchange (like GET_VERSION)
func (*Device) SendRawCommandContext ¶
SendRawCommandContext sends a raw command with context support
func (*Device) SetPollConfig ¶
func (d *Device) SetPollConfig(config *ContinuousPollConfig) error
SetPollConfig sets the continuous polling configuration
func (*Device) SetRetryConfig ¶
func (d *Device) SetRetryConfig(config *RetryConfig)
SetRetryConfig updates the retry configuration
func (*Device) SetTimeout ¶
SetTimeout sets the default timeout for operations
func (*Device) WaitForTag ¶
func (d *Device) WaitForTag(ctx context.Context) (*DetectedTag, error)
type DeviceConfig ¶
type DeviceConfig struct {
// RetryConfig configures retry behavior for transport operations
RetryConfig *RetryConfig
// Timeout is the default timeout for operations
Timeout time.Duration
}
DeviceConfig contains configuration options for the Device
func DefaultDeviceConfig ¶
func DefaultDeviceConfig() *DeviceConfig
DefaultDeviceConfig returns default device configuration
type DiagnoseResult ¶
DiagnoseResult contains the result of a diagnose test
type FeliCaTag ¶
type FeliCaTag struct {
BaseTag
// contains filtered or unexported fields
}
FeliCaTag represents a FeliCa NFC tag implementing the Tag interface Field ordering optimized for memory alignment to reduce struct size from 96 to 80 bytes
func NewFeliCaTag ¶
NewFeliCaTag creates a new FeliCa tag instance from polling response data targetData should contain the FeliCa polling response (POL_RES)
func (*FeliCaTag) GetServiceCode ¶
GetServiceCode returns the current service code
func (*FeliCaTag) GetSystemCode ¶
GetSystemCode returns the current system code
func (*FeliCaTag) Polling ¶
Polling performs a FeliCa polling operation to detect and initialize the tag This is a FeliCa-specific operation for card detection and system code discovery
func (*FeliCaTag) ReadBlock ¶
ReadBlock reads a single block from the FeliCa tag For FeliCa, block numbers are 16-bit, but we use uint8 for interface compatibility TODO: Consider extending interface for 16-bit block addressing
func (*FeliCaTag) ReadBlockExtended ¶
ReadBlockExtended reads a single block using 16-bit block addressing
func (*FeliCaTag) ReadNDEF ¶
func (f *FeliCaTag) ReadNDEF() (*NDEFMessage, error)
ReadNDEF reads NDEF data from the FeliCa tag Uses system code 0x12FC and service code 0x000B for NFC Forum Type 3 compliance
func (*FeliCaTag) RequestService ¶
RequestService requests service information from the FeliCa tag This is used to check if specific service codes are available
func (*FeliCaTag) SetServiceCode ¶
SetServiceCode sets the service code for operations
func (*FeliCaTag) SetSystemCode ¶
SetSystemCode sets the system code for operations
func (*FeliCaTag) WriteBlock ¶
WriteBlock writes a single block to the FeliCa tag For FeliCa, block numbers are 16-bit, but we use uint8 for interface compatibility
func (*FeliCaTag) WriteBlockExtended ¶
WriteBlockExtended writes a single block using 16-bit block addressing
func (*FeliCaTag) WriteNDEF ¶
func (f *FeliCaTag) WriteNDEF(message *NDEFMessage) error
WriteNDEF writes NDEF data to the FeliCa tag Uses system code 0x12FC and service code 0x0009 for NFC Forum Type 3 compliance
type FirmwareVersion ¶
type FirmwareVersion struct {
Version string
SupportIso14443a bool
SupportIso14443b bool
SupportIso18092 bool
}
FirmwareVersion contains PN532 firmware information
type GeneralStatus ¶
GeneralStatus contains PN532 general status information
type MIFARETag ¶
type MIFARETag struct {
BaseTag
// contains filtered or unexported fields
}
MIFARETag represents a MIFARE Classic tag
func NewMIFARETag ¶
NewMIFARETag creates a new MIFARE tag instance
func (*MIFARETag) AnalyzeLastError ¶
AnalyzeLastError provides detailed error analysis based on research findings
func (*MIFARETag) Authenticate ¶
Authenticate authenticates a sector on the MIFARE tag
func (*MIFARETag) AuthenticateRobust ¶
AuthenticateRobust performs robust authentication with retry logic and Chinese clone support This is the recommended method for authenticating with unreliable tags
func (*MIFARETag) GetTimingVariance ¶
GetTimingVariance returns the timing variance for hardware issue detection
func (*MIFARETag) IsTimingUnstable ¶
IsTimingUnstable checks if timing variance indicates hardware issues
func (*MIFARETag) ReadBlockAuto ¶
ReadBlockAuto reads a block with automatic authentication using the key provider
func (*MIFARETag) ReadBlockDirect ¶
ReadBlockDirect reads a block directly without authentication (for clone tags)
func (*MIFARETag) ReadNDEF ¶
func (t *MIFARETag) ReadNDEF() (*NDEFMessage, error)
ReadNDEF reads NDEF data from the MIFARE tag using bulk sector reads
func (*MIFARETag) ResetAuthState ¶
ResetAuthState resets the PN532's internal authentication state This can help when previous failed authentication attempts have polluted the state
func (*MIFARETag) WriteBlock ¶
WriteBlock writes a block to the MIFARE tag
func (*MIFARETag) WriteBlockAuto ¶
WriteBlockAuto writes a block with automatic authentication using the key provider
func (*MIFARETag) WriteBlockDirect ¶
WriteBlockDirect writes a block directly without authentication (for clone tags)
func (*MIFARETag) WriteNDEF ¶
func (t *MIFARETag) WriteNDEF(message *NDEFMessage) error
WriteNDEF writes NDEF data to the MIFARE tag
type NDEFMessage ¶
type NDEFMessage struct {
Records []NDEFRecord
}
NDEFMessage represents an NDEF message
func ParseNDEFData ¶
func ParseNDEFData(data []byte) (*NDEFMessage, error)
ParseNDEFData parses raw NDEF data into an NDEFMessage
func ParseNDEFMessage ¶
func ParseNDEFMessage(data []byte) (*NDEFMessage, error)
ParseNDEFMessage parses a complete NDEF message using go-ndef
type NDEFRecord ¶
type NDEFRecord struct {
WiFi *WiFiCredential
VCard *VCardContact
Text string
URI string
Type NDEFRecordType
Payload []byte
}
NDEFRecord represents a single NDEF record
type NDEFRecordType ¶
type NDEFRecordType string
NDEFRecordType represents the type of an NDEF record
const ( // NDEFTypeText represents a text record type NDEFTypeText NDEFRecordType = "text" // NDEFTypeURI represents a URI record type NDEFTypeURI NDEFRecordType = "uri" // NDEFTypeSmartPoster represents a smart poster record type NDEFTypeSmartPoster NDEFRecordType = "smartposter" )
const ( // NDEFTypeWiFi represents a WiFi credential record NDEFTypeWiFi NDEFRecordType = "wifi" // NDEFTypeVCard represents a vCard contact record NDEFTypeVCard NDEFRecordType = "vcard" // NDEFTypeBluetooth represents a Bluetooth pairing record NDEFTypeBluetooth NDEFRecordType = "bluetooth" )
Extended NDEF record types
type NTAGTag ¶
type NTAGTag struct {
BaseTag
// contains filtered or unexported fields
}
NTAGTag represents an NTAG21X tag
func NewNTAGTag ¶
NewNTAGTag creates a new NTAG tag instance
func (*NTAGTag) DetectType ¶
DetectType attempts to detect the NTAG variant using GET_VERSION command with fallback
func (*NTAGTag) DisablePasswordProtection ¶
DisablePasswordProtection disables password protection by setting AUTH0 to 0xFF
func (*NTAGTag) FastRead ¶
FastRead performs a fast read operation on NTAG tags It reads multiple blocks from startAddr to endAddr (inclusive)
func (*NTAGTag) GetConfigPage ¶
GetConfigPage returns the configuration page address for the tag type
func (*NTAGTag) GetPasswordPage ¶
GetPasswordPage returns the password page address for the tag type
func (*NTAGTag) GetTotalPages ¶
GetTotalPages returns the total number of pages for the tag type
func (*NTAGTag) GetUserMemoryRange ¶
GetUserMemoryRange returns the start and end pages for user memory based on tag type.
func (*NTAGTag) GetVersion ¶
func (t *NTAGTag) GetVersion() (*NTAGVersion, error)
GetVersion retrieves version information from the NTAG tag using proper GET_VERSION command This implementation uses SendRawCommand (like FastRead) for better compatibility across PN532 variants
func (*NTAGTag) LockPage ¶
LockPage permanently locks a page from writing (irreversible!) This uses the static lock bytes for pages 0-15 or dynamic lock bytes for higher pages
func (*NTAGTag) PwdAuth ¶
PwdAuth performs password authentication on the NTAG tag password must be exactly 4 bytes (32-bit) Returns the 2-byte PACK (Password ACKnowledge) on success
func (*NTAGTag) ReadNDEF ¶
func (t *NTAGTag) ReadNDEF() (*NDEFMessage, error)
ReadNDEF reads NDEF data from the NTAG tag using FastRead for optimal performance
func (*NTAGTag) SetAccessControl ¶
func (t *NTAGTag) SetAccessControl(config AccessControlConfig) error
SetAccessControl configures the access control settings
func (*NTAGTag) SetPasswordProtection ¶
SetPasswordProtection enables password protection on the tag password must be exactly 4 bytes, pack must be exactly 2 bytes auth0 defines from which page password protection starts (0x00 = disable, 0xFF = only config area)
func (*NTAGTag) WriteBlock ¶
WriteBlock writes a block to the NTAG tag
func (*NTAGTag) WriteNDEF ¶
func (t *NTAGTag) WriteNDEF(message *NDEFMessage) error
WriteNDEF writes NDEF data to the NTAG tag
type NTAGVersion ¶
type NTAGVersion struct {
FixedHeader uint8 // Should be 0x00
VendorID uint8 // 0x04 = NXP Semiconductors
ProductType uint8 // 0x04 = NTAG
ProductSubtype uint8 // 0x02 = 50 pF
MajorVersion uint8 // Major product version
MinorVersion uint8 // Minor product version
StorageSize uint8 // Storage size (encoded)
ProtocolType uint8 // 0x03 = ISO/IEC 14443-3
}
NTAGVersion holds the version information from GET_VERSION command
func (*NTAGVersion) GetNTAGType ¶
func (v *NTAGVersion) GetNTAGType() NTAGType
GetNTAGType determines the NTAG variant from version information
func (*NTAGVersion) GetStorageSize ¶
func (v *NTAGVersion) GetStorageSize() int
GetStorageSize calculates the actual storage size from the encoded value
type OptimizedPollParams ¶
type OptimizedPollParams struct {
TargetTypes []AutoPollTarget
StabilizationDelay time.Duration
RetryDelay time.Duration
MaxRetries int
PollPeriod byte
}
OptimizedPollParams contains transport-optimized polling parameters
type Option ¶
Option is a functional option for configuring a Device
func WithMaxRetries ¶
WithMaxRetries sets the maximum number of retries for device operations
func WithRetryBackoff ¶
WithRetryBackoff sets the initial backoff duration for retries
func WithRetryConfig ¶
func WithRetryConfig(config *RetryConfig) Option
WithRetryConfig sets the retry configuration for the device
func WithTimeout ¶
WithTimeout sets the default timeout for device operations
type PollStrategy ¶
type PollStrategy string
PollStrategy represents the polling strategy to use for tag detection
const ( // PollStrategyAuto automatically selects the best polling strategy // based on transport capabilities and previous detection results PollStrategyAuto PollStrategy = "auto" // PollStrategyAutoPoll uses the PN532's InAutoPoll command for continuous polling // This is the preferred strategy for transports that support native InAutoPoll PollStrategyAutoPoll PollStrategy = "autopoll" // PollStrategyLegacy uses the traditional InListPassiveTarget approach // This is used as a fallback when InAutoPoll is not available or fails PollStrategyLegacy PollStrategy = "legacy" // PollStrategyManual disables automatic polling and requires explicit calls // This gives applications full control over when and how polling occurs PollStrategyManual PollStrategy = "manual" )
type RetryConfig ¶
type RetryConfig struct {
// MaxAttempts is the maximum number of attempts (0 = no retry)
MaxAttempts int
// InitialBackoff is the initial backoff duration
InitialBackoff time.Duration
// MaxBackoff is the maximum backoff duration
MaxBackoff time.Duration
// BackoffMultiplier is the factor by which the backoff increases
BackoffMultiplier float64
// Jitter adds randomness to backoff to avoid thundering herd
Jitter float64
// RetryTimeout is the overall timeout for all retry attempts
RetryTimeout time.Duration
}
RetryConfig configures retry behavior
func DefaultRetryConfig ¶
func DefaultRetryConfig() *RetryConfig
DefaultRetryConfig returns a default retry configuration
type RetryableFunc ¶
type RetryableFunc func() error
RetryableFunc is a function that can be retried
type SAMMode ¶
type SAMMode byte
SAMMode represents the SAM configuration mode
const ( // SAMModeNormal - normal mode (default) SAMModeNormal SAMMode = 0x01 // SAMModeVirtualCard - Virtual Card mode SAMModeVirtualCard SAMMode = 0x02 // SAMModeWiredCard - Wired Card mode SAMModeWiredCard SAMMode = 0x03 // SAMModeDualCard - Dual Card mode SAMModeDualCard SAMMode = 0x04 // SAMNormal is an alias for SAMModeNormal for backward compatibility SAMNormal = SAMModeNormal )
type Tag ¶
type Tag interface {
// Type returns the tag type
Type() TagType
// UID returns the tag's unique identifier as hex string
UID() string
// UIDBytes returns the tag's unique identifier as bytes
UIDBytes() []byte
// ReadBlock reads a block of data from the tag
ReadBlock(block uint8) ([]byte, error)
// WriteBlock writes a block of data to the tag
WriteBlock(block uint8, data []byte) error
// ReadNDEF reads NDEF data from the tag
ReadNDEF() (*NDEFMessage, error)
// WriteNDEF writes NDEF data to the tag
WriteNDEF(message *NDEFMessage) error
// ReadText reads the first text record from the tag's NDEF data
ReadText() (string, error)
// WriteText writes a simple text record to the tag
WriteText(text string) error
// DebugInfo returns detailed debug information about the tag
DebugInfo() string
// Summary returns a brief summary of the tag
Summary() string
}
Tag represents an NFC tag interface
type TagContext ¶
type TagContext interface {
Tag
// ReadBlockContext reads a block of data from the tag with context support
ReadBlockContext(ctx context.Context, block uint8) ([]byte, error)
// WriteBlockContext writes a block of data to the tag with context support
WriteBlockContext(ctx context.Context, block uint8, data []byte) error
// ReadNDEFContext reads NDEF data from the tag with context support
ReadNDEFContext(ctx context.Context) (*NDEFMessage, error)
// WriteNDEFContext writes NDEF data to the tag with context support
WriteNDEFContext(ctx context.Context, message *NDEFMessage) error
}
TagContext represents an NFC tag interface with context support
func AsTagContext ¶
func AsTagContext(tag Tag, device *Device) TagContext
AsTagContext converts a Tag to TagContext
type TagType ¶
type TagType string
TagType represents the type of NFC tag
const ( // TagTypeNTAG represents NTAG tag types. TagTypeNTAG TagType = "NTAG" // TagTypeMIFARE represents MIFARE tag types. TagTypeMIFARE TagType = "MIFARE" // TagTypeFeliCa represents FeliCa tag types. TagTypeFeliCa TagType = "FELICA" // TagTypeUnknown represents unknown tag types. TagTypeUnknown TagType = "UNKNOWN" // CardTypeAny represents any tag type (for detection) CardTypeAny TagType = "ANY" )
type Transport ¶
type Transport interface {
// SendCommand sends a command to the PN532 and waits for response
SendCommand(cmd byte, args []byte) ([]byte, error)
// Close closes the transport connection
Close() error
// SetTimeout sets the read timeout for the transport
SetTimeout(timeout time.Duration) error
// IsConnected returns true if the transport is connected
IsConnected() bool
// Type returns the transport type
Type() TransportType
}
Transport defines the interface for communication with PN532 devices. This can be implemented by UART, I2C, or SPI backends.
type TransportCapability ¶
type TransportCapability string
TransportCapability represents specific capabilities or behaviors of a transport
const ( // CapabilityRequiresInSelect indicates the transport requires explicit InSelect CapabilityRequiresInSelect TransportCapability = "requires_in_select" // CapabilityAutoPollNative indicates the transport supports native InAutoPoll // with full command set and reliable operation (e.g., UART, I2C, SPI) CapabilityAutoPollNative TransportCapability = "autopoll_native" )
type TransportCapabilityChecker ¶
type TransportCapabilityChecker interface {
// HasCapability returns true if the transport has the specified capability
HasCapability(capability TransportCapability) bool
}
TransportCapabilityChecker defines an interface for querying transport capabilities This provides a clean, type-safe alternative to reflection-based mode detection
type TransportContext ¶
type TransportContext interface {
Transport
// SendCommandContext sends a command to the PN532 with context support
SendCommandContext(ctx context.Context, cmd byte, args []byte) ([]byte, error)
}
TransportContext defines the interface for communication with PN532 devices with context support for cancellation and timeouts.
func AsTransportContext ¶
func AsTransportContext(t Transport) TransportContext
AsTransportContext converts a Transport to TransportContext
type TransportError ¶
type TransportError struct {
Err error // Underlying error
Op string // Operation that failed
Port string // Port or device identifier
Type ErrorType // Error category
Retryable bool // Whether the error is retryable
}
TransportError wraps transport-level errors with additional context
func NewChecksumMismatchError ¶
func NewChecksumMismatchError(op, port string) *TransportError
NewChecksumMismatchError creates a checksum mismatch error (transient)
func NewDataTooLargeError ¶
func NewDataTooLargeError(op, port string) *TransportError
NewDataTooLargeError creates a data too large error (permanent)
func NewFrameCorruptedError ¶
func NewFrameCorruptedError(op, port string) *TransportError
NewFrameCorruptedError creates a frame corruption error
func NewInvalidResponseError ¶
func NewInvalidResponseError(op, port string) *TransportError
NewInvalidResponseError creates an invalid response error (permanent)
func NewNACKReceivedError ¶
func NewNACKReceivedError(op, port string) *TransportError
NewNACKReceivedError creates a "NACK received" error (transient)
func NewNoACKError ¶
func NewNoACKError(op, port string) *TransportError
NewNoACKError creates a "no ACK received" error (timeout)
func NewTimeoutError ¶
func NewTimeoutError(op, port string) *TransportError
NewTimeoutError creates a timeout error for transport operations
func NewTransportError ¶
func NewTransportError(op, port string, err error, errType ErrorType) *TransportError
NewTransportError creates a standard transport error with consistent formatting
func NewTransportNotReadyError ¶
func NewTransportNotReadyError(op, port string) *TransportError
NewTransportNotReadyError creates a transport not ready error (timeout)
func NewTransportReadError ¶
func NewTransportReadError(op, port string) *TransportError
NewTransportReadError creates a read error (transient)
func NewTransportWriteError ¶
func NewTransportWriteError(op, port string) *TransportError
NewTransportWriteError creates a write error (transient)
func (*TransportError) Error ¶
func (e *TransportError) Error() string
func (*TransportError) Unwrap ¶
func (e *TransportError) Unwrap() error
type TransportFactory ¶
TransportFactory is a function type for creating transports
type TransportFromDeviceFactory ¶
type TransportFromDeviceFactory func(device detection.DeviceInfo) (Transport, error)
TransportFromDeviceFactory is a function type for creating transports from detected devices
type TransportOptimizer ¶
type TransportOptimizer interface {
// OptimizeForPolling returns transport-specific polling parameters
OptimizeForPolling(strategy PollStrategy) *OptimizedPollParams
// GetPreferredStrategy returns the preferred strategy for this transport
GetPreferredStrategy() PollStrategy
// GetStabilizationDelay returns the required stabilization delay
GetStabilizationDelay() time.Duration
}
TransportOptimizer provides transport-specific optimizations
type TransportType ¶
type TransportType string
TransportType represents the type of transport
const ( // TransportUART represents UART/serial transport. TransportUART TransportType = "uart" // TransportI2C represents I2C bus transport. TransportI2C TransportType = "i2c" // TransportSPI represents SPI bus transport. TransportSPI TransportType = "spi" // TransportMock represents a mock transport for testing TransportMock TransportType = "mock" )
type TransportWithRetry ¶
type TransportWithRetry struct {
// contains filtered or unexported fields
}
TransportWithRetry wraps a Transport with retry capabilities
func NewTransportWithRetry ¶
func NewTransportWithRetry(transport Transport, config *RetryConfig) *TransportWithRetry
NewTransportWithRetry creates a new transport wrapper with retry logic
func (*TransportWithRetry) Close ¶
func (t *TransportWithRetry) Close() error
Close closes the transport connection
func (*TransportWithRetry) HasCapability ¶
func (t *TransportWithRetry) HasCapability(capability TransportCapability) bool
HasCapability forwards capability checking to the underlying transport
func (*TransportWithRetry) IsConnected ¶
func (t *TransportWithRetry) IsConnected() bool
IsConnected returns true if the transport is connected
func (*TransportWithRetry) SendCommand ¶
func (t *TransportWithRetry) SendCommand(cmd byte, args []byte) ([]byte, error)
SendCommand sends a command with retry logic
func (*TransportWithRetry) SetRetryConfig ¶
func (t *TransportWithRetry) SetRetryConfig(config *RetryConfig)
SetRetryConfig updates the retry configuration
func (*TransportWithRetry) SetTimeout ¶
func (t *TransportWithRetry) SetTimeout(timeout time.Duration) error
SetTimeout sets the read timeout for the transport
func (*TransportWithRetry) Type ¶
func (t *TransportWithRetry) Type() TransportType
Type returns the transport type
type VCardContact ¶
type VCardContact struct {
Version string
FormattedName string
FirstName string
LastName string
Organization string
Title string
PhoneNumbers map[string]string // Type -> Number
EmailAddresses map[string]string // Type -> Email
Addresses map[string]Address
URL string
Note string
}
VCardContact represents contact information
func ParseVCardRecord ¶
func ParseVCardRecord(rec *ndef.Record) (*VCardContact, error)
ParseVCardRecord parses a vCard from an NDEF record
type ValidatedDevice ¶
type ValidatedDevice struct {
*Device
// contains filtered or unexported fields
}
ValidatedDevice wraps a Device with validation and reliability features
func NewValidatedDevice ¶
func NewValidatedDevice(transport Transport, config *ValidationConfig) (*ValidatedDevice, error)
NewValidatedDevice creates a new device with validation features
func (*ValidatedDevice) GetValidationMetrics ¶
func (vd *ValidatedDevice) GetValidationMetrics() ValidationMetrics
GetValidationMetrics returns current validation metrics (thread-safe)
func (*ValidatedDevice) ValidateInputSize ¶
func (vd *ValidatedDevice) ValidateInputSize(data []byte, operation string) error
ValidateInputSize performs comprehensive input size validation
type ValidatedMIFARETag ¶
type ValidatedMIFARETag struct {
*MIFARETag
// contains filtered or unexported fields
}
ValidatedMIFARETag wraps MIFARETag with validation
func NewValidatedMIFARETag ¶
func NewValidatedMIFARETag(tag *MIFARETag, config *ValidationConfig) *ValidatedMIFARETag
NewValidatedMIFARETag creates a validated MIFARE tag
func (*ValidatedMIFARETag) ReadBlockValidated ¶
func (t *ValidatedMIFARETag) ReadBlockValidated(block uint8) ([]byte, error)
ReadBlockValidated reads a block with optional verification for MIFARE
func (*ValidatedMIFARETag) ReadNDEFValidated ¶
func (t *ValidatedMIFARETag) ReadNDEFValidated() (*NDEFMessage, error)
ReadNDEFValidated reads NDEF with enhanced validation for MIFARE
func (*ValidatedMIFARETag) ReadTextValidated ¶
func (t *ValidatedMIFARETag) ReadTextValidated() (string, error)
ReadTextValidated reads text with validation
func (*ValidatedMIFARETag) WriteBlockValidated ¶
func (t *ValidatedMIFARETag) WriteBlockValidated(block uint8, data []byte) error
WriteBlockValidated writes a block with verification for MIFARE
func (*ValidatedMIFARETag) WriteNDEFValidated ¶
func (t *ValidatedMIFARETag) WriteNDEFValidated(message *NDEFMessage) error
WriteNDEFValidated writes NDEF with verification for MIFARE
func (*ValidatedMIFARETag) WriteTextValidated ¶
func (t *ValidatedMIFARETag) WriteTextValidated(text string) error
WriteTextValidated writes text with validation
type ValidatedNTAGTag ¶
type ValidatedNTAGTag struct {
*NTAGTag
// contains filtered or unexported fields
}
ValidatedNTAGTag wraps NTAGTag with validation
func NewValidatedNTAGTag ¶
func NewValidatedNTAGTag(tag *NTAGTag, config *ValidationConfig) *ValidatedNTAGTag
NewValidatedNTAGTag creates a validated NTAG tag
func (*ValidatedNTAGTag) ReadBlockValidated ¶
func (t *ValidatedNTAGTag) ReadBlockValidated(block uint8) ([]byte, error)
ReadBlockValidated reads a block with optional verification
func (*ValidatedNTAGTag) ReadNDEFValidated ¶
func (t *ValidatedNTAGTag) ReadNDEFValidated() (*NDEFMessage, error)
ReadNDEFValidated reads NDEF with enhanced validation
func (*ValidatedNTAGTag) ReadTextValidated ¶
func (t *ValidatedNTAGTag) ReadTextValidated() (string, error)
ReadTextValidated reads text with validation
func (*ValidatedNTAGTag) WriteBlockValidated ¶
func (t *ValidatedNTAGTag) WriteBlockValidated(block uint8, data []byte) error
WriteBlockValidated writes a block with verification
func (*ValidatedNTAGTag) WriteNDEFValidated ¶
func (t *ValidatedNTAGTag) WriteNDEFValidated(message *NDEFMessage) error
WriteNDEFValidated writes NDEF with verification
func (*ValidatedNTAGTag) WriteTextValidated ¶
func (t *ValidatedNTAGTag) WriteTextValidated(text string) error
WriteTextValidated writes text with validation
type ValidatedTag ¶
type ValidatedTag interface {
// ReadBlockValidated reads a block with optional verification
ReadBlockValidated(block uint8) ([]byte, error)
// WriteBlockValidated writes a block with verification
WriteBlockValidated(block uint8, data []byte) error
// ReadNDEFValidated reads NDEF with enhanced validation
ReadNDEFValidated() (*NDEFMessage, error)
// WriteNDEFValidated writes NDEF with verification
WriteNDEFValidated(message *NDEFMessage) error
}
ValidatedTag provides validation for tag operations
type ValidationConfig ¶
type ValidationConfig struct {
// RetryDelay specifies delay between retry attempts
RetryDelay time.Duration
// ReadRetries specifies max number of read retries on validation failure
ReadRetries int
// WriteRetries specifies max number of write retries on verification failure
WriteRetries int
// EnableReadVerification enables automatic verification of read data
EnableReadVerification bool
// EnableWriteVerification enables automatic write-after-verify
EnableWriteVerification bool
}
ValidationConfig holds configuration for data validation and reliability
func DefaultValidationConfig ¶
func DefaultValidationConfig() *ValidationConfig
DefaultValidationConfig returns default validation configuration
type ValidationMetrics ¶
type ValidationMetrics struct {
LastValidation time.Time
TotalOperations uint64
FailedValidations uint64
SecurityViolations uint64
}
ValidationMetrics tracks validation statistics
type ValidationResult ¶
ValidationResult represents the outcome of a validation operation
type WiFiCredential ¶
type WiFiCredential struct {
SSID string
NetworkKey string
MACAddress string // Optional
AuthType uint16
EncryptionType uint16
Hidden bool // Hidden SSID
}
WiFiCredential represents WiFi network credentials
func ParseWiFiRecord ¶
func ParseWiFiRecord(rec *ndef.Record) (*WiFiCredential, error)
ParseWiFiRecord parses a WiFi credential from an NDEF record
Source Files
¶
- autopoll.go
- commands.go
- communication.go
- debug.go
- detection.go
- device.go
- device_context.go
- doc.go
- errors.go
- felica.go
- firmware.go
- mifare.go
- ndef.go
- ndef_extended.go
- ndef_parser.go
- ndef_validation.go
- ntag.go
- options.go
- polling_strategy.go
- retry.go
- sam.go
- tag.go
- tag_context.go
- transport.go
- transport_capabilities.go
- transport_context.go
- validation.go
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
nfctest
command
|
|
|
readtag
command
|
|
|
internal
|
|
|
transport
Package transport provides internal transport utilities
|
Package transport provides internal transport utilities |
|
transport
|
|
|
i2c
Package i2c provides I2C transport implementation for PN532
|
Package i2c provides I2C transport implementation for PN532 |
|
spi
Package spi provides SPI transport implementation for PN532
|
Package spi provides SPI transport implementation for PN532 |