A Threaded Secure MQTT Client example. Uses MBED TLS for SSL/TLS connection. QoS0 only for now. Example has been tested with K64F connected via Ethernet.

Dependencies:   FP MQTTPacket

Fork of HelloMQTT by MQTT

main.cpp

Committer:
vpcola
Date:
2017-03-21
Revision:
21:a7506c90aa84
Parent:
20:49c9daf2b0ff
Child:
22:826657a00c44

File content as of revision 21:a7506c90aa84:

/*******************************************************************************
 * Copyright (c) 2014, 2015 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
 *    Ian Craggs - make sure QoS2 processing works, and add device headers
 *******************************************************************************/

 /**
  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 "mbed.h"
#include "rtos.h"
#include "easy-connect.h"
#include "MQTTNetwork.h"
#include "MQTTmbed.h"
#include "MQTTClient.h"

Serial pc(USBTX, USBRX, 115200);
int arrivedcount = 0;

Thread msgSender;

static MemoryPool<MQTT::Message, 16> pool;
static Queue<MQTT::Message, 16> queue;

void messageArrived(MQTT::MessageData& md)
{
    MQTT::Message &message = md.message;
    printf("Message arrived: qos %d, retained %d, dup %d, packetid %d\r\n", message.qos, message.retained, message.dup, message.id);
    printf("Payload %.*s\r\n", message.payloadlen, (char*)message.payload);
    ++arrivedcount;
}

void SendDataThread()
{
    unsigned int i;
    while(true)
    {
        MQTT::Message * message = pool.alloc();
        char * buff = new char[sizeof(char) * 100];
        
        sprintf(buff, "message test %d", i);
        message->qos = MQTT::QOS0;
        message->retained = false;
        message->dup = false;
        message->payload = (void*)buff;
        message->payloadlen = strlen(buff)+1;
                    
        // publish the message to mqtt
        queue.put(message);  
        i++;
        
        Thread::wait(2000);         
    }   
}

int main(int argc, char* argv[])
{
    float version = 0.6;
    char* topic = "mbed-sample";

    printf("HelloMQTT: version is %.2f\r\n", version);

    NetworkInterface* network = easy_connect(true);
    if (!network) {
        return -1;
    }

    MQTTNetwork mqttNetwork(network);

    MQTT::Client<MQTTNetwork, Countdown> client = MQTT::Client<MQTTNetwork, Countdown>(mqttNetwork);

    const char* hostname = "m2m.eclipse.org";
    int port = 1883;
    printf("Connecting to %s:%d\r\n", hostname, port);
    int rc = mqttNetwork.connect(hostname, port);
    if (rc != 0)
        printf("rc from TCP connect is %d\r\n", rc);

    MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
    data.MQTTVersion = 3;
    data.clientID.cstring = "mbed-sample";
    data.username.cstring = "testuser";
    data.password.cstring = "testpassword";
    if ((rc = client.connect(data)) != 0)
        printf("rc from MQTT connect is %d\r\n", rc);

    if ((rc = client.subscribe(topic, MQTT::QOS2, messageArrived)) != 0)
        printf("rc from MQTT subscribe is %d\r\n", rc);

    // Start the data source
    msgSender.start(SendDataThread);
    
    while(true)
    {
        osEvent evt = queue.get(10);
        if (evt.status == osEventMessage) {
            printf("Message arrived from main thread ...\r\n");
            // Unpack the message
            MQTT::Message * message = (MQTT::Message *)evt.value.p;
            
            printf("Publishing message to MQTT ...\r\n");
            // Push to mqtt
            int rc = client.publish(topic, *message);
            if (rc < 0)
                printf("Error sending mqtt message \r\n");
            else
                printf("Message published ...\r\n");
            
            printf("Deleting payload ...\r\n");
            // Delete payload
            delete [] message->payload;
            
            printf("Deleting pool allocation ...\r\n");
            // Don't forget this!
            pool.free(message);
        }
        
        printf("MQTT client yeild ...\r\n");
        if (client.yield(100) != MQTT::SUCCESS)
        {
            printf("Yield error, client disconnected? ...\r\n");
            break;
        }
        printf("MQTT client yeild successful ...\r\n");               
    }

    if ((rc = client.unsubscribe(topic)) != 0)
        printf("rc from unsubscribe was %d\r\n", rc);

    if ((rc = client.disconnect()) != 0)
        printf("rc from disconnect was %d\r\n", rc);

    mqttNetwork.disconnect();

    printf("Version %.2f: finish %d msgs\r\n", version, arrivedcount);

    return 0;
}