This application provides a set of demos with X-NUCLEO-NFC01A1 expansion board.

Dependencies:   NDefLib X_NUCLEO_NFC01A1 mbed

Fork of X-MBED-NFC1 by Giovanni Visentini

This application provides a set of demos with X-NUCLEO-NFC01A1 expansion board.

The available demos are:

  • SAMPLE_WRITE_URL: write a tag with the ST home page URL
  • SAMPLE_COUNT_CLICK: create a custom tag to count and report the user button clicks.
  • SAMPLE_WRITE_AND_CHANGE_ALL: write a tag with all the supported records and update the tag contents when the user button is pressed.
  • SAMPLE_LOCK_TAG_CONTENT: use the M24SR component API to set the NFC tag as read-only.

To enable the different demos comment/uncomment the SAMPLE_* macros provided in main.cpp .

Revision:
13:685d95525ec8
Child:
14:3b604972b89f
diff -r c4a778f52d8a -r 685d95525ec8 Samples/SampleAsync_writeAndChangeAll.cpp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Samples/SampleAsync_writeAndChangeAll.cpp	Mon Feb 01 15:33:26 2016 +0000
@@ -0,0 +1,490 @@
+/**
+  ******************************************************************************
+  * @file       Sample_writeAndChangeAll.cpp
+  * @author     ST / Central Labs
+  * @date       03 Dic 2015
+  * @brief      This demo write an ndef message different records, when the user press the buttun
+  *             read the tag, change some data and write it again
+  ******************************************************************************
+  *
+  * COPYRIGHT(c) 2015 STMicroelectronics
+  *
+  * Redistribution and use in source and binary forms, with or without modification,
+  * are permitted provided that the following conditions are met:
+  *   1. Redistributions of source code must retain the above copyright notice,
+  *      this list of conditions and the following disclaimer.
+  *   2. Redistributions in binary form must reproduce the above copyright notice,
+  *      this list of conditions and the following disclaimer in the documentation
+  *      and/or other materials provided with the distribution.
+  *   3. Neither the name of STMicroelectronics nor the names of its contributors
+  *      may be used to endorse or promote products derived from this software
+  *      without specific prior written permission.
+  *
+  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+  * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+  *
+  ******************************************************************************
+  */
+  
+#include "mbed.h"
+
+#include "NDefLib/NDefNfcTag.h"
+
+#include "NDefLib/RecordType/RecordAAR.h"
+#include "NDefLib/RecordType/RecordSMS.h"
+#include "NDefLib/RecordType/RecordGeo.h"
+#include "NDefLib/RecordType/RecordURI.h"
+#include "NDefLib/RecordType/RecordMail.h"
+#include "NDefLib/RecordType/RecordText.h"
+#include "NDefLib/RecordType/RecordMimeType.h"
+#include "NDefLib/RecordType/RecordVCard.h"
+
+#include "X_NUCLEO_NFC01A1.h"
+
+/**
+ * Shift the led status between the 3 leds.
+ */
+static void shiftLed(DigitalOut &led1,DigitalOut &led2,DigitalOut &led3){
+    const uint8_t prevLed1=led1;
+    const uint8_t prevLed2=led2;
+    const uint8_t prevLed3=led3;
+    led1=prevLed3;
+    led2=prevLed1;
+    led3=prevLed2;
+}
+
+/**
+ * Print in the console some data about the record.
+ * @param r Record to print.
+ */
+static void printRecord(NDefLib::Record *const r){
+    using namespace NDefLib;
+    switch(r->getType()){
+        case Record::TYPE_TEXT: {
+            const RecordText *const temp = ( RecordText* )r;
+            printf("Read Text: %s\r\n",temp->getText().c_str());
+            break; }
+        case Record::TYPE_AAR:{
+            const RecordAAR *const temp = ( RecordAAR* )r;
+            printf("Read ARR: %s\r\n",temp->getPackage().c_str());
+            break; }
+        case Record::TYPE_MIME:{
+            const RecordMimeType *const temp = ( RecordMimeType* )r;
+            printf("Read mimeType: %s\r\n",temp->getMimeType().c_str());
+            printf("Read mimeData: %s\r\n",
+                    std::string((const char*)temp->getMimeData(),
+                            temp->getMimeDataLenght()).c_str());
+            break;}
+        case Record::TYPE_URI:{
+            RecordURI *const temp = (RecordURI*)r;
+            printf("Read uriId: %d\r\n",temp->getUriId());
+            printf("Read uriType: %s\r\n",temp->getUriType().c_str());
+            printf("Read uriContent: %s\r\n",temp->getContent().c_str());
+            break;}
+        case Record::TYPE_URI_MAIL:{
+            const RecordMail*const temp = (RecordMail*)r;
+            printf("Read Dest: %s\r\n",temp->getToAddress().c_str());
+            printf("Read Subject: %s\r\n",temp->getSubject().c_str());
+            printf("Read Body: %s\r\n",temp->getBody().c_str());
+            break;}
+        case Record::TYPE_URI_SMS:{
+            const RecordSMS*const temp = (RecordSMS*)r;
+            printf("Read number: %s\r\n",temp->getNumber().c_str());
+            printf("Read message: %s\r\n",temp->getMessagge().c_str());
+            break;}
+        case Record::TYPE_URI_GEOLOCATION:{
+            const RecordGeo*const temp = (RecordGeo*)r;
+            printf("Read lat: %f\r\n",temp->getLatitude());
+            printf("Read long: %f\r\n",temp->getLongitude());
+            break;}
+        case Record::TYPE_MIME_VCARD:{
+            const RecordVCard *const temp = (RecordVCard*)r;
+            printf("Read Name: %s\r\n",(*temp)[RecordVCard::NAME].c_str());
+            printf("Read Mail: %s\r\n",(*temp)[RecordVCard::EMAIL_WORK].c_str());
+            printf("Read ORG: %s\r\n",(*temp)[RecordVCard::ORGANIZATION].c_str());
+            break;}
+        case Record::TYPE_UNKNOWN:{
+            printf("Unknown record\r\n");
+            break;}
+    }//switch
+}//printRecord
+
+/**
+ * Change the record content.
+ * @param r Record to change.
+ */
+static void changeRecord(NDefLib::Record const* r){
+    using namespace NDefLib;
+    switch(r->getType()){
+        case Record::TYPE_TEXT: {
+            RecordText *temp = (RecordText*)r;
+            temp->setText("CIAOCiao");
+            break; }
+        case Record::TYPE_AAR:{
+            RecordAAR *temp = (RecordAAR*)r;
+            temp->setPackage("set Package Ok");
+            break; }
+        case Record::TYPE_MIME:{
+            RecordMimeType *temp = (RecordMimeType*)r;
+            temp->copyMimeData((const uint8_t *)"String2",sizeof("String2"));
+            break;}
+        case Record::TYPE_URI:{
+            RecordURI *temp = (RecordURI*)r;
+            temp->setContent("google.it");
+            break;}
+        case Record::TYPE_URI_MAIL:{
+            RecordMail *temp = (RecordMail*)r;
+            temp->setToAddress("newMail@st.com");
+            temp->setSubject("tag change");
+            temp->setBody("read/change Works!");
+            break;}
+        case Record::TYPE_URI_SMS:{
+            RecordSMS *temp = (RecordSMS*)r;
+            temp->setMessage("Message Change");
+            temp->setNumber("0987654321");
+            break;}
+        case Record::TYPE_URI_GEOLOCATION:{
+            RecordGeo *temp = (RecordGeo*)r;
+            temp->setLatitude(-temp->getLatitude());
+            temp->setLongitude(-temp->getLongitude());
+            break;}
+        case Record::TYPE_MIME_VCARD:{
+            RecordVCard *temp = (RecordVCard*)r;
+            (*temp)[RecordVCard::NAME]="name change";
+            (*temp)[RecordVCard::NICKNAME]="nic change";
+            break;}
+        case Record::TYPE_UNKNOWN:{
+            printf("Unknown record\r\n");
+            break;}
+    }//switch
+}//changeRecord
+
+
+/**
+ * Class that print read a message and print it on console,
+ * and enable the user button when it finish
+ */
+class ReadMessageCallback : public NDefLib::NDefNfcTag::Callback{
+
+	NDefLib::Message *mMsg; /// Message where read
+	bool *mDisableButton; /// enable the user button
+
+	void onFinish(char *msg){
+		printf(msg);
+		*mDisableButton=false;
+	}
+
+public:
+	/**
+	 *
+	 * @param disableEnable set to false when the read finish
+	 */
+	ReadMessageCallback(bool *disableEnable):mMsg(NULL),
+		mDisableButton(disableEnable){}
+
+	/**
+	 * Create the message and ask to read it
+	 */
+	virtual void onSessionOpen(NDefLib::NDefNfcTag *tag,bool success){
+		if(!success){
+			return onFinish("Error Opening Session\r\n");
+		}//if
+		mMsg = new NDefLib::Message;
+		tag->read(mMsg);
+	}
+
+	/**
+	 * Print all the record inside the message
+	 */
+	virtual void onMessageRead(NDefLib::NDefNfcTag *tag,bool success,
+			const NDefLib::Message *readMsg){
+		if(!success || readMsg->getNRecords()==0){
+			delete mMsg;
+			return onFinish("Error Reading\r\n");
+		}else{
+			for(uint32_t i=0;i<readMsg->getNRecords();i++){
+				NDefLib::Record *r = (*readMsg)[i];
+				printRecord(r);
+				delete r;
+			}//for
+			delete mMsg;
+		}//if-else
+		tag->closeSession();
+	}
+
+	/**
+	 * Enable the button
+	 */
+	virtual void onSessionClose(NDefLib::NDefNfcTag *,bool success){
+		if(success)
+			onFinish("Read Session close\r\n");
+		else
+			onFinish("Read Session close Error\r\n");
+	}
+
+};
+
+/**
+ * Read the message, change some data and write it back
+ */
+class ChangeMessageCallback : public NDefLib::NDefNfcTag::Callback{
+
+	ReadMessageCallback* mReadMessage;
+	NDefLib::Message *mMsg;
+
+	/**
+	 * Change all the record in the message.
+	 * @param readMsg Message to change.
+	 */
+	static void changeContent(const NDefLib::Message *readMsg){
+		for(uint32_t i=0;i<readMsg->getNRecords();i++){
+			changeRecord((*readMsg)[i]);
+		}//for
+	}//changeContent
+
+	/**
+	 * Delete all the record and the message.
+	 */
+	void deleteMessage(){
+		for(uint32_t i=0;i<mMsg->getNRecords();i++){
+			delete (*mMsg)[i];
+		}//for
+		delete mMsg;
+	}//deleteMessage
+
+public:
+
+	/**
+	 * @param readCallback Callback needed for print the tag content after the change
+	 */
+	ChangeMessageCallback(ReadMessageCallback* readCallback):
+		mReadMessage(readCallback),mMsg(NULL){}
+
+	/**
+	 * Ask to read the tag content
+	 */
+	virtual void onSessionOpen(NDefLib::NDefNfcTag *tag,bool success){
+		if(!success){
+			printf("Error Opening the session");
+			return;
+		}//else
+		mMsg = new NDefLib::Message;
+		tag->read(mMsg);
+	}
+
+	/**
+	 * Change the message content and write it back
+	 */
+	virtual void onMessageRead(NDefLib::NDefNfcTag *tag,bool success,
+			const NDefLib::Message *readMsg){
+		if(!success || readMsg->getNRecords()==0){
+			printf("Error Reading\r\n");
+			deleteMessage();
+		}else{
+			changeContent(readMsg);
+			tag->write(*mMsg);
+		}//if-else
+	}
+
+	/**
+	 * Delete the Message and close the session
+	 */
+	virtual void onMessageWrite(NDefLib::NDefNfcTag *tag,bool success,
+							const NDefLib::Message &){
+		deleteMessage();
+		if(success)
+			tag->closeSession();
+		else
+			printf("Error Writing\r\n");
+	}//onMessageWrite
+
+	/**
+	 * Set the callback for print the tag content and open a new session
+	 */
+	virtual void onSessionClose(NDefLib::NDefNfcTag *tag,bool success){
+		if(success){
+			printf("Change Session close\r\n");
+			tag->setCallback(mReadMessage);
+			tag->openSession();
+		}else
+			printf("Change Session close Error\r\n");
+	}
+
+};
+
+/**
+ * Create and write a message in a nfc tag
+ */
+class WriteMessageCallback : public NDefLib::NDefNfcTag::Callback{
+
+	ReadMessageCallback* mReadMessage;
+
+public:
+
+	/**
+	 *
+	 * @param readCallback Callbacks to use for print the tag content
+	 */
+	WriteMessageCallback(ReadMessageCallback* readCallback):
+		mReadMessage(readCallback){}
+
+	/**
+	 *
+	 */
+	virtual void onSessionOpen(NDefLib::NDefNfcTag *tag,bool success){
+		if(!success){
+			printf("Error Opening the Session\r\n");
+			return;
+		}//else
+
+		//create the message
+		 NDefLib::Message msg;
+
+		NDefLib::RecordAAR rAAR("com.st.BlueMS");
+		msg.addRecord(&rAAR);
+
+		NDefLib::RecordSMS rSMS("123456789","st.com.BlueMS");
+		msg.addRecord(&rSMS);
+
+		NDefLib::RecordGeo rGeo(123.123,-456.789);
+		msg.addRecord(&rGeo);
+
+		NDefLib::RecordURI rUri(NDefLib::RecordURI::HTTP_WWW,"http://www.st.com");
+		msg.addRecord(&rUri);
+
+		NDefLib::RecordMail rMail("mail@st.com","ciao","da nfc tag");
+		msg.addRecord(&rMail);
+
+		NDefLib::RecordMimeType rText1("text/plain",(const uint8_t*)"ciao",4);
+		msg.addRecord(&rText1);
+
+		NDefLib::RecordText rText3(NDefLib::RecordText::UTF8,"it","ciao");
+		msg.addRecord(&rText3);
+
+		NDefLib::RecordVCard::VCardInfo_t cardInfo;
+		cardInfo[NDefLib::RecordVCard::FORMATTED_NAME]="prova prova1";
+		cardInfo[NDefLib::RecordVCard::ADDRESS_HOME]=";;1 Main St.;Springfield;IL;12345;USA";
+		cardInfo[NDefLib::RecordVCard::ADDRESS_WORK]=";;2 Main St.;Springfield;IL;12345;USA";
+		cardInfo[NDefLib::RecordVCard::EMAIL_WORK]="workmail@st.com";
+		cardInfo[NDefLib::RecordVCard::EMAIL_HOME]="homemail@st.com";
+		cardInfo[NDefLib::RecordVCard::GEO]="39.95;-75.1667";
+		cardInfo[NDefLib::RecordVCard::IMPP]="aim:johndoe@aol.com";
+		cardInfo[NDefLib::RecordVCard::NAME]="prova2;prova3";
+		cardInfo[NDefLib::RecordVCard::NICKNAME]="test";
+		cardInfo[NDefLib::RecordVCard::NOTE]="A good test";
+		cardInfo[NDefLib::RecordVCard::ORGANIZATION]="STM";
+		cardInfo[NDefLib::RecordVCard::TEL_HOME]="123";
+		cardInfo[NDefLib::RecordVCard::TEL_MOBILE]="456";
+		cardInfo[NDefLib::RecordVCard::TEL_WORK]="789";
+		cardInfo[NDefLib::RecordVCard::TITLE]="King";
+		cardInfo[NDefLib::RecordVCard::URL]="www.st.com";
+		cardInfo[NDefLib::RecordVCard::PHOTO_URI]="http://www.st.com/st-web-ui/static/active/en/fragment/multimedia/image/picture/customer_focus.jpg";
+		NDefLib::RecordVCard rVCard(cardInfo);
+		msg.addRecord(&rVCard);
+
+		//write it
+		tag->write(msg);
+	}
+
+
+	/**
+	 * Close the session
+	 */
+	virtual void onMessageWrite(NDefLib::NDefNfcTag *tag,bool success,
+						const NDefLib::Message &){
+		if(!success)
+			printf("Error Writing\r\n");
+
+		tag->closeSession();
+	}
+
+	/**
+	 * Set the callback for print the tag content and open a new session
+	 */
+	virtual void onSessionClose(NDefLib::NDefNfcTag *tag,bool success){
+		if(success){
+			printf("Write Session close\r\n");
+			tag->setCallback(mReadMessage);
+			tag->openSession();
+		}else
+			printf("Write Session close Error\r\n");
+	}//onSessionClose
+
+};
+
+
+static bool buttonPress=false; /// true when the user press the message
+
+/**
+ * Call back called when the user press the button
+ */
+static void setButtonPress(){
+    buttonPress=true;
+}//if buttonPress
+
+static bool nfcEvent=false; /// true if there is an nfc interrupt
+
+/**
+ * Call back called when the user press the button
+ */
+static void setNfcEvent(){
+	nfcEvent=true;
+}//if buttonPress
+
+/**
+ * Write a message and when the user press the button it read the message, change it and update it.
+ */
+void sampleAsync_writeAndChangeAll() {
+    DigitalOut nucleoLed(LED1);
+    
+    //instance the board with the default parameters
+    I2C i2cChannel(X_NUCLEO_NFC01A1::DEFAULT_SDA_PIN,X_NUCLEO_NFC01A1::DEFAULT_SDL_PIN);
+    X_NUCLEO_NFC01A1 *nfcNucleo = X_NUCLEO_NFC01A1::Instance(i2cChannel,&setNfcEvent);
+
+    //retrieve the Nfc component
+    M24SR &nfc = nfcNucleo->getM24SR();
+    //retrieve the NdefLib interface
+    NDefLib::NDefNfcTag& tag = nfc.getNDefTag();
+
+    //switch on the first led    
+    nfcNucleo->getLed1()=1;
+    nfcNucleo->getLed2()=0;
+    nfcNucleo->getLed3()=0;
+
+    ReadMessageCallback readMessageCallback(&buttonPress);
+    WriteMessageCallback writeBigMessageCallback(&readMessageCallback);
+    ChangeMessageCallback changeMessageCallback(&readMessageCallback);
+
+    //Enable async mode
+    if(nfcNucleo->getM24SR().GetSession()!=NFC_SUCCESS)
+        	nfcNucleo->getM24SR().ManageI2CGPO(I2C_ANSWER_READY);
+
+    //write the message
+    tag.setCallback(&writeBigMessageCallback);
+    tag.openSession();
+
+    //enable the button
+    InterruptIn mybutton(USER_BUTTON);
+    mybutton.fall(setButtonPress);
+
+    while(true) {
+        if(buttonPress){
+        	shiftLed(nfcNucleo->getLed1(),nfcNucleo->getLed2(),nfcNucleo->getLed3());
+        	tag.setCallback(&changeMessageCallback);
+        	tag.openSession();
+        }else if (nfcEvent){
+        	nucleoLed=!nucleoLed;
+        	nfcNucleo->getM24SR().ManageEvent();
+        }//if-else
+        __WFE();
+    }//while
+}
+