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

Dependencies:   UIPEthernet MQTTClient

main.cpp

Committer:
hudakz
Date:
2020-07-23
Revision:
17:fd2c65e246aa
Parent:
16:2c61673000e8

File content as of revision 17:fd2c65e246aa:

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

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

// MAC address must unique within the connected network! Change it as needed.
const uint8_t   MAC[6] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05 };
UipEthernet     net(MAC, D11, D12, D13, D10);   // mac, mosi, miso, sck, cs
MQTTClient      mqttClient(BROKER_IP, MQTT_PORT);
char            msgBuf[MQTT_MAX_PACKET_SIZE];   // buffer to store received MQTT messages

/**
 * @brief   ISR to handle received MQTT messages
 * @note    Called on arrival of new MQTT message
 * @param   topic       The topic of received message
 * @param   payload     The payload of received message
 * @param   length      Payload's length
 * @retval
 */
void onMqttMessage(char* topic, uint8_t* payload, uint16_t 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++) {
        msgBuf[i] = payload[i];
    }

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

/**
 * @brief
 * @note
 * @param
 * @retval
 */
int main(void)
{
    const int       MAX_TRIES = 1;
    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   
    SocketAddress   addr;
    net.get_ip_address(&addr);
    printf("IP address: %s\n", addr.get_ip_address() ? addr.get_ip_address() : "None");
    net.get_netmask(&addr);
    printf("Netmask: %s\n", addr.get_ip_address() ? addr.get_ip_address() : "None");
    net.get_gateway(&addr);
    printf("Gateway: %s\n", addr.get_ip_address() ? addr.get_ip_address() : "None");


    printf("Connecting to the MQTT broker ...\r\n");
    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;
    }

    // Attach ISR (callback) handling new MQTT message from the broker
    mqttClient.attach(onMqttMessage);

    while (1) {
        mqttClient.poll();  // poll new MQTT messages from the broker

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