fastoch13

Chevalet V2.0

Aug 4th, 2023
1,149
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 12.99 KB | None | 0 0
  1. #include <Arduino.h>
  2. #include <ESP8266WiFi.h>
  3. #include <ESP8266HTTPClient.h>
  4. #include <WiFiClient.h>
  5. #include <WiFiClientSecure.h>
  6. #include <ESP8266WebServer.h>
  7. #include <LittleFS.h>
  8. #include <PubSubClient.h>
  9. #include <ESP8266WiFi.h>
  10. #include <SPI.h>
  11. #include <MFRC522.h>
  12.  
  13. #define SS_PIN D8
  14. #define RST_PIN D3
  15. MFRC522 mfrc522(SS_PIN, RST_PIN);
  16.  
  17. ESP8266WebServer server(80);
  18. WiFiClient wifiClient;
  19.  
  20. /* MQTT */
  21. const char* mqttServer         = "192.168.1.55";
  22. const int   mqttPort           = 1883;
  23. const char* mqttUser           = "";
  24. const char* mqttPassword       = "";
  25. const char* mqttTopic          = "timestamp_topic";
  26.  
  27. const char* ssidAP             = "Chevalet";
  28. const char* passwordAP         = "Password";
  29. const char* configFile         = "/config.txt";
  30. const char* adminUsername      = "Admin";
  31. const char* adminPassword      = "flagstuff";
  32. int         connectionAttempts = 0;
  33.  
  34. char* last_card_id = "";
  35.  
  36.  
  37. String ssid;
  38. String password;
  39. //String apiKey;
  40. String ID;
  41. String owner;
  42. String hostnameAP = "Chevalet Libre";
  43. //String Server;
  44.  
  45. PubSubClient mqttClient(wifiClient);
  46.  
  47. void mqttCallback(char* topic, byte* payload, unsigned int length)
  48. {
  49.     // Handle incoming MQTT messages if needed
  50.     // You can add your own logic here
  51. }
  52.  
  53. void mqttConnect()
  54. {
  55.     Serial.print("Connecting to MQTT...");
  56.  
  57.     mqttClient.setServer(mqttServer, mqttPort);
  58.     mqttClient.setCallback(mqttCallback);
  59.  
  60.     while (!mqttClient.connected())
  61.     {
  62.         if (mqttClient.connect("WemosD1MiniPro", mqttUser, mqttPassword))
  63.         {
  64.             Serial.println("Connected to MQTT!");
  65.             mqttClient.subscribe(mqttTopic);
  66.         }
  67.         else
  68.         {
  69.             Serial.print("Failed, rc=");
  70.             Serial.print(mqttClient.state());
  71.             Serial.println(" Retrying in 5 seconds...");
  72.             delay(5000);
  73.         }
  74.     }
  75. }
  76.  
  77.  
  78.  
  79.  
  80.  
  81.  
  82.  
  83. /* end MQTT */
  84.  
  85. void handleRoot()
  86. {
  87.     if (!server.authenticate(adminUsername, adminPassword)) { return server.requestAuthentication(); }
  88.  
  89.     String _ssid(ssid);
  90.     String _password(password);
  91.     String _owner(owner);
  92.     String _ID(ID);
  93.     String _mqttServer(mqttServer);
  94.     String _mqttPort(mqttPort);
  95.     String _mqttUser(mqttUser);
  96.     String _mqttPassword(mqttPassword);
  97.     String _mqttTopic(mqttTopic);
  98.  
  99.     String title = "<title>" + owner + ID + "</title>";
  100.     String html = "";
  101.     html += "<html>";
  102.     html += "   <head>" + title + "</head>";
  103.     html += "   <body>";
  104.     html += "       <h1>Chevalet Setup</h1>";
  105.     html += "       <form method='post' action='/save'>";
  106.     html += "           <label>SSID:        </label><br><input type='text'     name='ssid'          value='" + _ssid + "'        ><br>";
  107.     html += "           <label>Password:    </label><br><input type='password' name='password'      value='" + _password + "'    ><br>";
  108.     html += "           <label>Owner:       </label><br><input type='text'     name='owner'         value='" + _owner + "'       ><br>";
  109.     html += "           <label>ID:          </label><br><input type='text'     name='ID'            value='" + _ID + "'          ><br>";
  110.     html += "           <label>MQTT Server  </label><br><input type='text'     name='mqttServer'    value='" + _mqttServer + "'  ><br>";
  111.     html += "           <label>MQTT Port    </label><br><input type='text'     name='mqttPort'      value='" + _mqttPort + "'    ><br>";
  112.     html += "           <label>MQTT Username</label><br><input type='text'     name='mqttUser'      value='" + _mqttUser + "'    ><br>";
  113.     html += "           <label>MQTT Password</label><br><input type='text'     name='mqttPassword'  value='" + _mqttPassword + "'><br>";
  114.     html += "           <label>MQTT Topic   </label><br><input type='text'     name='mqttTopic'     value='" + _mqttTopic + "'   ><br>";
  115.     html += "           <inputtype='submit' value='Save and restart'>";
  116.     html += "       </form>";
  117.     html += "   </body>";
  118.     html += "</html>";
  119.     server.send(200, "text/html", html);
  120. }
  121.  
  122.  
  123.  
  124. void handleBravo()
  125. {
  126.     if (!server.authenticate(adminUsername, adminPassword)) { return server.requestAuthentication(); }
  127.     String html = "<html><title>"+owner + ID+"</title>";
  128.     html += "<body><h1>CONGRATULATION!</h1>";
  129.     html += "<script>function check_card(){}</script>";
  130.     html += "<p>Your order "+ ID +" is ready</p>";
  131.     html += "<script>settimout(check_card; 3000);</script>";
  132.     html += "</body></html>";
  133.     server.send(200, "text/html", html);
  134. }
  135.  
  136. ////
  137. void handleSave()
  138. {
  139.     if (!server.authenticate(adminUsername, adminPassword)) { return server.requestAuthentication(); }
  140.  
  141.     ssid            = server.arg("ssid");
  142.     password        = server.arg("password");
  143.     owner           = server.arg("owner");
  144.     ID              = server.arg("ID");
  145.     mqttServer      = server.arg("mqttServer");
  146.     mqttPort        = server.arg("mqttPort");
  147.     mqttUser        = server.arg("mqttUser");
  148.     mqttPassword    = server.arg("mqttPassword");
  149.     mqttTopic       = server.arg("mqttTopic");
  150.  
  151.     File configFile = LittleFS.open("/config.txt", "w");
  152.     if (!configFile) { Serial.println("Error opening configuration file"); return; }
  153.  
  154.     configFile.println(ssid);
  155.     configFile.println(password);
  156.     configFile.println(owner);
  157.     configFile.println(ID);
  158.     configFile.println(mqttServer);
  159.     configFile.println(mqttPort);
  160.     configFile.println(mqttUser);
  161.     configFile.println(mqttPassword);
  162.     configFile.println(mqttTopic);
  163.     configFile.close();
  164.  
  165.     server.send(200, "text/plain", "Configuration saved. Restart in progress...");
  166.     delay(2000);
  167.     ESP.restart();
  168. }
  169.  
  170. bool connectToWifi()
  171. {
  172.     connectionAttempts = 0;
  173.     delay(1000);
  174.     Serial.print(".");
  175.  
  176.     connectionAttempts++;
  177.     if (connectionAttempts > 20)
  178.     {
  179.         Serial.println("");
  180.         Serial.println("WiFi network failed to connect. Startup in AP mode");
  181.         WiFi.disconnect();
  182.         WiFi.hostname(hostnameAP);
  183.         WiFi.softAP(ssidAP, passwordAP);
  184.         WiFi.hostname(hostnameAP);
  185.  
  186.         Serial.print("Access point IP address: ");
  187.         Serial.println(WiFi.softAPIP());
  188.         Serial.print("Mot de passe du point d'accès: ");
  189.         Serial.println(passwordAP);
  190.  
  191.         server.on("/", handleRoot);
  192.         server.on("/save", HTTP_POST, handleSave);
  193.         //server.on("/led", handleLed); // Ajout de la gestion de l'allumage des LEDs
  194.         server.begin();
  195.         return true;
  196.     }
  197.     else
  198.     {
  199.         return false;
  200.     }
  201. }
  202.  
  203. void handleSuccess()
  204. {
  205.     if (!server.authenticate(adminUsername, adminPassword)) { return server.requestAuthentication(); }
  206.  
  207.     String html = "<html><title>" + owner + ID + "</title>";
  208.     html += "<body><h1>Successful connection</h1>";
  209.     html += "<p>SSID: "    + ssid + "</p>";
  210.     html += "<p>Owner: "   + owner + "</p>";
  211.     html += "<p>Server: "  + mqttServer + "</p>";
  212.     html += "<label for='ID'>Number:</label><br>";
  213.     html += "<input type='number' name='ID' id='ID' value='" + ID + "'><br>";
  214.     //html += "<a href='/" + apiKey + "'>Go To Animation Page</a>"; // Ajout du lien
  215.     html += "<form method='post' action='/save'>";
  216.     html += "<input type='submit' value='Save'>";
  217.     html += "</form>";
  218.     html += "<form method='post' action='/cancel'>";
  219.     html += "<input type='submit' value='Cancel'>";
  220.     html += "</form>";
  221.     html += "<form method='post' action='/reset'>";
  222.     html += "<input type='submit' value='Erase configuration and restart in AP mode'>";
  223.     html += "</form>";
  224.     html += "<form method='post' action='/led'>";
  225.     html += "<input type='submit' value='Test LEDs'>";
  226.     html += "</form>";
  227.     html += "</body></html>";
  228.     server.send(200, "text/html", html);
  229. }
  230.  
  231. void handleReset()
  232. {
  233.     if (!server.authenticate(adminUsername, adminPassword)) { return server.requestAuthentication(); }
  234.  
  235.     LittleFS.remove(configFile);
  236.     server.send(200, "text/plain", "Configuration erased. Restart in progress...");
  237.     delay(2000);
  238.     ESP.restart();
  239. }
  240.  
  241. void handleCancel()
  242. {
  243.     if (!server.authenticate(adminUsername, adminPassword)) { return server.requestAuthentication(); }
  244.     server.send(200, "text/plain", "Configuration cancelled. Restart in progress...");
  245.     delay(2000);
  246.     ESP.restart();
  247. }
  248.  
  249. void handleNotFound()
  250. {
  251.     String html = "<html><body>";
  252.     html += "<h1>Page not found</h1>";
  253.     html += "<p>The requested page does not exist.</p>";
  254.     html += "</body></html>";
  255.     server.send(404, "text/html", html);
  256. }
  257.  
  258. void onStationModeGotIP(const WiFiEventStationModeGotIP& event)
  259. {
  260.     server.sendHeader("Location", String("http://") + WiFi.localIP().toString(), true);
  261.     server.send(302, "text/plain", "");
  262. }
  263.  
  264. void ConnectedAnimation()
  265. {
  266.  
  267. }
  268.  
  269. /////////////////////////////////////////////////////
  270.  
  271. char* checkCard()
  272. {
  273.     String cardData = "";
  274.     if (mfrc522.PICC_IsNewCardPresent() && mfrc522.PICC_ReadCardSerial())
  275.     {
  276.         String content = "Card Detected!<br>Card ID: ";
  277.         for (byte i = 0; i < mfrc522.uid.size; i++)
  278.         {
  279.             content.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
  280.             content.concat(String(mfrc522.uid.uidByte[i], HEX));
  281.         }
  282.         cardData = "data: " + content;
  283.     }
  284.     char * val;
  285.     strcpy(val, cardData.c_str());
  286.     return val;
  287. }
  288.  
  289. void setup()
  290. {
  291.     Serial.begin(115200);
  292.     delay(100);
  293.  
  294.     if (!LittleFS.begin()) { Serial.println("Error initializing LittleFS"); return; }
  295.  
  296.     if (!LittleFS.exists(configFile))
  297.     {
  298.         Serial.println("No configuration file found. Startup in AP mode");
  299.         WiFi.softAP(ssidAP, passwordAP);
  300.         WiFi.hostname(hostnameAP);
  301.        
  302.         Serial.print("Access point IP address: ");
  303.         Serial.println(WiFi.softAPIP());
  304.         Serial.print("Access point password: ");
  305.         Serial.println(passwordAP);
  306.  
  307.         server.on("/", handleRoot);
  308.         server.on("/save", HTTP_POST, handleSave);
  309.         //server.on("/" + apiKey, handleAnimation); //
  310.  
  311.         server.begin();
  312.         return;
  313.     }
  314.  
  315.     File configFile = LittleFS.open("/config.txt", "r");
  316.    
  317.     if (!configFile) { Serial.println("Error opening configuration file"); return; }
  318.  
  319.     ssid            = configFile.readStringUntil('\n'); ssid.trim();
  320.     password        = configFile.readStringUntil('\n'); password.trim();
  321.     owner           = configFile.readStringUntil('\n'); owner.trim();
  322.     ID              = configFile.readStringUntil('\n'); ID.trim();
  323.     mqttServer      = configFile.readStringUntil('\n'); mqttServer.trim();
  324.     mqttPort        = configFile.readStringUntil('\n'); mqttPort.trim();
  325.     mqttUser        = configFile.readStringUntil('\n'); mqttUser.trim();
  326.     mqttPassword    = configFile.readStringUntil('\n'); mqttPassword.trim();
  327.     mqttTopic       = configFile.readStringUntil('\n'); mqttTopic.trim();
  328.  
  329.     configFile.close();
  330.  
  331.     WiFi.hostname(owner + ID);
  332.     WiFi.begin(ssid.c_str(), password.c_str());
  333.     int connectionAttempts = 0;
  334.     while (WiFi.status() != WL_CONNECTED)
  335.     {
  336.         delay(1000);
  337.         Serial.print(".");
  338.         connectionAttempts++;
  339.  
  340.         if (connectionAttempts > 20)
  341.         {
  342.             Serial.println("");
  343.             Serial.println("WiFi network failed to connect. Startup in AP mode");
  344.             WiFi.disconnect();
  345.             WiFi.hostname(hostnameAP);
  346.             WiFi.softAP(ssidAP, passwordAP);
  347.             WiFi.hostname(hostnameAP);
  348.             //APAnimation();
  349.             Serial.print("Access point IP address: ");
  350.             Serial.println(WiFi.softAPIP());
  351.             Serial.print("Mot de passe du point d'accès: ");
  352.             Serial.println(passwordAP);
  353.             server.on("/", handleRoot);
  354.             server.on("/save", HTTP_POST, handleSave);
  355.             //server.on("/led", handleLed); // Ajout de la gestion de l'allumage des LEDs
  356.             server.begin();
  357.             return;
  358.         }
  359.     }
  360.  
  361.     Serial.println("");
  362.     Serial.println("WiFi network connection established");
  363.     Serial.print("IP address: ");
  364.     Serial.println(WiFi.localIP());
  365.     WiFi.hostname(owner + ID);
  366.     ConnectedAnimation();
  367.  
  368.     server.on("/", handleSuccess);
  369.     server.on("/save", HTTP_POST, handleSave);
  370.     server.on("/cancel", HTTP_POST, handleCancel);
  371.     server.on("/reset", HTTP_POST, handleReset);
  372.     server.onNotFound(handleNotFound);
  373.     server.begin();
  374.  
  375.     mqttConnect();
  376.    
  377. }
  378.  
  379. void loop()
  380. {
  381.     server.handleClient();
  382.  
  383.    /**/
  384.     if (wifiClient.status() == WL_CONNECTED)
  385.     {
  386.         if (mqttClient.connected())
  387.         {
  388.             const char* cardid = checkCard();
  389.             if (strcmp(cardid, "")==0)
  390.             {
  391.                 last_card_id = cardid;
  392.                 mqttClient.publish(mqttTopic, cardid);
  393.                 //Serial.println("Published: " + cardid);
  394.             }
  395.             delay(1000);
  396.         }
  397.         else
  398.         {
  399.             mqttConnect();
  400.         }
  401.     }
  402.     else
  403.     {
  404.         if (!connectToWifi())
  405.         {
  406.             // run config
  407.         }        
  408.     }
  409. }
Advertisement
Add Comment
Please, Sign In to add comment