The following code samples illustrate how to write to an NFC tag or an NFC device using the NFC C API (libnfc and libnfc_bps) and how to receive NFC events using BlackBerry Platform Services. This approach allows BlackBerry Platform Services to manage your app's connection to the NFC system and to deliver NFC events to your app.
Alternatively, you can set up and manage your NFC connection directly. In this approach, you receive NFC events using nfc_connect() and nfc_read_event(), manage events using nfc_get_fd() and nfc_free_event(), and disconnect from the NFC system using nfc_disconnect().
#include <bps/bps.h>
#include <nfc/nfc_bps.h>
#include <nfc/nfc.h>
#include <nfc/nfc_types.h>
#include <nfc/nfc_ndef.h>
void handle_write_event(bps_event_t event);
/* Register for both tag events and SNEP events.
* Write an NDEF message to target.
*/
void main () {
nfc_result_t rc = -1;
if (bps_initialize() != BPS_SUCCESS) {
// handle error
...
return;
}
if (nfc_request_events() != BPS_SUCCESS) {
// handle error
bps_shutdown();
return;
}
rc = nfc_register_tag_readerwriter(TAG_TYPE_NDEF);
if (rc != NFC_RESULT_SUCCESS) {
// handle error
bps_shutdown();
return;
}
// register as a SNEP client in order to
// receive LLCP connection events
rc = nfc_register_snep_client();
if (rc != NFC_RESULT_SUCCESS) {
// handle error
bps_shutdown();
return;
}
for (;;) {
bps_event_t *event;
if (bps_get_event(&event, BPS_EVENT_TIMEOUT)
!= BPS_SUCCESS) {
// handle error
...
};
handle_write_event(event);
}
bps_shutdown();
}
/* Write an NDEF message that contains a smart poster
* record to a tag.
* Write an NDEF message that contains a text record
* to another device (through an LLCP connection).
*/
void handle_write_event(bps_event_t event) {
nfc_ndef_record_t* rec;
nfc_ndef_message_t* myNdefMessage;
int domain = bps_event_get_domain( event );
if( nfc_get_domain() != domain ){
return;
}
...
if (bps_event_get_code(event) ==
NFC_TAG_READWRITE_EVENT) {
rc = nfc_get_nfc_event(event, &nfcEvent);
// get target
nfc_get_target(nfcEvent, &target);
// create an NDEF message with an sp record
nfc_create_sp_record("http://abc.de", &rec);
nfc_set_sp_type(rec, "test");
nfc_create_ndef_message(&myNdefMessage);
nfc_add_ndef_record(myNdefMessage, rec);
nfc_write_ndef_message_to_tag(target,
myNdefMessage,
false);
// free memory
nfc_delete_ndef_message(myNdefMessage, true);
nfc_destroy_target(target);
}
if (bps_event_get_code(event) ==
NFC_SNEP_CONNECTION_EVENT) {
nfc_get_nfc_event(event, &nfc_event);
nfc_get_target (nfc_event, &target );
// create an NDEF message with a text record
char *textstr = "Hello";
char *langstr = "en";
nfc_create_text_record(textstr, langstr, &rec);
nfc_create_ndef_message(&myNdefMessage);
nfc_add_ndef_record(myNdefMessage, rec);
nfc_push_ndef_message(target, myNdefMessage);
}
// free memory
nfc_delete_ndef_message(myNdefMessage, true);
nfc_destroy_target(target);
}