Do you have any idea how to control leds and lcd of esp32 thru flask app that is deployed on heroku? my code works fine on localhost, but gives an error on heroku deployed app.I've tried sending data to heroku using esp32, it does receive but doesn't go with the condition I have like putting the data into database.flask code:
@views.route('/add_table', methods=['GET', 'POST'])def add_table(): if request.method == 'POST': # Get form data table_number = request.form.get('table_number') status = request.form.get('status') ip_address = request.form.get('ip_address') store_id = request.form.get('store_id') # Assuming the form includes a hidden field for store_id try: # Create a new table instance new_table = lamesa(table_number=table_number, status=status, store_id=store_id,ip_address=ip_address) # Add the new table to the database db.session.add(new_table) db.session.commit() # Control the LED based on the status of the table if status == 'Open': led_route = "/led_open" elif status == 'Reserved': led_route = "/led_res" # Send request to ESP32 to control LED if 'led_route' in locals(): url = f"{heroku_url}command?command={led_route.split('/')[-1]}" # Extract the LED command from the route response = requests.get(url) # Check response if needed flash('Table added successfully', 'success') # Optional: Use flash for displaying a success message return redirect(url_for('views.menu_view')) # Redirect to the home or any other appropriate route except IntegrityError as e: # Rollback the session to avoid partially committed data db.session.rollback() # Log the error current_app.logger.error(f'IntegrityError: {str(e)}') # Flash an error message flash('A table with this IP address and table number already exists. Please enter another IP address or table number.', 'danger') return redirect(url_for('views.menu_view')) else: # If it's a GET request, render the form return render_template('table_add.html', user=current_user) # Replace 'add_table.html' with the actual template nameesp code:
#include <WiFi.h>#include <ESPAsyncWebServer.h>#include <LiquidCrystal_I2C.h>#include <HTTPClient.h>// const int touchSensorPin = 4; // Connect the first touch sensor to pin 4// const int touchSensorPin2 = 16; // Connect the second touch sensor to pin 16// const float thresholdVoltage = 0.5; // Set your threshold voltage here//SDA on gpio 21 orange//SCL on gpio 22 violetint lcdColumns = 16;int lcdRows = 2;LiquidCrystal_I2C lcd(0x27, lcdColumns, lcdRows); // const char* ssid = "Oyda's Starlink 2.4Ghz";// const char* password = "OydaFamily@888";const char* ssid = "Smart_Bro_AFB0D";const char* password = "smartbro";// const int TOUCH_THRESHOLD = 100;const int touchSensorPin = 4;const int touchSensorPin2 = 16; const int ledPin = 13; // Pin connected to the LEDconst int ledPin2 = 14;const char* base64Encoding = "TWlzaE1hc2hMYWJzOm1pc2htYXNo"; // base64encoding user:pass - "dXNlcjpwYXNz", MishMashLabs:mishmash - "TWlzaE1hc2hMYWJzOm1pc2htYXNo"const char* serverUrl = "https://capstone-icpep-43a1865f7868.herokuapp.com/update_sensor_data";// const char* espUrl = "https://capstone-icpep-cb6ecaaac56d.herokuapp.com/command";// const char* timerUrl = "https://capstone-icpep-cb6ecaaac56d.herokuapp.com/update_timer";// const char* serverUrl = "http://192.168.1.9:5000/update_sensor_data";// const char* timerUrl = "http://192.168.1.9:5000/update_timer"; // New URL for updating the timer// Define Static IP Settings// IPAddress local_IP(192,168,1,22);IPAddress local_IP(192,168,1,30);IPAddress gateway(192,168,1,1);IPAddress subnet(255,255,255,0); IPAddress primaryDNS(8,8,8,8);IPAddress secondaryDNS(8,8,4,4);AsyncWebServer server(80);// unsigned long timerStartMillis = 0; // Global variable for timer start time// // Global variable for timer start time// bool timerRunning = false; // Global flag to indicate if the timer is running// int seconds = 300; void handleCommand(AsyncWebServerRequest *request) { String command = request->arg("command"); // Perform actions based on the received command if (command == "led_open") { lcd.clear(); digitalWrite(ledPin, HIGH); digitalWrite(ledPin2, LOW); // Turn on the LED lcd.print("OPEN TABLE"); } else if (command == "led_res") { lcd.clear(); digitalWrite(ledPin2, HIGH); // Turn off the LED digitalWrite(ledPin, LOW); lcd.print("TABLE RESERVED"); } else { digitalWrite(ledPin2, LOW); // Turn off the LED digitalWrite(ledPin, LOW); lcd.clear(); lcd.print("Waiting.."); } request->send(200, "text/plain", "Command received");}// void handleTimerUpdate(AsyncWebServerRequest *request) {// // Start or reset the timer// startTimer(); // This function sets up the timer variables to start or reset the countdown// // Respond to the HTTP request indicating that the timer has been updated// request->send(200, "text/plain", "Timer updated");// }void setup() { Serial.begin(115200); // Initialize LCD lcd.init(); lcd.backlight(); // Turn on LCD backlight // Connect to Wi-Fi Serial.print("Connecting to "); Serial.println(ssid); if(!WiFi.config(local_IP, gateway, subnet, primaryDNS, secondaryDNS)) { Serial.println("STA Failed to configure"); } WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(1000); Serial.print("."); } Serial.println(""); Serial.println("WiFi connected."); Serial.println("IP address: "); Serial.println(WiFi.localIP()); pinMode(ledPin, OUTPUT); pinMode(ledPin2, OUTPUT); // Start the server server.on("/command", HTTP_GET, handleCommand); // server.on("/update_timer", HTTP_GET, handleTimerUpdate); // New endpoint for updating the timer server.begin();}void loop() { // updateTimer(); // Read touch sensor data int touchValue = digitalRead(touchSensorPin); int touchValue2 = digitalRead(touchSensorPin2); // float voltage1 = (touchValue / 4095.0) * 3.3; // float voltage2 = (touchValue2 / 4095.0) * 3.3; // // Determine the touch status String touchStatus; if (touchValue == HIGH) { touchStatus = "Sensor 1 touched"; sendJsonData(touchStatus); delay(500); } else if (touchValue2 == HIGH ) { touchStatus = "Sensor 2 touched"; sendJsonData(touchStatus); delay(500); } // Handle other tasks or actions}void sendCommand(String command) { HTTPClient http; // Declare HTTPClient object http.begin(serverUrl); http.addHeader("Content-Type", "application/x-www-form-urlencoded"); // Construct the POST body String postBody = "command=" + command; int httpResponseCode = http.POST(postBody); if (httpResponseCode > 0) { Serial.print("HTTP Response code: "); Serial.println(httpResponseCode); } else { Serial.println("Error sending data"); // Add error handling code here } http.end();}void sendJsonData(String touchStatus) { // // Prepare JSON payload // updateTimer(); // String jsonPayload = "{\"touch_status\":\"" + touchStatus +"\"}"; String ipAddress = WiFi.localIP().toString(); // Include the IP address in the JSON payload String jsonPayload = "{\"touch_status\":\"" + touchStatus +"\", \"ip_address\":\"" + ipAddress +"\"}"; // Send HTTP POST request HTTPClient http; // Declare HTTPClient object http.begin(serverUrl); http.addHeader("Content-Type", "application/json"); int httpResponseCode = http.POST(jsonPayload); if (httpResponseCode > 0) { Serial.print("HTTP Response code: "); Serial.println(httpResponseCode); Serial.println(touchStatus); } else { Serial.println("Error sending data"); // Add error handling code here } http.end();}