Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
#define DEBUG
#ifdef DEBUG
// https://forum.arduino.cc/index.php?topic=46900.0
#define DEBUG_PRINT(str) Serial.println(str);
#define DEBUG_PRINT2(str1, str2) Serial.print(str1); Serial.println(str2);
#else
#define DEBUG_PRINT(str)
#define DEBUG_PRINT2(str1, str2)
#endif
#include <UIPEthernet.h>
#include <PubSubClient.h>
#include "include/DebugUtils.h"
#define MQTT_CLIENT_ID "arduino-client" // replace with desired client name
#define MQTT_SERVER "mqtt-server.com" // replace with MQTT server or port
#define MQTT_SERVERPORT 1883U // mqtt port
#define MQTT_USERNAME "my-username" // replace with real username
#define MQTT_PASSWORD "some-long-password" // replace with real password
#define MQTT_REQUEST_TOPIC "/request/" // topic via which responses are sent
#define MQTT_RESPONSE_TOPIC "/response/" // topic which we subscribe to for requests
EthernetClient ethClient;
PubSubClient mqttClient;
void setup() {
#ifdef DEBUG
Serial.begin(9600);
#endif
DEBUG_PRINT("\n[setup started]");
initNetworking();
initMqtt();
}
/** sets up the MQTT client */
void initMqtt() {
mqttClient.setClient(ethClient);
mqttClient.setServer(MQTT_SERVER, MQTT_SERVERPORT);
mqttClient.setCallback(mqttMessageHandler);
}
/** Sets up the network layer */
void initNetworking() {
// ethernet mac address - must be unique on your network
uint8_t mymac[6] = { 0x74,0x69,0x69,0x2D,0x30,0x31 };
if(Ethernet.begin(mymac)) {
DEBUG_PRINT(F("=> DHCP lease issued"));
DEBUG_PRINT2(F(" IP: "), Ethernet.localIP());
DEBUG_PRINT2(F(" GW: "), Ethernet.gatewayIP());
DEBUG_PRINT2(F(" DNS:"), Ethernet.dnsServerIP());
} else {
DEBUG_PRINT(F("=> failed to get DHCP lease"));
}
// Allow the hardware to sort itself out
delay(1500);
}
void loop() {
if (!mqttClient.connected()) {
mqttReconnect();
}
mqttClient.loop();
}
/** connects to MQTT server */
void mqttReconnect() {
if(mqttClient.connect(MQTT_CLIENT_ID, MQTT_USERNAME, MQTT_PASSWORD)) {
DEBUG_PRINT("\n=> MQTT connected");
DEBUG_PRINT2("\n=> subscribed to ", MQTT_REQUEST_TOPIC);
mqttClient.subscribe(MQTT_REQUEST_TOPIC);
if(mqttClient.publish(MQTT_RESPONSE_TOPIC, "Hello world! I'm listening...")) {
DEBUG_PRINT("\n=> MQTT successfull publish");
} else {
DEBUG_PRINT("\n=> MQTT publish failed");
}
} else {
DEBUG_PRINT("\n=> MQTT connection failed");
}
}
/** Handles messages received via MQTT */
void mqttMessageHandler(char* topic, byte* payload, unsigned int length) {
char buff[length+1];
memcpy(buff, payload, length);
buff[length] = 0; // string terminator
DEBUG_PRINT2("\n=> MQTT message received in topic", topic);
DEBUG_PRINT2("\n message=", buff);
mqttClient.publish(MQTT_RESPONSE_TOPIC, "Thank you for your message!");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment