Go - NFC Bricklet

This is the description of the Go API bindings for the NFC Bricklet. General information and technical specifications for the NFC Bricklet are summarized in its hardware description.

An installation guide for the Go API bindings is part of their general description. Additional documentation can be found on godoc.org.

Examples

The example code below is Public Domain (CC0 1.0).

Scan For Tags

Download (example_scan_for_tags.go)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package main

import (
    "fmt"
    "github.com/Tinkerforge/go-api-bindings/ipconnection"
    "github.com/Tinkerforge/go-api-bindings/nfc_bricklet"
)

const ADDR string = "localhost:4223"
const UID string = "XYZ" // Change XYZ to the UID of your NFC Bricklet.

func main() {
    ipcon := ipconnection.New()
    defer ipcon.Close()
    nfc, _ := nfc_bricklet.New(UID, &ipcon) // Create device object.

    ipcon.Connect(ADDR) // Connect to brickd.
    defer ipcon.Disconnect()
    // Don't use device before ipcon is connected.

    nfc.RegisterReaderStateChangedCallback(func(state nfc_bricklet.ReaderState, idle bool) {
        if state == nfc_bricklet.ReaderStateRequestTagIDReady {
            tagID, tagType, _ := nfc.ReaderGetTagID()
            fmt.Printf("Found tag of type %d with ID %v", tagType, tagID)
        } else if state == nfc_bricklet.ReaderStateRequestTagIDError {
            fmt.Println("Request tag ID error")
        }
        if idle {
            nfc.ReaderRequestTagID()
        }
    })

    // Enable reader mode
    nfc.SetMode(nfc_bricklet.ModeReader)

    fmt.Print("Press enter to exit.")
    fmt.Scanln()
}

Emulate Ndef

Download (example_emulate_ndef.go)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package main

import (
    "fmt"
    "github.com/Tinkerforge/go-api-bindings/ipconnection"
    "github.com/Tinkerforge/go-api-bindings/nfc_bricklet"
)

const ADDR string = "localhost:4223"
const UID string = "XYZ" // Change XYZ to the UID of your NFC Bricklet.
const NDEF_URI = "www.tinkerforge.com"

func main() {
    ipcon := ipconnection.New()
    defer ipcon.Close()
    nfc, _ := nfc_bricklet.New(UID, &ipcon) // Create device object.

    ipcon.Connect(ADDR) // Connect to brickd.
    defer ipcon.Disconnect()
    // Don't use device before ipcon is connected.

    nfc.RegisterCardemuStateChangedCallback(func(state nfc_bricklet.CardemuState, idle bool) {
        switch state {
        case nfc_bricklet.CardemuStateIdle:
            ndefRecordUDI := []uint8{0xd1, 0x01, uint8(len(NDEF_URI)) + 1, uint8('U'), 0x04}
            ndefRecordUDI = append(ndefRecordUDI, []byte(NDEF_URI)...)

            err := nfc.CardemuWriteNDEF(ndefRecordUDI)
            if err != nil {
                fmt.Printf("Error while writing ndef %s", err)
            }
            nfc.CardemuStartDiscovery()
        case nfc_bricklet.CardemuStateDiscoverReady:
            nfc.CardemuStartTransfer(nfc_bricklet.CardemuTransferWrite)
        case nfc_bricklet.CardemuStateDiscoverError:
            fmt.Println("Discover error")
        case nfc_bricklet.CardemuStateTransferNDEFError:
            fmt.Println("Transfer NDEF error")
        }
    })

    // Enable cardemu mode
    nfc.SetMode(nfc_bricklet.ModeCardemu)

    fmt.Print("Press enter to exit.")
    fmt.Scanln()
}

Write Read Type2

Download (example_write_read_type2.go)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package main

import (
    "fmt"
    "github.com/Tinkerforge/go-api-bindings/ipconnection"
    "github.com/Tinkerforge/go-api-bindings/nfc_bricklet"
)

const ADDR string = "localhost:4223"
const UID string = "XYZ" // Change XYZ to the UID of your NFC Bricklet.

