Jack Hansdampf
/
MQTT_HelloENC28J60
MQTT client to test the ENC28J60-EMAC on NUCLEO-L152RE
main.cpp
- Committer:
- hudakz
- Date:
- 2021-03-27
- Revision:
- 2:2a16a9f4509c
- Parent:
- 1:1c2544eafc9c
- Child:
- 4:f8abf1fc6615
File content as of revision 2:2a16a9f4509c:
#include "mbed.h" #include "EthernetInterface.h" #include "MQTTNetwork.h" #include "MQTTmbed.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 const uint8_t MAC[6] = { 0, 1, 2, 3, 4, 5 }; // Global variables char topic[256]; EthernetInterface net; TCPSocket socket; MQTTNetwork mqttNetwork(&net); MQTT::Client<MQTTNetwork, Countdown> mqttClient(mqttNetwork); // Function prototypes void onMqttMsgReceived(MQTT::MessageData& md); /** * @brief * @note * @param * @retval */ FileHandle* mbed::mbed_override_console(int) { static BufferedSerial myConsole(USBTX, USBRX, 460800); return &myConsole; } /** * @brief * @note * @param * @retval */ int main(void) { // Bring up the ethernet interface net.set_network(IP, NETMASK, GATEWAY); // include this to use static IP address net.get_emac().set_hwaddr(MAC); // set MAC address printf("MQTT client example\n"); if (net.connect() != 0) { printf("Error connecting\n"); return -1; } // Show 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 %s:%d\r\n", BROKER_IP, MQTT_PORT); nsapi_error_t error = mqttNetwork.connect(BROKER_IP, MQTT_PORT); if (error == NSAPI_ERROR_OK) { printf("Server connected.\r\n"); } else { printf("Cannot connect server.\r\n"); return -1; } MQTTPacket_connectData data = MQTTPacket_connectData_initializer; data.MQTTVersion = 3; data.clientID.cstring = "MyMqttClient"; data.username.cstring = NULL; data.password.cstring = NULL; // Connect MQTT client to MQTT broker printf("Connecting MQTT Broker\r\n"); if (mqttClient.connect(data) != 0) { printf("Cannot connect MQTT broker.\r\n"); return -1; }; printf("MQTT Broker connected.\r\n"); // Subscribe to topics mqttClient.subscribe("workroomThermostat/#", MQTT::QOS0, onMqttMsgReceived); // Main thread loop while (1) { mqttClient.yield(10); } } /** * @brief * @note * @param * @retval */ void onMqttMsgReceived(MQTT::MessageData& md) { memset(topic, 0, sizeof(topic)); memcpy(topic, md.topicName.lenstring.data, md.topicName.lenstring.len); printf("topic: %s\r\n", topic); }