#include "my_mqtt.h" #include "config.h" #ifndef MQTT_ENABLE #pragma message "MQTT_ENABLE is false. Skipping MQTT." #else #include #include #include "EffectEntry.h" #include "Effect.h" #include "effects.h" #include "functions.h" WiFiClient wifi; PubSubClient mqtt_client(wifi); long mqtt_last_reconnect_attempt = 0; 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 // Here, payload is a char* (but has to be casted). if(strcmp(topic, "mode")==0) { for (int i=0; isize(); i++) { EffectEntry e = effects->get(i); if (strcmp(e.name, payload)==0) { //Serial.printf("Effect found in mqtt_callback: %p\n", (void *)&e->effect); current_effect->stop(); current_effect = e.effect; current_effect->start(); clear(); return; } } } else if (strcmp(topic, "reboot")==0) { ESP.restart(); } long value = atol(payload); if (strcmp(topic, "brightness")==0 && value > 0 && value <= 255) { FastLED.setBrightness(value); } } boolean mqtt_connect() { 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."); mqtt_client.publish(MQTT_TOPIC "status", "ONLINE"); mqtt_client.subscribe(MQTT_TOPIC "+"); } 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(); } } String mqtt_log_str = String(); void mqtt_publish(const char* topic, int number) { char t[127]; sprintf(t, MQTT_TOPIC "%s", topic); char b[32]; sprintf(b, "%d", number); mqtt_client.publish(t, b); } void mqtt_log(const char* message) { mqtt_log_str.concat(message); } void mqtt_log(int number) { mqtt_log(String(number).c_str()); } void mqtt_log(long unsigned int number) { mqtt_log(String(number).c_str()); } void mqtt_log_ln(int number) { mqtt_log_ln(String(number).c_str()); } void mqtt_log_ln(long unsigned int number) { mqtt_log_ln(String(number).c_str()); } void mqtt_log_ln(const char* message) { if (mqtt_log_str.length()==0) { mqtt_log_send(message); return; } else { mqtt_log_str.concat(message); mqtt_log_send(mqtt_log_str.c_str()); mqtt_log_str = String(); } } void mqtt_log_send(const char* message) { if (mqtt_client.connected()) { mqtt_client.publish(MQTT_TOPIC_LOG, message); } } #endif // MQTT_ENABLE