#include "mqtt.h" #include "tools.h" #include "prototypes.h" #include "state.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 "available", "online", true); char buffer[40]; snprintf(buffer, 40, "online %s", wifi.localIP().toString().c_str()); mqtt.publish(MQTT_TOPIC "available_long", buffer, true); mqtt.subscribe(MQTT_TOPIC"cmnd"); String discovery_msg = "{\"" "\"~\":\"" MQTT_TOPIC ",\"avty_t\":\"~available\",\"cmd_t\":\"~cmnd\",\"stat_t\":\"~state\"," "\"name\":\"ESPleaf\",\"schema\":\"json\"," "\"brightness\":true,\"bri_scl\":255," "\"effect\":true,\"effect_list\":[\"off\",\"corners\",\"nodes\",\"flash\",\"static\"]," "\"rgb\":true}"; mqtt.publish("homeassistant/light/" HOMEASSISTANT_OBJECT_ID "/config", discovery_msg.c_str(), true); } else { LOGln("Connection failed. Reason: %d", mqtt.state()); delay(1000); } } void callback(char* topic, byte* pl, unsigned int length) { pl[length] = 0; State s; if (pl[0]=='{') { s.parse_json((char*)pl); } else { String payload((char*)pl); // Syntax: key=value&key2=value2... String current_part; LOGln("Received command %s", payload.c_str()); while (payload.length() > 0) { int offset = payload.indexOf("&"); if (offset != -1) { current_part = payload.substring(0, offset); payload = payload.substring(offset + 1); } else { current_part = payload; payload = ""; } offset = current_part.indexOf("="); if (offset==-1) { LOGln("Parameter without '=' detected: %s", current_part.c_str()); continue; } String key = current_part.substring(0, offset); String value = current_part.substring(offset+1); s.set(key, value); } } s.commit(); } 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(); } void mqtt_publish_current_state(String state) { mqtt.publish(MQTT_TOPIC "state", state.c_str(), true); };