[209] | 1 | /*
|
---|
| 2 | Publishing in the callback
|
---|
| 3 |
|
---|
| 4 | - connects to an MQTT server
|
---|
| 5 | - subscribes to the topic "inTopic"
|
---|
| 6 | - when a message is received, republishes it to "outTopic"
|
---|
| 7 |
|
---|
| 8 | This example shows how to publish messages within the
|
---|
| 9 | callback function. The callback function header needs to
|
---|
| 10 | be declared before the PubSubClient constructor and the
|
---|
| 11 | actual callback defined afterwards.
|
---|
| 12 | This ensures the client reference in the callback function
|
---|
| 13 | is valid.
|
---|
| 14 |
|
---|
| 15 | */
|
---|
| 16 |
|
---|
| 17 | #include <SPI.h>
|
---|
| 18 | #include <Ethernet.h>
|
---|
| 19 | #include <PubSubClient.h>
|
---|
| 20 |
|
---|
| 21 | // Update these with values suitable for your network.
|
---|
| 22 | byte mac[] = { 0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xED };
|
---|
| 23 | IPAddress ip(172, 16, 0, 100);
|
---|
| 24 | IPAddress server(172, 16, 0, 2);
|
---|
| 25 |
|
---|
| 26 | // Callback function header
|
---|
| 27 | void callback(char* topic, byte* payload, unsigned int length);
|
---|
| 28 |
|
---|
| 29 | EthernetClient ethClient;
|
---|
| 30 | PubSubClient client(server, 1883, callback, ethClient);
|
---|
| 31 |
|
---|
| 32 | // Callback function
|
---|
| 33 | void callback(char* topic, byte* payload, unsigned int length) {
|
---|
| 34 | // In order to republish this payload, a copy must be made
|
---|
| 35 | // as the orignal payload buffer will be overwritten whilst
|
---|
| 36 | // constructing the PUBLISH packet.
|
---|
| 37 |
|
---|
| 38 | // Allocate the correct amount of memory for the payload copy
|
---|
| 39 | byte* p = (byte*)malloc(length);
|
---|
| 40 | // Copy the payload to the new buffer
|
---|
| 41 | memcpy(p,payload,length);
|
---|
| 42 | client.publish("outTopic", p, length);
|
---|
| 43 | // Free the memory
|
---|
| 44 | free(p);
|
---|
| 45 | }
|
---|
| 46 |
|
---|
| 47 | void setup()
|
---|
| 48 | {
|
---|
| 49 |
|
---|
| 50 | Ethernet.begin(mac, ip);
|
---|
| 51 | if (client.connect("arduinoClient")) {
|
---|
| 52 | client.publish("outTopic","hello world");
|
---|
| 53 | client.subscribe("inTopic");
|
---|
| 54 | }
|
---|
| 55 | }
|
---|
| 56 |
|
---|
| 57 | void loop()
|
---|
| 58 | {
|
---|
| 59 | client.loop();
|
---|
| 60 | }
|
---|