Simple usage example of MQTTS library

Dependencies:   EthernetInterface MQTTS NTPClient SDFileSystem mbed-rtos mbed wolfSSL

Fork of HelloMQTT by MQTT

MQTT is light weight protocol for M2M, IoT. MQTTS adds TLS(SSL) security layer into the MQTT. This program shows simple usage example of MQTTS library.

Connect information has to be stored in SD file "connectInfo.txt", with following lines in it.

  • Host Name
  • User Name
  • Password
  • Client ID
  • Topic

The program asks following information on the terminal

  • Port Number to be connected. If the port is >8000 it assumes MQTTS.
  • Message to be published
  • Certificate file name, if MQTTS. Input file name on SD card. Simply Return key force it to no server verification. The program set up the realtime clock by NTP for certificate verification.

This program was tested with FRDM-K64F, against Sango MQTT server by Shiguredo. https://sango.shiguredo.jp/

References:

Revision:
17:25584027fae0
Parent:
16:28d062c5522b
Child:
20:0404c7f31c69
diff -r 28d062c5522b -r 25584027fae0 main.cpp
--- a/main.cpp	Mon Oct 06 11:42:25 2014 +0000
+++ b/main.cpp	Sun Jul 26 09:55:46 2015 +0000
@@ -13,121 +13,215 @@
  * Contributors:
  *    Ian Craggs - initial API and implementation and/or initial documentation
  *******************************************************************************/
- 
- /**
-  This is a sample program to illustrate the use of the MQTT Client library
-  on the mbed platform.  The Client class requires two classes which mediate
-  access to system interfaces for networking and timing.  As long as these two
-  classes provide the required public programming interfaces, it does not matter
-  what facilities they use underneath. In this program, they use the mbed
-  system libraries.
- 
- */
 
+/**
+ This is a sample program to illustrate the use of the MQTT Client library
+ on the mbed platform.  The Client class requires two classes which mediate
+ access to system interfaces for networking and timing.  As long as these two
+ classes provide the required public programming interfaces, it does not matter
+ what facilities they use underneath. In this program, they use the mbed
+ system libraries.
 
-#include "C12832.h"
-C12832 lcd(p5, p7, p6, p8, p11);
+*/
 
 #include "MQTTEthernet.h"
 #include "MQTTClient.h"
 
+#include "NTPClient.h"
+#include "getline.h"
+#include "SDFileSystem.h"
+SDFileSystem sdCard(PTE3, PTE1, PTE2, PTE4, "sd"); /* pins for FRDM-K64F */
+const char* certFile = "/sd/mqtts-cert.pem";
+
 int arrivedcount = 0;
 
-
 void messageArrived(MQTT::MessageData& md)
 {
     MQTT::Message &message = md.message;
-    lcd.cls();
-    lcd.locate(0,3);
     printf("Message arrived: qos %d, retained %d, dup %d, packetid %d\n", message.qos, message.retained, message.dup, message.id);
     printf("Payload %.*s\n", message.payloadlen, (char*)message.payload);
     ++arrivedcount;
-    lcd.puts((char*)message.payload);
+    puts((char*)message.payload);
+}
+
+static char * removeNL(char *str)
+{
+    for(int i=strlen(str)-1; (str[i]=='\n')||(str[i]=='\r'); i--)str[i]='\0' ;
+    return str ;
 }
 
+static bool getConnectInfo(char **hn, char **un, char **pwd, char **cID,
+                           char **tc, int *pt, char **ms, char **cert)
+{
+    static char hostname[100] ;
+    static char username[20] ;
+    static char password[20] ;
+    static char clientID[20] ;
+    static char topic[50] ;
+    static char port_s[10] ;
+    static int  port ;
+    static char msg[100] ;
+    static char certName[30] ;
+    static char fullName[sizeof(certName)+10] ;
 
-int main(int argc, char* argv[])
-{   
+    *hn = hostname ;
+    *un = username ;
+    *pwd= password ;
+    *cID= clientID ;
+    *tc = topic ;
+    *ms = msg ;
+    *cert=fullName ;
+
+    FILE *fp = fopen("/sd/connectInfo.txt", "r");
+    if (fp == NULL) {
+        printf("Cannot open \"connectInfo.txt\"\n") ;
+        return false ;
+    }
+    fgets(hostname, sizeof(hostname), fp) ;
+    fgets(username , sizeof(username), fp);
+    fgets(password, sizeof(password), fp) ;
+    fgets(clientID, sizeof(clientID), fp) ;
+    fgets(topic, sizeof(topic), fp) ;
+    getline("Port(1883/8883): ", port_s, sizeof(port_s)) ;
+    getline("Message: ", msg, sizeof(msg)) ;
+    removeNL(hostname) ;
+    removeNL(username) ;    
+    removeNL(password) ;
+    removeNL(clientID) ;
+    removeNL(topic) ;
+    port = atoi(removeNL(port_s)) ;
+    *pt = port ;
+    printf("Connecting to %s:%d, %s\n", hostname, port, port>8000? "MQTT-TLS":"MQTT" );
+    if(port>8000) {
+        getline("Cert File name: ", certName, sizeof(certName)) ;
+        removeNL(certName) ;
+        if(*certName != '\0') {
+            sprintf(fullName, "/sd/%s", certName) ;
+            FILE *fp = fopen(fullName, "r");
+            if (fp != NULL) {
+                NTPClient ntp; /* set Realtime clock for cert verification */
+                if(ntp.setTime("ntp.jst.mfeed.ad.jp") != 0) {
+                    printf("NTP Error\n") ;
+                    return false ;
+                }
+                printf("Verify Server: %s\n", certName) ;
+            } else {
+                printf("ERROR: file not found\n") ;
+                return false ;
+            }
+        } else {
+            fullName[0] = '\0' ;
+            printf("No verify Server\n") ;
+        }
+    }
+    return true ;
+}
+
+void mqtt_main(void const *av)
+{
     MQTTEthernet ipstack = MQTTEthernet();
     float version = 0.47;
-    char* topic = "mbed-sample";
-    
-    lcd.printf("Version is %f\n", version);
+
     printf("Version is %f\n", version);
-              
+    printf("Version is %f\n", version);
+
     MQTT::Client<MQTTEthernet, Countdown> client = MQTT::Client<MQTTEthernet, Countdown>(ipstack);
-    
-    char* hostname = "m2m.eclipse.org";
-    int port = 1883;
-    lcd.printf("Connecting to %s:%d\n", hostname, port);
-    int rc = ipstack.connect(hostname, port);
+    MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
+    data.MQTTVersion = 3;
+
+    /* get connect info */
+    char *hostname ;
+    char *username ;
+    char *password ;
+    char *clientID ;
+    char *topic ;
+    int  port ;
+    char *msg ;
+    char *fullName ;
+
+    if(!getConnectInfo(&hostname, &username, &password, &clientID, &topic, &port, &msg, &fullName))
+        return ;
+    data.username.cstring = username ;
+    data.password.cstring = password ;
+    data.clientID.cstring = clientID ;
+        
+    int rc = ipstack.connect(hostname, port, port>8000 ? fullName : NULL);
     if (rc != 0)
-        lcd.printf("rc from TCP connect is %d\n", rc);
- 
-    MQTTPacket_connectData data = MQTTPacket_connectData_initializer;       
-    data.MQTTVersion = 3;
-    data.clientID.cstring = "mbed-sample";
-    data.username.cstring = "testuser";
-    data.password.cstring = "testpassword";
+        printf("rc from TCP connect is %d\n", rc);
+
     if ((rc = client.connect(data)) != 0)
-        lcd.printf("rc from MQTT connect is %d\n", rc);
-    
-    if ((rc = client.subscribe(topic, MQTT::QOS1, messageArrived)) != 0)
-        lcd.printf("rc from MQTT subscribe is %d\n", rc);
-
+        printf("rc from MQTT connect is %d\n", rc);
+    printf("MQTT connected\n") ;
+    if ((rc = client.subscribe(topic, MQTT::QOS0, messageArrived)) != 0)
+        printf("rc from MQTT subscribe is %d\n", rc);
+    printf("Subscribed\n") ;
     MQTT::Message message;
 
-    // QoS 0
-    char buf[100];
-    sprintf(buf, "Hello World!  QoS 0 message from app version %f\n", version);
+// QoS 0
+    char buf[sizeof(message)+50] ;
+    sprintf(buf, "\"%s\", QoS 0 message from app version %f\n", msg, version);
     message.qos = MQTT::QOS0;
     message.retained = false;
     message.dup = false;
     message.payload = (void*)buf;
     message.payloadlen = strlen(buf)+1;
     rc = client.publish(topic, message);
+
+    printf("QoS0: Published to %s\n\t%s\n", topic, message.payload) ;
     while (arrivedcount < 1)
         client.yield(100);
-        
-    // QoS 1
-    sprintf(buf, "Hello World!  QoS 1 message from app version %f\n", version);
+
+// QoS 1
+    sprintf(buf, "\"%s\", QoS 1 message from app version %f\n", msg, version);
     message.qos = MQTT::QOS1;
+
     message.payloadlen = strlen(buf)+1;
     rc = client.publish(topic, message);
+    printf("QoS1: Published to %s\n\t%s\n", topic, message.payload) ;
     while (arrivedcount < 2)
         client.yield(100);
-        
-    // QoS 2
-    sprintf(buf, "Hello World!  QoS 2 message from app version %f\n", version);
+
+#if 0 /* QoS 2 not tested */
+// QoS 2
+    sprintf(buf, "\"%s\",  QoS 2 message from app version %f\n", version);
     message.qos = MQTT::QOS2;
     message.payloadlen = strlen(buf)+1;
     rc = client.publish(topic, message);
+    printf("QoS2: Published to %s\n\t%s\n", topic, message.payload) ;
     while (arrivedcount < 3)
         client.yield(100);
-        
-    // n * QoS 2
-    for (int i = 1; i <= 10; ++i)
-    {
-        sprintf(buf, "Hello World!  QoS 2 message number %d from app version %f\n", i, version);
+
+// n * QoS 2
+    for (int i = 1; i <= 10; ++i) {
+        sprintf(buf, "\"%s\", QoS 2 message number %d from app version %f\n", i, version);
         message.qos = MQTT::QOS2;
         message.payloadlen = strlen(buf)+1;
         rc = client.publish(topic, message);
+        printf("QoS2[%d]: Published to %s\n\t%s\n", i, topic, message.payload) ;
         while (arrivedcount < i + 3)
             client.yield(100);
     }
-    
+#endif
+
+    printf("unsubscribing\n") ;
     if ((rc = client.unsubscribe(topic)) != 0)
         printf("rc from unsubscribe was %d\n", rc);
-    
+
     if ((rc = client.disconnect()) != 0)
         printf("rc from disconnect was %d\n", rc);
-    
+
     ipstack.disconnect();
-    
-    lcd.cls();
-    lcd.locate(0,3);
-    lcd.printf("Version %.2f: finish %d msgs\n", version, arrivedcount);
+    printf("Version %.2f: finish %d msgs\n", version, arrivedcount);
     printf("Finishing with %d messages received\n", arrivedcount);
-    
-    return 0;
+
+    return ;
 }
+
+main()
+{
+#define STACK_SIZE 24000
+    Thread t(mqtt_main, NULL, osPriorityNormal, STACK_SIZE);
+    while (true) {
+        Thread::wait(1000);
+    }
+}