MQTT Client example program. Ethernet connection is via an ENC28J60 module.

Dependencies:   UIPEthernet MQTTClient

main.cpp

Committer:
hudakz
Date:
2019-09-03
Revision:
12:3af0ae09bd01
Parent:
11:a049ad4b63c0
Child:
13:6b2f125cc9b8

File content as of revision 12:3af0ae09bd01:

// In this example we create an MQTT client.
// It's publishing messages with topic 'example/hello' and 'Hello World!' payload.
// The MQTT client also subscribes to some topics which are in its interest to receive.
// Ethernet connection is assured by an affordable ENC28J60 Ethernet module.
//
// MQTT broker is like a post office.
// Its task is to distribute messages published by clients to all subscribers (other clients).
// So the 'example/hello' messages published by this client will be sent to the broker.
// Then the broker will send them to all clients which subscribed to such topic (example/hello).
// Also this client will receive all messages with topics it subscribed to (if published such by other clients).
// 'Mosquitto' is a free implementation of MQTT broker for Linux (e.g. Raspberry Pi, Ubuntu etc.)
//
#include "mbed.h"
#include "UipEthernet.h"
#include "MQTTClient.h"
#include <string>

#define IP          "192.168.1.35"
#define GATEWAY     "192.168.1.1"
#define NETMASK     "255.255.255.0"
#define SERVER_IP   "192.168.1.31"              // IP address of your MQTT broker. Change to match your case.

// MAC address must unique within the connected network! Change it as needed.
const uint8_t   MAC[6] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x06 };
UipEthernet     net(MAC, D11, D12, D13, D10);   // mac, mosi, miso, sck, cs
void            onMqttMessage(char* topic, uint8_t* payload, unsigned int length);  // ISR (callback) to handle arrived MQTT messages.
TcpClient       client;
MQTTClient      mqttClient(SERVER_IP, 1883, onMqttMessage, client);
char            message_buff[MQTT_MAX_PACKET_SIZE];                                 // buffer to store received messages

/**
 * @brief
 * @note
 * @param
 * @retval
 */
int main(void)
{
    const int       MAX_TRIES = 5;
    const time_t    INTERVAL = 5;
    int             i = 0;
    bool            connected = false;
    char            payload[] = "Hello World!";
    time_t          t = 0;
    time_t          lastTime = t;

    // Bring up the ethernet interface
    //net.set_network(IP, NETMASK, GATEWAY);  // include this to use static IP address
    printf("MQTT client example\n");
    if (net.connect() != 0) {
        printf("Error connecting\n");
        return -1;
    }

    // Show the network address
    const char*     ip = net.get_ip_address();
    const char*     netmask = net.get_netmask();
    const char*     gateway = net.get_gateway();
    printf("IP address: %s\n", ip ? ip : "None");
    printf("Netmask: %s\n", netmask ? netmask : "None");
    printf("Gateway: %s\n", gateway ? gateway : "None");

    printf("Connecting to the MQTT broker ...  ");
    do {
        wait(1.0);
        connected = mqttClient.connect("myMQTTHelloClient");
    } while (!connected && (i++ < MAX_TRIES));

    if (connected) {
        printf("Connected.\r\n\r\n");
        // We can subscribe to various topics published by other clients.
        printf("Subscribing to topics:\r\n");
        printf("outdoor/temperature\r\n");
        printf("boiler/outlet/temperature\r\n");
        printf("\r\n");
        mqttClient.subscribe("outdoor/temperature");
        mqttClient.subscribe("boiler/outlet/temperature");
    }
    else {
        printf("Failed to connect to the MQTT broker.\r\n");
        return -1;
    }

    while (1) {
        t = time(NULL);
        if (t > (lastTime + INTERVAL)) {
            lastTime = t;
            if (connected) {
                printf("Publishing: example/hello\r\n");
                mqttClient.publish("example/hello", payload);
            }
        }

        mqttClient.loop();  // MQTT client loop processing (receiving messages)
    }
}

/**
 * @brief   Called on new MQTT message arrival
 * @note
 * @param   topic:      The topic of the new message
 *          payload:    The payload of the new message
 *          length:     Payload's length
 * @retval
 */
void onMqttMessage(char* topic, uint8_t* payload, unsigned int length)
{
    int i = 0;

    printf("Message arrived:\r\n");
    printf("    Topic: %s\r\n", topic);
    printf("    Length: %d\r\n", length);

    // create character buffer with ending null terminator (string)
    for (i = 0; i < length; i++) {
        message_buff[i] = payload[i];
    }

    message_buff[i] = '\0';
    printf("    Payload: %s\r\n\r\n", message_buff);
}