mqtt_publish_in_callback.ino 1.5 KB

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