53 lines
1.4 KiB
C++
53 lines
1.4 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);
|
||
|
uint16_t duration = 0;
|
||
|
int cp = payload.indexOf(",");
|
||
|
if (cp != -1) {
|
||
|
duration = payload.substring(cp+1).toInt();
|
||
|
payload = payload.substring(0, cp);
|
||
|
}
|
||
|
AnimationMode am;
|
||
|
if (payload.equals("corners")) am = AM_CORNERS;
|
||
|
else if (payload.equals("nodes")) am = AM_NODES;
|
||
|
|
||
|
if (duration > 0) {
|
||
|
temp_mode = am;
|
||
|
temp_mode_until = millis() + duration*1000;
|
||
|
} else {
|
||
|
mode = am;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
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();
|
||
|
}
|