Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <FS.h>
- #include <ESP8266WiFi.h>
- #include <DNSServer.h>
- #include <ESP8266WebServer.h>
- #include <WiFiManager.h>
- #include <ArduinoJson.h>
- #define MQTT_MAX_PACKET_SIZE 256 // fix for MQTT client dropping messages over 128B
- #include <PubSubClient.h>
- #include <Ticker.h>
- Ticker ticker;
- WiFiClient espClient;
- PubSubClient client(espClient);
- char mqtt_server[40] = "XXXXXXX";
- char mqtt_temp[6] = "1883"; //PubSub needs uint16_t, this is used for port saving
- uint16_t mqtt_port;
- char mqtt_user[20]="XXXXXXX";
- char mqtt_password[20]="XXXXXXX";
- char mqtt_pub_topic[40] = "esp/XXXXXXX/pub";
- char mqtt_sub_topic[40] = "esp/XXXXXXX/sub";
- char mqtt_device[40] = "ESP-XXXXXXX";
- bool shouldSaveConfig = false;
- bool debug = false;
- // Button Stuff
- #define raus D1
- #define rein D2
- // misc Stuff
- int LED = LED_BUILTIN;
- // MQTT Stuff
- char msg[100];
- unsigned long MQTTstart = 0;
- unsigned long DELAY_TIME = 100;
- void tick() {
- digitalWrite(LED, !digitalRead(LED));
- }
- void saveConfigCallback () {
- if (debug) {
- Serial.println("[SETUP] Should save config");
- }
- shouldSaveConfig = true;
- }
- void configModeCallback (WiFiManager *myWiFiManager) {
- if (debug) {
- Serial.println("[SETUP] Entered config mode");
- Serial.println(WiFi.softAPIP());
- Serial.println(myWiFiManager->getConfigPortalSSID());
- }
- ticker.attach(0.2, tick);
- }
- void setup()
- {
- WiFi.mode(WIFI_STA);
- pinMode(LED, OUTPUT);
- pinMode(raus, OUTPUT);
- pinMode(rein, OUTPUT);
- digitalWrite(rein, HIGH);
- digitalWrite(raus, HIGH);
- delay(5000);
- ticker.attach(0.6, tick);
- if (debug) {
- Serial.begin(115200);
- Serial.setTimeout(2000);
- while (!Serial) { }
- Serial.println();
- Serial.println("######################");
- Serial.println("[SETUP] Boot started");
- Serial.println("[SETUP] Mounting FS...");
- }
- if (SPIFFS.begin()) {
- if (debug) {
- Serial.println("[SETUP] Mounted file system");
- }
- if (SPIFFS.exists("/config.json")) {
- if (debug) {
- Serial.println("[SETUP] Reading config file");
- }
- File configFile = SPIFFS.open("/config.json", "r");
- if (configFile) {
- if (debug) {
- Serial.println("[SETUP] Opened config file");
- }
- size_t size = configFile.size();
- std::unique_ptr<char[]> buf(new char[size]);
- configFile.readBytes(buf.get(), size);
- DynamicJsonDocument json(1024);
- auto deserializeError = deserializeJson(json, buf.get());
- serializeJson(json, Serial);
- if (!deserializeError) {
- if (debug) {
- Serial.println("\n[SETUP] Restore saved values");
- }
- strcpy(mqtt_server, json["mqtt_server"]);
- strcpy(mqtt_temp, json["mqtt_port"]);
- strcpy(mqtt_user, json["mqtt_user"]);
- strcpy(mqtt_password, json["mqtt_password"]);
- strcpy(mqtt_pub_topic, json["mqtt_pub_topic"]);
- strcpy(mqtt_sub_topic, json["mqtt_sub_topic"]);
- strcpy(mqtt_device, json["mqtt_device"]);
- } else {
- if (debug) {
- Serial.println("[SETUP] Failed to load json config");
- }
- }
- configFile.close();
- }
- }
- } else {
- if (debug) {
- Serial.println("[SETUP] Failed to mount FS");
- }
- }
- WiFiManagerParameter custom_mqtt_server("server", "MQTT Server IP/DNS Address", mqtt_server, 40);
- WiFiManagerParameter custom_mqtt_port("port", "MQTT Port (Default: 1883)", mqtt_temp, 6);
- WiFiManagerParameter custom_mqtt_user("user", "MQTT Username", mqtt_user, 20);
- WiFiManagerParameter custom_mqtt_password("pass", "MQTT Password", mqtt_password, 20);
- WiFiManagerParameter custom_mqtt_pub_topic("pubtopic", "MQTT Topic to publish Messages", mqtt_pub_topic, 40);
- WiFiManagerParameter custom_mqtt_sub_topic("subtopic", "MQTT Topic to subscribe Messages", mqtt_sub_topic, 40);
- WiFiManagerParameter custom_mqtt_device("device", "MQTT Device Name", mqtt_device, 40);
- WiFiManager wm;
- wm.setTimeout(180);
- wm.setMinimumSignalQuality(25);
- wm.setRemoveDuplicateAPs(true);
- wm.setDebugOutput(debug);
- wm.setWiFiAutoReconnect(true);
- wm.setConnectTimeout(60);
- wm.setAPCallback(configModeCallback);
- wm.setSaveConfigCallback(saveConfigCallback);
- wm.addParameter(&custom_mqtt_server);
- wm.addParameter(&custom_mqtt_port);
- wm.addParameter(&custom_mqtt_user);
- wm.addParameter(&custom_mqtt_password);
- wm.addParameter(&custom_mqtt_pub_topic);
- wm.addParameter(&custom_mqtt_sub_topic);
- wm.addParameter(&custom_mqtt_device);
- wm.addParameter(&custom_mqtt_device);
- //wm.resetSettings();
- if (!wm.autoConnect()) {
- ESP.restart();
- ticker.detach();
- digitalWrite(LED, LOW);
- delay(5000);
- }
- if (debug) {
- Serial.println("[SETUP] Connected");
- }
- strcpy(mqtt_server, custom_mqtt_server.getValue());
- strcpy(mqtt_temp, custom_mqtt_port.getValue());
- strcpy(mqtt_user, custom_mqtt_user.getValue());
- strcpy(mqtt_password, custom_mqtt_password.getValue());
- strcpy(mqtt_pub_topic, custom_mqtt_pub_topic.getValue());
- strcpy(mqtt_sub_topic, custom_mqtt_sub_topic.getValue());
- strcpy(mqtt_device, custom_mqtt_device.getValue());
- if (shouldSaveConfig) {
- if (debug) {
- Serial.println("[SETUP] Saving config");
- }
- DynamicJsonDocument json(1024);
- json["mqtt_server"] = mqtt_server;
- json["mqtt_port"] = mqtt_temp;
- json["mqtt_user"] = mqtt_user;
- json["mqtt_password"] = mqtt_password;
- json["mqtt_pub_topic"] = mqtt_pub_topic;
- json["mqtt_sub_topic"] = mqtt_sub_topic;
- json["mqtt_device"] = mqtt_device;
- File configFile = SPIFFS.open("/config.json", "w");
- if (!configFile && debug) {
- Serial.println("[SETUP] Failed to open config file for writing");
- }
- serializeJson(json, Serial);
- serializeJson(json, configFile);
- configFile.close();
- }
- if (debug) {
- Serial.print("[SETUP] Local ip: ");
- Serial.println(WiFi.localIP());
- }
- mqtt_port = (uint16_t)strtol(mqtt_temp, NULL, 10);
- client.setServer(mqtt_server, mqtt_port);
- client.setCallback(callback);
- while (!client.connected()) {
- if (debug) {
- Serial.println("[SETUP] Connecting to MQTT-Server");
- Serial.println((String)"[SETUP] IP: " + mqtt_server + ":" + mqtt_port);
- Serial.println((String)"[SETUP] State: " + client.state());
- }
- if (client.connect(mqtt_device, mqtt_user, mqtt_password)) {
- if (debug) {
- Serial.println("[SETUP] Succeeded");
- }
- ticker.detach();
- digitalWrite(LED, HIGH);
- } else {
- if (debug) {
- Serial.println("[SETUP] Failed");
- }
- ticker.detach();
- digitalWrite(LED, LOW);
- delay(2000);
- }
- }
- if (debug) {
- Serial.println((String)"[SETUP] SSID: " + wm.getWiFiSSID() + " PW: " + wm.getWiFiPass());
- }
- const size_t capacity = JSON_OBJECT_SIZE(3) + JSON_OBJECT_SIZE(6) + 130;
- DynamicJsonDocument doc(capacity);
- doc["status"] = "connected";
- doc["subTopic"] = mqtt_sub_topic;
- char JSONmessageBuffer[capacity];
- serializeJson(doc, JSONmessageBuffer);
- client.publish(mqtt_pub_topic, JSONmessageBuffer);
- client.subscribe(mqtt_sub_topic);
- if (debug) {
- Serial.println("[SETUP] Boot finished");
- Serial.println("######################");
- Serial.println();
- }
- }
- void callback(char* topic, byte* payload, unsigned int length) {
- String msg;
- for (byte i = 0; i < length; i++) {
- char tmp = char(payload[i]);
- msg += tmp;
- }
- if (debug) {
- Serial.println();
- Serial.println("[MQTT] *******************************");
- Serial.println("[MQTT] New Message arrived");
- Serial.println((String)"[MQTT] Topic: " + topic);
- Serial.println((String)"[MQTT] Message: " + msg);
- Serial.println("[MQTT] *******************************");
- Serial.println();
- }
- const size_t capacity = JSON_OBJECT_SIZE(3) + JSON_OBJECT_SIZE(6) + 130;
- DynamicJsonDocument doc(capacity);
- doc["status"] = msg;
- char JSONmessageBuffer[capacity];
- serializeJson(doc, JSONmessageBuffer);
- client.publish(mqtt_pub_topic, JSONmessageBuffer);
- if (msg == "true") {
- digitalWrite(raus, LOW);
- delay(1500);
- digitalWrite(raus, HIGH);
- }
- if (msg == "false") {
- digitalWrite(rein, LOW);
- delay(1500);
- digitalWrite(rein, HIGH);
- }
- if (msg == "restart") {
- ESP.restart();
- }
- }
- boolean reconnect()
- {
- if (client.connect(mqtt_device, mqtt_user, mqtt_password )) {
- ticker.attach(0.2, tick);
- const size_t capacity = JSON_OBJECT_SIZE(3) + JSON_OBJECT_SIZE(6) + 130;
- DynamicJsonDocument doc(capacity);
- doc["status"] = "reconnected";
- doc["subTopic"] = mqtt_sub_topic;
- char JSONmessageBuffer[capacity];
- serializeJson(doc, JSONmessageBuffer);
- client.publish(mqtt_pub_topic, JSONmessageBuffer);
- client.subscribe(mqtt_sub_topic);
- if (debug) {
- Serial.println("[MQTT] Reconnected");
- }
- ticker.detach();
- digitalWrite(LED, HIGH);
- }
- return client.connected();
- }
- void mqttConnection()
- {
- if (!client.connected()) {
- if ((millis() - MQTTstart) >= 5000) {
- MQTTstart += 5000;
- ticker.attach(1.6, tick);
- if (debug) {
- Serial.println("[MQTT] Connection is lost");
- }
- if (reconnect()) {
- }
- }
- } else {
- client.loop();
- }
- }
- void loop()
- {
- mqttConnection();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement