This article is mainly based on “Flying book” small program, compatible with “wechat” small program, if you have not known “flying book” students, you can click here to learn about the official website

What is the NFC

Near-field communication (NFC), also known as Near field communication or Near field communication, is a communication protocol that allows two electronic devices (one of which is usually a mobile device, such as a smartphone) to communicate within a few centimeters of each other.

Near field communication technology evolved from contactless radio frequency identification (RFID), developed by Philips Semiconductor (now NXP Semiconductor, abbreviation OF NXP), Nokia and SONY in 2004, based on RFID and interconnection technology. Near field communication (NFC) is a short-range, high-frequency radio technology operating at 13.56MHz over a distance of 20 cm. The transmission speed is 106 Kbit/ s, 212 Kbit/ s or 424 Kbit/ s.

In fact, I have been paying attention to NFC since its birth, but not only there are few applications, but also few devices. Xiaomi even has the magical situation that the previous generation carries NFC but the next generation does not. In addition, it is also very complicated to use. At the beginning, if you want to use NFC to swipe the bus card, you need to change a special SIM card to be able to support it.

At present, with the unremitting efforts of Android manufacturers, the installation rate of both applications and devices has been gradually popularized. From the original NFC can scan the bank card in Alipay and input the card number quickly, to the current bus card swiping, X Pay, and even file transfer, Huawei has even changed the name of this thing called Yiping System.

In addition, it can also promote the development of intelligence. For example, when a new device is added to your home network, you can simply scan the NFC id on the device and add it to your home network without the cumbersome networking process. Or a touch on a Huawei router to connect to Wifi is a great application, I think. When a guest comes to the house, there is no longer a need for a person to enter the password.

NFC technology overview

The operation mode

There are three main operating modes of NFC: Card Emulation Mode, Host Emulation Mode, Reader/Writer Mode, and P2P Mode.

Card simulation mode

  • NFC phone can be simulated as a contactless card, powered by the RF of POS machine (contactless card reader), even if the NFC phone is out of power.
  • Now common keys such as Apple Pay and BYD NFC can be swiped in the case of power failure

Host simulation mode

  • This mode is very similar to the card simulation mode, except that card simulation can be done without power supply or without the participation of the App, but not the host simulation mode. It is by forwarding all the messages to the App, and the App decides what to simulate, that is, what to return
  • At present, many payment wallets, such as cloud flash payment, jingdong flash payment and so on, are realized through this mode.

Read card write card mode

  • The NFC mobile phone can read the content of the contact-free Tag by touching the NFC Tag, collect data and send it to the corresponding application for processing.
  • In fact, the most common application is Huawei’s Yipan series. In addition, Alipay can directly read the card numbers of credit cards and savings cards.

P2P model

  • Two NFC devices can be connected to each other in a close distance and directly transfer data to achieve point-to-point data transmission.
  • For example, assist in setting up bluetooth connections quickly, exchanging mobile phone business cards and data communication.
  • The most common ones are phone to phone, Android Beam.

Protocol standard Type

Because of the development process of NFC, there have been multiple protocols, and even each company has different protocol content. But now there are mainly a few protocol standards:

ISO / IEC

The following protocols are mainly defined:

  • ISO/IEC 18092 / ECMA-340 — (NFCIP-1)

    Near Field Communication Interface and Protocol-1

  • ISO/IEC 21481 / ECMA-352 — (NFCIP-2)

    Near Field Communication Interface and Protocol-2

In addition, there is a protocol standard is very commonly used, isO-14443 protocol, in fact, this protocol is the RFID protocol, and the only difference is that the above is more than some other mode of the standard, such as point-to-point mode.

The ISO-14443 protocol has two subclasses, type-A and Type-b, which are also known as NFC-A and NFC-B on Android.

Unfortunately, these agreements are not free to read. They cost money

NFC Forum

The NFC Forum is a non-profit industry association created in 2004 with members from all parts of the NFC ecosystem. In addition, I mainly pay attention to domestic companies, such as Xiaomi and China Mobile.

But if you want to get any NFC related technical standards from the organization, your company has to be a member of the organization first, because byte is not in the organization at all, so there is no way to get first-hand information from it.

However, there are ways to do this. The website of NXP, the founder of the association, has relevant data resources, which are referred to in the following article.

other

No need to worry. JPG

Communication protocol

NFC – A, for example

The whole NFC card is actually a finite state machine inside, according to the current different states need different operations. The diagram looks complicated, but it basically contains two additional operations:

  • Password checking
    • The NFC card is encrypted, and only after the password is verified can relevant operations be carried out.
    • In particular, NFC passwords are a fixed length of 32 bits, 4 bytes.
  • anti-collision
    • The reason for this design is that multiple NFC devices may be detected at the same time in the process of use. At this time, the two states of READY1/READY2 are needed to select the correct NFC device for operation.
    • Each card has a unique UID that is 7 bytes long, and you can only select 4 bytes per operation, so you have to split it into two states and two steps.

