Simple mqtt client using the MqttPacket lib to create a connect to the public broker and publish series of message. Done over Ethernet.

Dependencies:   C12832_lcd EthernetInterface MQTTPacket mbed-rtos mbed

main.cpp

Committer:
dvn
Date:
2018-06-14
Revision:
2:c285b1e518a6
Parent:
1:d7773c5860c2

File content as of revision 2:c285b1e518a6:

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

#include "mbed.h"
#include "EthernetInterface.h"
#include "C12832_lcd.h"

#include "MQTTPacket.h"

DigitalOut myled(LED2);
C12832_LCD lcd;

int publish(char* payload)
{
    int rc = 0;
    int len = 0;
    int payloadlen = strlen(payload);
    MQTTString topicString = MQTTString_initializer;
    MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
    TCPSocketConnection mysock;
    unsigned char buf[1024];
    int buflen = sizeof(buf);

    data.clientID.cstring = "0x556677448899330000";
    data.keepAliveInterval = 30;
    data.cleansession = 1;
    data.MQTTVersion = 3;    
    
    mysock.connect("m2m.eclipse.org", 1883);
    
    len = MQTTSerialize_connect((unsigned char*)buf, buflen, &data);

    topicString.cstring = "base";
    len += MQTTSerialize_publish((unsigned char*)buf + len, buflen - len, 0, 0, 0, 0, topicString, (unsigned char*)payload, payloadlen);

    len += MQTTSerialize_disconnect((unsigned char*)buf + len, buflen - len);

    rc = 0;
    while (rc < len) {
        int rc1 = mysock.send((char*)buf, len);
        if (rc1 == -1) {
            lcd.printf("Send failed\n");
            break;
        } else
            rc += rc1;
    }
    if (rc == len)
        lcd.printf("Sent: %s \n", payload);
    wait(0.2);

    return 0;
}

int main()
{
    EthernetInterface eth;
    eth.init(); //Use DHCP
    eth.connect();
    lcd.printf("IP Address is %s\n", eth.getIPAddress());

    myled = 1;
    publish("Message 1");
    wait(0.2);
    myled = 0;
    publish("Message 2");
    wait(0.2);

    eth.disconnect();
}