Documentation
¶
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 IsCommandNotSupported(err error) bool
- func IsDebugEnabled() bool
- func IsPN532AuthenticationError(err error) bool
- func IsPN532TimeoutError(err error) bool
- func IsRecoverable(err error) 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 (*BaseTag) WriteNDEFWithContext(_ context.Context, _ *NDEFMessage) error
- func (t *BaseTag) WriteText(text string) error
- type CommandRetryProfile
- type ConnectOption
- func WithAutoDetection() ConnectOption
- func WithConnectTimeout(timeout time.Duration) ConnectOption
- func WithConnectionRetries(maxAttempts int) ConnectOption
- func WithDeviceDetector(detector func(*detection.Options) ([]detection.DeviceInfo, error)) ConnectOption
- func WithDeviceOptions(opts ...Option) ConnectOption
- func WithTransportFactory(factory TransportFactory) ConnectOption
- func WithTransportFromDeviceFactory(factory TransportFromDeviceFactory) ConnectOption
- type DetectedTag
- type Device
- func (d *Device) ClearTransportState() error
- 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) 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) 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) InListPassiveTargetWithTimeoutContext(ctx context.Context, maxTg, brTy, mxRtyATR 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) 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) SetPassiveActivationRetries(maxRetries byte) error
- func (d *Device) SetPollingRetries(mxRtyATR byte) error
- func (d *Device) SetRetryConfig(config *RetryConfig)
- func (d *Device) SetTimeout(timeout time.Duration) error
- func (d *Device) SimplePoll(ctx context.Context, interval time.Duration) (*DetectedTag, 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) WriteNDEFWithContext(_ context.Context, message *NDEFMessage) error
- func (f *FeliCaTag) WriteText(text string) error
- type FirmwareVersion
- type GeneralStatus
- type IsRetryableFunc
- type MIFAREConfig
- type MIFARETag
- func (*MIFARETag) AnalyzeLastError(err error) string
- func (t *MIFARETag) Authenticate(sector uint8, keyType byte, key []byte) error
- func (t *MIFARETag) AuthenticateContext(ctx context.Context, sector uint8, keyType byte, key []byte) error
- func (t *MIFARETag) AuthenticateRobust(sector uint8, keyType byte, key []byte) error
- func (t *MIFARETag) AuthenticateRobustContext(ctx context.Context, sector uint8, keyType byte, key []byte) error
- func (t *MIFARETag) DebugInfo() string
- func (t *MIFARETag) FormatForNDEF() error
- func (t *MIFARETag) GetDevice() *Device
- func (t *MIFARETag) GetTimingVariance() time.Duration
- func (t *MIFARETag) IsNDEFFormatted() bool
- 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) ReadNDEFRobust() (*NDEFMessage, error)
- func (t *MIFARETag) ResetAuthState() error
- func (t *MIFARETag) SetConfig(config *MIFAREConfig)
- func (t *MIFARETag) SetRetryConfig(config *RetryConfig)
- func (t *MIFARETag) WriteBlock(block uint8, data []byte) error
- func (t *MIFARETag) WriteBlockAuto(block uint8, data []byte) error
- func (t *MIFARETag) WriteBlockAutoAlternative(block uint8, data []byte) error
- func (t *MIFARETag) WriteBlockDirect(block uint8, data []byte) error
- func (t *MIFARETag) WriteNDEF(message *NDEFMessage) error
- func (t *MIFARETag) WriteNDEFAlternative(message *NDEFMessage) error
- func (t *MIFARETag) WriteNDEFWithContext(ctx context.Context, message *NDEFMessage) error
- func (t *MIFARETag) WriteText(text string) error
- type MockTransport
- func (m *MockTransport) ClearError(cmd byte)
- func (m *MockTransport) Close() error
- func (m *MockTransport) GetCallCount(cmd byte) int
- func (m *MockTransport) IsConnected() bool
- func (m *MockTransport) Reset()
- func (m *MockTransport) SendCommand(cmd byte, _ []byte) ([]byte, error)
- func (m *MockTransport) SendCommandWithContext(ctx context.Context, cmd byte, _ []byte) ([]byte, error)
- func (m *MockTransport) SetDelay(delay time.Duration)
- func (m *MockTransport) SetError(cmd byte, err error)
- func (m *MockTransport) SetResponse(cmd byte, response []byte)
- func (m *MockTransport) SetTimeout(timeout time.Duration) error
- func (*MockTransport) Type() TransportType
- 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) ReadNDEFRobust() (*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) WriteNDEFWithContext(ctx context.Context, message *NDEFMessage) error
- func (t *NTAGTag) WriteText(text string) error
- type NTAGType
- type NTAGVersion
- type Option
- type PN532Error
- type ReadNDEFFunc
- type RetryConfig
- type RetryableFunc
- type SAMMode
- type Tag
- type TagType
- type Transport
- type TransportCapability
- type TransportCapabilityChecker
- 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 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) SendCommandWithContext(ctx context.Context, 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 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") ErrCommandNotSupported = errors.New("command not supported by device") // 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") ErrTagEmptyData = errors.New("tag detected but returned empty data") ErrTagDataCorrupt = errors.New("tag data appears corrupted") ErrTagUnreliable = errors.New("tag readings are inconsistent") // 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 IsCommandNotSupported ¶ added in v0.8.0
IsCommandNotSupported checks if an error indicates a command is not supported
func IsDebugEnabled ¶
func IsDebugEnabled() bool
IsDebugEnabled returns the current debug logging state
func IsPN532AuthenticationError ¶ added in v0.8.0
IsPN532AuthenticationError checks if an error is a PN532 authentication failure
func IsPN532TimeoutError ¶ added in v0.8.0
IsPN532TimeoutError checks if an error is a PN532 timeout
func IsRecoverable ¶ added in v0.8.0
IsRecoverable checks if an error indicates the device might be in a stuck state that could potentially be recovered with a soft reset sequence
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
func (*BaseTag) WriteNDEFWithContext ¶ added in v0.5.0
func (*BaseTag) WriteNDEFWithContext(_ context.Context, _ *NDEFMessage) error
WriteNDEFWithContext provides a default implementation that returns an error Specific tag types should override this method
type CommandRetryProfile ¶ added in v0.8.0
type CommandRetryProfile int
CommandRetryProfile defines retry behavior for different command types
const ( // ProfileDetection for commands that detect tags (higher retry count) ProfileDetection CommandRetryProfile = iota // ProfileDataExchange for data read/write operations ProfileDataExchange // ProfileStatus for status/info commands (quick retry) ProfileStatus // ProfileDefault for general commands ProfileDefault )
func GetCommandRetryProfile ¶ added in v0.8.0
func GetCommandRetryProfile(cmd byte) CommandRetryProfile
GetCommandRetryProfile determines the retry profile for a specific command
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 WithConnectionRetries ¶ added in v0.5.0
func WithConnectionRetries(maxAttempts int) ConnectOption
WithConnectionRetries sets the number of connection retry attempts
func WithDeviceDetector ¶ added in v0.5.0
func WithDeviceDetector(detector func(*detection.Options) ([]detection.DeviceInfo, error)) ConnectOption
WithDeviceDetector sets a custom device detector function for auto-detection
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
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) ClearTransportState ¶ added in v0.8.1
ClearTransportState clears corrupted transport state to prevent firmware lockup This is critical when switching between InCommunicateThru and InDataExchange operations after frame reception failures
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 with InListPassiveTarget as the preferred default
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) 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) 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) InListPassiveTargetWithTimeoutContext ¶ added in v0.4.0
func (d *Device) InListPassiveTargetWithTimeoutContext( ctx context.Context, maxTg, brTy, mxRtyATR byte, ) ([]*DetectedTag, error)
InListPassiveTargetWithTimeoutContext detects passive targets using InListPassiveTarget command with timeout support. The mxRtyATR parameter controls the maximum retry count for target detection: - 0x00: Try once, no retry - 0x01-0xFE: Retry count (each retry is ~150ms according to PN532 datasheet) - 0xFF: Retry infinitely (blocking mode - use with caution)
For continuous polling with card removal detection, use low values (0x01-0x10) to ensure the command returns quickly when no card is present.
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) 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) SetPassiveActivationRetries ¶ added in v0.8.0
SetPassiveActivationRetries configures the maximum number of retries for passive activation to prevent infinite waiting that can cause the PN532 to lock up. A finite number like 10 (0x0A) is recommended instead of 0xFF (infinite) to avoid stuck states requiring power cycling.
func (*Device) SetPollingRetries ¶ added in v0.8.0
SetPollingRetries configures the MxRtyATR parameter for passive target detection retries. This controls how many times the PN532 will retry detecting a passive target before giving up. Each retry is approximately 150ms according to the PN532 datasheet.
Parameters:
- mxRtyATR: Number of retries (0x00 = immediate, 0x01-0xFE = retry count, 0xFF = infinite)
Common values:
- 0x00: Immediate return (no retries)
- 0x10: ~2.4 seconds (16 retries)
- 0x20: ~4.8 seconds (32 retries)
- 0xFF: Infinite retries (use with caution)
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) SimplePoll ¶ added in v0.4.0
SimplePoll performs straightforward polling with InListPassiveTarget on a regular schedule This is a simplified alternative to WaitForTag that removes complex error handling and strategy selection, providing predictable poll-poll-poll behavior at regular intervals.
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
// MaxFastReadPages limits the number of pages in a single FastRead operation
// Set to 0 to use platform-specific defaults (16 pages on Windows UART, unlimited elsewhere)
// This helps avoid PN532 firmware lockups with large InCommunicateThru payloads
MaxFastReadPages int
}
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
func (*FeliCaTag) WriteNDEFWithContext ¶ added in v0.5.0
func (f *FeliCaTag) WriteNDEFWithContext(_ context.Context, message *NDEFMessage) error
WriteNDEFWithContext writes NDEF data to the FeliCa tag with context support
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 IsRetryableFunc ¶ added in v0.8.0
IsRetryableFunc defines a function that determines if an error is retryable
type MIFAREConfig ¶ added in v0.4.0
type MIFAREConfig struct {
RetryConfig *RetryConfig // Retry backoff configuration
HardwareDelay time.Duration // Hardware timing delays (reinitialization, tag processing)
}
MIFAREConfig holds all configurable timing parameters for MIFARE operations
func DefaultMIFAREConfig ¶ added in v0.4.0
func DefaultMIFAREConfig() *MIFAREConfig
DefaultMIFAREConfig returns production-safe MIFARE configuration These values are optimized based on real-world testing and provide a good balance between speed and reliability for most hardware setups.
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) AuthenticateContext ¶ added in v0.5.0
func (t *MIFARETag) AuthenticateContext(ctx context.Context, sector uint8, keyType byte, key []byte) error
AuthenticateContext performs authentication with context support
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) AuthenticateRobustContext ¶ added in v0.5.0
func (t *MIFARETag) AuthenticateRobustContext(ctx context.Context, sector uint8, keyType byte, key []byte) error
AuthenticateRobustContext performs robust authentication with context support
func (*MIFARETag) FormatForNDEF ¶ added in v0.7.0
FormatForNDEF formats a blank MIFARE Classic tag for NDEF data storage. This process takes approximately 2 seconds and sets up: - Sector 0 with MAD (MIFARE Application Directory) structure - Remaining sectors with NDEF keys and access control bits
The tag must be in factory state (using factory keys) before calling this method. After formatting, the tag will be ready for NDEF data storage using standard NDEF read/write operations.
Returns an error if formatting fails at any step.
func (*MIFARETag) GetTimingVariance ¶
GetTimingVariance returns the timing variance for hardware issue detection
func (*MIFARETag) IsNDEFFormatted ¶ added in v0.7.0
IsNDEFFormatted checks if the tag is NDEF formatted by attempting to authenticate with the MAD key on sector 0. This is a fast check that takes approximately 60ms compared to 550ms for a full NDEF read attempt on a blank tag.
Returns true if the tag appears to be NDEF formatted, false otherwise. This method checks sector 0 with the MAD key as per MIFARE Application Directory standards rather than sector 1 with the NDEF key.
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) ReadNDEFRobust ¶ added in v0.8.0
func (t *MIFARETag) ReadNDEFRobust() (*NDEFMessage, error)
ReadNDEFRobust reads NDEF data with retry logic to handle intermittent empty data issues This addresses the "empty valid tag" problem where tags are detected but return no data
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) SetConfig ¶ added in v0.4.0
func (t *MIFARETag) SetConfig(config *MIFAREConfig)
SetConfig allows runtime configuration of MIFARE behavior for testing
func (*MIFARETag) SetRetryConfig ¶ added in v0.4.0
func (t *MIFARETag) SetRetryConfig(config *RetryConfig)
SetRetryConfig allows runtime configuration of retry behavior for testing
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) WriteBlockAutoAlternative ¶ added in v0.7.0
WriteBlockAutoAlternative writes a block with automatic sector authentication. It handles authentication caching and tries both Key A and Key B as needed.
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
func (*MIFARETag) WriteNDEFAlternative ¶ added in v0.7.0
func (t *MIFARETag) WriteNDEFAlternative(message *NDEFMessage) error
WriteNDEFAlternative provides an optimized NDEF writing implementation for tags formatted with FormatForNDEF. This method skips some validation steps and uses pre-known sector layouts for improved performance.
WARNING: This method is optimized for specific use cases where performance is critical. It assumes the tag was formatted using FormatForNDEF and may not work correctly with tags formatted by other applications.
Use the standard WriteNDEF method for general compatibility.
func (*MIFARETag) WriteNDEFWithContext ¶ added in v0.5.0
func (t *MIFARETag) WriteNDEFWithContext(ctx context.Context, message *NDEFMessage) error
WriteNDEFWithContext writes NDEF data to the MIFARE tag with context support TODO: Add proper context cancellation checks throughout the operation
type MockTransport ¶ added in v0.4.0
type MockTransport struct {
// contains filtered or unexported fields
}
MockTransport provides a mock implementation of Transport for testing
func NewMockTransport ¶ added in v0.4.0
func NewMockTransport() *MockTransport
NewMockTransport creates a new mock transport
func (*MockTransport) ClearError ¶ added in v0.4.0
func (m *MockTransport) ClearError(cmd byte)
ClearError removes error injection for a command
func (*MockTransport) Close ¶ added in v0.4.0
func (m *MockTransport) Close() error
Close implements Transport interface
func (*MockTransport) GetCallCount ¶ added in v0.4.0
func (m *MockTransport) GetCallCount(cmd byte) int
GetCallCount returns how many times a command was called
func (*MockTransport) IsConnected ¶ added in v0.4.0
func (m *MockTransport) IsConnected() bool
IsConnected implements Transport interface
func (*MockTransport) Reset ¶ added in v0.4.0
func (m *MockTransport) Reset()
Reset clears all call counts and resets state
func (*MockTransport) SendCommand ¶ added in v0.4.0
func (m *MockTransport) SendCommand(cmd byte, _ []byte) ([]byte, error)
SendCommand implements Transport interface
func (*MockTransport) SendCommandWithContext ¶ added in v0.5.0
func (m *MockTransport) SendCommandWithContext(ctx context.Context, cmd byte, _ []byte) ([]byte, error)
SendCommandWithContext implements Transport interface with context support
func (*MockTransport) SetDelay ¶ added in v0.4.0
func (m *MockTransport) SetDelay(delay time.Duration)
SetDelay configures a delay to simulate hardware response time
func (*MockTransport) SetError ¶ added in v0.4.0
func (m *MockTransport) SetError(cmd byte, err error)
SetError configures an error to be returned for a specific command
func (*MockTransport) SetResponse ¶ added in v0.4.0
func (m *MockTransport) SetResponse(cmd byte, response []byte)
SetResponse configures a response for a specific command
func (*MockTransport) SetTimeout ¶ added in v0.4.0
func (m *MockTransport) SetTimeout(timeout time.Duration) error
SetTimeout implements Transport interface
func (*MockTransport) Type ¶ added in v0.4.0
func (*MockTransport) Type() TransportType
Type implements Transport interface
type NDEFMessage ¶
type NDEFMessage struct {
Records []NDEFRecord
}
NDEFMessage represents an NDEF message
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) ReadNDEFRobust ¶ added in v0.8.0
func (t *NTAGTag) ReadNDEFRobust() (*NDEFMessage, error)
ReadNDEFRobust reads NDEF data with retry logic to handle intermittent empty data issues This addresses the "empty valid tag" problem where tags are detected but return no data
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
func (*NTAGTag) WriteNDEFWithContext ¶ added in v0.5.0
func (t *NTAGTag) WriteNDEFWithContext(ctx context.Context, message *NDEFMessage) error
WriteNDEFWithContext writes NDEF data to the NTAG tag with context support
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 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 PN532Error ¶ added in v0.8.0
PN532Error wraps PN532 device errors with error code context
func NewPN532Error ¶ added in v0.8.0
func NewPN532Error(errorCode byte, command, context string) *PN532Error
NewPN532Error creates a PN532 error with the specified error code and context
func (*PN532Error) Error ¶ added in v0.8.0
func (e *PN532Error) Error() string
func (*PN532Error) IsAuthenticationError ¶ added in v0.8.0
func (e *PN532Error) IsAuthenticationError() bool
IsAuthenticationError returns true if the error is authentication-related
func (*PN532Error) IsCommandNotSupported ¶ added in v0.8.0
func (e *PN532Error) IsCommandNotSupported() bool
IsCommandNotSupported returns true if the error indicates the command is not supported
func (*PN532Error) IsTimeoutError ¶ added in v0.8.0
func (e *PN532Error) IsTimeoutError() bool
IsTimeoutError returns true if the error is timeout-related
type ReadNDEFFunc ¶ added in v0.8.0
type ReadNDEFFunc func() (*NDEFMessage, error)
ReadNDEFFunc defines a function that reads NDEF data from a tag
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
func GetRetryConfigForCommand ¶ added in v0.8.0
func GetRetryConfigForCommand(cmd byte) *RetryConfig
GetRetryConfigForCommand returns retry configuration optimized for specific command types
func GetRetryConfigForProfile ¶ added in v0.8.0
func GetRetryConfigForProfile(profile CommandRetryProfile) *RetryConfig
GetRetryConfigForProfile returns retry configuration for a specific profile
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
// WriteNDEFWithContext writes NDEF data to the tag with context support
WriteNDEFWithContext(ctx context.Context, 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 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" // TagTypeAny represents any tag type (for detection) TagTypeAny 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)
// SendCommandWithContext sends a command to the PN532 with context support
SendCommandWithContext(ctx context.Context, 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" // CapabilityUART indicates the transport uses UART communication // UART transport is prone to PN532 firmware lockups with large InCommunicateThru payloads CapabilityUART TransportCapability = "uart" )
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 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 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) SendCommandWithContext ¶ added in v0.5.0
func (t *TransportWithRetry) SendCommandWithContext(ctx context.Context, cmd byte, args []byte) ([]byte, error)
SendCommandWithContext sends a command with context support and 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 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
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
reader
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 |