nfc

package module
v2.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 9, 2024 License: LGPL-3.0 Imports: 7 Imported by: 0

Documentation

Overview

Package nfc wraps the libnfc to provide an API for Go. Most documentation was taken unchanged from the documentation inside the libnfc. Some functions and names have been altered to fit the conventions and idioms used in Go.

To use this package, obtain and install libnfc. By default, pkg-config is used to find and link libnfc. If you cannot use pkg-config, you can compile with build-tag nopkgconfig or no_pkgconfig to instead link with -lnfc.

Index

Constants

View Source
const (
	// Default command processing timeout
	// Property value's (duration) unit is ms and 0 means no timeout (infinite).
	// Default value is set by driver layer
	TimeoutCommand = iota

	// Timeout between ATR_REQ and ATR_RES
	// When the device is in initiator mode, a target is considered as mute
	// if no valid ATR_RES is received within this timeout value.
	// Default value for this property is 103 ms on PN53x based devices.
	TimeoutATR

	// Timeout value to give up reception from the target in case of no answer.
	// Default value for this property is 52 ms).
	TimeoutCom

	// Let the PN53X chip handle the CRC bytes. This means that the chip
	// appends the CRC bytes to the frames that are transmitted. It will
	// parse the last bytes from received frames as incoming CRC bytes. They
	// will be verified against the used modulation and protocol. If a frame
	// is expected with incorrect CRC bytes this option should be disabled.
	// Example frames where this is useful are the ATQA and UID+BCC that are
	// transmitted without CRC bytes during the anti-collision phase of the
	// ISO14443-A protocol.
	HandleCRC

	// Parity bits in the network layer of ISO14443-A are by default
	// generated and validated in the PN53X chip. This is a very convenient
	// feature. On certain times though it is useful to get full control of
	// the transmitted data. The proprietary MIFARE Classic protocol uses
	// for example custom (encrypted) parity bits. For interoperability it
	// is required to be completely compatible, including the arbitrary
	// parity bits. When this option is disabled, the functions to
	// communicating bits should be used.
	HandleParity

	// This option can be used to enable or disable the electronic field of
	// the NFC device.
	ActivateField

	// The internal CRYPTO1 co-processor can be used to transmit messages
	// encrypted. This option is automatically activated after a successful
	// MIFARE Classic authentication.
	ActivateCrypto1

	// The default configuration defines that the PN53X chip will try
	// indefinitely to invite a tag in the field to respond. This could be
	// desired when it is certain a tag will enter the field. On the other
	// hand, when this is uncertain, it will block the application. This
	// option could best be compared to the (NON)BLOCKING option used by
	// (socket)network programming.
	InfiniteSelect

	// If this option is enabled, frames that carry less than 4 bits are
	// allowed. According to the standards these frames should normally be
	// handles as invalid frames.
	AcceptInvalidFrames

	// If the NFC device should only listen to frames, it could be useful to
	// let it gather multiple frames in a sequence. They will be stored in
	// the internal FIFO of the PN53X chip. This could be retrieved by using
	// the receive data functions. Note that if the chip runs out of bytes
	// (FIFO = 64 bytes long), it will overwrite the first received frames,
	// so quick retrieving of the received data is desirable.
	AcceptMultipleFrames

	// This option can be used to enable or disable the auto-switching mode
	// to ISO14443-4 is device is compliant.
	// In initiator mode, it means that NFC chip will send RATS
	// automatically when select and it will automatically poll for
	// ISO14443-4 card when ISO14443A is requested.
	// In target mode, with a NFC chip compliant (ie. PN532), the chip will
	// emulate a 14443-4 PICC using hardware capability.
	AutoISO14443_4

	// Use automatic frames encapsulation and chaining.
	EasyFraming

	// Force the chip to switch in ISO14443-A
	ForceISO14443a

	// Force the chip to switch in ISO14443-B
	ForceISO14443b

	// Force the chip to run at 106 kbps
	ForceSpeed106
)

Properties for (*Device).SetPropertyInt() and (*Device).SetPropertyBool().

View Source
const (
	ISO14443a = iota + 1
	Jewel
	ISO14443b
	ISO14443bi   // pre-ISO14443B aka ISO/IEC 14443 B' or Type B'
	ISO14443b2sr // ISO14443-2B ST SRx
	ISO14443b2ct // ISO14443-2B ASK CTx
	Felica
	DEP
	Barcode         // Thinfilm NFC Barcode
	ISO14443biClass // HID iClass 14443B mode
)

