MQTT Client example program. Ethernet connection is via an ENC28J60 module.
Dependencies: UIPEthernet MQTTClient
Diff: main.cpp
- Revision:
- 14:b2c96d7b4335
- Parent:
- 13:6b2f125cc9b8
- Child:
- 15:da8fef967438
--- a/main.cpp Sat Sep 07 18:14:51 2019 +0000 +++ b/main.cpp Thu Sep 12 20:27:21 2019 +0000 @@ -13,21 +13,44 @@ #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. -#define MQTT_PORT 1883 +#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 -void onMqttMessage(char* topic, uint8_t* payload, unsigned int length); // ISR (callback) to handle arrived MQTT messages. -TcpClient client; -MQTTClient mqttClient(SERVER_IP, MQTT_PORT, onMqttMessage, client); -char message_buff[MQTT_MAX_PACKET_SIZE]; // buffer to store received messages +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 + +/** + * @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 + * @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 @@ -92,31 +115,6 @@ } } - mqttClient.loop(); // MQTT client loop processing (receiving messages) + mqttClient.process(); // 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); -}