I've an Arduino with some room light controls and I want to add Wifi connection using the ESP as a simple WiFi to Serial bridge.
No problem from WiFi to Serial but connection from Serial to Wifi doesn't work as expected.
I think it's a problem of synchronism.
The handleStatus wifi method need to send a serial command to the Arduino, wait for the answer (via serial) and the respond to the wifi client.
Is there a way to do this?
Somethink like "put the wifi client on hold until the serial command is received than forward the serial command to the wifi client"...?
This is my code:
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
const char* ssid = "ssid";
const char* password = "psw";
MDNSResponder mdns;
ESP8266WebServer server(80);
String serialCommand = "";
void handleRoot() {
server.send(200, "text/plain", "hello from esp8266!");
}
void handleNotFound(){
String message = "File Not Found\n\n";
message += "URI: ";
message += server.uri();
message += "\nMethod: ";
message += (server.method() == HTTP_GET)?"GET":"POST";
message += "\nArguments: ";
message += server.args();
message += "\n";
for (uint8_t i=0; i<server.args(); i++){
message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
}
server.send(404, "text/plain", message);
}
void handleHome() {
String message = "{";
for (uint8_t i=0; i<server.args(); i++){
message += """" + server.argName(i) + """" + ":" + """" + server.arg(i) + """,";
}
message.remove(message.length()-1);
message += "}";
server.send(200, "text/plain", message);
Serial.println(message);
}
void handleStatus() {
Serial.println("status");
/////////////////////////////////////////////////
//Problem is here - start
if(Serial.available() > 0) {
serialCommand = Serial.readStringUntil('\n');
if (serialCommand.indexOf("status")!=-1 ) {
server.send(200, "text/plain", serialCommand);
}
serialCommand = "";
}
//Problem is here - end
/////////////////////////////////////////////////
}
void setup(void){
Serial.begin(9600);
WiFi.begin(ssid, password);
Serial.println("");
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
if (mdns.begin("esp8266", WiFi.localIP())) {
Serial.println("MDNS responder started");
}
server.on("/", handleRoot);
server.on("/home", handleHome);
server.on("/status", handleStatus);
server.onNotFound(handleNotFound);
server.begin();
Serial.println("HTTP server started");
}
void loop(void){
server.handleClient();
if(Serial.available() > 0) {
serialCommand = Serial.readStringUntil('\n');
if (serialCommand.indexOf("check")!=-1 ) {
Serial.println(serialCommand);
}
serialCommand = "";
}
} This first version is just a test, in the future I'd like to switch to MQTT protocol or something similar.
Thx guys!