Example project to publish messages to a MQTT-SN broker using the u-blox SARA-N200 NB-IoT modem

Dependencies:   MQTTSNPacket X-NUCLEO-SARA-N200

Revision:
7:ab32680de141
Parent:
6:16be6bf59d30
diff -r 16be6bf59d30 -r ab32680de141 main.cpp
--- a/main.cpp	Tue Aug 21 16:37:21 2018 +0200
+++ b/main.cpp	Wed Aug 22 16:31:30 2018 +0200
@@ -27,10 +27,12 @@
 			message.retained,
 			message.dup,
 			message.id);
+    char *payload = (char*)message.payload;
+    payload[message.payloadlen] = 0;
 
-    TRACE("Payload %s\n", message.payload);
+    TRACE("Payload %s\n", payload);
     char *ptr;
-    float new_rate = strtof((const char*)message.payload, &ptr);
+    float new_rate = strtof((const char*)payload, &ptr);
     if(new_rate > 0)
     {
     	TRACE("New rate %f\n", new_rate);
@@ -54,10 +56,35 @@
 MQTTSN_topicid topicid;
 MQTTSN::QoS grantedQoS;
 char topicString[64];
-char publishMessage[100];
+char publishMessage[32];
+bool buttonPressed = false;
+int aliveCount = 0;
+int colorIndex = 0;
+char sendBuffer[512];
+
+char *colorNames[] =
+{
+		"red",
+		"green",
+		"yellow",
+		"blue",
+		"grey"
+};
 
-bool buttonPressed = false;
+void fillMessage(char *msg)
+{
+	char temp[64];
 
+	sprintf(msg, "{\"IMEA\":\"%s\",", sara_mdm.getIMEA());
+	sprintf(temp, "\"SIM\":\"%s\",",  sara_mdm.getSIMserial());
+	strcat(msg, temp);
+	sprintf(temp, "\"message\":\"%s\",", publishMessage);
+	strcat(msg, temp);
+	sprintf(temp, "\"color\":\"%s\",", colorNames[colorIndex]);
+	strcat(msg, temp);
+	sprintf(temp, "\"alive\":%d}", aliveCount);
+	strcat(msg, temp);
+}
 
 void mqtt_fsm(MQTTSN::Client<MQTTSNUDP, Countdown> *client)
 {
@@ -109,16 +136,18 @@
 		{
 			pub_count = 0;
 
+			fillMessage(sendBuffer);
+
 			MQTTSN::Message message;
 			message.qos = MQTTSN::QOS0;
 			message.retained = false;
 			message.dup = false;
-			message.payload = (void*)publishMessage;
-			message.payloadlen = strlen(publishMessage)+1;
+			message.payload = (void*)sendBuffer;
+			message.payloadlen = strlen(sendBuffer);
 			int rc = client->publish(topicid, message);
 			if(rc == MQTTSN::SUCCESS)
 			{
-				TRACE("Publishes %s\n", publishMessage);
+				TRACE("Publishes %s\n", sendBuffer);
 			}
 
 			mMQTTstate = MQTT_CLIENT_SUBSCRIBED;
@@ -132,15 +161,18 @@
 		{
 			buttonPressed = false;
 			mMQTTstate = MQTT_CLIENT_PUBLISH;
-			sprintf(publishMessage, "Button pressed");
+
+			sprintf(publishMessage, "Color changed");
+			if(++colorIndex > 4)
+				colorIndex = 0;
 		}
 
 		if(pub_count++ > 100)
 		{
 			mMQTTstate = MQTT_CLIENT_PUBLISH;
+			sprintf(publishMessage, "X-Nucleo is alive");
 
-			static int aliveCount = 0;
-			sprintf(publishMessage, "I am alive %d", aliveCount++);
+			aliveCount++;
 		}
 
 	}