NFC modulation types

View Source
const (
	Nbr106 = iota + 1
	Nbr212
	Nbr424
	Nbr847
)

NFC baud rates. UNDEFINED is also a valid baud rate, albeit defined further below.

View Source
const (
	TargetMode = iota
	InitiatorMode
)

NFC modes. An NFC device can either be a target or an initiator.

View Source
const (
	SUCCESS      = 0   // Success (no error)
	EIO          = -1  // Input / output error, device may not be usable anymore without re-open it
	EINVARG      = -2  // Invalid argument(s)
	EDEVNOTSUPP  = -3  // Operation not supported by device
	ENOTSUCHDEV  = -4  // No such device
	EOVFLOW      = -5  // Buffer overflow
	ETIMEOUT     = -6  // Operation timed out
	EOPABORTED   = -7  // Operation aborted (by user)
	ENOTIMPL     = -8  // Not (yet) implemented
	ETGRELEASED  = -10 // Target released
	ERFTRANS     = -20 // Error during RF transmission
	EMFCAUTHFAIL = -30 // MIFARE Classic: authentication failed
	ESOFT        = -80 // Software error (allocation, file/pipe creation, etc.)
	ECHIP        = -90 // Device's internal chip error
)

Error codes. Casted to Error, these yield all possible errors this package provides. Use nfc.Error(errorcode).Error() to get a descriptive string for an error code.

View Source
const (
	Undefined = iota
	Passive
	Active
)

NFC D.E.P. (Data Exchange Protocol) active/passive mode

View Source
const BufsizeConnstring = 1024

Maximum length for an NFC connection string

Variables

View Source
var BaudRates = [...]string{
	Undefined: "Undefined",
	Nbr106:    "106",
	Nbr212:    "212",
	Nbr424:    "424",
	Nbr847:    "847",
}

Baud rates corresponding to the baud rate enumeration constants

View Source
var ModulationTypes = [...]string{
	0:               "0",
	ISO14443a:       "ISO14443a",
	Jewel:           "Jewel",
	ISO14443b:       "ISO14443b",
	ISO14443bi:      "ISO14443bi",
	ISO14443b2sr:    "ISO14443b2sr",
	ISO14443b2ct:    "ISO14443b2ct",
	Felica:          "Felica",
	DEP:             "DEP",
	Barcode:         "Barcode",
	ISO14443biClass: "ISO14443biClass",
}

Names corresponding to the NFC modulation types

Functions

func AppendISO14443aCRC

func AppendISO14443aCRC(data []byte) []byte

Calculate an ISO 14443a CRC and append it to the supplied slice.

func AppendISO14443bCRC

func AppendISO14443bCRC(data []byte) []byte

Calculate an ISO 14443b CRC and append it to the supplied slice.

func ISO14443CascadeUID

func ISO14443CascadeUID(uid []byte) (cascadedUID []byte)

Add cascade tags (0x88) in UID. See ISO/IEC 14443-3 sec. 6.4.4.

func ISO14443aCRC

func ISO14443aCRC(data []byte) [2]byte

Calculate an ISO 14443a CRC. Code translated from the code in iso14443a_crc().

func ISO14443aLocateHistoricalBytes

func ISO14443aLocateHistoricalBytes(ats []byte) []byte

Locate historical bytes according to ISO/IEC 14443-4 sec. 5.2.7. Return nil if that fails.

func ISO14443bCRC

func ISO14443bCRC(data []byte) [2]byte

Calculate an ISO 14443b CRC. Code translated from the code in iso14443b_crc().

func ListDevices

func ListDevices() ([]string, error)

