Advertisement
Guest User

somfy_esp8266_mqtt

a guest
Aug 8th, 2021
184
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <FS.h>
  2. #include <ESP8266WiFi.h>
  3. #include <DNSServer.h>
  4. #include <ESP8266WebServer.h>
  5. #include <WiFiManager.h>
  6. #include <ArduinoJson.h>
  7. #define MQTT_MAX_PACKET_SIZE 256  // fix for MQTT client dropping messages over 128B
  8. #include <PubSubClient.h>
  9. #include <Ticker.h>
  10.  
  11. Ticker ticker;
  12. WiFiClient espClient;
  13. PubSubClient client(espClient);
  14.  
  15. char mqtt_server[40] = "XXXXXXX";
  16. char mqtt_temp[6] = "1883"; //PubSub needs uint16_t, this is used for port saving
  17. uint16_t mqtt_port;
  18. char mqtt_user[20]="XXXXXXX";
  19. char mqtt_password[20]="XXXXXXX";
  20. char mqtt_pub_topic[40] = "esp/XXXXXXX/pub";
  21. char mqtt_sub_topic[40] = "esp/XXXXXXX/sub";
  22. char mqtt_device[40] = "ESP-XXXXXXX";
  23.  
  24. bool shouldSaveConfig = false;
  25. bool debug = false;
  26.  
  27. // Button Stuff
  28. #define raus D1
  29. #define rein D2
  30.  
  31. // misc Stuff
  32. int LED = LED_BUILTIN;
  33.  
  34. // MQTT Stuff
  35. char msg[100];
  36. unsigned long MQTTstart = 0;
  37. unsigned long DELAY_TIME = 100;
  38.  
  39. void tick() {
  40.   digitalWrite(LED, !digitalRead(LED));
  41. }
  42.  
  43. void saveConfigCallback () {
  44.   if (debug) {
  45.     Serial.println("[SETUP] Should save config");
  46.   }
  47.   shouldSaveConfig = true;
  48. }
  49.  
  50. void configModeCallback (WiFiManager *myWiFiManager) {
  51.   if (debug) {
  52.     Serial.println("[SETUP] Entered config mode");
  53.     Serial.println(WiFi.softAPIP());
  54.     Serial.println(myWiFiManager->getConfigPortalSSID());
  55.   }
  56.   ticker.attach(0.2, tick);
  57. }
  58.  
  59. void setup()
  60. {
  61.   WiFi.mode(WIFI_STA);
  62.   pinMode(LED, OUTPUT);
  63.   pinMode(raus, OUTPUT);
  64.   pinMode(rein, OUTPUT);
  65.  
  66.   digitalWrite(rein, HIGH);
  67.   digitalWrite(raus, HIGH);
  68.  
  69.   delay(5000);
  70.   ticker.attach(0.6, tick);
  71.  
  72.   if (debug) {
  73.     Serial.begin(115200);
  74.     Serial.setTimeout(2000);
  75.     while (!Serial) { }
  76.     Serial.println();
  77.     Serial.println("######################");
  78.     Serial.println("[SETUP] Boot started");
  79.     Serial.println("[SETUP] Mounting FS...");
  80.   }
  81.  
  82.   if (SPIFFS.begin()) {
  83.     if (debug) {
  84.       Serial.println("[SETUP] Mounted file system");
  85.     }
  86.     if (SPIFFS.exists("/config.json")) {
  87.       if (debug) {
  88.         Serial.println("[SETUP] Reading config file");
  89.       }
  90.       File configFile = SPIFFS.open("/config.json", "r");
  91.       if (configFile) {
  92.         if (debug) {
  93.           Serial.println("[SETUP] Opened config file");
  94.         }
  95.         size_t size = configFile.size();
  96.         std::unique_ptr<char[]> buf(new char[size]);
  97.  
  98.         configFile.readBytes(buf.get(), size);
  99.         DynamicJsonDocument json(1024);
  100.         auto deserializeError = deserializeJson(json, buf.get());
  101.         serializeJson(json, Serial);
  102.         if (!deserializeError) {
  103.           if (debug) {
  104.             Serial.println("\n[SETUP] Restore saved values");
  105.           }
  106.  
  107.           strcpy(mqtt_server, json["mqtt_server"]);
  108.           strcpy(mqtt_temp, json["mqtt_port"]);
  109.           strcpy(mqtt_user, json["mqtt_user"]);
  110.           strcpy(mqtt_password, json["mqtt_password"]);
  111.           strcpy(mqtt_pub_topic, json["mqtt_pub_topic"]);
  112.           strcpy(mqtt_sub_topic, json["mqtt_sub_topic"]);
  113.           strcpy(mqtt_device, json["mqtt_device"]);
  114.  
  115.         } else {
  116.           if (debug) {
  117.             Serial.println("[SETUP] Failed to load json config");
  118.           }
  119.         }
  120.         configFile.close();
  121.       }
  122.     }
  123.   } else {
  124.     if (debug) {
  125.       Serial.println("[SETUP] Failed to mount FS");
  126.     }
  127.   }
  128.  
  129.   WiFiManagerParameter custom_mqtt_server("server", "MQTT Server IP/DNS Address", mqtt_server, 40);
  130.   WiFiManagerParameter custom_mqtt_port("port", "MQTT Port (Default: 1883)", mqtt_temp, 6);
  131.   WiFiManagerParameter custom_mqtt_user("user", "MQTT Username", mqtt_user, 20);
  132.   WiFiManagerParameter custom_mqtt_password("pass", "MQTT Password", mqtt_password, 20);
  133.   WiFiManagerParameter custom_mqtt_pub_topic("pubtopic", "MQTT Topic to publish Messages", mqtt_pub_topic, 40);
  134.   WiFiManagerParameter custom_mqtt_sub_topic("subtopic", "MQTT Topic to subscribe Messages", mqtt_sub_topic, 40);
  135.   WiFiManagerParameter custom_mqtt_device("device", "MQTT Device Name", mqtt_device, 40);
  136.  
  137.   WiFiManager wm;
  138.  
  139.   wm.setTimeout(180);
  140.   wm.setMinimumSignalQuality(25);
  141.   wm.setRemoveDuplicateAPs(true);
  142.   wm.setDebugOutput(debug);
  143.   wm.setWiFiAutoReconnect(true);
  144.   wm.setConnectTimeout(60);
  145.  
  146.   wm.setAPCallback(configModeCallback);
  147.   wm.setSaveConfigCallback(saveConfigCallback);
  148.  
  149.   wm.addParameter(&custom_mqtt_server);
  150.   wm.addParameter(&custom_mqtt_port);
  151.   wm.addParameter(&custom_mqtt_user);
  152.   wm.addParameter(&custom_mqtt_password);
  153.   wm.addParameter(&custom_mqtt_pub_topic);
  154.   wm.addParameter(&custom_mqtt_sub_topic);
  155.   wm.addParameter(&custom_mqtt_device);
  156.   wm.addParameter(&custom_mqtt_device);
  157.  
  158.   //wm.resetSettings();
  159.  
  160.   if (!wm.autoConnect()) {
  161.     ESP.restart();
  162.     ticker.detach();
  163.     digitalWrite(LED, LOW);
  164.     delay(5000);
  165.   }
  166.  
  167.   if (debug) {
  168.     Serial.println("[SETUP] Connected");
  169.   }
  170.  
  171.   strcpy(mqtt_server, custom_mqtt_server.getValue());
  172.   strcpy(mqtt_temp, custom_mqtt_port.getValue());
  173.   strcpy(mqtt_user, custom_mqtt_user.getValue());
  174.   strcpy(mqtt_password, custom_mqtt_password.getValue());
  175.   strcpy(mqtt_pub_topic, custom_mqtt_pub_topic.getValue());
  176.   strcpy(mqtt_sub_topic, custom_mqtt_sub_topic.getValue());
  177.   strcpy(mqtt_device, custom_mqtt_device.getValue());
  178.  
  179.   if (shouldSaveConfig) {
  180.     if (debug) {
  181.       Serial.println("[SETUP] Saving config");
  182.     }
  183.     DynamicJsonDocument json(1024);
  184.     json["mqtt_server"] = mqtt_server;
  185.     json["mqtt_port"] = mqtt_temp;
  186.     json["mqtt_user"] = mqtt_user;
  187.     json["mqtt_password"] = mqtt_password;
  188.     json["mqtt_pub_topic"] = mqtt_pub_topic;
  189.     json["mqtt_sub_topic"] = mqtt_sub_topic;
  190.     json["mqtt_device"] = mqtt_device;
  191.  
  192.     File configFile = SPIFFS.open("/config.json", "w");
  193.     if (!configFile && debug) {
  194.       Serial.println("[SETUP] Failed to open config file for writing");
  195.     }
  196.  
  197.     serializeJson(json, Serial);
  198.     serializeJson(json, configFile);
  199.     configFile.close();
  200.   }
  201.  
  202.   if (debug) {
  203.     Serial.print("[SETUP] Local ip: ");
  204.     Serial.println(WiFi.localIP());
  205.   }
  206.  
  207.   mqtt_port = (uint16_t)strtol(mqtt_temp, NULL, 10);
  208.  
  209.   client.setServer(mqtt_server, mqtt_port);
  210.   client.setCallback(callback);
  211.  
  212.   while (!client.connected()) {
  213.     if (debug) {
  214.       Serial.println("[SETUP] Connecting to MQTT-Server");
  215.       Serial.println((String)"[SETUP] IP:    " + mqtt_server + ":" + mqtt_port);
  216.       Serial.println((String)"[SETUP] State: " + client.state());
  217.     }
  218.     if (client.connect(mqtt_device, mqtt_user, mqtt_password)) {
  219.  
  220.       if (debug) {
  221.         Serial.println("[SETUP] Succeeded");
  222.       }
  223.       ticker.detach();
  224.       digitalWrite(LED, HIGH);
  225.     } else {
  226.       if (debug) {
  227.         Serial.println("[SETUP] Failed");
  228.       }
  229.       ticker.detach();
  230.       digitalWrite(LED, LOW);
  231.       delay(2000);
  232.     }
  233.   }
  234.  
  235.   if (debug) {
  236.     Serial.println((String)"[SETUP] SSID: " + wm.getWiFiSSID() + " PW: " + wm.getWiFiPass());
  237.   }
  238.  
  239.   const size_t capacity = JSON_OBJECT_SIZE(3) + JSON_OBJECT_SIZE(6) + 130;
  240.   DynamicJsonDocument doc(capacity);
  241.   doc["status"] = "connected";
  242.   doc["subTopic"] = mqtt_sub_topic;
  243.  
  244.   char JSONmessageBuffer[capacity];
  245.   serializeJson(doc, JSONmessageBuffer);
  246.   client.publish(mqtt_pub_topic, JSONmessageBuffer);
  247.   client.subscribe(mqtt_sub_topic);
  248.  
  249.   if (debug) {
  250.     Serial.println("[SETUP] Boot finished");
  251.     Serial.println("######################");
  252.     Serial.println();
  253.   }
  254. }
  255.  
  256. void callback(char* topic, byte* payload, unsigned int length) {
  257.   String msg;
  258.   for (byte i = 0; i < length; i++) {
  259.       char tmp = char(payload[i]);
  260.       msg += tmp;
  261.   }
  262.   if (debug) {
  263.     Serial.println();
  264.     Serial.println("[MQTT] *******************************");
  265.     Serial.println("[MQTT] New Message arrived");
  266.     Serial.println((String)"[MQTT] Topic:   " + topic);
  267.     Serial.println((String)"[MQTT] Message: " + msg);
  268.     Serial.println("[MQTT] *******************************");
  269.     Serial.println();
  270.   }
  271.  
  272.   const size_t capacity = JSON_OBJECT_SIZE(3) + JSON_OBJECT_SIZE(6) + 130;
  273.   DynamicJsonDocument doc(capacity);
  274.   doc["status"] = msg;
  275.   char JSONmessageBuffer[capacity];
  276.   serializeJson(doc, JSONmessageBuffer);
  277.   client.publish(mqtt_pub_topic, JSONmessageBuffer);
  278.  
  279.   if (msg == "true") {
  280.     digitalWrite(raus, LOW);
  281.     delay(1500);
  282.     digitalWrite(raus, HIGH);
  283.   }
  284.  
  285.   if (msg == "false") {
  286.     digitalWrite(rein, LOW);
  287.     delay(1500);
  288.     digitalWrite(rein, HIGH);
  289.   }
  290.  
  291.   if (msg == "restart") {
  292.     ESP.restart();
  293.   }
  294. }
  295.  
  296. boolean reconnect()
  297. {
  298.   if (client.connect(mqtt_device, mqtt_user, mqtt_password )) {
  299.     ticker.attach(0.2, tick);
  300.  
  301.   const size_t capacity = JSON_OBJECT_SIZE(3) + JSON_OBJECT_SIZE(6) + 130;
  302.   DynamicJsonDocument doc(capacity);
  303.   doc["status"] = "reconnected";
  304.   doc["subTopic"] = mqtt_sub_topic;
  305.  
  306.   char JSONmessageBuffer[capacity];
  307.   serializeJson(doc, JSONmessageBuffer);
  308.   client.publish(mqtt_pub_topic, JSONmessageBuffer);
  309.   client.subscribe(mqtt_sub_topic);
  310.  
  311.     if (debug) {
  312.       Serial.println("[MQTT] Reconnected");
  313.     }
  314.     ticker.detach();
  315.     digitalWrite(LED, HIGH);
  316.   }
  317.   return client.connected();
  318. }
  319.  
  320. void mqttConnection()
  321. {
  322.   if (!client.connected()) {
  323.     if ((millis() - MQTTstart) >= 5000) {
  324.       MQTTstart += 5000;
  325.       ticker.attach(1.6, tick);
  326.       if (debug) {
  327.         Serial.println("[MQTT] Connection is lost");
  328.       }
  329.       if (reconnect()) {
  330.       }
  331.     }
  332.   } else {
  333.     client.loop();
  334.   }
  335. }
  336.  
  337. void loop()
  338. {
  339.   mqttConnection();
  340. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement