espleaf/src/mqtt.cpp

85 lines
2.9 KiB
C++

#include "mqtt.h"
#include "tools.h"
#include "prototypes.h"
void connect() {
LOGln("Connecting to MQTT broker...");
if (mqtt.connect(MQTT_CLIENT_ID, MQTT_USER, MQTT_PASS, MQTT_TOPIC_STATE, 0, true, "OFFLINE")) {
LOGln("Connected.");
mqtt.publish(MQTT_TOPIC_STATE, "ONLINE", true);
char buffer[40];
snprintf(buffer, 40, "ONLINE %s", wifi.localIP().toString().c_str());
mqtt.publish(MQTT_TOPIC_STATE_LONG, buffer, true);
mqtt.subscribe(MQTT_TOPIC_COMMANDS);
} else {
LOGln("Connection failed. Reason: %d", mqtt.state());
delay(1000);
}
}
void callback(char* topic, byte* pl, unsigned int length) {
pl[length] = 0;
String payload((char*)pl);
// Syntax: key=value&key2=value2...
uint16_t duration = 0;
AnimationMode new_mode = AM_NONE;
String current_part;
while (payload.length() > 0) {
int offset = payload.indexOf("&");
if (offset != -1) {
current_part = payload.substring(0, offset);
payload = payload.substring(offset + 1);
}
offset = current_part.indexOf("=");
if (offset==-1) continue;
String key = current_part.substring(0, offset);
String value = current_part.substring(offset+1);
if (key.equals("mode")) {
if (value.equals("nodes")) { new_mode = AM_NODES; }
else if (value.equals("first_node")) { new_mode = AM_FIRST_NODE; }
else if (value.equals("corners")) { new_mode = AM_CORNERS; }
else if (value.equals("first_corner")) { new_mode = AM_FIRST_CORNER; }
else if (value.equals("off")) { new_mode = AM_OFF; }
else if (value.equals("flash")) { new_mode = AM_FLASH; }
else { LOGln("Unknown mode '%s'.", value.c_str()); }
} else if (key.equals("duration")) {
duration = value.toInt();
} else if (key.equals("brightness")) {
if (temp_mode_until == 0) {
return_to_brightness = FastLED.getBrightness();
}
FastLED.setBrightness(value.toInt());
} else if (key.equals("color")) {
if (value.equals("red")) { color = CRGB::Red; }
else if (value.equals("green")) { color = CRGB::Green; }
else if (value.equals("blue")) { color = CRGB::Blue; }
else { LOGln("Unknown color name %s.", value.c_str());}
} else {
LOGln("Unknown key '%s'. (For reference: Value is '%s'.)", key.c_str(), value.c_str());
}
}
if (new_mode != AM_NONE) {
if (duration > 0) {
temp_mode = new_mode;
temp_mode_until = millis() + duration*1000;
} else {
mode = new_mode;
}
}
}
void mqtt_setup() {
mqtt.setServer(MQTT_SERVER, MQTT_SERVER_PORT);
mqtt.setCallback(callback);
mqtt.setSocketTimeout(1);
connect();
}
void mqtt_loop() {
if (!mqtt.connected()) {
connect();
}
mqtt.loop();
}