2012-09-13 22:35:48 +01:00
|
|
|
/*
|
2015-08-27 14:18:16 +01:00
|
|
|
Publishing in the callback
|
|
|
|
|
2012-09-13 22:35:48 +01:00
|
|
|
- connects to an MQTT server
|
|
|
|
- subscribes to the topic "inTopic"
|
|
|
|
- when a message is received, republishes it to "outTopic"
|
2015-08-27 14:18:16 +01:00
|
|
|
|
2012-09-13 22:35:48 +01:00
|
|
|
This example shows how to publish messages within the
|
|
|
|
callback function. The callback function header needs to
|
2015-08-27 14:18:16 +01:00
|
|
|
be declared before the PubSubClient constructor and the
|
2012-09-13 22:35:48 +01:00
|
|
|
actual callback defined afterwards.
|
|
|
|
This ensures the client reference in the callback function
|
|
|
|
is valid.
|
2015-08-27 14:18:16 +01:00
|
|
|
|
2012-09-13 22:35:48 +01:00
|
|
|
*/
|
|
|
|
|
|
|
|
#include <SPI.h>
|
|
|
|
#include <Ethernet.h>
|
|
|
|
#include <PubSubClient.h>
|
|
|
|
|
|
|
|
// Update these with values suitable for your network.
|
|
|
|
byte mac[] = { 0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xED };
|
2015-08-27 14:18:16 +01:00
|
|
|
IPAddress ip(172, 16, 0, 100);
|
|
|
|
IPAddress server(172, 16, 0, 2);
|
2012-09-13 22:35:48 +01:00
|
|
|
|
|
|
|
// Callback function header
|
|
|
|
void callback(char* topic, byte* payload, unsigned int length);
|
|
|
|
|
|
|
|
EthernetClient ethClient;
|
|
|
|
PubSubClient client(server, 1883, callback, ethClient);
|
|
|
|
|
|
|
|
// Callback function
|
|
|
|
void callback(char* topic, byte* payload, unsigned int length) {
|
2012-11-04 14:07:56 +00:00
|
|
|
// In order to republish this payload, a copy must be made
|
|
|
|
// as the orignal payload buffer will be overwritten whilst
|
|
|
|
// constructing the PUBLISH packet.
|
2015-08-27 14:18:16 +01:00
|
|
|
|
2012-11-04 14:07:56 +00:00
|
|
|
// Allocate the correct amount of memory for the payload copy
|
|
|
|
byte* p = (byte*)malloc(length);
|
|
|
|
// Copy the payload to the new buffer
|
|
|
|
memcpy(p,payload,length);
|
|
|
|
client.publish("outTopic", p, length);
|
|
|
|
// Free the memory
|
|
|
|
free(p);
|
2012-09-13 22:35:48 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
void setup()
|
|
|
|
{
|
2015-08-27 14:18:16 +01:00
|
|
|
|
2012-09-13 22:35:48 +01:00
|
|
|
Ethernet.begin(mac, ip);
|
|
|
|
if (client.connect("arduinoClient")) {
|
|
|
|
client.publish("outTopic","hello world");
|
|
|
|
client.subscribe("inTopic");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
void loop()
|
|
|
|
{
|
|
|
|
client.loop();
|
|
|
|
}
|