A friendly software forest ghost that takes care of your self-contained microbiomes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

80 lines
1.9 KiB

  1. #include "mqtt.h"
  2. #include "config.h"
  3. WiFiClient espClient;
  4. PubSubClient broker(espClient);
  5. String byte2str(byte* message, unsigned int length) {
  6. String retval;
  7. for (int i = 0; i < length; i++) {
  8. Serial.print((char)message[i]);
  9. retval += (char)message[i];
  10. }
  11. return retval;
  12. }
  13. void mqtt_callback(char* _topic, byte* _message, unsigned int _length) {
  14. String topic = String(_topic);
  15. String payload = byte2str( _message, _length );
  16. Serial.print("MQTT << ");
  17. Serial.print(topic);
  18. Serial.print(" [");
  19. Serial.print(payload);
  20. Serial.print("]");
  21. Serial.println();
  22. // // Feel free to add more if statements to control more GPIOs with MQTT
  23. // // If a message is received on the topic esp32/output, you check if the message is either "on" or "off".
  24. // // Changes the output state according to the message
  25. // if (String(topic) == "esp32/output") {
  26. // Serial.print("Changing output to ");
  27. // if(messageTemp == "on"){
  28. // Serial.println("on");
  29. // digitalWrite(ledPin, HIGH);
  30. // }
  31. // else if(messageTemp == "off"){
  32. // Serial.println("off");
  33. // digitalWrite(ledPin, LOW);
  34. // }
  35. // }
  36. }
  37. bool mqtt_init() {
  38. Serial.println("Initializing mqtt data stream...");
  39. broker.setServer(MQTT_BROKER, 1883);
  40. broker.setCallback(mqtt_callback);
  41. }
  42. void mqtt_reconnect() {
  43. // Loop until we're reconnected
  44. while (!broker.connected()) {
  45. Serial.print("Attempting MQTT connection...");
  46. // Attempt to connect
  47. if (broker.connect("kodama-AC234", MQTT_TOKEN, MQTT_PASSWD)) {
  48. Serial.println("connected");
  49. // Subscribe
  50. broker.subscribe("kodama/incoming");
  51. } else {
  52. Serial.print("failed, rc=");
  53. Serial.print(broker.state());
  54. Serial.println(" try again in 5 seconds");
  55. // Wait 5 seconds before retrying
  56. delay(5000);
  57. }
  58. }
  59. }
  60. void mqtt_pump() {
  61. if (!broker.connected()) {
  62. mqtt_reconnect();
  63. }
  64. broker.loop();
  65. }