Warning

This section contains snippets that were automatically translated from C++ to Python and may contain errors.

Annotated URL#

The example shows reading from formatted NFC Data Exchange Format (NDEF) messages.

The Annotated URL example displays the contents of specifically formatted NFC Data Exchange Format (NDEF) messages read from an NFC Tag. The NDEF message should contain a URI record, an optional image/* MIME record, and one or more localized Text records.

This is the initial state of the example:

../_images/annotatedurl.png

In this example the NFC Tag used contains a text record and an URI record. The UI gets updated accordingly to:

../_images/annotatedurl2.png

When the screen is tapped, the URL will be opened in the browser.

AnnotatedUrl Class Definition#

The AnnotatedUrl class wraps QNearFieldManager , the class providing the NFC Tag detection functionality. NDEF messages are read by QNearFieldManager and forwarded to a handler contained in the AnnotatedUrl class. After parsing the NDEF message the class emits the annotatedUrl() signal. The UI reacts to the signal displaying the contents of the NDEF message.

class AnnotatedUrl(QObject):

    Q_OBJECT
# public
    AnnotatedUrl = explicit(QObject parent = 0)
    ~AnnotatedUrl()
    def startDetection():
# signals
    def annotatedUrl(url, title, pixmap):
    def nfcStateChanged(enabled):
    def tagError(error):
# public slots
    def targetDetected(target):
    def targetLost(target):
    def handleMessage(message, target):
    def handlePolledNdefMessage(message):
    def handleAdapterStateChange(state):
# private
    manager = QNearFieldManager()
    messageFilter = QNdefFilter()

Note

The startDetection() method is used to defer the actual tag detection until all the connections between the UI and NFC-related logic are established. This is important when the application is automatically started once an NFC tag is touched. Such usecase is currently supported on Android.

if __name__ == "__main__":

    a = QApplication(argc, argv)
    mainWindow = MainWindow()
    annotatedUrl = AnnotatedUrl()
    annotatedUrl.annotatedUrl.connect(
                     mainWindow.displayAnnotatedUrl)
    annotatedUrl.nfcStateChanged.connect(
                     mainWindow.nfcStateChanged)
    annotatedUrl.tagError.connect(
                     mainWindow.showTagError)
    annotatedUrl.startDetection()
    mainWindow.show()
    return a.exec()

Message Filtering#

As it is mentioned above, the application supports the NDEF messages of a specific format. A correct message should contain the following fields:

  • At least one NDEF Text record, which will be used as a header.

  • Exactly one NDEF URI record.

  • An optional MIME record with an icon.

The order of the records is not strictly specified.

An instance of QNdefFilter is used to validate the NDEF message. The filter is populated as follows:

messageFilter.setOrderMatch(False)
messageFilter.appendRecord<QNdefNfcTextRecord>(1, 100)
messageFilter.appendRecord<QNdefNfcUriRecord>(1, 1)
messageFilter.appendRecord(QNdefRecord.Mime, "", 0, 1)

If the incoming message does not match the filter, an error message is shown:

../_images/annotatedurl3.png

Note

The NDEF Editor example application can be used to create the tags with correct or incorrect message structure.

AnnotatedUrl Handler Implementation#

NFC messages read by the QNearFieldManager are forwarded to AnnotatedUrl::handleMessage.

def handleMessage(self, message, target):

At first the messages are validated using the match() method:

if not messageFilter.match(message):
    tagError.emit("Invalid message format")
    return

If the messages have the correct format, the parsing continues.

Because NFC messages are composed of several NDEF records, looping through all of the records allows the extraction of the 3 parameters to be displayed in the UI: the Uri, the Title and the Pixmap:

for record in message:
    if record.isRecordType<QNdefNfcTextRecord>():
        textRecord = QNdefNfcTextRecord(record)
        title = textRecord.text()
        locale = QLocale(textRecord.locale())
elif record.isRecordType<QNdefNfcUriRecord>():
   uriRecord = QNdefNfcUriRecord(record)
   url = uriRecord.uri()
elif (record.typeNameFormat() == QNdefRecord.Mime and
          record.type().startsWith("image/")) {
   pixmap = QPixmap.fromImage(QImage.fromData(record.payload()))

Finally after having extracted the parameters of the NFC message the corresponding signal is emitted so that the UI can handle it.

annotatedUrl.emit(url, title, pixmap)

Adapter State Handling#

On Android the adapter state changes can be detected by connecting to the adapterStateChanged() signal. This allows stopping the detection when the NFC adapter is disabled, and restarting it when the adapter is enabled again. This approach is implemented in the AnnotatedUrl::handleAdapterStateChange slot.

def handleAdapterStateChange(self, state):

    if state == QNearFieldManager.AdapterState.Online:
        startDetection()
     elif state == QNearFieldManager.AdapterState.Offline:
        manager.stopTargetDetection()
        nfcStateChanged.emit(False)

Automatic Application Startup#

Android supports automatic application startup when the NDEF tag is touched. See Qt NFC on Android for the required changes to the Android manifest file.

Introduction of a custom AndroidManifest.xml requires special steps on the build system side.

Building with qmake#

When using qmake, the following needs to be added to the .pro file:

Building with CMake#

When using CMake, the following needs to be added to the CMakeLists.txt:

Running the Example#

To run the example from Qt Creator, open the Welcome mode and select the example from Examples. For more information, visit Building and Running an Example.

See also

Qt NFC

Example project @ code.qt.io