func main() {
    ipcon := ipconnection.New()
    defer ipcon.Close()
    nfc, _ := nfc_bricklet.New(UID, &ipcon) // Create device object.

    ipcon.Connect(ADDR) // Connect to brickd.
    defer ipcon.Disconnect()
    // Don't use device before ipcon is connected.

    nfc.RegisterReaderStateChangedCallback(func(state nfc_bricklet.ReaderState, idle bool) {
        switch state {
        case nfc_bricklet.ReaderStateIdle:
            nfc.ReaderRequestTagID()
        case nfc_bricklet.ReaderStateRequestTagIDReady:
            tagID, tagType, _ := nfc.ReaderGetTagID()
            if tagType != nfc_bricklet.TagTypeType2 {
                fmt.Println("Tag is not type-2")
                return
            }

            fmt.Printf("Found tag of type %d with ID %v", tagType, tagID)
        case nfc_bricklet.ReaderStateRequestPageReady:
            page, _ := nfc.ReaderReadPage()
            fmt.Printf("Page read: % x", page)
            nfc.ReaderWritePage(1, page)
        case nfc_bricklet.ReaderStateWritePageReady:
            fmt.Println("Write page ready")
        case nfc_bricklet.ReaderStateRequestPageError:
            fmt.Println("Request page error")
        case nfc_bricklet.ReaderStateWritePageError:
            fmt.Println("Write page error")
        }
    })

    // Enable reader mode
    nfc.SetMode(nfc_bricklet.ModeReader)

    fmt.Print("Press enter to exit.")
    fmt.Scanln()
}

API

The NFC Bricklet's API is defined in the package github.com/Tinkerforge/go-api-bindings/nfc_bricklet

Nearly every function of the Go bindings can return an BrickletError, implementing the error interface. The error can have one of the following values:

  • BrickletErrorSuccess = 0
  • BrickletErrorInvalidParameter = 1
  • BrickletErrorFunctionNotSupported = 2
  • BrickletErrorUnknownError = 3

which correspond to the values returned from Bricks and Bricklets.

All functions listed below are thread-safe.

Basic Functions

func NewNFCBricklet(uid string, ipcon *IPConnection)(device NFCBricklet, err error)

Creates a new NFCBricklet object with the unique device ID uid and adds it to the IPConnection ipcon:

This device object can be used after the IP connection has been connected (see examples above).

func (*NFCBricklet)SetMode(mode Mode)(err error)

Sets the mode. The NFC Bricklet supports four modes:

  • Off
  • Card Emulation (Cardemu): Emulates a tag for other readers
  • Peer to Peer (P2P): Exchange data with other readers
  • Reader: Reads and writes tags

If you change a mode, the Bricklet will reconfigure the hardware for this mode. Therefore, you can only use functions corresponding to the current mode. For example, in Reader mode you can only use Reader functions.

The default mode is "off".

The following constants are available for this function:

  • ModeOff = 0
  • ModeCardemu = 1
  • ModeP2P = 2
  • ModeReader = 3
func (*NFCBricklet)GetMode()(mode Mode, err error)

Returns the mode as set by (*NFCBricklet) SetMode.

The following constants are available for this function:

  • ModeOff = 0
  • ModeCardemu = 1
  • ModeP2P = 2
  • ModeReader = 3
func (*NFCBricklet)ReaderRequestTagID()(err error)

To read or write a tag that is in proximity of the NFC Bricklet you first have to call this function with the expected tag type as parameter. It is no problem if you don't know the tag type. You can cycle through the available tag types until the tag answers the request.

Currently the following tag types are supported:

  • Mifare Classic
  • NFC Forum Type 1
  • NFC Forum Type 2
  • NFC Forum Type 3
  • NFC Forum Type 4

After you call (*NFCBricklet) ReaderRequestTagID the NFC Bricklet will try to read the tag ID from the tag. After this process is done the state will change. You can either register the (*NFCBricklet) RegisterReaderStateChangedCallback callback or you can poll (*NFCBricklet) ReaderGetState to find out about the state change.

If the state changes to ReaderRequestTagIDError it means that either there was no tag present or that the tag has an incompatible type. If the state changes to ReaderRequestTagIDReady it means that a compatible tag was found and that the tag ID has been saved. You can now read out the tag ID by calling (*NFCBricklet) ReaderGetTagID.

If two tags are in the proximity of the NFC Bricklet, this function will cycle through the tags. To select a specific tag you have to call (*NFCBricklet) ReaderRequestTagID until the correct tag ID is found.

In case of any ReaderError state the selection is lost and you have to start again by calling (*NFCBricklet) ReaderRequestTagID.

func (*NFCBricklet)ReaderGetTagID()(tagID []uint8, tagType TagType, err error)

Returns the tag type and the tag ID. This function can only be called if the NFC Bricklet is currently in one of the ReaderReady states. The returned tag ID is the tag ID that was saved through the last call of (*NFCBricklet) ReaderRequestTagID.

To get the tag ID of a tag the approach is as follows:

  1. Call (*NFCBricklet) ReaderRequestTagID
  2. Wait for state to change to ReaderRequestTagIDReady (see (*NFCBricklet) ReaderGetState or (*NFCBricklet) RegisterReaderStateChangedCallback callback)
  3. Call (*NFCBricklet) ReaderGetTagID

The following constants are available for this function:

  • TagTypeMifareClassic = 0
  • TagTypeType1 = 1
  • TagTypeType2 = 2
  • TagTypeType3 = 3
  • TagTypeType4 = 4
func (*NFCBricklet)ReaderGetState()(state ReaderState, idle bool, err error)

Returns the current reader state of the NFC Bricklet.

On startup the Bricklet will be in the ReaderInitialization state. The initialization will only take about 20ms. After that it changes to ReaderIdle.

The Bricklet is also reinitialized if the mode is changed, see (*NFCBricklet) SetMode.

The functions of this Bricklet can be called in the ReaderIdle state and all of the ReaderReady and ReaderError states.

Example: If you call (*NFCBricklet) ReaderRequestPage, the state will change to ReaderRequestPage until the reading of the page is finished. Then it will change to either ReaderRequestPageReady if it worked or to ReaderRequestPageError if it didn't. If the request worked you can get the page by calling (*NFCBricklet) ReaderReadPage.

The same approach is used analogously for the other API functions.

The following constants are available for this function:

  • ReaderStateInitialization = 0
  • ReaderStateIdle = 128
  • ReaderStateError = 192
  • ReaderStateRequestTagID = 2
  • ReaderStateRequestTagIDReady = 130
  • ReaderStateRequestTagIDError = 194
  • ReaderStateAuthenticateMifareClassicPage = 3
  • ReaderStateAuthenticateMifareClassicPageReady = 131
  • ReaderStateAuthenticateMifareClassicPageError = 195
  • ReaderStateWritePage = 4
  • ReaderStateWritePageReady = 132
  • ReaderStateWritePageError = 196
  • ReaderStateRequestPage = 5
  • ReaderStateRequestPageReady = 133
  • ReaderStateRequestPageError = 197
  • ReaderStateWriteNDEF = 6
  • ReaderStateWriteNDEFReady = 134
  • ReaderStateWriteNDEFError = 198
  • ReaderStateRequestNDEF = 7
  • ReaderStateRequestNDEFReady = 135
  • ReaderStateRequestNDEFError = 199
func (*NFCBricklet)ReaderWriteNDEF(ndef []uint8)(err error)

Writes NDEF formated data with a maximum of 255 bytes.

This function currently supports NFC Forum Type 2 and 4.

The general approach for writing a NDEF message is as follows:

  1. Call (*NFCBricklet) ReaderRequestTagID
  2. Wait for state to change to ReaderRequestTagIDReady (see (*NFCBricklet) ReaderGetState or (*NFCBricklet) RegisterReaderStateChangedCallback callback)
  3. If looking for a specific tag then call (*NFCBricklet) ReaderGetTagID and check if the expected tag was found, if it was not found got back to step 1
  4. Call (*NFCBricklet) ReaderWriteNDEF with the NDEF message that you want to write
  5. Wait for state to change to ReaderWriteNDEFReady (see (*NFCBricklet) ReaderGetState or (*NFCBricklet) RegisterReaderStateChangedCallback callback)
func (*NFCBricklet)ReaderRequestNDEF()(err error)

Reads NDEF formated data from a tag.

This function currently supports NFC Forum Type 1, 2, 3 and 4.

The general approach for reading a NDEF message is as follows:

  1. Call (*NFCBricklet) ReaderRequestTagID
  2. Wait for state to change to RequestTagIDReady (see (*NFCBricklet) ReaderGetState or (*NFCBricklet) RegisterReaderStateChangedCallback callback)
  3. If looking for a specific tag then call (*NFCBricklet) ReaderGetTagID and check if the expected tag was found, if it was not found got back to step 1
  4. Call (*NFCBricklet) ReaderRequestNDEF
  5. Wait for state to change to ReaderRequestNDEFReady (see (*NFCBricklet) ReaderGetState or (*NFCBricklet) RegisterReaderStateChangedCallback callback)
  6. Call (*NFCBricklet) ReaderReadNDEF to retrieve the NDEF message from the buffer
func (*NFCBricklet)ReaderReadNDEF()(ndef []uint8, err error)

Returns the NDEF data from an internal buffer. To fill the buffer with a NDEF message you have to call (*NFCBricklet) ReaderRequestNDEF beforehand.

The buffer can have a size of up to 8192 bytes.

func (*NFCBricklet)ReaderAuthenticateMifareClassicPage(page uint16, keyNumber Key, key [6]uint8)(err error)

Mifare Classic tags use authentication. If you want to read from or write to a Mifare Classic page you have to authenticate it beforehand. Each page can be authenticated with two keys: A (key_number = 0) and B (key_number = 1). A new Mifare Classic tag that has not yet been written to can be accessed with key A and the default key [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF].

The approach to read or write a Mifare Classic page is as follows:

  1. Call (*NFCBricklet) ReaderRequestTagID
  2. Wait for state to change to ReaderRequestTagIDReady (see (*NFCBricklet) ReaderGetState or (*NFCBricklet) RegisterReaderStateChangedCallback callback)
  3. If looking for a specific tag then call (*NFCBricklet) ReaderGetTagID and check if the expected tag was found, if it was not found got back to step 1
  4. Call (*NFCBricklet) ReaderAuthenticateMifareClassicPage with page and key for the page
  5. Wait for state to change to ReaderAuthenticatingMifareClassicPageReady (see (*NFCBricklet) ReaderGetState or (*NFCBricklet) RegisterReaderStateChangedCallback callback)
  6. Call (*NFCBricklet) ReaderRequestPage or (*NFCBricklet) ReaderWritePage to read/write page

The authentication will always work for one whole sector (4 pages).

The following constants are available for this function:

  • KeyA = 0
  • KeyB = 1
func (*NFCBricklet)ReaderWritePage(page ReaderWrite, data []uint8)(err error)

Writes a maximum of 8192 bytes starting from the given page. How many pages are written depends on the tag type. The page sizes are as follows:

  • Mifare Classic page size: 16 byte
  • NFC Forum Type 1 page size: 8 byte
  • NFC Forum Type 2 page size: 4 byte
  • NFC Forum Type 3 page size: 16 byte
  • NFC Forum Type 4: No pages, page = file selection (CC or NDEF, see below)

The general approach for writing to a tag is as follows:

  1. Call (*NFCBricklet) ReaderRequestTagID
  2. Wait for state to change to ReaderRequestTagIDReady (see (*NFCBricklet) ReaderGetState or (*NFCBricklet) RegisterReaderStateChangedCallback callback)
  3. If looking for a specific tag then call (*NFCBricklet) ReaderGetTagID and check if the expected tag was found, if it was not found got back to step 1
  4. Call (*NFCBricklet) ReaderWritePage with page number and data
  5. Wait for state to change to ReaderWritePageReady (see (*NFCBricklet) ReaderGetState or (*NFCBricklet) RegisterReaderStateChangedCallback callback)

If you use a Mifare Classic tag you have to authenticate a page before you can write to it. See (*NFCBricklet) ReaderAuthenticateMifareClassicPage.

NFC Forum Type 4 tags are not organized into pages but different files. We currently support two files: Capability Container file (CC) and NDEF file.

Choose CC by setting page to 3 or NDEF by setting page to 4.

The following constants are available for this function:

  • ReaderWriteType4CapabilityContainer = 3
  • ReaderWriteType4NDEF = 4
func (*NFCBricklet)ReaderRequestPage(page ReaderRequest, length uint16)(err error)

Reads a maximum of 8192 bytes starting from the given page and stores them into a buffer. The buffer can then be read out with (*NFCBricklet) ReaderReadPage. How many pages are read depends on the tag type. The page sizes are as follows:

  • Mifare Classic page size: 16 byte
  • NFC Forum Type 1 page size: 8 byte
  • NFC Forum Type 2 page size: 4 byte
  • NFC Forum Type 3 page size: 16 byte
  • NFC Forum Type 4: No pages, page = file selection (CC or NDEF, see below)

The general approach for reading a tag is as follows:

  1. Call (*NFCBricklet) ReaderRequestTagID
  2. Wait for state to change to RequestTagIDReady (see (*NFCBricklet) ReaderGetState or (*NFCBricklet) RegisterReaderStateChangedCallback callback)
  3. If looking for a specific tag then call (*NFCBricklet) ReaderGetTagID and check if the expected tag was found, if it was not found got back to step 1
  4. Call (*NFCBricklet) ReaderRequestPage with page number
  5. Wait for state to change to ReaderRequestPageReady (see (*NFCBricklet) ReaderGetState or (*NFCBricklet) RegisterReaderStateChangedCallback callback)
  6. Call (*NFCBricklet) ReaderReadPage to retrieve the page from the buffer

If you use a Mifare Classic tag you have to authenticate a page before you can read it. See (*NFCBricklet) ReaderAuthenticateMifareClassicPage.

NFC Forum Type 4 tags are not organized into pages but different files. We currently support two files: Capability Container file (CC) and NDEF file.

Choose CC by setting page to 3 or NDEF by setting page to 4.

The following constants are available for this function:

  • ReaderRequestType4CapabilityContainer = 3
  • ReaderRequestType4NDEF = 4
func (*NFCBricklet)ReaderReadPage()(data []uint8, err error)

Returns the page data from an internal buffer. To fill the buffer with specific pages you have to call (*NFCBricklet) ReaderRequestPage beforehand.

The buffer can have a size of up to 8192 bytes.

func (*NFCBricklet)CardemuGetState()(state CardemuState, idle bool, err error)

Returns the current cardemu state of the NFC Bricklet.

On startup the Bricklet will be in the CardemuInitialization state. The initialization will only take about 20ms. After that it changes to CardemuIdle.

The Bricklet is also reinitialized if the mode is changed, see (*NFCBricklet) SetMode.

The functions of this Bricklet can be called in the CardemuIdle state and all of the CardemuReady and CardemuError states.

Example: If you call (*NFCBricklet) CardemuStartDiscovery, the state will change to CardemuDiscover until the discovery is finished. Then it will change to either CardemuDiscoverReady if it worked or to CardemuDiscoverError if it didn't.

The same approach is used analogously for the other API functions.

The following constants are available for this function:

  • CardemuStateInitialization = 0
  • CardemuStateIdle = 128
  • CardemuStateError = 192
  • CardemuStateDiscover = 2
  • CardemuStateDiscoverReady = 130
  • CardemuStateDiscoverError = 194
  • CardemuStateTransferNDEF = 3
  • CardemuStateTransferNDEFReady = 131
  • CardemuStateTransferNDEFError = 195
func (*NFCBricklet)CardemuStartDiscovery()(err error)

Starts the discovery process. If you call this function while a NFC reader device is near to the NFC Bricklet the state will change from CardemuDiscovery to CardemuDiscoveryReady.

If no NFC reader device can be found or if there is an error during discovery the cardemu state will change to CardemuDiscoveryError. In this case you have to restart the discovery process.

If the cardemu state changes to CardemuDiscoveryReady you can start the NDEF message transfer with (*NFCBricklet) CardemuWriteNDEF and (*NFCBricklet) CardemuStartTransfer.

func (*NFCBricklet)CardemuWriteNDEF(ndef []uint8)(err error)

Writes the NDEF messages that is to be transferred to the NFC peer.

The maximum supported NDEF message size in Cardemu mode is 255 byte.

You can call this function at any time in Cardemu mode. The internal buffer will not be overwritten until you call this function again or change the mode.

func (*NFCBricklet)CardemuStartTransfer(transfer CardemuTransfer)(err error)

You can start the transfer of a NDEF message if the cardemu state is CardemuDiscoveryReady.

Before you call this function to start a write transfer, the NDEF message that is to be transferred has to be written via (*NFCBricklet) CardemuWriteNDEF first.

After you call this function the state will change to CardemuTransferNDEF. It will change to CardemuTransferNDEFReady if the transfer was successful or CardemuTransferNDEFError if it wasn't.

The following constants are available for this function:

  • CardemuTransferAbort = 0
  • CardemuTransferWrite = 1
func (*NFCBricklet)P2PGetState()(state P2PState, idle bool, err error)

Returns the current P2P state of the NFC Bricklet.

On startup the Bricklet will be in the P2PInitialization state. The initialization will only take about 20ms. After that it changes to P2PIdle.

The Bricklet is also reinitialized if the mode is changed, see (*NFCBricklet) SetMode.

The functions of this Bricklet can be called in the P2PIdle state and all of the P2PReady and P2PError states.

Example: If you call (*NFCBricklet) P2PStartDiscovery, the state will change to P2PDiscover until the discovery is finished. Then it will change to either P2PDiscoverReady* if it worked or to P2PDiscoverError if it didn't.

The same approach is used analogously for the other API functions.

The following constants are available for this function:

  • P2PStateInitialization = 0
  • P2PStateIdle = 128
  • P2PStateError = 192
  • P2PStateDiscover = 2
  • P2PStateDiscoverReady = 130
  • P2PStateDiscoverError = 194
  • P2PStateTransferNDEF = 3
  • P2PStateTransferNDEFReady = 131
  • P2PStateTransferNDEFError = 195
func (*NFCBricklet)P2PStartDiscovery()(err error)

Starts the discovery process. If you call this function while another NFC P2P enabled device is near to the NFC Bricklet the state will change from P2PDiscovery to P2PDiscoveryReady.

If no NFC P2P enabled device can be found or if there is an error during discovery the P2P state will change to P2PDiscoveryError. In this case you have to restart the discovery process.

If the P2P state changes to P2PDiscoveryReady you can start the NDEF message transfer with (*NFCBricklet) P2PStartTransfer.

func (*NFCBricklet)P2PWriteNDEF(ndef []uint8)(err error)

Writes the NDEF messages that is to be transferred to the NFC peer.

The maximum supported NDEF message size for P2P transfer is 255 byte.

You can call this function at any time in P2P mode. The internal buffer will not be overwritten until you call this function again, change the mode or use P2P to read an NDEF messages.

func (*NFCBricklet)P2PStartTransfer(transfer P2PTransfer)(err error)

You can start the transfer of a NDEF message if the P2P state is P2PDiscoveryReady.

Before you call this function to start a write transfer, the NDEF message that is to be transferred has to be written via (*NFCBricklet) P2PWriteNDEF first.

After you call this function the P2P state will change to P2PTransferNDEF. It will change to P2PTransferNDEFReady if the transfer was successfull or P2PTransferNDEFError if it wasn't.

If you started a write transfer you are now done. If you started a read transfer you can now use (*NFCBricklet) P2PReadNDEF to read the NDEF message that was written by the NFC peer.

The following constants are available for this function:

  • P2PTransferAbort = 0
  • P2PTransferWrite = 1
  • P2PTransferRead = 2
func (*NFCBricklet)P2PReadNDEF()(ndef []uint8, err error)

Returns the NDEF message that was written by a NFC peer in NFC P2P mode. The maximum NDEF length is 8192 byte.

The NDEF message is ready if you called (*NFCBricklet) P2PStartTransfer with a read transfer and the P2P state changed to P2PTransferNDEFReady.

Advanced Functions

func (*NFCBricklet)SetDetectionLEDConfig(config DetectionLEDConfig)(err error)

Sets the detection LED configuration. By default the LED shows if a card/reader is detected.

You can also turn the LED permanently on/off or show a heartbeat.

If the Bricklet is in bootloader mode, the LED is off.

The following constants are available for this function:

  • DetectionLEDConfigOff = 0
  • DetectionLEDConfigOn = 1
  • DetectionLEDConfigShowHeartbeat = 2
  • DetectionLEDConfigShowDetection = 3
func (*NFCBricklet)GetDetectionLEDConfig()(config DetectionLEDConfig, err error)

Returns the configuration as set by (*NFCBricklet) SetDetectionLEDConfig

The following constants are available for this function:

  • DetectionLEDConfigOff = 0
  • DetectionLEDConfigOn = 1
  • DetectionLEDConfigShowHeartbeat = 2
  • DetectionLEDConfigShowDetection = 3
func (*NFCBricklet)SetMaximumTimeout(timeout uint16)(err error)

Sets the maximum timeout in ms.

This is a global maximum used for all internal state timeouts. The timeouts depend heavily on the used tags etc. For example: If you use a Type 2 tag and you want to detect if it is present, you have to use (*NFCBricklet) ReaderRequestTagID and wait for the state to change to either the error state or the ready state.

With the default configuration this takes 2-3 seconds. By setting the maximum timeout to 100ms you can reduce this time to ~150-200ms. For Type 2 this would also still work with a 20ms timeout (a Type 2 tag answers usually within 10ms). A type 4 tag can take up to 500ms in our tests.

If you need a fast response time to discover if a tag is present or not you can find a good timeout value by trial and error for your specific tag.

By default we use a very conservative timeout, to be sure that any Tag can always answer in time.

Default timeout: 2000ms.

New in version 2.0.1 (Plugin).

func (*NFCBricklet)GetMaximumTimeout()(timeout uint16, err error)

Returns the timeout as set by (*NFCBricklet) SetMaximumTimeout

New in version 2.0.1 (Plugin).

func (*NFCBricklet)GetAPIVersion()(apiVersion [3]uint8, err error)

Returns the version of the API definition (major, minor, revision) implemented by this API bindings. This is neither the release version of this API bindings nor does it tell you anything about the represented Brick or Bricklet.

func (*NFCBricklet)GetResponseExpected(functionId uint8)(responseExpected bool, err error)

Returns the response expected flag for the function specified by the function ID parameter. It is true if the function is expected to send a response, false otherwise.

For getter functions this is enabled by default and cannot be disabled, because those functions will always send a response. For callback configuration functions it is enabled by default too, but can be disabled by (*NFCBricklet) SetResponseExpected. For setter functions it is disabled by default and can be enabled.

Enabling the response expected flag for a setter function allows to detect timeouts and other error conditions calls of this setter as well. The device will then send a response for this purpose. If this flag is disabled for a setter function then no response is send and errors are silently ignored, because they cannot be detected.

See (*NFCBricklet) SetResponseExpected for the list of function ID constants available for this function.

func (*NFCBricklet)SetResponseExpected(functionId uint8, responseExpected bool)(err error)

Changes the response expected flag of the function specified by the function ID parameter. This flag can only be changed for setter (default value: false) and callback configuration functions (default value: true). For getter functions it is always enabled.

Enabling the response expected flag for a setter function allows to detect timeouts and other error conditions calls of this setter as well. The device will then send a response for this purpose. If this flag is disabled for a setter function then no response is send and errors are silently ignored, because they cannot be detected.

The following function ID constants are available for this function:

  • FunctionSetMode = 1
  • FunctionReaderRequestTagID = 3
  • FunctionReaderWriteNDEF = 6
  • FunctionReaderRequestNDEF = 7
  • FunctionReaderAuthenticateMifareClassicPage = 9
  • FunctionReaderWritePage = 10
  • FunctionReaderRequestPage = 11
  • FunctionCardemuStartDiscovery = 15
  • FunctionCardemuWriteNDEF = 16
  • FunctionCardemuStartTransfer = 17
  • FunctionP2PStartDiscovery = 20
  • FunctionP2PWriteNDEF = 21
  • FunctionP2PStartTransfer = 22
  • FunctionSetDetectionLEDConfig = 25
  • FunctionSetMaximumTimeout = 27
  • FunctionSetWriteFirmwarePointer = 237
  • FunctionSetStatusLEDConfig = 239
  • FunctionReset = 243
  • FunctionWriteUID = 248
func (*NFCBricklet)SetResponseExpectedAll(responseExpected bool)(err error)

Changes the response expected flag for all setter and callback configuration functions of this device at once.

func (*NFCBricklet)GetSPITFPErrorCount()(errorCountAckChecksum uint32, errorCountMessageChecksum uint32, errorCountFrame uint32, errorCountOverflow uint32, err error)

Returns the error count for the communication between Brick and Bricklet.

The errors are divided into

  • ACK checksum errors,
  • message checksum errors,
  • framing errors and
  • overflow errors.

The errors counts are for errors that occur on the Bricklet side. All Bricks have a similar function that returns the errors on the Brick side.

func (*NFCBricklet)SetBootloaderMode(mode BootloaderMode)(status BootloaderStatus, err error)

Sets the bootloader mode and returns the status after the requested mode change was instigated.

You can change from bootloader mode to firmware mode and vice versa. A change from bootloader mode to firmware mode will only take place if the entry function, device identifier and CRC are present and correct.

This function is used by Brick Viewer during flashing. It should not be necessary to call it in a normal user program.

The following constants are available for this function:

  • BootloaderModeBootloader = 0
  • BootloaderModeFirmware = 1
  • BootloaderModeBootloaderWaitForReboot = 2
  • BootloaderModeFirmwareWaitForReboot = 3
  • BootloaderModeFirmwareWaitForEraseAndReboot = 4
  • BootloaderStatusOK = 0
  • BootloaderStatusInvalidMode = 1
  • BootloaderStatusNoChange = 2
  • BootloaderStatusEntryFunctionNotPresent = 3
  • BootloaderStatusDeviceIdentifierIncorrect = 4
  • BootloaderStatusCRCMismatch = 5
func (*NFCBricklet)GetBootloaderMode()(mode BootloaderMode, err error)

Returns the current bootloader mode, see (*NFCBricklet) SetBootloaderMode.

The following constants are available for this function:

  • BootloaderModeBootloader = 0
  • BootloaderModeFirmware = 1
  • BootloaderModeBootloaderWaitForReboot = 2
  • BootloaderModeFirmwareWaitForReboot = 3
  • BootloaderModeFirmwareWaitForEraseAndReboot = 4
func (*NFCBricklet)SetWriteFirmwarePointer(pointer uint32)(err error)

Sets the firmware pointer for (*NFCBricklet) WriteFirmware. The pointer has to be increased by chunks of size 64. The data is written to flash every 4 chunks (which equals to one page of size 256).

This function is used by Brick Viewer during flashing. It should not be necessary to call it in a normal user program.

func (*NFCBricklet)WriteFirmware(data [64]uint8)(status uint8, err error)

Writes 64 Bytes of firmware at the position as written by (*NFCBricklet) SetWriteFirmwarePointer before. The firmware is written to flash every 4 chunks.

You can only write firmware in bootloader mode.

This function is used by Brick Viewer during flashing. It should not be necessary to call it in a normal user program.

func (*NFCBricklet)SetStatusLEDConfig(config StatusLEDConfig)(err error)

Sets the status LED configuration. By default the LED shows communication traffic between Brick and Bricklet, it flickers once for every 10 received data packets.

You can also turn the LED permanently on/off or show a heartbeat.

If the Bricklet is in bootloader mode, the LED is will show heartbeat by default.

The following constants are available for this function:

  • StatusLEDConfigOff = 0
  • StatusLEDConfigOn = 1
  • StatusLEDConfigShowHeartbeat = 2
  • StatusLEDConfigShowStatus = 3
func (*NFCBricklet)GetStatusLEDConfig()(config StatusLEDConfig, err error)

Returns the configuration as set by (*NFCBricklet) SetStatusLEDConfig

The following constants are available for this function:

  • StatusLEDConfigOff = 0
  • StatusLEDConfigOn = 1
  • StatusLEDConfigShowHeartbeat = 2
  • StatusLEDConfigShowStatus = 3
func (*NFCBricklet)GetChipTemperature()(temperature int16, err error)

Returns the temperature in °C as measured inside the microcontroller. The value returned is not the ambient temperature!

The temperature is only proportional to the real temperature and it has bad accuracy. Practically it is only useful as an indicator for temperature changes.

func (*NFCBricklet)Reset()(err error)

Calling this function will reset the Bricklet. All configurations will be lost.

After a reset you have to create new device objects, calling functions on the existing ones will result in undefined behavior!

func (*NFCBricklet)WriteUID(uid uint32)(err error)

Writes a new UID into flash. If you want to set a new UID you have to decode the Base58 encoded UID string into an integer first.

We recommend that you use Brick Viewer to change the UID.

func (*NFCBricklet)ReadUID()(uid uint32, err error)

Returns the current UID as an integer. Encode as Base58 to get the usual string version.

func (*NFCBricklet)GetIdentity()(uid string, connectedUid string, position rune, hardwareVersion [3]uint8, firmwareVersion [3]uint8, deviceIdentifier uint16, err error)

Returns the UID, the UID where the Bricklet is connected to, the position, the hardware and firmware version as well as the device identifier.

The position can be 'a', 'b', 'c' or 'd'.

The device identifier numbers can be found here. There is also a constant for the device identifier of this Bricklet.

Callback Configuration Functions

Callbacks

Callbacks can be registered to receive time critical or recurring data from the device. The registration is done with the corresponding Register*Callback function, which returns a unique callback ID. This ID can be used to deregister the callback later.

Note

Using callbacks for recurring events is always preferred compared to using getters. It will use less USB bandwidth and the latency will be a lot better, since there is no round trip time.

func (*NFCBricklet)RegisterReaderStateChangedCallback(func(state ReaderState, idle bool))(callbackID uint64)

A callback can be registered for this event with the RegisterReaderStateChangedCallback() function. This function returns the ID of the registered callback. An added callback can be removed with the DeregisterReaderStateChangedCallback(callbackID uint64) function.

This callback is called if the reader state of the NFC Bricklet changes. See (*NFCBricklet) ReaderGetState for more information about the possible states.

The following constants are available for this function:

  • ReaderStateInitialization = 0
  • ReaderStateIdle = 128
  • ReaderStateError = 192
  • ReaderStateRequestTagID = 2
  • ReaderStateRequestTagIDReady = 130
  • ReaderStateRequestTagIDError = 194
  • ReaderStateAuthenticateMifareClassicPage = 3
  • ReaderStateAuthenticateMifareClassicPageReady = 131
  • ReaderStateAuthenticateMifareClassicPageError = 195
  • ReaderStateWritePage = 4
  • ReaderStateWritePageReady = 132
  • ReaderStateWritePageError = 196
  • ReaderStateRequestPage = 5
  • ReaderStateRequestPageReady = 133
  • ReaderStateRequestPageError = 197
  • ReaderStateWriteNDEF = 6
  • ReaderStateWriteNDEFReady = 134
  • ReaderStateWriteNDEFError = 198
  • ReaderStateRequestNDEF = 7
  • ReaderStateRequestNDEFReady = 135
  • ReaderStateRequestNDEFError = 199
func (*NFCBricklet)RegisterCardemuStateChangedCallback(func(state CardemuState, idle bool))(callbackID uint64)

A callback can be registered for this event with the RegisterCardemuStateChangedCallback() function. This function returns the ID of the registered callback. An added callback can be removed with the DeregisterCardemuStateChangedCallback(callbackID uint64) function.

This callback is called if the cardemu state of the NFC Bricklet changes. See (*NFCBricklet) CardemuGetState for more information about the possible states.

The following constants are available for this function:

  • CardemuStateInitialization = 0
  • CardemuStateIdle = 128
  • CardemuStateError = 192
  • CardemuStateDiscover = 2
  • CardemuStateDiscoverReady = 130
  • CardemuStateDiscoverError = 194
  • CardemuStateTransferNDEF = 3
  • CardemuStateTransferNDEFReady = 131
  • CardemuStateTransferNDEFError = 195
func (*NFCBricklet)RegisterP2PStateChangedCallback(func(state P2PState, idle bool))(callbackID uint64)

A callback can be registered for this event with the RegisterP2PStateChangedCallback() function. This function returns the ID of the registered callback. An added callback can be removed with the DeregisterP2PStateChangedCallback(callbackID uint64) function.

This callback is called if the P2P state of the NFC Bricklet changes. See (*NFCBricklet) P2PGetState for more information about the possible states.

The following constants are available for this function:

  • P2PStateInitialization = 0
  • P2PStateIdle = 128
  • P2PStateError = 192
  • P2PStateDiscover = 2
  • P2PStateDiscoverReady = 130
  • P2PStateDiscoverError = 194
  • P2PStateTransferNDEF = 3
  • P2PStateTransferNDEFReady = 131
  • P2PStateTransferNDEFError = 195

Constants

nfc_bricklet.DeviceIdentifier

This constant is used to identify a NFC Bricklet.

The (*NFCBricklet) GetIdentity function and the (*IPConnection) RegisterEnumerateCallback callback of the IP Connection have a deviceIdentifier parameter to specify the Brick's or Bricklet's type.

nfc_bricklet.DeviceDisplayName

This constant represents the human readable name of a NFC Bricklet.