Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <WiFi.h>
- #include <WebServer.h>
- #include <HTTPClient.h>
- #include <ArduinoJson.h>
- #include <EEPROM.h>
- const char* ssidAP = "hamama_hahama";
- const char* passwordAP = "1234512345";
- WebServer server(80);
- String wifiSSID;
- String wifiPassword;
- String firebaseURL;
- String firebaseAPIKey;
- String firebaseNode;
- const int EEPROM_SIZE = 512;
- const int ledPin = 2; // פין הלד המובנה ב-ESP32
- unsigned long startTime = 0; // משתנה לשמירת זמן ההתחלה
- bool ledOn = false; // משתנה למעקב אחרי מצב ה-LED
- int duration = 0; // משתנה לאחסון זמן ההדלקה
- String globalSerialData = "";
- int preValue1 = -1;
- int preValue2 = -1;
- int preValue3 = -1;
- // פונקציה שמחלצת ערכים מספריים מ-JSON ושולחת אותם כערכים עשרוניים ל-Serial2
- void processJsonAndSendSerial2(const String &jsonString) {
- // יצירת אובייקט JSON
- StaticJsonDocument<200> jsonDoc;
- // ניסיון לפענח את ה-JSON
- DeserializationError error = deserializeJson(jsonDoc, jsonString);
- if (error) {
- Serial.print("deserializeJson() failed: ");
- Serial.println(error.f_str());
- return;
- }
- Serial.print("json send to serial ============> ");
- Serial.println(jsonString);
- // חילוץ 4 הערכים מתוך ה-JSON (בהנחה שהם מספרים שלמים)
- int value1 = jsonDoc["A"];
- int value2 = jsonDoc["B"];
- int value3 = jsonDoc["C"];
- preValue1 = value1;
- preValue2 = value2;
- preValue3 = value3;
- Serial2.write(jsonString.toInt());
- }
- void turnOnLED() {
- pinMode(ledPin, OUTPUT); // הגדרת פין ה-LED כיציאה
- if (!ledOn || duration == 0) { // אם ה-LED כבוי, להדליק אותו ולשמור את זמן ההתחלה
- digitalWrite(ledPin, HIGH); // הדלקת ה-LED
- startTime = millis(); // שמירת זמן ההתחלה
- ledOn = true; // עדכון מצב ה-LED
- }
- // בדיקה אם ה-LED דולק ואם עבר הזמן שנקבע
- if (ledOn && (millis() - startTime >= duration) && duration > 0) {
- digitalWrite(ledPin, LOW); // כיבוי ה-LED
- ledOn = false; // עדכון מצב ה-LED
- }
- }
- bool connectToWiFi() {
- if (wifiSSID.length() > 0 ) {
- WiFi.softAPdisconnect();
- WiFi.begin(wifiSSID.c_str(), wifiPassword.c_str());
- Serial.print("Connecting to WiFi");
- int attempts = 0;
- while (WiFi.status() != WL_CONNECTED && attempts < 20) {
- delay(500);
- Serial.print(".");
- attempts++;
- }
- Serial.println();
- if (WiFi.status() == WL_CONNECTED) {
- Serial.println("Connected to WiFi");
- Serial.print("IP address: ");
- Serial.println(WiFi.localIP());
- Serial.println(WiFi.getHostname());
- duration = 0;
- return true;
- } else {
- Serial.println("Failed to connect to WiFi, setting up Access Point...");
- duration = 1000;
- return false;
- }
- } else {
- Serial.println("No WiFi credentials stored, setting up Access Point...");
- duration = 500;
- return false;
- }
- }
- int x=0;
- bool setupAccessPoint() {
- //IPAddress IP = WiFi.softAPIP();
- if(x==0){
- IPAddress local_ip(192, 168, 4, 1); // הגדרת כתובת IP קבועה ל-AP
- IPAddress gateway(192, 168, 4, 1);
- IPAddress subnet(255, 255, 255, 0);
- WiFi.softAPConfig(local_ip, gateway, subnet); // הגדרת כתובת IP קבועה
- WiFi.softAP(ssidAP, passwordAP);
- IPAddress IP = WiFi.softAPIP();
- server.on("/", handleRoot);
- server.on("/submit", handleFormSubmission);
- server.begin();
- Serial.println("Web server started.");
- x=1;
- return true;
- }else{
- duration = 10;
- Serial.print("AP IP address: ");
- Serial.println(WiFi.softAPIP());
- duration = 1000;
- delay(500);
- return true;
- }
- return false;
- }
- void saveToEEPROM() {
- EEPROM.writeString(0, wifiSSID);
- EEPROM.writeString(100, wifiPassword);
- EEPROM.writeString(200, firebaseURL);
- EEPROM.writeString(300, firebaseAPIKey);
- EEPROM.writeString(400, firebaseNode);
- EEPROM.commit();
- }
- void handleRoot() {
- String html = "<!DOCTYPE html><html lang='en'><head><meta charset='UTF-8'><meta name='viewport' content='width=device-width, initial-scale=1.0'>";
- html += "<link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css'>";
- html += "<title>ESP32 Configuration</title></head><body>";
- html += "<div class='container'><h2>ESP32 Configuration</h2>";
- html += "<form action='/submit' method='post'>";
- html += "<div class='form-group'><label for='ssid'>WiFi SSID:</label><input type='text' class='form-control' id='ssid' name='ssid' value='" + wifiSSID + "' required></div>";
- html += "<div class='form-group'><label for='password'>WiFi Password:</label><input type='password' class='form-control' id='password' name='password' value='" + wifiPassword + "' required></div>";
- html += "<div class='form-group'><label for='firebaseURL'>Firebase URL:</label><input type='text' class='form-control' id='firebaseURL' name='firebaseURL' value='" + firebaseURL + "' required></div>";
- html += "<div class='form-group'><label for='firebaseAPIKey'>Firebase API Key:</label><input type='text' class='form-control' id='firebaseAPIKey' name='firebaseAPIKey' value='" + firebaseAPIKey + "' required></div>";
- html += "<div class='form-group'><label for='firebaseNode'>Firebase Node:</label><input type='text' class='form-control' id='firebaseNode' name='firebaseNode' value='" + firebaseNode + "' required></div>";
- html += "<button type='submit' class='btn btn-primary'>Submit</button></form></div>";
- html += "</body></html>";
- server.send(200, "text/html", html);
- }
- void handleFormSubmission() {
- if (server.method() == HTTP_POST) {
- wifiSSID = server.arg("ssid");
- if(server.hasArg("password")){
- wifiPassword = server.arg("password");
- }else{
- wifiPassword = "";
- }
- firebaseURL = server.arg("firebaseURL");
- firebaseAPIKey = server.arg("firebaseAPIKey");
- firebaseNode = server.arg("firebaseNode");
- Serial.print("Connected to WiFi => ");
- Serial.println(wifiPassword);
- saveToEEPROM();
- if (connectToWiFi()) {
- Serial.println("Connected to WiFi");
- Serial.print("IP address: ");
- Serial.println(WiFi.localIP());
- server.on("/", handleRoot);
- server.on("/submit", handleFormSubmission);
- server.begin();
- Serial.println("Web server started.");
- String ip = WiFi.localIP().toString();
- String response = "<html><body><h2>Data saved successfully!</h2>";
- response += "<p>WiFi SSID: " + wifiSSID + "</p>";
- response += "<p>WiFi Password: " + wifiPassword + "</p>";
- response += "<p>Firebase URL: " + firebaseURL + "</p>";
- response += "<p>Firebase API Key: " + firebaseAPIKey + "</p>";
- response += "<p>Firebase Node: " + firebaseNode + "</p>";
- response += "<p>Web server IP: " + ip + "</p>";
- response += "</body></html>";
- server.send(200, "text/html", response);
- } else {
- Serial.println("Failed to connect to WiFi");
- setupAccessPoint();
- }
- } else {
- server.send(405, "text/plain", "Method Not Allowed");
- }
- }
- void readFromEEPROM() {
- wifiSSID = EEPROM.readString(0);
- wifiPassword = EEPROM.readString(100);
- firebaseURL = EEPROM.readString(200);
- firebaseAPIKey = EEPROM.readString(300);
- firebaseNode = EEPROM.readString(400);
- }
- byte incomingByte[13];
- int cnt = 0;
- char str;
- //int incomingByte =0;
- String readFromSerial2() {
- if (Serial2.available()>=13) {
- uint8_t receivedData[13];
- String serialData = "";
- // Read the 13 bytes from Serial2
- for (int i = 0; i < 13; i++) {
- receivedData[i] = Serial2.read();
- }
- for (int i = 0; i < 13; i++) {
- if (i==3 || i==7 || i==11){
- serialData += String(receivedData[i]);
- }else{
- serialData += char(receivedData[i]);
- }
- //Serial.println(serialData);
- }
- //Serial2.flush();
- return serialData;
- }
- return globalSerialData;
- }
- String convertToJsonString(const String &input) {
- // לבדוק אם המחרוזת מתחילה ב- '{' ומסתיימת ב- '}'
- if (input.charAt(0) != '{' || input.charAt(input.length() - 1) != '}') {
- return ""; // פורמט לא חוקי
- }
- String jsonString = "{";
- int startPos = 1; // התחל אחרי '{'
- int endPos = 0;
- while (startPos < input.length() - 1) {
- endPos = input.indexOf(':', startPos);
- if (endPos == -1) {
- return ""; // לא נמצא הסימן ':'
- }
- String name = input.substring(startPos, endPos);
- startPos = endPos + 1;
- endPos = input.indexOf(',', startPos);
- if (endPos == -1) {
- endPos = input.length() - 1; // הסימן האחרון הוא '}'
- }
- String value = input.substring(startPos, endPos);
- jsonString += "\"" + name + "\":\"" + value + "\"";
- startPos = endPos + 1;
- if (startPos < input.length() - 1) {
- jsonString += ",";
- }
- }
- jsonString += "}";
- return jsonString;
- }
- String parseInputToJsonString(const String &input) {
- String jsonString = "{";
- int startPos = 0;
- int endPos = 0;
- while (startPos < input.length()) {
- endPos = input.indexOf(':', startPos);
- if (endPos == -1) {
- return ""; // לא נמצא הסימן ":"
- }
- String name = input.substring(startPos, endPos);
- startPos = endPos + 1;
- endPos = input.indexOf('/', startPos);
- if (endPos == -1) {
- return ""; // לא נמצא הסימן "/"
- }
- String value = input.substring(startPos, endPos);
- jsonString += "\"" + name + "\":\"" + value + "\"";
- startPos = endPos + 1;
- if (startPos < input.length()) {
- jsonString += ",";
- }
- }
- jsonString += "}";
- Serial.print("jsonString =>");
- Serial.println();
- return jsonString;
- }
- void processAndSendSerialData(String data) {
- StaticJsonDocument<200> jsonDoc;
- DeserializationError error = deserializeJson(jsonDoc, data);
- if (error) {
- Serial.print("deserializeJson() failed: ");
- Serial.println(error.f_str());
- return;
- }
- if (WiFi.status() == WL_CONNECTED) {
- HTTPClient http;
- String url = firebaseURL + "/" + firebaseNode+"/TX" + ".json?auth=" + firebaseAPIKey;
- duration = 3000;
- String jsonData;
- serializeJson(jsonDoc, jsonData);
- http.begin(url);
- http.addHeader("Content-Type", "application/json");
- int httpResponseCode = http.PUT(jsonData);
- if (httpResponseCode > 0) {
- String response = http.getString();
- // Serial.println("HTTP PUT Response : " + String(httpResponseCode));
- Serial.println("HTTP PUT Response : " + response);
- } else {
- Serial.println("Error in sending PUT: " + String(httpResponseCode));
- }
- http.end();
- } else {
- Serial.println("Wi-Fi not connected");
- duration = 1000;
- }
- }
- String getFirebaseData() {
- String jsonData = "";
- if (WiFi.status() == WL_CONNECTED) {
- HTTPClient http;
- String url = firebaseURL + "/" + firebaseNode+"/RX" + ".json?auth=" + firebaseAPIKey;
- duration = 3000;
- http.begin(url);
- int httpResponseCode = http.GET();
- if (httpResponseCode > 0) {
- jsonData = http.getString();
- // Serial.println("HTTP Response code: GET " + String(httpResponseCode));
- Serial.println("HTTP Response: GET" + jsonData);
- http.end();
- return jsonData;
- }
- http.end();
- } else {
- Serial.println("Wi-Fi not connected");
- duration = 1000;
- return "Wi-Fi not connected";
- }
- }
- void getSerialDataTask(void *pvParameters);
- void setup() {
- Serial.begin(115200);
- Serial2.begin(9600, SERIAL_8N1, 16, 17); // הגדרת Serial2 עם פינים RX ו-TX
- EEPROM.begin(EEPROM_SIZE);
- readFromEEPROM();
- if(!connectToWiFi()){
- setupAccessPoint();
- }else{
- server.on("/", handleRoot);
- server.on("/submit", handleFormSubmission);
- server.begin();
- Serial.println("Web server started.");
- StaticJsonDocument<200> jsonDoc;
- jsonDoc["IP"] = WiFi.localIP().toString();
- HTTPClient http;
- String url = firebaseURL + "/" + firebaseNode+"/espServerIP" + ".json?auth=" + firebaseAPIKey;
- String jsonData;
- serializeJson(jsonDoc, jsonData);
- Serial.println("firebaseNode: " + url);
- http.begin(url);
- http.addHeader("Content-Type", "application/json");
- int httpResponseCode = http.PUT(jsonData);
- if (httpResponseCode > 0) {
- String response = http.getString();
- Serial.println("HTTP PUT Response code: " + String(httpResponseCode));
- Serial.println("Response: " + response);
- } else {
- Serial.println("Error in sending POST: " + String(httpResponseCode));
- }
- xTaskCreatePinnedToCore(
- getSerialDataTask, // פונקציית המשימה
- "get FB data", // שם המשימה
- 4096, // גודל מחסנית
- NULL, // פרמטרים
- 1, // עדיפות
- NULL, // מזהה משימה
- 1 // ליבה
- );
- }
- }
- void getSerialDataTask(void *pvParameters) {
- while (true) {
- globalSerialData =readFromSerial2();
- //vTaskDelay(500 / portTICK_PERIOD_MS);
- delay(200);
- //Serial.println("serialData 2 Received =>"+globalSerialData);
- }
- }
- unsigned long start = millis();
- String prevJsonString = "";
- void loop(){
- server.handleClient();
- if(WiFi.status() == WL_CONNECTED){
- //Serial.println("serialData 2 Received =>"+serialData);
- // if (serialData.length() >= 13) {
- String tempJsonString = convertToJsonString(globalSerialData);
- //Serial.println("tempJsonString =>"+globalSerialData);
- //Serial.println("tempJsonString =>"+tempJsonString);
- //if( prevJsonString == "" && tempJsonString.length()>1){
- Serial.println("prevJsonString =>"+prevJsonString);
- Serial.println("tempJsonString =>"+tempJsonString);
- prevJsonString = tempJsonString;
- processAndSendSerialData(tempJsonString);
- //delay(500);
- // }
- //Serial2.flush();
- String jsonData = getFirebaseData();
- Serial.println("Received from FirebaseData = "+jsonData);
- processJsonAndSendSerial2(jsonData);
- delay(500);
- }else{
- setupAccessPoint();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement