Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AlphaSierraHotel/d1c49cb6f6abfef14ed27205627c1791 to your computer and use it in GitHub Desktop.
Save AlphaSierraHotel/d1c49cb6f6abfef14ed27205627c1791 to your computer and use it in GitHub Desktop.
pubsubclient MQTT Basic example receiving a message, process it in the main loop()
/*
The link below was the starting point for this program. Compare this gist with that to see the changes made.
https://github.com/knolleary/pubsubclient/blob/2d228f2f862a95846c65a8518c79f48dfc8f188c/examples/mqtt_basic/mqtt_basic.ino
*/
/*
Basic MQTT example
This sketch demonstrates the basic capabilities of the library.
It connects to an MQTT server then:
- publishes "hello world" to the topic "outTopic"
- subscribes to the topic "inTopic", printing out any messages
it receives. NB - it assumes the received payloads are strings not binary
It will reconnect to the server if the connection is lost using a blocking
reconnect function. See the 'mqtt_reconnect_nonblocking' example for how to
achieve the same result without blocking the main loop.
*/
#ifdef PLATFORMIO
#include <Arduino.h>
#endif
#include <SPI.h>
#include <Ethernet.h>
#include <PubSubClient.h>
// Global variables to share between the callback() function and the main loop()
const int MSG_BUFFER_SIZE = 128;
char rcvBuffer[MSG_BUFFER_SIZE];
char rcvTopic[MSG_BUFFER_SIZE];
boolean rcvFlag=false;
int rcvLen;
// Update these with values suitable for your network.
byte mac[] = { 0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0x89 };
IPAddress ip(172, 16, 0, 89);
IPAddress server(172, 16, 0, 12);
void callback(char* topic, byte* payload, unsigned int length) {
// We need to make copies of the data as topic and payload are pointers and once we leave
// this function, those pointers are reused and the data is no longer available to us.
// Copy topic, length and the payload so we can use them in the main loop
rcvFlag = true; // We use this to tell the main loop() that we have data
strcpy(rcvTopic,topic); // Copies the C string of the topic into variable rcvTopic
rcvLen = length; // Copies the value of length into rcvLen
// Since the payload is an array of bytes rather than chars, we use memcpy to copy the recieved
// message to our char array (C string). This all assumes that we are expecting a string
// but MQTT messages can also be binary data. Know your data. If you have JSON data being sent,
// see https://forum.arduino.cc/t/arduino-mqtt-client-decoding-subscribe-message/703415/21
memcpy(rcvBuffer, payload, length); // Copies a block of memory 'length' long to our rcvBuffer
rcvBuffer[length] = '\0'; // ensure the C string in rcvBuffer is properly terminated
}
EthernetClient ethClient;
PubSubClient client(ethClient);
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("arduinoClient")) {
Serial.println("connected");
// Once connected, publish an announcement...
client.publish("outTopic","hello world");
// ... and resubscribe
client.subscribe("inTopic");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void setup()
{
Serial.begin(57600);
client.setServer(server, 1883);
client.setCallback(callback);
Ethernet.begin(mac, ip);
// Allow the hardware to sort itself out
delay(1500);
}
void(* resetFunc) (void) = 0; //declare reset function at address 0
void loop()
{
if (!client.connected()) {
reconnect();
}
client.loop();
if (rcvFlag) {
Serial.println("A message was received.");
Serial.print("Length: "); Serial.println(rcvLen);
Serial.print("Topic: "); Serial.println(rcvTopic);
Serial.print("Message: "); Serial.println(rcvBuffer);
if (strcmp(rcvBuffer, "restart") == 0) {
Serial.println("Restart Command received");
Serial.flush();
delay(100);
resetFunc(); //call reset
}
rcvFlag = false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment