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

Dependencies:   UIPEthernet MQTTClient

Revision:
15:da8fef967438
Parent:
14:b2c96d7b4335
Child:
16:2c61673000e8
--- a/main.cpp	Thu Sep 12 20:27:21 2019 +0000
+++ b/main.cpp	Thu Sep 12 22:01:55 2019 +0000
@@ -23,16 +23,15 @@
 // 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
-void            onMqttMessage(char* topic, uint8_t* payload, uint16_t length);  // ISR (callback) to handle received MQTT messages.
-MQTTClient      mqttClient(BROKER_IP, MQTT_PORT, onMqttMessage);
-char            msgBuf[MQTT_MAX_PACKET_SIZE];                                   // buffer to store received MQTT messages
+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
- *          payload:    The payload of received message
- *          length:     Payload's length
+ * @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)
@@ -105,7 +104,13 @@
         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;
@@ -114,7 +119,5 @@
                 mqttClient.publish("example/hello", payload);
             }
         }
-
-        mqttClient.process();   // MQTT client loop processing (receiving messages)
     }
 }