2019-05-29 22:49:54 +00:00
|
|
|
#include "my_mqtt.h"
|
|
|
|
#include "config.h"
|
|
|
|
#include <ESP8266WiFi.h>
|
|
|
|
#include <PubSubClient.h>
|
|
|
|
#include "EffectEntry.h"
|
|
|
|
#include "Effect.h"
|
|
|
|
#include "effects.h"
|
|
|
|
#include "functions.h"
|
|
|
|
|
|
|
|
WiFiClient wifi;
|
2019-05-21 03:52:57 +00:00
|
|
|
PubSubClient mqtt_client(wifi);
|
|
|
|
long mqtt_last_reconnect_attempt = 0;
|
|
|
|
|
2019-05-27 16:11:37 +00:00
|
|
|
void mqtt_callback(char* complete_topic, byte* pl, unsigned int length) {
|
|
|
|
pl[length] = '\0';
|
|
|
|
char* payload = (char*)pl;
|
|
|
|
char* topic = complete_topic + strlen(MQTT_TOPIC); // Strip MQTT_TOPIC from the beginning
|
2019-05-27 19:17:05 +00:00
|
|
|
|
2019-05-27 16:11:37 +00:00
|
|
|
// Here, payload is a char* (but has to be casted).
|
|
|
|
if(strcmp(topic, "mode")==0) {
|
2019-05-29 22:49:54 +00:00
|
|
|
for (int i=0; i<effects->size(); i++) {
|
|
|
|
EffectEntry e = effects->get(i);
|
|
|
|
if (strcmp(e.name, payload)==0) {
|
2019-05-25 18:30:11 +00:00
|
|
|
//Serial.printf("Effect found in mqtt_callback: %p\n", (void *)&e->effect);
|
2019-05-29 22:49:54 +00:00
|
|
|
current_effect = e.effect;
|
2019-05-25 18:30:11 +00:00
|
|
|
clear();
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
}
|
2019-05-27 16:11:37 +00:00
|
|
|
} else if (strcmp(topic, "reboot")==0) {
|
2019-05-25 21:38:41 +00:00
|
|
|
ESP.restart();
|
2019-05-21 03:52:57 +00:00
|
|
|
}
|
2019-05-27 19:17:05 +00:00
|
|
|
|
2019-05-27 16:11:37 +00:00
|
|
|
long value = atol(payload);
|
2019-05-27 19:17:05 +00:00
|
|
|
|
2019-05-27 16:11:37 +00:00
|
|
|
if (strcmp(topic, "brightness")==0 && value > 0 && value <= 255) {
|
2019-05-28 19:19:35 +00:00
|
|
|
FastLED.setBrightness(value);
|
2019-05-29 22:49:54 +00:00
|
|
|
}
|
2019-05-21 03:52:57 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
boolean mqtt_connect() {
|
2019-05-23 19:18:15 +00:00
|
|
|
char client_id[30];
|
|
|
|
snprintf(client_id, 30, HOSTNAME, ESP.getChipId());
|
|
|
|
LOG("MQTT * Connecting to MQTT server with client id "); LOGln(client_id);
|
|
|
|
if (mqtt_client.connect(client_id, MQTT_USER, MQTT_PASS)) {
|
|
|
|
LOGln("MQTT * Connected.");
|
2019-05-27 16:11:37 +00:00
|
|
|
mqtt_client.publish(MQTT_TOPIC "status", "ONLINE");
|
|
|
|
mqtt_client.subscribe(MQTT_TOPIC "+");
|
2019-05-21 03:52:57 +00:00
|
|
|
}
|
|
|
|
return mqtt_client.connected();
|
|
|
|
}
|
|
|
|
|
|
|
|
void mqtt_setup() {
|
|
|
|
mqtt_client.setServer(MQTT_SERVER, MQTT_PORT);
|
|
|
|
mqtt_client.setCallback(mqtt_callback);
|
|
|
|
mqtt_last_reconnect_attempt = 0;
|
|
|
|
}
|
|
|
|
|
|
|
|
void mqtt_loop() {
|
|
|
|
if (!mqtt_client.connected()) {
|
|
|
|
long now = millis();
|
|
|
|
if (now - mqtt_last_reconnect_attempt > 5000) {
|
|
|
|
mqtt_last_reconnect_attempt = now;
|
|
|
|
if (mqtt_connect()) {
|
|
|
|
mqtt_last_reconnect_attempt = 0;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
mqtt_client.loop();
|
|
|
|
}
|
|
|
|
}
|