nfc.clf¶
-
class
nfc.clf.
ContactlessFrontend
(path=None)¶ Bases:
object
This class is the main interface for working with contactless devices. The
connect()
method provides easy access to the contactless functionality through automated discovery of remote cards and devices and activation of appropiate upper level protocols for further interaction. Thesense()
,listen()
andexchange()
methods provide a low-level interface for more specialized tasks.An instance of the
ContactlessFrontend
class manages a single contactless device locally connect through either USB, TTY or COM port. A special UDP port driver allows for emulation of a contactless device that connects through UDP to another emulated contactless device for test and development of higher layer functions.A locally connected contactless device can be opened by either supplying a path argument when an an instance of the contactless frontend class is created or by calling
open()
at a later time. In either case the path argument must be constructed as described inopen()
and the same exceptions may occur. The difference is thatopen()
returns False if a device could not be found whereas the initialization method raisesIOError
witherrno.ENODEV
.The methods of the
ContactlessFrontend
class are thread-safe.-
open
(path)¶ Open a contactless reader identified by the search path.
The
open()
method searches and then opens a contactless reader device for further communication. The path argument can be flexibly constructed to identify more or less precisely the device to open. A path that only partially identifies a device is completed by search. The first device that is found and successfully opened causesopen()
to return True. If no device is found return value is False. If a device was found but could not be opened thenopen()
returns False if path was partial or raiseIOError
if path was fully qualified. Typical I/O error reasons areerrno.EACCES
if the calling process has insufficient access rights orerrno.EBUSY
if the device is used by another process.A path is constructed as follows:
usb[:vendor[:product]]
with optional vendor and product as four digit hexadecimal numbers. For example,usb:054c:06c3
would open the first Sony RC-S380 reader whileusb:054c
would open the first Sony reader found on USB.usb[:bus[:device]]
with optional bus and device number as three-digit decimals. For example,usb:001:023
would open the device enumerated as number 23 on bus 1 whileusb:001
would open the first device found on bust 1. Note that a new device number is generated every time the device is plugged into USB. Bus and device numbers are shown bylsusb
.tty:port:driver
with mandatory port and driver name. This is for Posix systems to open the serial port/dev/tty<port>
and use the driver modulenfc/dev/<driver>.py
for access. For example,tty:USB0:arygon
would open/dev/ttyUSB0
and load the Arygon APPx/ADRx driver.com:port:driver
with mandatory port and driver name. This is for Windows systems to open the serial portCOM<port>
and use the driver modulenfc/dev/<driver>.py
for access.udp[:host][:port]
with optional host name or address and port number. This will emulate a communication channel over UDP/IP. The defaults for host and port arelocalhost:54321
.
-
close
()¶ Close the contacless reader device.
-
connect
(**options)¶ Connect with a Target or Initiator
The calling thread is blocked until a single activation and deactivation has completed or a callback function supplied as the keyword argument
terminate
returns a true value. The example below makesconnect()
return after 5 seconds, regardless of whether a peer device was connected or not.>>> import nfc, time >>> clf = nfc.ContactlessFrontend('usb') >>> after5s = lambda: time.time() - started > 5 >>> started = time.time(); clf.connect(llcp={}, terminate=after5s)
Connect options are given as keyword arguments with dictionary values. Possible options are:
rdwr={key: value, ...}
- options for reader/writerllcp={key: value, ...}
- options for peer to peercard={key: value, ...}
- options for card emulation
Reader/Writer Options
- ‘targets’ : iterable
- A list of bitrate and technology type strings that will
produce the
RemoteTarget
objects to discover. The default is('106A', '106B', '212F')
. - ‘on-startup’ : function(targets)
- This function is called before any attempt to discover a
remote card. The targets argument provides a list of
RemoteTarget
objects prepared from the ‘targets’ bitrate and technology type strings. The function must return a list of of thoseRemoteTarget
objects that shall be finally used for discovery, those targets may have additional attributes. An empty list or anything else that evaluates false will remove the ‘rdwr’ option completely. - ‘on-discover’ : function(target)
- This function is called when a
RemoteTarget
has been discovered. The target argument contains the technology type specific discovery responses and should be evaluated for multi-protocol support. The target will be further activated only if this function returns a true value. The default function depends on the ‘llcp’ option, if present then the function returns True only if the target does not indicate peer to peer protocol support, otherwise it returns True for all targets. - ‘on-connect’ : function(tag)
- This function is called when a remote tag has been
activated. The tag argument is an instance of class
nfc.tag.Tag
and can be used for tag reading and writing within the callback or in a separate thread. Any true return value instructsconnect()
to wait until the tag is no longer present and then return True, any false return value implies immediate return of thenfc.tag.Tag
object. - ‘on-release’ : function(tag)
- This function is called when the presence check was run (the ‘on-connect’ function returned a true value) and determined that communication with the tag has become impossible, or when the ‘terminate’ function returned a true value. The tag object may be used for cleanup actions but not for communication.
- ‘iterations’ : integer
- This determines the number of sense cycles performed between calls to the terminate function. Each iteration searches once for all specified targets. The default value is 5 iterations and between each iteration is a waiting time determined by the ‘interval’ option described below. As an effect of math there will be no waiting time if iterations is set to 1.
- ‘interval’ : float
- This determines the waiting time between iterations. The default value of 0.5 seconds is considered a sensible tradeoff between responsiveness in terms of tag discovery and power consumption. It should be clear that changing this value will impair one or the other. There is no free beer.
- ‘beep-on-connect’: boolean
- If the device supports beeping or flashing an LED, automatically perform this functionality when a tag is successfully detected AND the ‘on-connect’ function returns a true value. Defaults to True.
import nfc def on_startup(targets): for target in targets: target.sensf_req = bytearray.fromhex("0012FC0000") return targets def on_connect(tag): print(tag) rdwr_options = { 'targets': ['212F', '424F'], 'on-startup': on_startup, 'on-connect': on_connect, } with nfc.ContactlessFrontend('usb') as clf: tag = clf.connect(rdwr=rdwr_options) if tag.ndef: print(tag.ndef.message.pretty())
Peer To Peer Options
- ‘on-startup’ : function(llc)
- This function is called before any attempt to establish
peer to peer communication. The llc argument provides the
LogicalLinkController
that may be used to allocate and bind listen sockets for local services. The function should return the llc object if activation shall continue. Any other value removes the ‘llcp’ option. - ‘on-connect’ : function(llc)
- This function is called when peer to peer communication is
successfully established. The llc argument provides the
now activated
LogicalLinkController
ready for allocation of client communication sockets and data exchange in separate work threads. The function should a true value return more or less immediately, unless it wishes to handle the logical link controller run loop by itself and anytime later return a false value. - ‘on-release’ : function(llc)
- This function is called when the symmetry loop was run (the ‘on-connect’ function returned a true value) and determined that communication with the remote peer has become impossible, or when the ‘terminate’ function returned a true value. The llc object may be used for cleanup actions but not for communication.
- ‘role’ : string
- This attribute determines whether the local device will
restrict itself to either
'initiator'
or'target'
mode of operation. As Initiator the local device will try to discover a remote device. As Target it waits for being discovered. The default is to alternate between both roles. - ‘miu’ : integer
- This attribute sets the maximum information unit size that is announced to the remote device during link activation. The default and also smallest possible value is 128 bytes.
- ‘lto’ : integer
- This attribute sets the link timeout value (given in milliseconds) that is announced to the remote device during link activation. It informs the remote device that if the local device does not return a protocol data unit before the timeout expires, the communication link is broken and can not be recovered. The lto is an important part of the user experience, it ultimately tells when the user should no longer expect communication to continue. The default value is 500 millisecond.
- ‘agf’ : boolean
- Some early phone implementations did not properly handle aggregated protocol data units. This attribute allows to disable the use af aggregation at the cost of efficiency. Aggregation is disabled with a false value. The default is to use aggregation.
- ‘brs’ : integer
- For the local device in Initiator role the bit rate selector determines the the bitrate to negotiate with the remote Target. The value may be 0, 1, or 2 for 106, 212, or 424 kbps, respectively. The default is to negotiate 424 kbps.
- ‘acm’ : boolean
- For the local device in Initiator role this attribute determines whether a remote Target may also be activated in active communication mode. In active communication mode both peer devices mutually generate a radio field when sending. The default is to use passive communication mode.
- ‘rwt’ : float
- For the local device in Target role this attribute sets the
response waiting time announced during link activation. The
response waiting time is a medium access layer (NFC-DEP)
value that indicates when the remote Initiator shall
attempt error recovery after missing a Target response. The
value is the waiting time index wt that determines the
effective response waiting time by the formula
rwt = 4096/13.56E6 * pow(2, wt)
. The value shall not be greater than 14. The default value is 8 and yields an effective response waiting time of 77.33 ms. - ‘lri’ : integer
- For the local device in Initiator role this attribute sets the length reduction for medium access layer (NFC-DEP) information frames. The value may be 0, 1, 2, or 3 for a maximum payload size of 64, 128, 192, or 254 bytes, respectively. The default value is 3.
- ‘lrt’ : integer
- For the local device in Target role this attribute sets the length reduction for medium access layer (NFC-DEP) information frames. The value may be 0, 1, 2, or 3 for a maximum payload size of 64, 128, 192, or 254 bytes, respectively. The default value is 3.
import nfc import nfc.llcp import threading def server(socket): message, address = socket.recvfrom() socket.sendto("It's me!", address) socket.close() def client(socket): socket.sendto("Hi there!", address=32) socket.close() def on_startup(llc): socket = nfc.llcp.Socket(llc, nfc.llcp.LOGICAL_DATA_LINK) socket.bind(address=32) threading.Thread(target=server, args=(socket,)).start() return llc def on_connect(llc): socket = nfc.llcp.Socket(llc, nfc.llcp.LOGICAL_DATA_LINK) threading.Thread(target=client, args=(socket,)).start() return True llcp_options = { 'on-startup': on_startup, 'on-connect': on_connect, } with nfc.ContactlessFrontend('usb') as clf: clf.connect(llcp=llcp_options) print("link terminated")
Card Emulation Options
- ‘on-startup’ : function(target)
- This function is called to prepare a local target for
discovery. The input argument is a fresh instance of an
unspecific
LocalTarget
that can be set to the desired bitrate and modulation type and populated with the type specific discovery responses (seelisten()
for response data that is needed). The fully specified target object must then be returned. - ‘on-discover’ : function(target)
- This function is called when the
LocalTarget
has been discovered. The target argument contains the technology type specific discovery commands. The target will be further activated only if this function returns a true value. The default function always returns True. - ‘on-connect’ : function(tag)
- This function is called when the local target was
discovered and a
nfc.tag.TagEmulation
object successfully initialized. The function receives the emulated tag object which stores the first command received after inialization astag.cmd
. The function should return a true value if the tag.process_command() and tag.send_response() methods shall be called repeatedly until either the remote device terminates communication or the ‘terminate’ function returns a true value. The function should return a false value if theconnect()
method shall return immediately with the emulated tag object. - ‘on-release’ : function(tag)
- This function is called when the Target was released by the Initiator or simply moved away, or if the terminate callback function has returned a true value. The emulated tag object may be used for cleanup actions but not for communication.
import nfc def on_startup(target): idm = bytearray.fromhex("01010501b00ac30b") pmm = bytearray.fromhex("03014b024f4993ff") sys = bytearray.fromhex("1234") target.brty = "212F" target.sensf_res = chr(1) + idm + pmm + sys return target def on_connect(tag): print("discovered by remote reader") return True def on_release(tag): print("remote reader is gone") return True card_options = { 'on-startup': on_startup, 'on-connect': on_connect, 'on-release': on_release, } with nfc.ContactlessFrontend('usb') as clf: clf.connect(card=card_options)
Return Value
The
connect()
method returnsNone
if there were no options left after the ‘on-startup’ functions have been executed or when the ‘terminate’ function returned a true value. It returnsFalse
when terminated by any of the following exceptions:KeyboardInterrupt
,IOError
,UnsupportedTargetError
.The
connect()
method returns aTag
,LogicalLinkController
, orTagEmulation
object if the associated ‘on-connect’ function returned a false value to indicate that it will handle presence check, peer to peer symmetry loop, or command/response processing by itself.
-
sense
(*targets, **options)¶ Discover a contactless card or listening device.
Note
The
sense()
method is intended for experts with a good understanding of the commands and responses exchanged during target activation (the notion used for commands and responses follows the NFC Forum Digital Specification). If the greater level of control is not needed it is recommended to use theconnect()
method.All positional arguments build the list of potential targets to discover and must be of type
RemoteTarget
. Keyword argument options may be the number ofiterations
of the sense loop set by targets and theinterval
between iterations. The return value is either aRemoteTarget
instance orNone
.>>> import nfc, nfc.clf >>> from binascii import hexlify >>> clf = nfc.ContactlessFrontend("usb") >>> target1 = nfc.clf.RemoteTarget("106A") >>> target2 = nfc.clf.RemoteTarget("212F") >>> print(clf.sense(target1, target2, iterations=5, interval=0.2)) 106A(sdd_res=04497622D93881, sel_res=00, sens_res=4400)
A Type A Target is specified with the technology letter
A
following the bitrate to be used for the SENS_REQ command (almost always must the bitrate be 106 kbps). To discover only a specific Type A target, the NFCID1 (UID) can be set with a 4, 7, or 10 bytesel_req
attribute (cascade tags are handled internally).>>> target = nfc.clf.RemoteTarget("106A") >>> print(clf.sense(target)) 106A sdd_res=04497622D93881 sel_res=00 sens_res=4400 >>> target.sel_req = bytearray.fromhex("04497622D93881") >>> print(clf.sense(target)) 106A sdd_res=04497622D93881 sel_res=00 sens_res=4400 >>> target.sel_req = bytearray.fromhex("04497622") >>> print(clf.sense(target)) None
A Type B Target is specified with the technology letter
B
following the bitrate to be used for the SENSB_REQ command (almost always must the bitrate be 106 kbps). A specific application family identifier can be set with the first byte of asensb_req
attribute (the second byte PARAM is ignored when it can not be set to local device, 00h is a safe value in all cases).>>> target = nfc.clf.RemoteTarget("106B") >>> print(clf.sense(target)) 106B sens_res=50E5DD3DC900000011008185 >>> target.sensb_req = bytearray.fromhex("0000") >>> print(clf.sense(target)) 106B sens_res=50E5DD3DC900000011008185 >>> target.sensb_req = bytearray.fromhex("FF00") >>> print(clf.sense(target)) None
A Type F Target is specified with the technology letter
F
following the bitrate to be used for the SENSF_REQ command (the typically supported bitrates are 212 and 424 kbps). The default SENSF_REQ command allows all targets to answer, requests system code information, and selects a single time slot for the SENSF_RES response. This can be changed with thesensf_req
attribute.>>> target = nfc.clf.RemoteTarget("212F") >>> print(clf.sense(target)) 212F sensf_res=0101010601B00ADE0B03014B024F4993FF12FC >>> target.sensf_req = bytearray.fromhex("0012FC0000") >>> print(clf.sense(target)) 212F sensf_res=0101010601B00ADE0B03014B024F4993FF >>> target.sensf_req = bytearray.fromhex("00ABCD0000") >>> print(clf.sense(target)) None
An Active Communication Mode P2P Target search is selected with an
atr_req
attribute. The choice of bitrate and modulation type is 106A, 212F, and 424F.>>> atr = bytearray.fromhex("D4000102030405060708091000000030") >>> target = clf.sense(nfc.clf.RemoteTarget("106A", atr_req=atr)) >>> if target and target.atr_res: >>> print(hexlify(target.atr_res).decode()) d501c023cae6b3182afe3dee0000000e3246666d01011103020013040196 >>> target = clf.sense(nfc.clf.RemoteTarget("424F", atr_req=atr)) >>> if target and target.atr_res: >>> print(hexlify(target.atr_res).decode()) d501dc0104f04584e15769700000000e3246666d01011103020013040196
Some drivers must modify the ATR_REQ to cope with hardware limitations, for example change length reduction value to reduce the maximum size of target responses. The ATR_REQ that has been send is given by the
atr_req
attribute of the returned RemoteTarget object.A Passive Communication Mode P2P Target responds to 106A discovery with bit 6 of SEL_RES set to 1, and to 212F/424F discovery (when the request code RC is 0 in the SENSF_REQ command) with an NFCID2 that starts with 01FEh in the SENSF_RES response. Responses below are from a Nexus 5 configured for NFC-DEP Protocol (SEL_RES bit 6 is set) and Type 4A Tag (SEL_RES bit 5 is set).
>>> print(clf.sense(nfc.clf.RemoteTarget("106A"))) 106A sdd_res=08796BEB sel_res=60 sens_res=0400 >>> sensf_req = bytearray.fromhex("00FFFF0000") >>> print(clf.sense(nfc.clf.RemoteTarget("424F", sensf_req=sensf_req))) 424F sensf_res=0101FE1444EFB88FD50000000000000000
Errors found in the targets argument list raise exceptions only if exactly one target is given. If multiple targets are provided, any target that is not supported or has invalid attributes is just ignored (but is logged as a debug message).
Exceptions
IOError
(ENODEV) when a local contacless communication device has not been opened or communication with the local device is no longer possible.nfc.clf.UnsupportedTargetError
if the single target supplied as input is not supported by the active driver. This exception is never raised whensense()
is called with multiple targets, those unsupported are then silently ignored.
-
listen
(target, timeout)¶ Listen timeout seconds to become activated as target.
Note
The
listen()
method is intended for experts with a good understanding of the commands and responses exchanged during target activation (the notion used for commands and responses follows the NFC Forum Digital Specification). If the greater level of control is not needed it is recommended to use theconnect()
method.The target argument is a
LocalTarget
object that provides bitrate, technology type and response data attributes. The return value is either aLocalTarget
object with bitrate, technology type and request/response data attributes orNone
.An P2P Target is selected when the
atr_res
attribute is set. The bitrate and technology type are decided by the Initiator and do not need to be specified. Thesens_res
,sdd_res
andsel_res
attributes for Type A technology as well as thesensf_res
attribute for Type F technolgy must all be set.When activated, the bitrate and type are set to the current communication values, the
atr_req
attribute contains the ATR_REQ received from the Initiator and thedep_req
attribute contains the first DEP_REQ received after activation. If the Initiator has changed communication parameters, thepsl_req
attribute holds the PSL_REQ that was received. Theatr_res
(and thepsl_res
if transmitted) are also made available.If the local target was activated in passive communication mode either the Type A response (
sens_res
,sdd_res
,sel_res
) or Type F response (sensf_res
) attributes will be present.With a Nexus 5 on a reader connected via USB the following code should be working and produce similar output (the Nexus 5 prioritizes active communication mode):
>>> import nfc, nfc.clf >>> clf = nfc.ContactlessFrontend("usb") >>> atr_res = "d50101fe0102030405060708000000083246666d010110" >>> target = nfc.clf.LocalTarget() >>> target.sensf_res = bytearray.fromhex("0101FE"+16*"FF") >>> target.sens_res = bytearray.fromhex("0101") >>> target.sdd_res = bytearray.fromhex("08010203") >>> target.sel_res = bytearray.fromhex("40") >>> target.atr_res = bytearray.fromhex(atr_res) >>> print(clf.listen(target, timeout=2.5)) 424F atr_res=D50101FE0102030405060708000000083246666D010110 ...
A Type A Target is selected when
atr_res
is not present and the technology type isA
. The bitrate should be set to 106 kbps, even if a driver supports higher bitrates they would need to be set after activation. Thesens_res
,sdd_res
andsel_res
attributes must all be provided.>>> target = nfc.clf.Localtarget("106A") >>> target.sens_res = bytearray.fromhex("0101")) >>> target.sdd_res = bytearray.fromhex("08010203") >>> target.sel_res = bytearray.fromhex("00") >>> print(clf.listen(target, timeout=2.5)) 106A sdd_res=08010203 sel_res=00 sens_res=0101 tt2_cmd=3000
A Type B Target is selected when
atr_res
is not present and the technology type isB
. Unfortunately none of the supported devices supports Type B technology for listen and annfc.clf.UnsupportedTargetError
exception will be the only result.>>> target = nfc.clf.LocalTarget("106B") >>> try: clf.listen(target, 2.5) ... except nfc.clf.UnsupportedTargetError: print("sorry") ... sorry
A Type F Target is selected when
atr_res
is not present and the technology type isF
. The bitrate may be 212 or 424 kbps. Thesensf_res
attribute must be provided.>>> idm, pmm, sys = "02FE010203040506", "FFFFFFFFFFFFFFFF", "12FC" >>> target = nfc.clf.LocalTarget("212F") >>> target.sensf_res = bytearray.fromhex("01" + idm + pmm + sys) >>> print(clf.listen(target, 2.5)) 212F sensf_req=00FFFF0003 tt3_cmd=0C02FE010203040506 ...
Exceptions
IOError
(ENODEV) when a local contacless communication device has not been opened or communication with the local device is no longer possible.nfc.clf.UnsupportedTargetError
if the single target supplied as input is not supported by the active driver. This exception is never raised whensense()
is called with multiple targets, those unsupported are then silently ignored.
-
exchange
(send_data, timeout)¶ Exchange data with an activated target (send_data is a command frame) or as an activated target (send_data is a response frame). Returns a target response frame (if data is send to an activated target) or a next command frame (if data is send from an activated target). Returns None if the communication link broke during exchange (if data is sent as a target). The timeout is the number of seconds to wait for data to return, if the timeout expires an nfc.clf.TimeoutException is raised. Other nfc.clf.CommunicationError exceptions may be raised if an error is detected during communication.
-
max_send_data_size
¶ The maximum number of octets that can be send with the
exchange()
method in the established operating mode.
-
max_recv_data_size
¶ The maximum number of octets that can be received with the
exchange()
method in the established operating mode.
-
-
class
nfc.clf.
RemoteTarget
(brty, **kwargs)¶ Bases:
nfc.clf.Target
A RemoteTarget instance provides bitrate and technology type and command/response data of a remote card or device that, when input to
sense()
, shall be attempted to discover and, when returned bysense()
, has been discovered by the local device. Command/response data attributes, whatever name, default to None.-
brty
¶ A string that combines bitrate and technology type, e.g. ‘106A’.
-
-
class
nfc.clf.
LocalTarget
(brty='106A', **kwargs)¶ Bases:
nfc.clf.Target
A LocalTarget instance provides bitrate and technology type and command/response data of the local card or device that, when input to
listen()
, shall be made available for discovery and, when returned bylisten()
, has been discovered by a remote device. Command/response data attributes, whatever name, default to None.-
brty
¶ A string that combines bitrate and technology type, e.g. ‘106A’.
-
-
exception
nfc.clf.
Error
¶ Bases:
Exception
Base class for exceptions specific to the contacless frontend module.
- UnsupportedTargetError
- CommunicationError
- ProtocolError
- TransmissionError
- TimeoutError
- BrokenLinkError
-
exception
nfc.clf.
UnsupportedTargetError
¶ Bases:
nfc.clf.Error
The
RemoteTarget
input toContactlessFrontend.sense()
orLocalTarget
input toContactlessFrontend.listen()
is not supported by the local device.
-
exception
nfc.clf.
CommunicationError
¶ Bases:
nfc.clf.Error
Base class for communication errors.
-
exception
nfc.clf.
ProtocolError
¶ Bases:
nfc.clf.CommunicationError
Raised when an NFC Forum Digital Specification protocol error occured.
-
exception
nfc.clf.
TransmissionError
¶ Bases:
nfc.clf.CommunicationError
Raised when an NFC Forum Digital Specification transmission error occured.
-
exception
nfc.clf.
TimeoutError
¶ Bases:
nfc.clf.CommunicationError
Raised when an NFC Forum Digital Specification timeout error occured.
-
exception
nfc.clf.
BrokenLinkError
¶ Bases:
nfc.clf.CommunicationError
The remote device (Reader/Writer or P2P Device) has deactivated the RF field or is no longer within communication distance.
Contactless Frontend¶
Note
The contactless frontend defined in this module is also
available as nfc.ContactlessFrontend
.
-
class
nfc.clf.
ContactlessFrontend
(path=None) Bases:
object
This class is the main interface for working with contactless devices. The
connect()
method provides easy access to the contactless functionality through automated discovery of remote cards and devices and activation of appropiate upper level protocols for further interaction. Thesense()
,listen()
andexchange()
methods provide a low-level interface for more specialized tasks.An instance of the
ContactlessFrontend
class manages a single contactless device locally connect through either USB, TTY or COM port. A special UDP port driver allows for emulation of a contactless device that connects through UDP to another emulated contactless device for test and development of higher layer functions.A locally connected contactless device can be opened by either supplying a path argument when an an instance of the contactless frontend class is created or by calling
open()
at a later time. In either case the path argument must be constructed as described inopen()
and the same exceptions may occur. The difference is thatopen()
returns False if a device could not be found whereas the initialization method raisesIOError
witherrno.ENODEV
.The methods of the
ContactlessFrontend
class are thread-safe.-
open
(path) Open a contactless reader identified by the search path.
The
open()
method searches and then opens a contactless reader device for further communication. The path argument can be flexibly constructed to identify more or less precisely the device to open. A path that only partially identifies a device is completed by search. The first device that is found and successfully opened causesopen()
to return True. If no device is found return value is False. If a device was found but could not be opened thenopen()
returns False if path was partial or raiseIOError
if path was fully qualified. Typical I/O error reasons areerrno.EACCES
if the calling process has insufficient access rights orerrno.EBUSY
if the device is used by another process.A path is constructed as follows:
usb[:vendor[:product]]
with optional vendor and product as four digit hexadecimal numbers. For example,usb:054c:06c3
would open the first Sony RC-S380 reader whileusb:054c
would open the first Sony reader found on USB.usb[:bus[:device]]
with optional bus and device number as three-digit decimals. For example,usb:001:023
would open the device enumerated as number 23 on bus 1 whileusb:001
would open the first device found on bust 1. Note that a new device number is generated every time the device is plugged into USB. Bus and device numbers are shown bylsusb
.tty:port:driver
with mandatory port and driver name. This is for Posix systems to open the serial port/dev/tty<port>
and use the driver modulenfc/dev/<driver>.py
for access. For example,tty:USB0:arygon
would open/dev/ttyUSB0
and load the Arygon APPx/ADRx driver.com:port:driver
with mandatory port and driver name. This is for Windows systems to open the serial portCOM<port>
and use the driver modulenfc/dev/<driver>.py
for access.udp[:host][:port]
with optional host name or address and port number. This will emulate a communication channel over UDP/IP. The defaults for host and port arelocalhost:54321
.
-
close
() Close the contacless reader device.
-
connect
(**options) Connect with a Target or Initiator
The calling thread is blocked until a single activation and deactivation has completed or a callback function supplied as the keyword argument
terminate
returns a true value. The example below makesconnect()
return after 5 seconds, regardless of whether a peer device was connected or not.>>> import nfc, time >>> clf = nfc.ContactlessFrontend('usb') >>> after5s = lambda: time.time() - started > 5 >>> started = time.time(); clf.connect(llcp={}, terminate=after5s)
Connect options are given as keyword arguments with dictionary values. Possible options are:
rdwr={key: value, ...}
- options for reader/writerllcp={key: value, ...}
- options for peer to peercard={key: value, ...}
- options for card emulation
Reader/Writer Options
- ‘targets’ : iterable
- A list of bitrate and technology type strings that will
produce the
RemoteTarget
objects to discover. The default is('106A', '106B', '212F')
. - ‘on-startup’ : function(targets)
- This function is called before any attempt to discover a
remote card. The targets argument provides a list of
RemoteTarget
objects prepared from the ‘targets’ bitrate and technology type strings. The function must return a list of of thoseRemoteTarget
objects that shall be finally used for discovery, those targets may have additional attributes. An empty list or anything else that evaluates false will remove the ‘rdwr’ option completely. - ‘on-discover’ : function(target)
- This function is called when a
RemoteTarget
has been discovered. The target argument contains the technology type specific discovery responses and should be evaluated for multi-protocol support. The target will be further activated only if this function returns a true value. The default function depends on the ‘llcp’ option, if present then the function returns True only if the target does not indicate peer to peer protocol support, otherwise it returns True for all targets. - ‘on-connect’ : function(tag)
- This function is called when a remote tag has been
activated. The tag argument is an instance of class
nfc.tag.Tag
and can be used for tag reading and writing within the callback or in a separate thread. Any true return value instructsconnect()
to wait until the tag is no longer present and then return True, any false return value implies immediate return of thenfc.tag.Tag
object. - ‘on-release’ : function(tag)
- This function is called when the presence check was run (the ‘on-connect’ function returned a true value) and determined that communication with the tag has become impossible, or when the ‘terminate’ function returned a true value. The tag object may be used for cleanup actions but not for communication.
- ‘iterations’ : integer
- This determines the number of sense cycles performed between calls to the terminate function. Each iteration searches once for all specified targets. The default value is 5 iterations and between each iteration is a waiting time determined by the ‘interval’ option described below. As an effect of math there will be no waiting time if iterations is set to 1.
- ‘interval’ : float
- This determines the waiting time between iterations. The default value of 0.5 seconds is considered a sensible tradeoff between responsiveness in terms of tag discovery and power consumption. It should be clear that changing this value will impair one or the other. There is no free beer.
- ‘beep-on-connect’: boolean
- If the device supports beeping or flashing an LED, automatically perform this functionality when a tag is successfully detected AND the ‘on-connect’ function returns a true value. Defaults to True.
import nfc def on_startup(targets): for target in targets: target.sensf_req = bytearray.fromhex("0012FC0000") return targets def on_connect(tag): print(tag) rdwr_options = { 'targets': ['212F', '424F'], 'on-startup': on_startup, 'on-connect': on_connect, } with nfc.ContactlessFrontend('usb') as clf: tag = clf.connect(rdwr=rdwr_options) if tag.ndef: print(tag.ndef.message.pretty())
Peer To Peer Options
- ‘on-startup’ : function(llc)
- This function is called before any attempt to establish
peer to peer communication. The llc argument provides the
LogicalLinkController
that may be used to allocate and bind listen sockets for local services. The function should return the llc object if activation shall continue. Any other value removes the ‘llcp’ option. - ‘on-connect’ : function(llc)
- This function is called when peer to peer communication is
successfully established. The llc argument provides the
now activated
LogicalLinkController
ready for allocation of client communication sockets and data exchange in separate work threads. The function should a true value return more or less immediately, unless it wishes to handle the logical link controller run loop by itself and anytime later return a false value. - ‘on-release’ : function(llc)
- This function is called when the symmetry loop was run (the ‘on-connect’ function returned a true value) and determined that communication with the remote peer has become impossible, or when the ‘terminate’ function returned a true value. The llc object may be used for cleanup actions but not for communication.
- ‘role’ : string
- This attribute determines whether the local device will
restrict itself to either
'initiator'
or'target'
mode of operation. As Initiator the local device will try to discover a remote device. As Target it waits for being discovered. The default is to alternate between both roles. - ‘miu’ : integer
- This attribute sets the maximum information unit size that is announced to the remote device during link activation. The default and also smallest possible value is 128 bytes.
- ‘lto’ : integer
- This attribute sets the link timeout value (given in milliseconds) that is announced to the remote device during link activation. It informs the remote device that if the local device does not return a protocol data unit before the timeout expires, the communication link is broken and can not be recovered. The lto is an important part of the user experience, it ultimately tells when the user should no longer expect communication to continue. The default value is 500 millisecond.
- ‘agf’ : boolean
- Some early phone implementations did not properly handle aggregated protocol data units. This attribute allows to disable the use af aggregation at the cost of efficiency. Aggregation is disabled with a false value. The default is to use aggregation.
- ‘brs’ : integer
- For the local device in Initiator role the bit rate selector determines the the bitrate to negotiate with the remote Target. The value may be 0, 1, or 2 for 106, 212, or 424 kbps, respectively. The default is to negotiate 424 kbps.
- ‘acm’ : boolean
- For the local device in Initiator role this attribute determines whether a remote Target may also be activated in active communication mode. In active communication mode both peer devices mutually generate a radio field when sending. The default is to use passive communication mode.
- ‘rwt’ : float
- For the local device in Target role this attribute sets the
response waiting time announced during link activation. The
response waiting time is a medium access layer (NFC-DEP)
value that indicates when the remote Initiator shall
attempt error recovery after missing a Target response. The
value is the waiting time index wt that determines the
effective response waiting time by the formula
rwt = 4096/13.56E6 * pow(2, wt)
. The value shall not be greater than 14. The default value is 8 and yields an effective response waiting time of 77.33 ms. - ‘lri’ : integer
- For the local device in Initiator role this attribute sets the length reduction for medium access layer (NFC-DEP) information frames. The value may be 0, 1, 2, or 3 for a maximum payload size of 64, 128, 192, or 254 bytes, respectively. The default value is 3.
- ‘lrt’ : integer
- For the local device in Target role this attribute sets the length reduction for medium access layer (NFC-DEP) information frames. The value may be 0, 1, 2, or 3 for a maximum payload size of 64, 128, 192, or 254 bytes, respectively. The default value is 3.
import nfc import nfc.llcp import threading def server(socket): message, address = socket.recvfrom() socket.sendto("It's me!", address) socket.close() def client(socket): socket.sendto("Hi there!", address=32) socket.close() def on_startup(llc): socket = nfc.llcp.Socket(llc, nfc.llcp.LOGICAL_DATA_LINK) socket.bind(address=32) threading.Thread(target=server, args=(socket,)).start() return llc def on_connect(llc): socket = nfc.llcp.Socket(llc, nfc.llcp.LOGICAL_DATA_LINK) threading.Thread(target=client, args=(socket,)).start() return True llcp_options = { 'on-startup': on_startup, 'on-connect': on_connect, } with nfc.ContactlessFrontend('usb') as clf: clf.connect(llcp=llcp_options) print("link terminated")
Card Emulation Options
- ‘on-startup’ : function(target)
- This function is called to prepare a local target for
discovery. The input argument is a fresh instance of an
unspecific
LocalTarget
that can be set to the desired bitrate and modulation type and populated with the type specific discovery responses (seelisten()
for response data that is needed). The fully specified target object must then be returned. - ‘on-discover’ : function(target)
- This function is called when the
LocalTarget
has been discovered. The target argument contains the technology type specific discovery commands. The target will be further activated only if this function returns a true value. The default function always returns True. - ‘on-connect’ : function(tag)
- This function is called when the local target was
discovered and a
nfc.tag.TagEmulation
object successfully initialized. The function receives the emulated tag object which stores the first command received after inialization astag.cmd
. The function should return a true value if the tag.process_command() and tag.send_response() methods shall be called repeatedly until either the remote device terminates communication or the ‘terminate’ function returns a true value. The function should return a false value if theconnect()
method shall return immediately with the emulated tag object. - ‘on-release’ : function(tag)
- This function is called when the Target was released by the Initiator or simply moved away, or if the terminate callback function has returned a true value. The emulated tag object may be used for cleanup actions but not for communication.
import nfc def on_startup(target): idm = bytearray.fromhex("01010501b00ac30b") pmm = bytearray.fromhex("03014b024f4993ff") sys = bytearray.fromhex("1234") target.brty = "212F" target.sensf_res = chr(1) + idm + pmm + sys return target def on_connect(tag): print("discovered by remote reader") return True def on_release(tag): print("remote reader is gone") return True card_options = { 'on-startup': on_startup, 'on-connect': on_connect, 'on-release': on_release, } with nfc.ContactlessFrontend('usb') as clf: clf.connect(card=card_options)
Return Value
The
connect()
method returnsNone
if there were no options left after the ‘on-startup’ functions have been executed or when the ‘terminate’ function returned a true value. It returnsFalse
when terminated by any of the following exceptions:KeyboardInterrupt
,IOError
,UnsupportedTargetError
.The
connect()
method returns aTag
,LogicalLinkController
, orTagEmulation
object if the associated ‘on-connect’ function returned a false value to indicate that it will handle presence check, peer to peer symmetry loop, or command/response processing by itself.
-
sense
(*targets, **options) Discover a contactless card or listening device.
Note
The
sense()
method is intended for experts with a good understanding of the commands and responses exchanged during target activation (the notion used for commands and responses follows the NFC Forum Digital Specification). If the greater level of control is not needed it is recommended to use theconnect()
method.All positional arguments build the list of potential targets to discover and must be of type
RemoteTarget
. Keyword argument options may be the number ofiterations
of the sense loop set by targets and theinterval
between iterations. The return value is either aRemoteTarget
instance orNone
.>>> import nfc, nfc.clf >>> from binascii import hexlify >>> clf = nfc.ContactlessFrontend("usb") >>> target1 = nfc.clf.RemoteTarget("106A") >>> target2 = nfc.clf.RemoteTarget("212F") >>> print(clf.sense(target1, target2, iterations=5, interval=0.2)) 106A(sdd_res=04497622D93881, sel_res=00, sens_res=4400)
A Type A Target is specified with the technology letter
A
following the bitrate to be used for the SENS_REQ command (almost always must the bitrate be 106 kbps). To discover only a specific Type A target, the NFCID1 (UID) can be set with a 4, 7, or 10 bytesel_req
attribute (cascade tags are handled internally).>>> target = nfc.clf.RemoteTarget("106A") >>> print(clf.sense(target)) 106A sdd_res=04497622D93881 sel_res=00 sens_res=4400 >>> target.sel_req = bytearray.fromhex("04497622D93881") >>> print(clf.sense(target)) 106A sdd_res=04497622D93881 sel_res=00 sens_res=4400 >>> target.sel_req = bytearray.fromhex("04497622") >>> print(clf.sense(target)) None
A Type B Target is specified with the technology letter
B
following the bitrate to be used for the SENSB_REQ command (almost always must the bitrate be 106 kbps). A specific application family identifier can be set with the first byte of asensb_req
attribute (the second byte PARAM is ignored when it can not be set to local device, 00h is a safe value in all cases).>>> target = nfc.clf.RemoteTarget("106B") >>> print(clf.sense(target)) 106B sens_res=50E5DD3DC900000011008185 >>> target.sensb_req = bytearray.fromhex("0000") >>> print(clf.sense(target)) 106B sens_res=50E5DD3DC900000011008185 >>> target.sensb_req = bytearray.fromhex("FF00") >>> print(clf.sense(target)) None
A Type F Target is specified with the technology letter
F
following the bitrate to be used for the SENSF_REQ command (the typically supported bitrates are 212 and 424 kbps). The default SENSF_REQ command allows all targets to answer, requests system code information, and selects a single time slot for the SENSF_RES response. This can be changed with thesensf_req
attribute.>>> target = nfc.clf.RemoteTarget("212F") >>> print(clf.sense(target)) 212F sensf_res=0101010601B00ADE0B03014B024F4993FF12FC >>> target.sensf_req = bytearray.fromhex("0012FC0000") >>> print(clf.sense(target)) 212F sensf_res=0101010601B00ADE0B03014B024F4993FF >>> target.sensf_req = bytearray.fromhex("00ABCD0000") >>> print(clf.sense(target)) None
An Active Communication Mode P2P Target search is selected with an
atr_req
attribute. The choice of bitrate and modulation type is 106A, 212F, and 424F.>>> atr = bytearray.fromhex("D4000102030405060708091000000030") >>> target = clf.sense(nfc.clf.RemoteTarget("106A", atr_req=atr)) >>> if target and target.atr_res: >>> print(hexlify(target.atr_res).decode()) d501c023cae6b3182afe3dee0000000e3246666d01011103020013040196 >>> target = clf.sense(nfc.clf.RemoteTarget("424F", atr_req=atr)) >>> if target and target.atr_res: >>> print(hexlify(target.atr_res).decode()) d501dc0104f04584e15769700000000e3246666d01011103020013040196
Some drivers must modify the ATR_REQ to cope with hardware limitations, for example change length reduction value to reduce the maximum size of target responses. The ATR_REQ that has been send is given by the
atr_req
attribute of the returned RemoteTarget object.A Passive Communication Mode P2P Target responds to 106A discovery with bit 6 of SEL_RES set to 1, and to 212F/424F discovery (when the request code RC is 0 in the SENSF_REQ command) with an NFCID2 that starts with 01FEh in the SENSF_RES response. Responses below are from a Nexus 5 configured for NFC-DEP Protocol (SEL_RES bit 6 is set) and Type 4A Tag (SEL_RES bit 5 is set).
>>> print(clf.sense(nfc.clf.RemoteTarget("106A"))) 106A sdd_res=08796BEB sel_res=60 sens_res=0400 >>> sensf_req = bytearray.fromhex("00FFFF0000") >>> print(clf.sense(nfc.clf.RemoteTarget("424F", sensf_req=sensf_req))) 424F sensf_res=0101FE1444EFB88FD50000000000000000
Errors found in the targets argument list raise exceptions only if exactly one target is given. If multiple targets are provided, any target that is not supported or has invalid attributes is just ignored (but is logged as a debug message).
Exceptions
IOError
(ENODEV) when a local contacless communication device has not been opened or communication with the local device is no longer possible.nfc.clf.UnsupportedTargetError
if the single target supplied as input is not supported by the active driver. This exception is never raised whensense()
is called with multiple targets, those unsupported are then silently ignored.
-
listen
(target, timeout) Listen timeout seconds to become activated as target.
Note
The
listen()
method is intended for experts with a good understanding of the commands and responses exchanged during target activation (the notion used for commands and responses follows the NFC Forum Digital Specification). If the greater level of control is not needed it is recommended to use theconnect()
method.The target argument is a
LocalTarget
object that provides bitrate, technology type and response data attributes. The return value is either aLocalTarget
object with bitrate, technology type and request/response data attributes orNone
.An P2P Target is selected when the
atr_res
attribute is set. The bitrate and technology type are decided by the Initiator and do not need to be specified. Thesens_res
,sdd_res
andsel_res
attributes for Type A technology as well as thesensf_res
attribute for Type F technolgy must all be set.When activated, the bitrate and type are set to the current communication values, the
atr_req
attribute contains the ATR_REQ received from the Initiator and thedep_req
attribute contains the first DEP_REQ received after activation. If the Initiator has changed communication parameters, thepsl_req
attribute holds the PSL_REQ that was received. Theatr_res
(and thepsl_res
if transmitted) are also made available.If the local target was activated in passive communication mode either the Type A response (
sens_res
,sdd_res
,sel_res
) or Type F response (sensf_res
) attributes will be present.With a Nexus 5 on a reader connected via USB the following code should be working and produce similar output (the Nexus 5 prioritizes active communication mode):
>>> import nfc, nfc.clf >>> clf = nfc.ContactlessFrontend("usb") >>> atr_res = "d50101fe0102030405060708000000083246666d010110" >>> target = nfc.clf.LocalTarget() >>> target.sensf_res = bytearray.fromhex("0101FE"+16*"FF") >>> target.sens_res = bytearray.fromhex("0101") >>> target.sdd_res = bytearray.fromhex("08010203") >>> target.sel_res = bytearray.fromhex("40") >>> target.atr_res = bytearray.fromhex(atr_res) >>> print(clf.listen(target, timeout=2.5)) 424F atr_res=D50101FE0102030405060708000000083246666D010110 ...
A Type A Target is selected when
atr_res
is not present and the technology type isA
. The bitrate should be set to 106 kbps, even if a driver supports higher bitrates they would need to be set after activation. Thesens_res
,sdd_res
andsel_res
attributes must all be provided.>>> target = nfc.clf.Localtarget("106A") >>> target.sens_res = bytearray.fromhex("0101")) >>> target.sdd_res = bytearray.fromhex("08010203") >>> target.sel_res = bytearray.fromhex("00") >>> print(clf.listen(target, timeout=2.5)) 106A sdd_res=08010203 sel_res=00 sens_res=0101 tt2_cmd=3000
A Type B Target is selected when
atr_res
is not present and the technology type isB
. Unfortunately none of the supported devices supports Type B technology for listen and annfc.clf.UnsupportedTargetError
exception will be the only result.>>> target = nfc.clf.LocalTarget("106B") >>> try: clf.listen(target, 2.5) ... except nfc.clf.UnsupportedTargetError: print("sorry") ... sorry
A Type F Target is selected when
atr_res
is not present and the technology type isF
. The bitrate may be 212 or 424 kbps. Thesensf_res
attribute must be provided.>>> idm, pmm, sys = "02FE010203040506", "FFFFFFFFFFFFFFFF", "12FC" >>> target = nfc.clf.LocalTarget("212F") >>> target.sensf_res = bytearray.fromhex("01" + idm + pmm + sys) >>> print(clf.listen(target, 2.5)) 212F sensf_req=00FFFF0003 tt3_cmd=0C02FE010203040506 ...
Exceptions
IOError
(ENODEV) when a local contacless communication device has not been opened or communication with the local device is no longer possible.nfc.clf.UnsupportedTargetError
if the single target supplied as input is not supported by the active driver. This exception is never raised whensense()
is called with multiple targets, those unsupported are then silently ignored.
-
exchange
(send_data, timeout) Exchange data with an activated target (send_data is a command frame) or as an activated target (send_data is a response frame). Returns a target response frame (if data is send to an activated target) or a next command frame (if data is send from an activated target). Returns None if the communication link broke during exchange (if data is sent as a target). The timeout is the number of seconds to wait for data to return, if the timeout expires an nfc.clf.TimeoutException is raised. Other nfc.clf.CommunicationError exceptions may be raised if an error is detected during communication.
-
max_send_data_size
The maximum number of octets that can be send with the
exchange()
method in the established operating mode.
-
max_recv_data_size
The maximum number of octets that can be received with the
exchange()
method in the established operating mode.
-
Technology Types¶
-
class
nfc.clf.
RemoteTarget
(brty, **kwargs) Bases:
nfc.clf.Target
A RemoteTarget instance provides bitrate and technology type and command/response data of a remote card or device that, when input to
sense()
, shall be attempted to discover and, when returned bysense()
, has been discovered by the local device. Command/response data attributes, whatever name, default to None.-
brty
A string that combines bitrate and technology type, e.g. ‘106A’.
-
-
class
nfc.clf.
LocalTarget
(brty='106A', **kwargs) Bases:
nfc.clf.Target
A LocalTarget instance provides bitrate and technology type and command/response data of the local card or device that, when input to
listen()
, shall be made available for discovery and, when returned bylisten()
, has been discovered by a remote device. Command/response data attributes, whatever name, default to None.-
brty
A string that combines bitrate and technology type, e.g. ‘106A’.
-
Exceptions¶
-
exception
nfc.clf.
Error
Bases:
Exception
Base class for exceptions specific to the contacless frontend module.
- UnsupportedTargetError
- CommunicationError
- ProtocolError
- TransmissionError
- TimeoutError
- BrokenLinkError
-
exception
nfc.clf.
UnsupportedTargetError
Bases:
nfc.clf.Error
The
RemoteTarget
input toContactlessFrontend.sense()
orLocalTarget
input toContactlessFrontend.listen()
is not supported by the local device.
-
exception
nfc.clf.
CommunicationError
Bases:
nfc.clf.Error
Base class for communication errors.
-
exception
nfc.clf.
ProtocolError
Bases:
nfc.clf.CommunicationError
Raised when an NFC Forum Digital Specification protocol error occured.
-
exception
nfc.clf.
TransmissionError
Bases:
nfc.clf.CommunicationError
Raised when an NFC Forum Digital Specification transmission error occured.
-
exception
nfc.clf.
TimeoutError
Bases:
nfc.clf.CommunicationError
Raised when an NFC Forum Digital Specification timeout error occured.
-
exception
nfc.clf.
BrokenLinkError
Bases:
nfc.clf.CommunicationError
The remote device (Reader/Writer or P2P Device) has deactivated the RF field or is no longer within communication distance.
Driver Interface¶
All contactless drivers must implement the interface defined in
Device
. Unsupported target discovery or target
emulation methods raise UnsupportedTargetError
. The
interface is used internally by ContactlessFrontend
and is not intended as an application programming interface. Device
driver methods are not thread-safe and do not necessarily check input
arguments when they are supposed to be valid. The interface may change
without notice at any time.
-
nfc.clf.device.
connect
(path)¶ Connect to a local device identified by path and load the appropriate device driver. The path argument is documented at
nfc.clf.ContactlessFrontend.open()
. The return value is either aDevice
instance orNone
. Note that not all drivers can be autodetected, specifically for serial devices path must usually also specify the driver.
-
class
nfc.clf.device.
Device
(*args, **kwargs)¶ Bases:
object
All device drivers inherit from the
Device
class and must implement it’s methods.-
vendor_name
¶ The device vendor name. An empty string if the vendor name could not be determined.
-
product_name
¶ The device product name. An empty string if the product name could not be determined.
-
chipset_name
¶ The name of the chipset embedded in the device.
-
mute
()¶ Mutes all existing communication, most notably the device will no longer generate a 13.56 MHz carrier signal when operating as Initiator.
-
sense_tta
(target)¶ Discover a Type A Target.
Activates the 13.56 MHz carrier signal and sends a SENS_REQ command at the bitrate set by target.brty. If a response is received, sends an RID_CMD for a Type 1 Tag or SDD_REQ and SEL_REQ for a Type 2/4 Tag and returns the responses.
Parameters: target (nfc.clf.RemoteTarget) – Supplies bitrate and optional command data for the target discovery. The only sensible command to set is sel_req populated with a UID to find only that specific target. Returns: - Response data received from a remote
- target if found. This includes at least sens_res and either rid_res (for a Type 1 Tag) or sdd_res and sel_res (for a Type 2/4 Tag).
Return type: nfc.clf.RemoteTarget Raises: nfc.clf.UnsupportedTargetError
– The method is not supported or the target argument requested an unsupported bitrate (or has a wrong technology type identifier).
-
sense_ttb
(target)¶ Discover a Type B Target.
Activates the 13.56 MHz carrier signal and sends a SENSB_REQ command at the bitrate set by target.brty. If a SENSB_RES is received, returns a target object with the sensb_res attribute.
Note that the firmware of some devices (least all those based on PN53x) automatically sends an ATTRIB command with varying but always unfortunate communication settings. The drivers correct that situation by sending S(DESELECT) and WUPB before return.
Parameters: target (nfc.clf.RemoteTarget) – Supplies bitrate and the optional sensb_req for target discovery. Most drivers do no not allow a fully customized SENSB_REQ, the only parameter that can always be changed is the AFI byte, others may be ignored. Returns: - Response data received from a remote
- target if found. The only response data attribute is sensb_res.
Return type: nfc.clf.RemoteTarget Raises: nfc.clf.UnsupportedTargetError
– The method is not supported or the target argument requested an unsupported bitrate (or has a wrong technology type identifier).
-
sense_ttf
(target)¶ Discover a Type F Target.
Activates the 13.56 MHz carrier signal and sends a SENSF_REQ command at the bitrate set by target.brty. If a SENSF_RES is received, returns a target object with the sensf_res attribute.
Parameters: target (nfc.clf.RemoteTarget) – Supplies bitrate and the optional sensf_req for target discovery. The default SENSF_REQ invites all targets to respond and requests the system code information bytes. Returns: - Response data received from a remote
- target if found. The only response data attribute is sensf_res.
Return type: nfc.clf.RemoteTarget Raises: nfc.clf.UnsupportedTargetError
– The method is not supported or the target argument requested an unsupported bitrate (or has a wrong technology type identifier).
-
sense_dep
(target)¶ Discover a NFC-DEP Target in active communication mode.
Activates the 13.56 MHz carrier signal and sends an ATR_REQ command at the bitrate set by target.brty. If an ATR_RES is received, returns a target object with the atr_res attribute.
Note that some drivers (like pn531) may modify the transport data bytes length reduction value in ATR_REQ and ATR_RES due to hardware limitations.
Parameters: target (nfc.clf.RemoteTarget) – Supplies bitrate and the mandatory atr_req for target discovery. The bitrate may be one of ‘106A’, ‘212F’, or ‘424F’. Returns: - Response data received from a remote
- target if found. The only response data attribute is atr_res. The actually sent and potentially modified ATR_REQ is also included as atr_req attribute.
Return type: nfc.clf.RemoteTarget Raises: nfc.clf.UnsupportedTargetError
– The method is not supported or the target argument requested an unsupported bitrate (or has a wrong technology type identifier).
-
listen_tta
(target, timeout)¶ Listen as Type A Target.
Waits to receive a SENS_REQ command at the bitrate set by target.brty and sends the target.sens_res response. Depending on the SENS_RES bytes, the Initiator then sends an RID_CMD (SENS_RES coded for a Type 1 Tag) or SDD_REQ and SEL_REQ (SENS_RES coded for a Type 2/4 Tag). Responses are then generated from the rid_res or sdd_res and sel_res attributes in target.
Note that none of the currently supported hardware can actually receive an RID_CMD, thus Type 1 Tag emulation is impossible.
Parameters: - target (nfc.clf.LocalTarget) – Supplies bitrate and mandatory response data to reply when being discovered.
- timeout (float) – The maximum number of seconds to wait for a discovery command.
Returns: - Command data received from the remote
Initiator if being discovered and to the extent supported by the device. The first command received after discovery is returned as one of the tt1_cmd, tt2_cmd or tt4_cmd attribute (note that unset attributes are always None).
Return type: Raises: nfc.clf.UnsupportedTargetError
– The method is not supported or the target argument requested an unsupported bitrate (or has a wrong technology type identifier).ValueError
– A required target response attribute is not present or does not supply the number of bytes expected.
-
listen_ttb
(target, timeout)¶ Listen as Type A Target.
Waits to receive a SENSB_REQ command at the bitrate set by target.brty and sends the target.sensb_res response.
Note that none of the currently supported hardware can actually listen as Type B target.
Parameters: - target (nfc.clf.LocalTarget) – Supplies bitrate and mandatory response data to reply when being discovered.
- timeout (float) – The maximum number of seconds to wait for a discovery command.
Returns: - Command data received from the remote
Initiator if being discovered and to the extent supported by the device. The first command received after discovery is returned as tt4_cmd attribute.
Return type: Raises: nfc.clf.UnsupportedTargetError
– The method is not supported or the target argument requested an unsupported bitrate (or has a wrong technology type identifier).ValueError
– A required target response attribute is not present or does not supply the number of bytes expected.
-
listen_ttf
(target, timeout)¶ Listen as Type A Target.
Waits to receive a SENSF_REQ command at the bitrate set by target.brty and sends the target.sensf_res response. Then waits for a first command that is not a SENSF_REQ and returns this as the tt3_cmd attribute.
Parameters: - target (nfc.clf.LocalTarget) – Supplies bitrate and mandatory response data to reply when being discovered.
- timeout (float) – The maximum number of seconds to wait for a discovery command.
Returns: - Command data received from the remote
Initiator if being discovered and to the extent supported by the device. The first command received after discovery is returned as tt3_cmd attribute.
Return type: Raises: nfc.clf.UnsupportedTargetError
– The method is not supported or the target argument requested an unsupported bitrate (or has a wrong technology type identifier).ValueError
– A required target response attribute is not present or does not supply the number of bytes expected.
-
listen_dep
(target, timeout)¶ Listen as NFC-DEP Target.
Waits to receive an ATR_REQ (if the local device supports active communication mode) or a Type A or F Target activation followed by an ATR_REQ in passive communication mode. The ATR_REQ is replied with target.atr_res. The first DEP_REQ command is returned as the dep_req attribute along with atr_req and atr_res. The psl_req and psl_res attributes are returned when the has Initiator performed a parameter selection. The sens_res or sensf_res attributes are returned when activation was in passive communication mode.
Parameters: - target (nfc.clf.LocalTarget) – Supplies mandatory response data to reply when being discovered. All of sens_res, sdd_res, sel_res, sensf_res, and atr_res must be provided. The bitrate does not need to be set, an NFC-DEP Target always accepts discovery at ‘106A’, ‘212F and ‘424F’.
- timeout (float) – The maximum number of seconds to wait for a discovery command.
Returns: - Command data received from the remote
Initiator if being discovered and to the extent supported by the device. The first command received after discovery is returned as dep_req attribute.
Return type: Raises: nfc.clf.UnsupportedTargetError
– The method is not supported by the local hardware.ValueError
– A required target response attribute is not present or does not supply the number of bytes expected.
-
send_cmd_recv_rsp
(target, data, timeout)¶ Exchange data with a remote Target
Sends command data to the remote target discovered in the most recent call to one of the sense_xxx() methods. Note that target becomes invalid with any call to mute(), sense_xxx() or listen_xxx()
Parameters: - target (nfc.clf.RemoteTarget) – The target returned by the last successful call of a sense_xxx() method.
- data (bytearray) – The binary data to send to the remote device.
- timeout (float) – The maximum number of seconds to wait for response data from the remote device.
Returns: Response data received from the remote device.
Return type: Raises: nfc.clf.CommunicationError
– When no data was received.
-
send_rsp_recv_cmd
(target, data, timeout=None)¶ Exchange data with a remote Initiator
Sends response data as the local target being discovered in the most recent call to one of the listen_xxx() methods. Note that target becomes invalid with any call to mute(), sense_xxx() or listen_xxx()
Parameters: - target (nfc.clf.LocalTarget) – The target returned by the last successful call of a listen_xxx() method.
- data (bytearray) – The binary data to send to the remote device.
- timeout (float) – The maximum number of seconds to wait for command data from the remote device.
Returns: Command data received from the remote device.
Return type: Raises: nfc.clf.CommunicationError
– When no data was received.
-
get_max_send_data_size
(target)¶ Returns the maximum number of data bytes for sending.
The maximum number of data bytes acceptable for sending with either
send_cmd_recv_rsp()
orsend_rsp_recv_cmd()
. The value reflects the local device capabilities for sending in the mode determined by target. It does not relate to any protocol capabilities and negotiations.Parameters: target (nfc.clf.Target) – The current local or remote communication target. Returns: Maximum number of data bytes supported for sending. Return type: int
-
get_max_recv_data_size
(target)¶ Returns the maximum number of data bytes for receiving.
The maximum number of data bytes acceptable for receiving with either
send_cmd_recv_rsp()
orsend_rsp_recv_cmd()
. The value reflects the local device capabilities for receiving in the mode determined by target. It does not relate to any protocol capabilities and negotiations.Parameters: target (nfc.clf.Target) – The current local or remote communication target. Returns: Maximum number of data bytes supported for receiving. Return type: int
-
turn_on_led_and_buzzer
()¶ If a device has an LED and/or a buzzer, this method can be implemented to turn those indicators to the ON state.
-
turn_off_led_and_buzzer
()¶ If a device has an LED and/or a buzzer, this method can be implemented to turn those indicators to the OFF state.
-
Device Drivers¶
rcs380¶
Driver module for contactless devices based on the Sony NFC Port-100 chipset. The only product known to use this chipset is the PaSoRi RC-S380. The RC-S380 connects to the host as a native USB device.
The RC-S380 has been the first NFC Forum certified device. It supports reading and writing of all NFC Forum tags as well as peer-to-peer mode. In addition, the NFC Port-100 also supports card emulation Type A and Type F Technology. A notable restriction is that peer-to-peer active communication mode (not required for NFC Forum certification) is not supported.
function | support | remarks |
---|---|---|
sense_tta | yes | |
sense_ttb | yes | |
sense_ttf | yes | |
sense_dep | no | |
listen_tta | yes | Type F responses can not be disabled |
listen_ttb | no | |
listen_ttf | yes | |
listen_dep | yes | Only passive communication mode |
-
class
nfc.clf.rcs380.
Device
(chipset, logger)¶ Bases:
nfc.clf.device.Device
-
mute
()¶ Mutes all existing communication, most notably the device will no longer generate a 13.56 MHz carrier signal when operating as Initiator.
-
sense_tta
(target)¶ Sense for a Type A Target is supported for 106, 212 and 424 kbps. However, there may not be any target that understands the activation commands in other than 106 kbps.
-
sense_ttb
(target)¶ Sense for a Type B Target is supported for 106, 212 and 424 kbps. However, there may not be any target that understands the activation command in other than 106 kbps.
-
sense_ttf
(target)¶ Sense for a Type F Target is supported for 212 and 424 kbps.
-
sense_dep
(target)¶ Sense for an active DEP Target is not supported. The device only supports passive activation via sense_tta/sense_ttf.
-
listen_tta
(target, timeout)¶ Listen as Type A Target in 106 kbps.
Restrictions:
- It is not possible to send short frames that are required for ACK and NAK responses. This means that a Type 2 Tag emulation can only implement a single sector memory model.
- It can not be avoided that the chipset responds to SENSF_REQ commands. The driver configures the SENSF_RES response to all zero and ignores all Type F communication but eventually it depends on the remote device whether Type A Target activation will still be attempted.
-
listen_ttb
(target, timeout)¶ Listen as Type B Target is not supported.
-
listen_ttf
(target, timeout)¶ Listen as Type F Target is supported for either 212 or 424 kbps.
-
listen_dep
(target, timeout)¶ Listen as NFC-DEP Target.
Waits to receive an ATR_REQ (if the local device supports active communication mode) or a Type A or F Target activation followed by an ATR_REQ in passive communication mode. The ATR_REQ is replied with target.atr_res. The first DEP_REQ command is returned as the dep_req attribute along with atr_req and atr_res. The psl_req and psl_res attributes are returned when the has Initiator performed a parameter selection. The sens_res or sensf_res attributes are returned when activation was in passive communication mode.
Parameters: - target (nfc.clf.LocalTarget) – Supplies mandatory response data to reply when being discovered. All of sens_res, sdd_res, sel_res, sensf_res, and atr_res must be provided. The bitrate does not need to be set, an NFC-DEP Target always accepts discovery at ‘106A’, ‘212F and ‘424F’.
- timeout (float) – The maximum number of seconds to wait for a discovery command.
Returns: - Command data received from the remote
Initiator if being discovered and to the extent supported by the device. The first command received after discovery is returned as dep_req attribute.
Return type: Raises: nfc.clf.UnsupportedTargetError
– The method is not supported by the local hardware.ValueError
– A required target response attribute is not present or does not supply the number of bytes expected.
-
get_max_send_data_size
(target)¶ Returns the maximum number of data bytes for sending.
The maximum number of data bytes acceptable for sending with either
send_cmd_recv_rsp()
orsend_rsp_recv_cmd()
. The value reflects the local device capabilities for sending in the mode determined by target. It does not relate to any protocol capabilities and negotiations.Parameters: target (nfc.clf.Target) – The current local or remote communication target. Returns: Maximum number of data bytes supported for sending. Return type: int
-
get_max_recv_data_size
(target)¶ Returns the maximum number of data bytes for receiving.
The maximum number of data bytes acceptable for receiving with either
send_cmd_recv_rsp()
orsend_rsp_recv_cmd()
. The value reflects the local device capabilities for receiving in the mode determined by target. It does not relate to any protocol capabilities and negotiations.Parameters: target (nfc.clf.Target) – The current local or remote communication target. Returns: Maximum number of data bytes supported for receiving. Return type: int
-
send_cmd_recv_rsp
(target, data, timeout)¶ Exchange data with a remote Target
Sends command data to the remote target discovered in the most recent call to one of the sense_xxx() methods. Note that target becomes invalid with any call to mute(), sense_xxx() or listen_xxx()
Parameters: - target (nfc.clf.RemoteTarget) – The target returned by the last successful call of a sense_xxx() method.
- data (bytearray) – The binary data to send to the remote device.
- timeout (float) – The maximum number of seconds to wait for response data from the remote device.
Returns: Response data received from the remote device.
Return type: Raises: nfc.clf.CommunicationError
– When no data was received.
-
send_rsp_recv_cmd
(target, data, timeout)¶ Exchange data with a remote Initiator
Sends response data as the local target being discovered in the most recent call to one of the listen_xxx() methods. Note that target becomes invalid with any call to mute(), sense_xxx() or listen_xxx()
Parameters: - target (nfc.clf.LocalTarget) – The target returned by the last successful call of a listen_xxx() method.
- data (bytearray) – The binary data to send to the remote device.
- timeout (float) – The maximum number of seconds to wait for command data from the remote device.
Returns: Command data received from the remote device.
Return type: Raises: nfc.clf.CommunicationError
– When no data was received.
-
pn531¶
Driver module for contactless devices based on the NXP PN531 chipset. This was once a (sort of) joint development between Philips and Sony to supply hardware capable of running the ISO/IEC 18092 Data Exchange Protocol. The chip has selectable UART, I2C, SPI, or USB host interfaces, For USB the vendor and product ID can be switched by a hardware pin to either Philips or Sony.
The internal chipset architecture comprises a small 8-bit MCU and a Contactless Interface Unit CIU that is basically a PN511. The CIU implements the analog and digital part of communication (modulation and framing) while the MCU handles the protocol parts and host communication. The PN511 and hence the PN531 does not support Type B Technology and can not handle the specific Jewel/Topaz (Type 1 Tag) communication. Compared to PN532/PN533 the host frame structure does not allow maximum size ISO/IEC 18092 packets to be transferred. The driver handles this restriction by modifying the initialization commands (ATR, PSL) when needed.
function | support | remarks |
---|---|---|
sense_tta | yes | Type 1 Tag is not supported |
sense_ttb | no | |
sense_ttf | yes | |
sense_dep | yes | Reduced transport data byte length (max 192) |
listen_tta | yes | |
listen_ttb | no | |
listen_ttf | yes | Maximimum frame size is 64 byte |
listen_dep | yes |
-
class
nfc.clf.pn531.
Device
(chipset, logger)¶ Bases:
nfc.clf.pn53x.Device
-
sense_tta
(target)¶ Activate the RF field and probe for a Type A Target.
The PN531 can discover some Type A Targets (Type 2 Tag and Type 4A Tag) at 106 kbps. Type 1 Tags (Jewel/Topaz) are completely unsupported. Because the firmware does not evaluate the SENS_RES before sending SDD_REQ, it may be that a warning message about missing Type 1 Tag support is logged even if a Type 2 or 4A Tag was present. This typically happens when the SDD_RES or SEL_RES are lost due to communication errors (normally when the tag is moved away).
-
sense_ttb
(target)¶ Sense for a Type B Target is not supported.
-
sense_ttf
(target)¶ Activate the RF field and probe for a Type F Target.
-
sense_dep
(target)¶ Search for a DEP Target in active communication mode.
Because the PN531 does not implement the extended frame syntax for host controller communication, it can not support the maximum payload size of 254 byte. The driver handles this by modifying the length-reduction values in atr_req and atr_res.
-
listen_tta
(target, timeout)¶ Listen timeout seconds for a Type A activation at 106 kbps. The
sens_res
,sdd_res
, andsel_res
response data must be provided andsdd_res
must be a 4 byte UID that starts with08h
. Depending onsel_res
an activation may return a target with att2_cmd
,tt4_cmd
oratr_req
attribute. The default RATS response sent for a Type 4 Tag activation can be replaced with arats_res
attribute.
-
listen_ttb
(target, timeout)¶ Listen as Type B Target is not supported.
-
listen_ttf
(target, timeout)¶ Listen timeout seconds for a Type F card activation. The target
brty
must be set to either 212F or 424F andsensf_res
provide 19 byte response data (response code + 8 byte IDm + 8 byte PMm + 2 byte system code). Note that the maximum command an response frame length is 64 bytes only (including the frame length byte), because the driver must directly program the contactless interface unit within the PN533.
-
listen_dep
(target, timeout)¶ Listen timeout seconds to become initialized as a DEP Target.
The PN531 can be set to listen as a DEP Target for passive and active communication mode.
-
pn532¶
Driver module for contactless devices based on the NXP PN532 chipset. This successor of the PN531 can additionally handle Type B Technology (type 4B Tags) and Type 1 Tag communication. It also supports an extended frame syntax for host communication that allows larger packets to be transferred. The chip has selectable UART, I2C or SPI host interfaces. A speciality of the PN532 is that it can manage two targets (cards) simultanously, although this is not used by nfcpy.
The internal chipset architecture comprises a small 8-bit MCU and a Contactless Interface Unit CIU that is basically a PN512. The CIU implements the analog and digital part of communication (modulation and framing) while the MCU handles the protocol parts and host communication. Almost all PN532 firmware limitations (or bugs) can be avoided by directly programming the CIU. Type F Target mode for card emulation is completely implemented with the CIU and limited to 64 byte frame exchanges by the CIU’s FIFO size. Type B Target mode is not possible.
function | support | remarks |
---|---|---|
sense_tta | yes | |
sense_ttb | yes | |
sense_ttf | yes | |
sense_dep | yes | |
listen_tta | yes | |
listen_ttb | no | |
listen_ttf | yes | Maximimum frame size is 64 byte |
listen_dep | yes |
-
class
nfc.clf.pn532.
Device
(chipset, logger)¶ Bases:
nfc.clf.pn53x.Device
-
sense_tta
(target)¶ Search for a Type A Target.
The PN532 can discover all kinds of Type A Targets (Type 1 Tag, Type 2 Tag, and Type 4A Tag) at 106 kbps.
-
sense_ttb
(target)¶ Search for a Type B Target.
The PN532 can discover Type B Targets (Type 4B Tag) at 106 kbps. For a Type 4B Tag the firmware automatically sends an ATTRIB command that configures the use of DID and 64 byte maximum frame size. The driver reverts this configuration with a DESELECT and WUPB command to return the target prepared for activation (which nfcpy does in the tag activation code).
-
sense_ttf
(target)¶ Search for a Type F Target.
The PN532 can discover Type F Targets (Type 3 Tag) at 212 and 424 kbps. The driver uses the default polling command
06FFFF0000
if notarget.sens_req
is supplied.
-
sense_dep
(target)¶ Search for a DEP Target in active communication mode.
-
listen_tta
(target, timeout)¶ Listen timeout seconds for a Type A activation at 106 kbps. The
sens_res
,sdd_res
, andsel_res
response data must be provided andsdd_res
must be a 4 byte UID that starts with08h
. Depending onsel_res
an activation may return a target with att2_cmd
,tt4_cmd
oratr_req
attribute. The default RATS response sent for a Type 4 Tag activation can be replaced with arats_res
attribute.
-
listen_ttb
(target, timeout)¶ Listen as Type B Target is not supported.
-
listen_ttf
(target, timeout)¶ Listen timeout seconds for a Type F card activation. The target
brty
must be set to either 212F or 424F andsensf_res
provide 19 byte response data (response code + 8 byte IDm + 8 byte PMm + 2 byte system code). Note that the maximum command an response frame length is 64 bytes only (including the frame length byte), because the driver must directly program the contactless interface unit within the PN533.
-
listen_dep
(target, timeout)¶ Listen timeout seconds to become initialized as a DEP Target.
The PN532 can be set to listen as a DEP Target for passive and active communication mode.
-
pn533¶
Driver module for contactless devices based on the NXP PN533 chipset. The PN533 is pretty similar to the PN532 except that it also has a USB host interface option and, probably due to the resources needed for USB, does not support two simultaneous targets. Anything else said about PN532 also applies to PN533.
function | support | remarks |
---|---|---|
sense_tta | yes | |
sense_ttb | yes | |
sense_ttf | yes | |
sense_dep | yes | |
listen_tta | yes | |
listen_ttb | no | |
listen_ttf | yes | Maximimum frame size is 64 byte |
listen_dep | yes |
-
class
nfc.clf.pn533.
Device
(chipset, logger)¶ Bases:
nfc.clf.pn53x.Device
-
sense_tta
(target)¶ Activate the RF field and probe for a Type A Target.
The PN533 can discover all kinds of Type A Targets (Type 1 Tag, Type 2 Tag, and Type 4A Tag) at 106 kbps.
-
sense_ttb
(target)¶ Activate the RF field and probe for a Type B Target.
The PN533 can discover Type B Targets (Type 4B Tag) at 106, 212, 424, and 848 kbps. The PN533 automatically sends an ATTRIB command that configures a 64 byte maximum frame size. The driver reverts this configuration with a DESELECT and WUPB command to return the target prepared for activation.
-
sense_ttf
(target)¶ Activate the RF field and probe for a Type F Target.
The PN533 can discover Type F Targets (Type 3 Tag) at 212 and 424 kbps.
-
sense_dep
(target)¶ Search for a DEP Target in active communication mode.
-
send_cmd_recv_rsp
(target, data, timeout)¶ Send command data to the remote target and return the response data if received within timeout seconds.
-
listen_tta
(target, timeout)¶ Listen timeout seconds for a Type A activation at 106 kbps. The
sens_res
,sdd_res
, andsel_res
response data must be provided andsdd_res
must be a 4 byte UID that starts with08h
. Depending onsel_res
an activation may return a target with att2_cmd
,tt4_cmd
oratr_req
attribute. The default RATS response sent for a Type 4 Tag activation can be replaced with arats_res
attribute.
-
listen_ttb
(target, timeout)¶ Listen as Type B Target is not supported.
-
listen_ttf
(target, timeout)¶ Listen timeout seconds for a Type F card activation. The target
brty
must be set to either 212F or 424F andsensf_res
provide 19 byte response data (response code + 8 byte IDm + 8 byte PMm + 2 byte system code). Note that the maximum command an response frame length is 64 bytes only (including the frame length byte), because the driver must directly program the contactless interface unit within the PN533.
-
listen_dep
(target, timeout)¶ Listen timeout seconds to become initialized as a DEP Target.
The PN533 can be set to listen as a DEP Target for passive and active communication mode.
-
send_rsp_recv_cmd
(target, data, timeout)¶ While operating as target send response data to the remote device and return new command data if received within timeout seconds.
-
rcs956¶
Driver for contacless devices based on the Sony RC-S956 chipset. Products known to use this chipset are the PaSoRi RC-S330, RC-S360, and RC-S370. The RC-S956 connects to the host as a native USB device.
The RC-S956 has the same hardware architecture as the NXP PN53x family, i.e. it has a PN512 Contactless Interface Unit (CIU) coupled with a 80C51 microcontroller and uses the same frame structure for host communication and mostly the same commands. However, the firmware that runs on the 80C51 is different and the most notable difference is a much stricter state machine. The state machine restricts allowed commands to certain modes. While direct access to the CIU registers is possible, some of the things that can be done with a PN53x are unfortunately prevented by the stricter state machine.
function | support | remarks |
---|---|---|
sense_tta | yes | Only Type 1 Tags up to 128 byte (Topaz-96) |
sense_ttb | yes | ATTRIB by firmware voided with S(DESELECT) |
sense_ttf | yes | |
sense_dep | yes | |
listen_tta | yes | Only DEP and Type 2 Target |
listen_ttb | no | |
listen_ttf | no | |
listen_dep | yes | Only passive communication mode |
-
class
nfc.clf.rcs956.
Device
(chipset, logger)¶ Bases:
nfc.clf.pn53x.Device
-
mute
()¶ Mutes all existing communication, most notably the device will no longer generate a 13.56 MHz carrier signal when operating as Initiator.
-
sense_tta
(target)¶ Activate the RF field and probe for a Type A Target.
The RC-S956 can discover all Type A Targets (Type 1 Tag, Type 2 Tag, and Type 4A Tag) at 106 kbps. Due to firmware restrictions it is not possible to read a Type 1 Tag with dynamic memory layout (more than 128 byte memory).
-
sense_ttb
(target)¶ Activate the RF field and probe for a Type B Target.
The RC-S956 can discover Type B Targets (Type 4B Tag) at 106 kbps. For a Type 4B Tag the firmware automatically sends an ATTRIB command that configures the use of DID and 64 byte maximum frame size. The driver reverts this configuration with a DESELECT and WUPB command to return the target prepared for activation (which nfcpy does in the tag activation code).
-
sense_ttf
(target)¶ Activate the RF field and probe for a Type F Target.
-
sense_dep
(target)¶ Search for a DEP Target in active or passive communication mode.
-
listen_tta
(target, timeout)¶ Listen timeout seconds for a Type A activation at 106 kbps. The
sens_res
,sdd_res
, andsel_res
response data must be provided andsdd_res
must be a 4 byte UID that starts with08h
. Depending onsel_res
an activation may return a target withtt2_cmd
oratr_req
attribute. A Type 4A Tag activation is not supported.
-
listen_ttb
(target, timeout)¶ Listen as Type B Target is not supported.
-
listen_ttf
(target, timeout)¶ Listen as Type F Target is not supported.
-
listen_dep
(target, timeout)¶ Listen timeout seconds to become initialized as a DEP Target.
The RC-S956 can be set to listen as a DEP Target for passive communication mode. Target active communication mode is disabled by the driver due to performance issues. It is also not possible to fully control the ATR_RES response, only the response waiting time (TO byte of ATR_RES) and the general bytes can be set by the driver. Because the TO value must be set before calling the hardware listen function, it can not be different for the Type A of Type F passive initalization (the driver uses the higher value if they are different).
-
acr122¶
Device driver for the Arygon ACR122U contactless reader.
The Arygon ACR122U is a PC/SC compliant contactless reader that connects via USB and uses the USB CCID profile. It is normally intented to be used with a PC/SC stack but this driver interfaces directly with the inbuilt PN532 chipset by tunneling commands through the PC/SC Escape command. The driver is limited in functionality because the embedded microprocessor (that implements the PC/SC stack) also operates the PN532; it does not allow all commands to pass as desired and reacts on chip responses with its own (legitimate) interpretation of state.
function | support | remarks |
---|---|---|
sense_tta | yes | Type 1 (Topaz) Tags are not supported |
sense_ttb | yes | ATTRIB by firmware voided with S(DESELECT) |
sense_ttf | yes | |
sense_dep | yes | |
listen_tta | no | |
listen_ttb | no | |
listen_ttf | no | |
listen_dep | no |
-
class
nfc.clf.acr122.
Device
(chipset)¶ Bases:
nfc.clf.pn532.Device
-
sense_tta
(target)¶ Activate the RF field and probe for a Type A Target at 106 kbps. Other bitrates are not supported. Type 1 Tags are not supported because the device does not allow to send the correct RID command (even though the PN532 does).
-
sense_ttb
(target)¶ Activate the RF field and probe for a Type B Target.
The RC-S956 can discover Type B Targets (Type 4B Tag) at 106 kbps. For a Type 4B Tag the firmware automatically sends an ATTRIB command that configures the use of DID and 64 byte maximum frame size. The driver reverts this configuration with a DESELECT and WUPB command to return the target prepared for activation (which nfcpy does in the tag activation code).
-
sense_ttf
(target)¶ Activate the RF field and probe for a Type F Target. Bitrates 212 and 424 kpbs are supported.
-
sense_dep
(target)¶ Search for a DEP Target. Both passive and passive communication mode are supported.
-
listen_tta
(target, timeout)¶ Listen as Type A Target is not supported.
-
listen_ttb
(target, timeout)¶ Listen as Type B Target is not supported.
-
listen_ttf
(target, timeout)¶ Listen as Type F Target is not supported.
-
listen_dep
(target, timeout)¶ Listen as DEP Target is not supported.
-
turn_on_led_and_buzzer
()¶ Buzz and turn red.
-
turn_off_led_and_buzzer
()¶ Back to green.
-
udp¶
Driver module for simulated contactless communication over
UDP/IP. It can be activated with the device path udp:<host>:<port>
where the optional host may be the IP address or name of the node
where the targeted communication partner is listening on port. The
default values for host and port are localhost:54321
.
The driver implements almost all communication modes, with the current exception of active communication mode data exchange protocol.
function | support | remarks |
---|---|---|
sense_tta | yes | |
sense_ttb | yes | |
sense_ttf | yes | |
sense_dep | no | |
listen_tta | yes | |
listen_ttb | yes | |
listen_ttf | yes | |
listen_dep | yes |
-
class
nfc.clf.udp.
Device
(host, port)¶ Bases:
nfc.clf.device.Device
-
mute
()¶ Mutes all existing communication, most notably the device will no longer generate a 13.56 MHz carrier signal when operating as Initiator.
-
sense_tta
(target)¶ Discover a Type A Target.
Activates the 13.56 MHz carrier signal and sends a SENS_REQ command at the bitrate set by target.brty. If a response is received, sends an RID_CMD for a Type 1 Tag or SDD_REQ and SEL_REQ for a Type 2/4 Tag and returns the responses.
Parameters: target (nfc.clf.RemoteTarget) – Supplies bitrate and optional command data for the target discovery. The only sensible command to set is sel_req populated with a UID to find only that specific target. Returns: - Response data received from a remote
- target if found. This includes at least sens_res and either rid_res (for a Type 1 Tag) or sdd_res and sel_res (for a Type 2/4 Tag).
Return type: nfc.clf.RemoteTarget Raises: nfc.clf.UnsupportedTargetError
– The method is not supported or the target argument requested an unsupported bitrate (or has a wrong technology type identifier).
-
sense_ttb
(target)¶ Discover a Type B Target.
Activates the 13.56 MHz carrier signal and sends a SENSB_REQ command at the bitrate set by target.brty. If a SENSB_RES is received, returns a target object with the sensb_res attribute.
Note that the firmware of some devices (least all those based on PN53x) automatically sends an ATTRIB command with varying but always unfortunate communication settings. The drivers correct that situation by sending S(DESELECT) and WUPB before return.
Parameters: target (nfc.clf.RemoteTarget) – Supplies bitrate and the optional sensb_req for target discovery. Most drivers do no not allow a fully customized SENSB_REQ, the only parameter that can always be changed is the AFI byte, others may be ignored. Returns: - Response data received from a remote
- target if found. The only response data attribute is sensb_res.
Return type: nfc.clf.RemoteTarget Raises: nfc.clf.UnsupportedTargetError
– The method is not supported or the target argument requested an unsupported bitrate (or has a wrong technology type identifier).
-
sense_ttf
(target)¶ Discover a Type F Target.
Activates the 13.56 MHz carrier signal and sends a SENSF_REQ command at the bitrate set by target.brty. If a SENSF_RES is received, returns a target object with the sensf_res attribute.
Parameters: target (nfc.clf.RemoteTarget) – Supplies bitrate and the optional sensf_req for target discovery. The default SENSF_REQ invites all targets to respond and requests the system code information bytes. Returns: - Response data received from a remote
- target if found. The only response data attribute is sensf_res.
Return type: nfc.clf.RemoteTarget Raises: nfc.clf.UnsupportedTargetError
– The method is not supported or the target argument requested an unsupported bitrate (or has a wrong technology type identifier).
-
sense_dep
(target)¶ Discover a NFC-DEP Target in active communication mode.
Activates the 13.56 MHz carrier signal and sends an ATR_REQ command at the bitrate set by target.brty. If an ATR_RES is received, returns a target object with the atr_res attribute.
Note that some drivers (like pn531) may modify the transport data bytes length reduction value in ATR_REQ and ATR_RES due to hardware limitations.
Parameters: target (nfc.clf.RemoteTarget) – Supplies bitrate and the mandatory atr_req for target discovery. The bitrate may be one of ‘106A’, ‘212F’, or ‘424F’. Returns: - Response data received from a remote
- target if found. The only response data attribute is atr_res. The actually sent and potentially modified ATR_REQ is also included as atr_req attribute.
Return type: nfc.clf.RemoteTarget Raises: nfc.clf.UnsupportedTargetError
– The method is not supported or the target argument requested an unsupported bitrate (or has a wrong technology type identifier).
-
listen_tta
(target, timeout)¶ Listen as Type A Target.
Waits to receive a SENS_REQ command at the bitrate set by target.brty and sends the target.sens_res response. Depending on the SENS_RES bytes, the Initiator then sends an RID_CMD (SENS_RES coded for a Type 1 Tag) or SDD_REQ and SEL_REQ (SENS_RES coded for a Type 2/4 Tag). Responses are then generated from the rid_res or sdd_res and sel_res attributes in target.
Note that none of the currently supported hardware can actually receive an RID_CMD, thus Type 1 Tag emulation is impossible.
Parameters: - target (nfc.clf.LocalTarget) – Supplies bitrate and mandatory response data to reply when being discovered.
- timeout (float) – The maximum number of seconds to wait for a discovery command.
Returns: - Command data received from the remote
Initiator if being discovered and to the extent supported by the device. The first command received after discovery is returned as one of the tt1_cmd, tt2_cmd or tt4_cmd attribute (note that unset attributes are always None).
Return type: Raises: nfc.clf.UnsupportedTargetError
– The method is not supported or the target argument requested an unsupported bitrate (or has a wrong technology type identifier).ValueError
– A required target response attribute is not present or does not supply the number of bytes expected.
-
listen_ttb
(target, timeout)¶ Listen as Type A Target.
Waits to receive a SENSB_REQ command at the bitrate set by target.brty and sends the target.sensb_res response.
Note that none of the currently supported hardware can actually listen as Type B target.
Parameters: - target (nfc.clf.LocalTarget) – Supplies bitrate and mandatory response data to reply when being discovered.
- timeout (float) – The maximum number of seconds to wait for a discovery command.
Returns: - Command data received from the remote
Initiator if being discovered and to the extent supported by the device. The first command received after discovery is returned as tt4_cmd attribute.
Return type: Raises: nfc.clf.UnsupportedTargetError
– The method is not supported or the target argument requested an unsupported bitrate (or has a wrong technology type identifier).ValueError
– A required target response attribute is not present or does not supply the number of bytes expected.
-
listen_ttf
(target, timeout)¶ Listen as Type A Target.
Waits to receive a SENSF_REQ command at the bitrate set by target.brty and sends the target.sensf_res response. Then waits for a first command that is not a SENSF_REQ and returns this as the tt3_cmd attribute.
Parameters: - target (nfc.clf.LocalTarget) – Supplies bitrate and mandatory response data to reply when being discovered.
- timeout (float) – The maximum number of seconds to wait for a discovery command.
Returns: - Command data received from the remote
Initiator if being discovered and to the extent supported by the device. The first command received after discovery is returned as tt3_cmd attribute.
Return type: Raises: nfc.clf.UnsupportedTargetError
– The method is not supported or the target argument requested an unsupported bitrate (or has a wrong technology type identifier).ValueError
– A required target response attribute is not present or does not supply the number of bytes expected.
-
listen_dep
(target, timeout)¶ Listen as NFC-DEP Target.
Waits to receive an ATR_REQ (if the local device supports active communication mode) or a Type A or F Target activation followed by an ATR_REQ in passive communication mode. The ATR_REQ is replied with target.atr_res. The first DEP_REQ command is returned as the dep_req attribute along with atr_req and atr_res. The psl_req and psl_res attributes are returned when the has Initiator performed a parameter selection. The sens_res or sensf_res attributes are returned when activation was in passive communication mode.
Parameters: - target (nfc.clf.LocalTarget) – Supplies mandatory response data to reply when being discovered. All of sens_res, sdd_res, sel_res, sensf_res, and atr_res must be provided. The bitrate does not need to be set, an NFC-DEP Target always accepts discovery at ‘106A’, ‘212F and ‘424F’.
- timeout (float) – The maximum number of seconds to wait for a discovery command.
Returns: - Command data received from the remote
Initiator if being discovered and to the extent supported by the device. The first command received after discovery is returned as dep_req attribute.
Return type: Raises: nfc.clf.UnsupportedTargetError
– The method is not supported by the local hardware.ValueError
– A required target response attribute is not present or does not supply the number of bytes expected.
-
send_cmd_recv_rsp
(target, data, timeout)¶ Exchange data with a remote Target
Sends command data to the remote target discovered in the most recent call to one of the sense_xxx() methods. Note that target becomes invalid with any call to mute(), sense_xxx() or listen_xxx()
Parameters: - target (nfc.clf.RemoteTarget) – The target returned by the last successful call of a sense_xxx() method.
- data (bytearray) – The binary data to send to the remote device.
- timeout (float) – The maximum number of seconds to wait for response data from the remote device.
Returns: Response data received from the remote device.
Return type: Raises: nfc.clf.CommunicationError
– When no data was received.
-
send_rsp_recv_cmd
(target, data, timeout)¶ Exchange data with a remote Initiator
Sends response data as the local target being discovered in the most recent call to one of the listen_xxx() methods. Note that target becomes invalid with any call to mute(), sense_xxx() or listen_xxx()
Parameters: - target (nfc.clf.LocalTarget) – The target returned by the last successful call of a listen_xxx() method.
- data (bytearray) – The binary data to send to the remote device.
- timeout (float) – The maximum number of seconds to wait for command data from the remote device.
Returns: Command data received from the remote device.
Return type: Raises: nfc.clf.CommunicationError
– When no data was received.
-
get_max_send_data_size
(target)¶ Returns the maximum number of data bytes for sending.
The maximum number of data bytes acceptable for sending with either
send_cmd_recv_rsp()
orsend_rsp_recv_cmd()
. The value reflects the local device capabilities for sending in the mode determined by target. It does not relate to any protocol capabilities and negotiations.Parameters: target (nfc.clf.Target) – The current local or remote communication target. Returns: Maximum number of data bytes supported for sending. Return type: int
-
get_max_recv_data_size
(target)¶ Returns the maximum number of data bytes for receiving.
The maximum number of data bytes acceptable for receiving with either
send_cmd_recv_rsp()
orsend_rsp_recv_cmd()
. The value reflects the local device capabilities for receiving in the mode determined by target. It does not relate to any protocol capabilities and negotiations.Parameters: target (nfc.clf.Target) – The current local or remote communication target. Returns: Maximum number of data bytes supported for receiving. Return type: int
-