#include <ESP8266WiFi.
h>
#include <WebSocketsServer.h>
#include <ESP8266HTTPClient.h> // Include the HTTP client for sending requests
const char* ssid = "GlobeAtHome_67589";
const char* password = "32G4AFN7D2A";
WebSocketsServer webSocket(81); // WebSocket on port 81
void setup() {
[Link](9600); // This is for communication with Arduino Mega (TX/RX)
[Link](ssid, password);
[Link]("Connecting to WiFi...");
while ([Link]() != WL_CONNECTED) {
delay(500);
[Link](".");
}
[Link]("\nWiFi connected.");
[Link]("IP: ");
[Link]([Link]());
[Link]();
[Link](webSocketEvent);
}
void loop() {
[Link]();
if ([Link]()) { // Reading from Serial (NodeMCU's TX/RX pins connected
to Mega)
String message = [Link](); // Read the serial message from Arduino
Mega
[Link](); // Clean up the message
// Log the received message for debugging
[Link]("Received from Arduino Mega: ");
[Link](message);
// Check if the message is in the correct format (SLOT <slot_number> STATUS
<1/0>)
if ([Link]("SLOT") && [Link]("STATUS") != -1) {
// Extract the slot number and status
int slot = [Link](5, [Link]("STATUS") - 1).toInt();
String status = [Link]([Link]("STATUS") + 7);
// Log the extracted slot and status
[Link]("Extracted Slot: ");
[Link](slot);
[Link]("Extracted Status: ");
[Link](status);
if (status == "1" || status == "0") {
sendPostRequest(slot, status); // Send the status to the backend
} else {
[Link]("Invalid status received.");
}
}
}
}
void webSocketEvent(uint8_t client_num, WStype_t type, uint8_t * payload, size_t
length) {
switch(type) {
case WStype_TEXT:
String message = (char*)payload; // Convert the payload to a string
message += "\n"; // Add a newline at the end to indicate end of message
[Link](message); // Send the whole message with a newline
break;
}
}
void sendPostRequest(int slot, String message) {
WiFiClient client;
const char* host = "[Link]"; // Replace with your server's IP or domain
const int port = 80; // Default HTTP port
if ([Link](host, port)) {
// Update status based on message from NodeMCU
String status = (message == "1") ? "occupied" : "available"; // 1 -> occupied,
0 -> available
String postData = "slot_number=" + String(slot) + "&status=" + message;
// Send slot and status
// Send HTTP POST request to the new PHP file
[Link]("POST /system/[Link] HTTP/1.1\r\n");
[Link]("Host: [Link]\r\n"); // Replace with your server's IP or
domain
[Link]("Content-Type: application/x-www-form-urlencoded\r\n");
[Link]("Content-Length: " + String([Link]()) + "\r\n");
[Link]("\r\n");
[Link](postData); // Send the POST data
[Link]("Status: " + status);
[Link]("POST Data: " + postData);
delay(500); // Wait for the server response
[Link](); // Close the connection
[Link]("Status sent to backend");
} else {
[Link]("Connection failed to backend");
}
}