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.
|
|
#include "mqtt.h"
#include "config.h"
WiFiClient espClient; PubSubClient broker(espClient);
String byte2str(byte* message, unsigned int length) { String retval; for (int i = 0; i < length; i++) { Serial.print((char)message[i]); retval += (char)message[i]; }
return retval; }
void mqtt_callback(char* _topic, byte* _message, unsigned int _length) {
String topic = String(_topic); String payload = byte2str( _message, _length );
Serial.print("MQTT << "); Serial.print(topic); Serial.print(" ["); Serial.print(payload); Serial.print("]"); Serial.println();
// // Feel free to add more if statements to control more GPIOs with MQTT
// // If a message is received on the topic esp32/output, you check if the message is either "on" or "off".
// // Changes the output state according to the message
// if (String(topic) == "esp32/output") {
// Serial.print("Changing output to ");
// if(messageTemp == "on"){
// Serial.println("on");
// digitalWrite(ledPin, HIGH);
// }
// else if(messageTemp == "off"){
// Serial.println("off");
// digitalWrite(ledPin, LOW);
// }
// }
}
bool mqtt_init() { Serial.println("Initializing mqtt data stream..."); broker.setServer(MQTT_BROKER, 1883); broker.setCallback(mqtt_callback); }
void mqtt_reconnect() { // Loop until we're reconnected
while (!broker.connected()) { Serial.print("Attempting MQTT connection..."); // Attempt to connect
if (broker.connect("kodama-AC234", MQTT_TOKEN, MQTT_PASSWD)) { Serial.println("connected"); // Subscribe
broker.subscribe("kodama/incoming"); } else { Serial.print("failed, rc="); Serial.print(broker.state()); Serial.println(" try again in 5 seconds"); // Wait 5 seconds before retrying
delay(5000); } } }
void mqtt_pump() { if (!broker.connected()) { mqtt_reconnect(); } broker.loop(); }
|