Sample MQTT program - simple send and receive

Dependencies:   C12832 MQTT

Dependents:   MQTT_G_SENSOR

This program and the MQTT libraries it uses are part of the EclipseTM Paho project; specifically the embedded client.

This example and API are working, but are still in progress. Please give us your feedback.

HelloMQTT is an example of using the MQTT API. The MQTT API is portable across network interface stacks. MQTT is designed to be used with TCP/IP, but any transport with similar characteristics should be suitable.

HelloMQTT uses the NetworkInterface APIs in mbed OS 5 to show how this works. The MQTT library contains an MQTTNetwork.h header, which is a wrapper around the mbed networking interface. To switch between connectivity methods (the default is Ethernet) the easy-connect library is provided in this example application. You can change the connectivity method in mbed_app.json.

Adding new connectivity methods to the program is trivial, as long as they implement the mbed OS 5 NetworkStack API.


Jan Jongboom
8 months ago

File content as of revision 20:49c9daf2b0ff:


#include "NetworkInterface.h"

class MQTTNetwork {
    MQTTNetwork(NetworkInterface* aNetwork) : network(aNetwork) {
        socket = new TCPSocket();

    ~MQTTNetwork() {
        delete socket;

    int read(unsigned char* buffer, int len, int timeout) {
        return socket->recv(buffer, len);

    int write(unsigned char* buffer, int len, int timeout) {
        return socket->send(buffer, len);

    int connect(const char* hostname, int port) {
        return socket->connect(hostname, port);

    void disconnect() {


    NetworkInterface* network;
    TCPSocket* socket;

#endif // _MQTTNETWORK_H_