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:

main.cpp

Committer:
wolfSSL
Date:
2015-08-01
Revision:
20:0404c7f31c69
Parent:
17:25584027fae0

File content as of revision 20:0404c7f31c69:

/*******************************************************************************
 * Copyright (c) 2014 IBM Corp.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * and Eclipse Distribution License v1.0 which accompany this distribution.
 *
 * The Eclipse Public License is available at
 *    http://www.eclipse.org/legal/epl-v10.html
 * and the Eclipse Distribution License is available at
 *   http://www.eclipse.org/org/documents/edl-v10.php.
 *
 * 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.

*/
#define MQTTCLIENT_QOS2 1
#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;
    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;
    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] ;

    *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;

    printf("Version is %f\n", version);
    printf("Version is %f\n", version);

    MQTT::Client<MQTTEthernet, Countdown> client = MQTT::Client<MQTTEthernet, Countdown>(ipstack);
    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)
        printf("rc from TCP connect is %d\n", rc);

    if ((rc = client.connect(data)) != 0)
        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[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, "\"%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);

#if 1 /* QoS 2 not tested */
// QoS 2
    sprintf(buf, "\"%s\",  QoS 2 message from app version %f\n", msg, 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, "\"%s\", QoS 2 message number %d from app version %f\n",msg,  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();
    printf("Version %.2f: finish %d msgs\n", version, arrivedcount);
    printf("Finishing with %d messages received\n", arrivedcount);

    return ;
}

main()
{
#define STACK_SIZE 24000
    Thread t(mqtt_main, NULL, osPriorityNormal, STACK_SIZE);
    while (true) {
        Thread::wait(1000);
    }
}