In the absence of the above two operations, the state flow of IDLE -> ACTIVE -> HALT can simply be performed, that is, connect, operate (read and write), and close.

Store design

NFC designs the concept of a page on storage, where a page represents four bytes and operates in the smallest unit. So the storage capacity of NFC cards is actually an integer multiple of 4.

Here, the 180-byte storage structure of NTAG213 is used as an example

There are only two points to note here:

  • The space for storing user data starts on page 4
  • There’s only 144 bytes of user-available storage

Just keep these two things in mind. When developing NFC requirements, don’t modify non-user space data and don’t store things that are too long.

Equipment preparation

With this foundation in place, don’t worry you can’t start developing NFC because you’re still missing one crucial thing, equipment

Unfortunately, not all devices come with NFC hardware, and that doesn’t mean they will work

  • Apple devices have to be upgraded to iOS 13 or higher to have the ability to develop NFC card readers, not write, and there are few other NFC capabilities available. The ring will also be called the neutered VERSION of NFC. (I don’t have the ability to investigate NFC capability for the time being. It must be hardware support or just software limitation.)
  • Android devices can theoretically use almost all of the NFC capabilities, known as full-featured NFC, including card reading, card writing, card emulation, P2P and other modes. However, different phones have different operating system limitations, so choose a suitable operating system (native Android, native Android is the most recommended).

So get an Android phone ready!

NFC card

After having the equipment, it is necessary to choose the right NFC card, because not any NFC card can be used, such as work card, bank card and so on. This is because NFC cards are encrypted and must be verified before operation. Therefore, it is recommended to buy some readable and writable NFC stickers without encryption on Taobao for testing.

However, what you buy on Taobao may be the model with the name NTAG213 written on it. In fact, it is A device from NXP, but it supports ISO NFC-A protocol and NFC Forum Type 2 protocol, so you can rest assured to use it.

Of course, you might also see NTAG215/NTAG216, which are no different, just different storage space.

Small application API

At this time in the above basic knowledge, don’t worry, but also to understand the small program API to better development.

For now, all NFC-related operations are encapsulated in the NfcAdaptar class, which gets the nfcAfaptar object via tt.getnfcadaptar ().

Please refer to “Feishu Open Platform” for details of API parameters.

Overall NFC process

  • Register the NFC discovery event callbacknfcAdaptar.onDiscovered
  • Enable NFC scanningnfcAdaptar.startDiscovered
  • The NFC card is close to the device
  • Triggers a callback to obtain the protocol supported by the NFC
    • The TEChs field in the callback parameter can be used to determine the protocol supported by the current card
  • Read and write the NFC card content according to the protocolnfcAdaptar.getNfcA()
  • Disable NFC scanning and event listeningnfcAdaptar.offDiscovered / nfcAdaptar.stopDiscovered()

You can find this process very easy to understand and very easy to follow. So let’s move on to the highlight

Read and write NFC cards

The NFC-A protocol is used

Use nfcadaptar.getnfca () to obtain the nfCA instance of the operation NFC-A card

  • Connection cardnfca.connect()
  • Read and write CARDSnfca.transceive()
  • Close the connection after reading and writingnfca.close()

The key point is that NFC cards do not read and write like other IO devices. There are special read and write functions. For THE NFC, different instructions are sent to the NFC card to accomplish different operations.

These instructions are written in the NTAG213 document. Here is a brief list of the commonly used data

The command code function parameter
Read 0x30 Read four pages of data at a time Addr:1B
Write 0xA2 Write data one page at a time Addr:1B Data:4B
Fast Read 0x3A Read multiple pages of data at once StartAddr:1B StopAddr:1B

For example, if I want to read the data on page 4, I can write the following code

nfca.transceive({
    data: new Uint8Array([0x30.0x04]).buffer, // ArrayBuffer must be passed in
    success: (res) = > {
        // Res. data is an ArrayBuffer, which can be converted into an array for easy viewing
        console.log(Array.from(new Uint8Array(res.data))
    }
})
Copy the code

According to the protocol, <CRC:2B>, also known as the check bit, is passed, but this operation is already done by Android, so there is no need to pass, and no need to understand the check algorithm

conclusion

At this point, NFC development is kind of a primer, but it’s important to note that different NFC cards and different protocols have different ways of reading and writing, depending on your particular card. And some of them are password protected and require additional verification logic.

Refs

  • Introduction to NFC – CSDN
  • Difference between ISO 14443 and ISO 18092, i.e. RFID vs NFC
  • NTAG213 protocol document