Scan for discoverable supported devices (ie. only available for some drivers. Returns a slice of strings that can be passed to Open() to open the devices found.

func TargetString

func TargetString(t Target, verbose bool) (string, error)

Make a string from a target with proper error reporting. This is a wrapper around str_nfc_target.

func Version

func Version() string

Get library version. This function returns the version of the libnfc wrapped by this package as returned by nfc_version().

Types

type BarcodeTarget

type BarcodeTarget struct {
	DataLen int
	Data    [32]byte
	Baud    int
}

Thinfilm NFC barcode tag information

func (*BarcodeTarget) Marshall

func (d *BarcodeTarget) Marshall() uintptr

Marshall() returns a pointer to an nfc_target allocated with C.malloc() that contains the same data as the Target. Don't forget to C.free() the result of Marshall() afterwards.

func (*BarcodeTarget) Modulation

func (t *BarcodeTarget) Modulation() Modulation

Type is always Barcode

func (*BarcodeTarget) String

func (t *BarcodeTarget) String() string

type DEPTarget

type DEPTarget struct {
	NFCID3  [10]byte // NFCID3
	DID     byte     // DID
	BS      byte     // supported send-bit rate
	BR      byte     // supported receive-bit rate
	TO      byte     // timeout value
	PP      byte     // PP parameters
	GB      [48]byte // general bytes
	GBLen   int      // length of the GB field
	DepMode int      // DEP mode
	Baud    int      // Baud rate
}

NFC target information in D.E.P. (Data Exchange Protocol) see ISO/IEC 18092 (NFCIP-1). DEPTarget mirrors nfc_dep_info.

func (*DEPTarget) Marshall

func (d *DEPTarget) Marshall() uintptr

Marshall() returns a pointer to an nfc_target allocated with C.malloc() that contains the same data as the Target. Don't forget to C.free() the result of Marshall() afterwards.

func (*DEPTarget) Modulation

func (t *DEPTarget) Modulation() Modulation

Type is always DEP

func (*DEPTarget) String

func (t *DEPTarget) String() string

type Device

type Device struct {
	// contains filtered or unexported fields
}

NFC device

func Open

func Open(conn string) (Device, error)

open a connection to an NFC device. If conn is "", the first available device will be used. If this operation fails, check the log on stderr for more details as the libnfc is not particulary verbose to us.

Depending on the desired operation mode, the device needs to be configured by using InitiatorInit() or TargetInit(), optionally followed by manual tuning of the parameters if the default parameters are not suiting your goals.

func (Device) AbortCommand

func (d Device) AbortCommand() error

Abort current running command. Some commands (ie. TargetInit()) are blocking functions and will return only in particular conditions (ie. external initiator request). This function attempt to abort the current running command.

func (Device) Close

func (d Device) Close() error

Close an NFC device.

func (Device) Connection

func (d Device) Connection() string

Returns the device's connection string. If the device has been closed before, this function returns the empty string.

func (Device) GoString

func (d Device) GoString() string

Return Go code that could be used to reproduce this device.

func (Device) Idle

func (d Device) Idle() error

Turn NFC device in idle mode. In initiator mode, the RF field is turned off and the device is set to low power mode (if avaible); In target mode, the emulation is stoped (no target available from external initiator) and the device is set to low power mode (if avaible).

func (Device) Information

func (d Device) Information() (string, error)

Print information about an NFC device.

func (Device) InitiatorDeselectTarget

func (d Device) InitiatorDeselectTarget() error

Deselect a selected passive or emulated tag. After selecting and communicating with a passive tag, this function could be used to deactivate and release the tag. This is very useful when there are multiple tags available in the field. It is possible to use the InitiatorSelectPassiveTarget() method to select the first available tag, test it for the available features and support, deselect it and skip to the next tag until the correct tag is found.

func (Device) InitiatorInit

func (d Device) InitiatorInit() error

Initialize NFC device as initiator (reader). After initialization it can be used to communicate to passive RFID tags and active NFC devices. The reader will act as initiator to communicate peer 2 peer (NFCIP) to other active NFC devices. The NFC device will be initialized with the following properties:

  • CRC is handled by the device (NP_HANDLE_CRC = true)
  • Parity is handled the device (NP_HANDLE_PARITY = true)
  • Cryto1 cipher is disabled (NP_ACTIVATE_CRYPTO1 = false)
  • Easy framing is enabled (NP_EASY_FRAMING = true)
  • Auto-switching in ISO14443-4 mode is enabled (NP_AUTO_ISO14443_4 = true)
  • Invalid frames are not accepted (NP_ACCEPT_INVALID_FRAMES = false)
  • Multiple frames are not accepted (NP_ACCEPT_MULTIPLE_FRAMES = false)
  • 14443-A mode is activated (NP_FORCE_ISO14443_A = true)
  • speed is set to 106 kbps (NP_FORCE_SPEED_106 = true)
  • Let the device try forever to find a target (NP_INFINITE_SELECT = true)
  • RF field is shortly dropped (if it was enabled) then activated again

func (Device) InitiatorInitSecureElement

func (d Device) InitiatorInitSecureElement() error

Initialize NFC device as initiator with its secure element initiator (reader). After initialization it can be used to communicate with the secure element. The RF field is deactivated in order to save power.

func (Device) InitiatorListPassiveTargets

func (d Device) InitiatorListPassiveTargets(m Modulation) ([]Target, error)

List passive or emulated tags. The NFC device will try to find the available passive tags. Some NFC devices are capable to emulate passive tags. The standards (ISO18092 and ECMA-340) describe the modulation that can be used for reader to passive communications. The chip needs to know with what kind of tag it is dealing with, therefore the initial modulation and speed (106, 212 or 424 kbps) should be supplied.

func (Device) InitiatorPollTarget

func (d Device) InitiatorPollTarget(modulations []Modulation, times int, period time.Duration) (n int, t Target, err error)

Poll for NFC targets. Returns polled target count or 0 and an error. modulations is a slice of all modulation types to poll for. times is the number of times we desire to poll (indefinite polling is not supported). period is the time to wait between polls. It is rounded up to the next 150 ms and must be between 150 ms and 2.25 s. If targets are found, one is selected and returned.

This function wraps nfc_initiator_poll_target but is extended to lack its limitation to 255 polls.

func (Device) InitiatorSelectPassiveTarget

func (d Device) InitiatorSelectPassiveTarget(m Modulation, initData []byte) (Target, error)

Select a passive or emulated tag. initData is used with different kind of data depending on modulation type:

  • for an ISO/IEC 14443 type A modulation, initData contains the UID you want to select;
  • for an ISO/IEC 14443 type B modulation, initData contains Application Family Identifier (AFI) (see ISO/IEC 14443-3) and optionally a second byte = 0x01 if you want to use probabilistic approach instead of timeslot approach;
  • for a FeliCa modulation, initData contains a 5-byte polling payload (see ISO/IEC 18092 11.2.2.5).
  • for ISO14443B', ASK CTx and ST SRx, see corresponding standards

if nil, default values adequate for the chosen modulation will be used.

func (Device) InitiatorTargetIsPresent

func (d Device) InitiatorTargetIsPresent(t Target) error

Check target presence. Returns nil on success, an error otherwise. The target has to be selected before you can check its presence. To run the test, one or more commands will be sent to the target. The t argument can be nil, in this case presence will be tested for the last selected tag.

func (Device) InitiatorTransceiveBits

func (d Device) InitiatorTransceiveBits(tx, txPar []byte, txLength uint, rx, rxPar []byte) (n int, err error)

Transceive raw bit-frame to a target. n contains the received byte count on success, or is meaningless on error. The current implementation will return the libnfc error code in case of error, but this is subject to change. If txLength is longer than the supplied slice, an error will occur. txPar has to have the same length as tx, dito for rxPar and rx. An error will occur if any of these invariants do not hold.

tx contains a byte slice of the frame that needs to be transmitted. txLength contains its length in bits.

For example the REQA (0x26) command (the first anti-collision command of ISO14443-A) must be precise 7 bits long. This is not possible using Device.InitiatorTransceiveBytes(). With that function you can only communicate frames that consist of full bytes. When you send a full byte (8 bits + 1 parity) with the value of REQA (0x26), a tag will simply not respond.

txPar contains a byte slice of the corresponding parity bits needed to send per byte.

For example if you send the SELECT_ALL (0x93, 0x20) = [ 10010011, 00100000 ] command, you have to supply the following parity bytes (0x01, 0x00) to define the correct odd parity bits. This is only an example to explain how it works, if you just are sending two bytes with ISO14443-A compliant parity bits you better can use the Device.InitiatorTransceiveBytes() method.

rx will contain the response from the target. This function will return EOVFLOW if more bytes are received than the length of rx. rxPar contains a byte slice of the corresponding parity bits.

The NFC device (configured as initiator) will transmit low-level messages where only the modulation is handled by the PN53x chip. Construction of the frame (data, CRC and parity) is completely done by libnfc. This can be very useful for testing purposes. Some protocols (e.g. MIFARE Classic) require to violate the ISO14443-A standard by sending incorrect parity and CRC bytes. Using this feature you are able to simulate these frames.

func (Device) InitiatorTransceiveBitsTimed

func (d Device) InitiatorTransceiveBitsTimed(tx, txPar []byte, txLength uint, rx, rxPar []byte, cycles uint32) (n int, c uint32, err error)

Transceive raw bit-frames to a target. n contains the received byte count on success, or is meaningless on error. c will contain the actual number of cycles waited. The current implementation will return the libnfc error code in case of error, but this is subject to change. If txLength is longer than the supplied slice, an error will occur. txPar has to have the same length as tx, dito for rxPar and rx. An error will occur if any of these invariants do not hold.

This function is similar to Device.InitiatorTransceiveBits() with the following differences:

  • A precise cycles counter will indicate the number of cycles between emission & reception of frames.
  • Only modes with EASY_FRAMING option disabled are supported and CRC must be handled manually.
  • Overall communication with the host is heavier and slower.

By default the timer configuration tries to maximize the precision, which also limits the maximum cycle count before saturation / timeout. E.g. with PN53x it can count up to 65535 cycles, avout 4.8ms with a precision of about 73ns. If you're ok with the defaults, call this function with cycles = 0. If you need to count more cycles, set cycles to the maximum you exprect, but don't forget you'll loose in precision and it'll take more time before timeout, so don't abuse!

Warning: The configuration option EASY_FRAMING must be set to false; the configuration option HANDLE_CRC must be set to false; the configuration option HANDLE_PARITY must be set to true (the default value).

func (Device) InitiatorTransceiveBytes

func (d Device) InitiatorTransceiveBytes(tx, rx []byte, timeout int) (n int, err error)

Send data to target then retrieve data from target. n contains received bytes count on success, or is meaningless on error. The current implementation will return the libnfc error code in case of error, but this is subject to change. This function will return EOVFLOW if more bytes are being received than the length of rx.

The NFC device (configured as initiator) will transmit the supplied bytes (tx) to the target. It waits for the response and stores the received bytes in rx. If the received bytes exceed rx, the error status will be NFC_EOVFLOW and rx will contain len(rx) received bytes.

If EASY_FRAMING option is disabled the frames will sent and received in raw mode: PN53x will not handle input neither output data.

The parity bits are handled by the PN53x chip. The CRC can be generated automatically or handled manually. Using this function, frames can be communicated very fast via the NFC initiator to the tag.

Tests show that on average this way of communicating is much faster than using the regular driver/middle-ware (often supplied by manufacturers).

Warning: The configuration option HANDLE_PARITY must be set to true (the default value).

If timeout equals to 0, the function blocks indefinitely (until an error is raised or function is completed). If timeout equals to -1, the default timeout will be used.

func (Device) InitiatorTransceiveBytesTimed

func (d Device) InitiatorTransceiveBytesTimed(tx, rx []byte, cycles uint32) (n int, c uint32, err error)

Send data to target then retrieve data from target with timing control. n contains the received byte count on success, or is meaningless on error. c will contain the actual number of cycles waited. The current implementation will return the libnfc error code in case of error, but this is subject to change. This function will return EOVFLOW if more bytes are being received than the length of rx.

This function is similar to Device.InitiatorTransceiveBytes() with the following differences:

  • A precise cycles counter will indicate the number of cycles between emission & reception of frames.
  • Only modes with EASY_FRAMING option disabled are supported.
  • Overall communication with the host is heavier and slower.

By default, the timer configuration tries to maximize the precision, which also limits the maximum cycle count before saturation / timeout. E.g. with PN53x it can count up to 65535 cycles, avout 4.8ms with a precision of about 73ns. If you're ok with the defaults, call this function with cycles = 0. If you need to count more cycles, set cycles to the maximum you exprect, but don't forget you'll loose in precision and it'll take more time before timeout, so don't abuse!

Warning: The configuration option EASY_FRAMING must be set to false; the configuration option HANDLE_PARITY must be set to true (default value).

func (Device) LastError

func (d Device) LastError() error

the error returned by the last operation on d. Every function that wraps some functions operating on an nfc_device should call this function and return the result. This wraps nfc_device_get_last_error.

func (Device) Pointer

func (d Device) Pointer() uintptr

Return a pointer to the wrapped nfc_device. This is useful if you try to use this wrapper to wrap other C code that builds onto the libnfc.

func (Device) SetPropertyBool

func (d Device) SetPropertyBool(property int, value bool) error

Set a device's boolean-property value. Returns nil on success, otherwise an error. See integer constants in this package for possible properties.

func (Device) SetPropertyInt

func (d Device) SetPropertyInt(property, value int) error

Set a device's integer-property value. Returns nil on success, otherwise an error. See integer constants in this package for possible properties.

func (Device) String

func (d Device) String() string

Returns the device's name. This information is not enough to uniquely determine the device.

func (Device) SupportedBaudRates

func (d Device) SupportedBaudRates(modulationType int) ([]int, error)

Get the suported baud rates for initiator mode. Returns either a slice of supported baud rates or an error. This function wraps nfc_device_get_supported_baud_rate().

func (Device) SupportedBaudRatesTargetMode

func (d Device) SupportedBaudRatesTargetMode(modulationType int) ([]int, error)

Get the suported baud rates for target mode. Returns either a slice of supported baud rates or an error. This function wraps nfc_device_get_supported_baud_rate_target_mode().

func (Device) SupportedModulations

func (d Device) SupportedModulations(mode int) ([]int, error)

Get supported modulations. Returns a slice of supported modulations or an error. Pass either TARGET or INITIATOR as mode. This function wraps nfc_device_get_supported_modulation()

func (Device) TargetInit

func (d Device) TargetInit(t Target, rx []byte, timeout int) (n int, tt Target, err error)

Initialize NFC device as an emulated tag. n contains the received byte count on success, or is meaningless on error. The current implementation will return the libnfc error code in case of error, but this is subject to change. The returned target tt will be the result of the modifications nfc_target_init() applies to t. Such modifications might happen if you set an Baud or DepMode to UNDEFINED. The fields will be updated with concrete values. timeout contains a timeout in milliseconds.

This function initializes NFC device in target mode in order to emulate a tag as the specified target t.

  • Crc is handled by the device (HANDLE_CRC = true)
  • Parity is handled the device (HANDLE_PARITY = true)
  • Cryto1 cipher is disabled (ACTIVATE_CRYPTO1 = false)
  • Auto-switching in ISO14443-4 mode is enabled (AUTO_ISO14443_4 = true)
  • Easy framing is disabled (EASY_FRAMING = false)
  • Invalid frames are not accepted (ACCEPT_INVALID_FRAMES = false)
  • Multiple frames are not accepted (ACCEPT_MULTIPLE_FRAMES = false)
  • RF field is dropped

Warning: Be aware that this function will wait (hang) until a command is received that is not part of the anti-collision. The RATS command for example would wake up the emulator. After this is received, the send and receive functions can be used.

If timeout equals to 0, the function blocks indefinitely (until an error is raised or function is completed). If timeout equals to -1, the default timeout will be used.

func (Device) TargetReceiveBytes

func (d Device) TargetReceiveBytes(rx []byte, timeout int) (n int, err error)

Receive bytes and APDU frames. n contains the received byte count on success, or is meaningless on error. The current implementation will return the libnfc error code in case of error, but this is subject to change. timeout contains a timeout in milliseconds.

This function retrieves bytes frames (e.g. ADPU) sent by the initiator to the NFC device (configured as target).

If timeout equals to 0, the function blocks indefinitely (until an error is raised or function is completed). If timeout equals to -1, the default timeout will be used.

func (Device) TargetSendBits

func (d Device) TargetSendBits(tx []byte, txPar []byte, txLength uint) (n int, err error)

Send raw bit-frames. Returns sent bits count on success, n contains the sent bit count on success, or is meaningless on error. The current implementation will return the libnfc error code in case of error, but this is subject to change. txPar has to have the same length as tx, an error will occur if this invariant does not hold.

tx contains a byte slice of the frame that needs to be transmitted. txLength contains its length in bits. txPar contains a byte slice of the corresponding parity bits needed to send per byte.

his function can be used to transmit (raw) bit-frames to the initiator using the specified NFC device (configured as target).

func (Device) TargetSendBytes

func (d Device) TargetSendBytes(tx []byte, timeout int) (n int, err error)

Send bytes and APDU frames. n contains the sent byte count on success, or is meaningless on error. The current implementation will return the libnfc error code in case of error, but this is subject to change. timeout contains a timeout in milliseconds.

This function make the NFC device (configured as target) send byte frames (e.g. APDU responses) to the initiator.

If timeout equals to 0, the function blocks indefinitely (until an error is raised or function is completed). If timeout equals to -1, the default timeout will be used.

func (Device) TargetTransceiveBits

func (d Device) TargetTransceiveBits(rx []byte, rxPar []byte, rxLength uint) (n int, err error)

Receive bit-frames. Returns received bits count on success, n contains the received bit count on success, or is meaningless on error. The current implementation will return the libnfc error code in case of error, but this is subject to change. rxPar has to have the same length as rx, an error will occur if this invariant does not hold.

rx contains a byte slice of the frame that you want to receive. rxLength contains its length in bits. rxPar contains a byte slice of the corresponding parity bits received per byte.

This function makes it possible to receive (raw) bit-frames. It returns all the messages that are stored in the FIFO buffer of the PN53x chip. It does not require to send any frame and thereby could be used to snoop frames that are transmitted by a nearby initiator. Check out the ACCEPT_MULTIPLE_FRAMES configuration option to avoid losing transmitted frames.

type Error

type Error int

An error as reported by various methods of Device. If device returns an error that is not castable to Error, something outside on the Go side went wrong.

func (Error) Error

func (e Error) Error() string

Returns the same strings as nfc_errstr except if the error is not among the known errors. Instead of reporting an "Unknown error", Error() will return something like "Error -123".

type FelicaTarget

type FelicaTarget struct {
	Len     uint
	ResCode byte
	ID      [8]byte
	Pad     [8]byte
	SysCode [2]byte
	Baud    int
}

NFC FeLiCa tag information

func (*FelicaTarget) Marshall

func (d *FelicaTarget) Marshall() uintptr

Marshall() returns a pointer to an nfc_target allocated with C.malloc() that contains the same data as the Target. Don't forget to C.free() the result of Marshall() afterwards.

func (*FelicaTarget) Modulation

func (t *FelicaTarget) Modulation() Modulation

Type is always FELICA

func (*FelicaTarget) String

func (t *FelicaTarget) String() string

type ISO14443aTarget

type ISO14443aTarget struct {
	Atqa   [2]byte
	Sak    byte
	UIDLen int // length of the Uid field
	UID    [10]byte
	AtsLen int // length of the ATS field
	// Maximal theoretical ATS is FSD-2, FSD=256 for FSDI=8 in RATS
	Ats  [254]byte // up to 254 bytes
	Baud int       // Baud rate
}

NFC ISO14443A tag (MIFARE) information. ISO14443aTarget mirrors nfc_iso14443a_info.

func (*ISO14443aTarget) Marshall

func (d *ISO14443aTarget) Marshall() uintptr

Marshall() returns a pointer to an nfc_target allocated with C.malloc() that contains the same data as the Target. Don't forget to C.free() the result of Marshall() afterwards. A runtime panic may occur if any slice referenced by a Target has been made larger than the maximum length mentioned in the respective comments.

func (*ISO14443aTarget) Modulation

func (t *ISO14443aTarget) Modulation() Modulation

Type is always ISO14443A

func (*ISO14443aTarget) String

func (t *ISO14443aTarget) String() string

type ISO14443b2ctTarget

type ISO14443b2ctTarget struct {
	UID      [4]byte
	ProdCode byte
	FabCode  byte
	Baud     int
}

NFC ISO14443-2B ASK CTx tag information

func (*ISO14443b2ctTarget) Marshall

func (d *ISO14443b2ctTarget) Marshall() uintptr

Marshall() returns a pointer to an nfc_target allocated with C.malloc() that contains the same data as the Target. Don't forget to C.free() the result of Marshall() afterwards.

func (*ISO14443b2ctTarget) Modulation

func (t *ISO14443b2ctTarget) Modulation() Modulation

Type is always ISO1444B2CT

func (*ISO14443b2ctTarget) String

func (t *ISO14443b2ctTarget) String() string

type ISO14443b2srTarget

type ISO14443b2srTarget struct {
	UID  [8]byte
	Baud int
}

NFC ISO14443-2B ST SRx tag information

func (*ISO14443b2srTarget) Marshall

func (d *ISO14443b2srTarget) Marshall() uintptr

Marshall() returns a pointer to an nfc_target allocated with C.malloc() that contains the same data as the Target. Don't forget to C.free() the result of Marshall() afterwards. A runtime panic may occur if any slice referenced by a Target has been made larger than the maximum length mentioned in the respective comments.

func (*ISO14443b2srTarget) Modulation

func (t *ISO14443b2srTarget) Modulation() Modulation

Type is always ISO14443B2SR

func (*ISO14443b2srTarget) String

func (t *ISO14443b2srTarget) String() string

type ISO14443bTarget

type ISO14443bTarget struct {
	Pupi            [4]byte // stores PUPI contained in ATQB (Answer To reQuest of type B)
	ApplicationData [4]byte // stores Application Data contained in ATQB
	ProtocolInfo    [3]byte // stores Protocol Info contained in ATQB
	CardIdentifier  byte    // store CID (Card Identifier) attributted by PCD to the PICC
	Baud            int
}

NFC ISO14443B tag information. See ISO14443-3 for more details.

func (*ISO14443bTarget) Marshall

func (d *ISO14443bTarget) Marshall() uintptr

Marshall() returns a pointer to an nfc_target allocated with C.malloc() that contains the same data as the Target. Don't forget to C.free() the result of Marshall() afterwards.

func (*ISO14443bTarget) Modulation

func (t *ISO14443bTarget) Modulation() Modulation

Type is always ISO14443B

func (*ISO14443bTarget) String

func (t *ISO14443bTarget) String() string

type ISO14443biClassTarget

type ISO14443biClassTarget struct {
	UID  [8]byte
	Baud int
}

NFC ISO14443BiClass, i.e. HID iClass (Picopass) tag information

func (*ISO14443biClassTarget) Marshall

func (d *ISO14443biClassTarget) Marshall() uintptr

Marshall() returns a pointer to an nfc_target allocated with C.malloc() that contains the same data as the Target. Don't forget to C.free() the result of Marshall() afterwards. A runtime panic may occur if any slice referenced by a Target has been made larger than the maximum length mentioned in the respective comments.

func (*ISO14443biClassTarget) Modulation

func (t *ISO14443biClassTarget) Modulation() Modulation

Type is always ISO14443biClass

func (*ISO14443biClassTarget) String

func (t *ISO14443biClassTarget) String() string

type ISO14443biTarget

type ISO14443biTarget struct {
	DIV    [4]byte  // 4 LSBytes of tag serial number
	VerLog byte     // Software version & type of REPGEN
	Config byte     // Config Byte, present if long REPGEN
	AtrLen int      // length of the Atr field
	Atr    [33]byte // ATR, if any. At most 33 bytes
	Baud   int
}

NFC ISO14443B' tag information

func (*ISO14443biTarget) Marshall

func (d *ISO14443biTarget) Marshall() uintptr

Marshall() returns a pointer to an nfc_target allocated with C.malloc() that contains the same data as the Target. Don't forget to C.free() the result of Marshall() afterwards.

func (*ISO14443biTarget) Modulation

func (t *ISO14443biTarget) Modulation() Modulation

Type is always ISO14443BI

func (*ISO14443biTarget) String

func (t *ISO14443biTarget) String() string

type JewelTarget

type JewelTarget struct {
	SensRes [2]byte
	ID      [4]byte
	Baud    int
}

NFC Jewel tag information

func (*JewelTarget) Marshall

func (d *JewelTarget) Marshall() uintptr

Marshall() returns a pointer to an nfc_target allocated with C.malloc() that contains the same data as the Target. Don't forget to C.free() the result of Marshall() afterwards.

func (*JewelTarget) Modulation

func (t *JewelTarget) Modulation() Modulation

Type is always Jewel

func (*JewelTarget) String

func (t *JewelTarget) String() string

type Modulation

type Modulation struct {
	Type     int
	BaudRate int
}

NFC modulation structure. Use the supplied constants.

func (Modulation) GoString added in v2.2.0

func (m Modulation) GoString() string

Print a modulation in Go syntax.

func (Modulation) String added in v2.2.0

func (m Modulation) String() string

Print a modulation in a human readable manner.

type Target

type Target interface {
	Modulation() Modulation
	Marshall() uintptr
	String() string // uses TargetString() with verbose = true
}

Go wrapper for nfc_target. Since the nfc_target structure contains a union, we cannot directly map it to a Go type. Modulation() can be used to figure out what kind of modulation was used for this Target and what type an interface can be casted into.

Marshall() returns a pointer to an nfc_target allocated with C.malloc() that contains the same data as the Target. Don't forget to C.free() the result of Marshall() afterwards.

func UnmarshallTarget

func UnmarshallTarget(ptr unsafe.Pointer) Target

Make a target from a pointer to an nfc_target. If the object you pass it not an nfc_target, undefined behavior occurs and your program is likely to blow up.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL