I'm despairing! I want to have my ESP8266 receive a string from a TCP client, execute the corresponding function and give a TCP response. But unfortunately the response string gets corrupted in some strange way: Assuming that I enter an 'unknown command', the first 11 bytes are printed correctly via the serial interface (the rest is dump) and the first 11 bytes received by the client are dump, but the rest is correct (see comments in script below). But when I enter the 'dim' command the result is correct (but the return string is also shorter than "error: unknown command"). For the moment I have absolutely no idea how to fix this, even though I've tried a lot.
#include <WiFiClient.h>
#include <ESP8266WiFi.h>
#include <Wire.h>
#include <string.h>
struct parsed_query{
String command;
String arguments;
};
struct parsed_query parser(void){
// this function receives and parses a query
struct parsed_query result;
result.command="entered command";
result.arguments="entered arguments"
return result
}
char* str2char(String as_string){
int i_0=0;
while(as_string[i_0]!='\0'){i_0++;}
char as_char[i_0+1];
as_char[i_0]='\0';
for(int i=0;i<i_0;i++){
as_char[i]=as_string[i];
}
return as_char;
}
String executor(String command,String arguments){
String response;
if(command=="dim"){
response="dimming";
}
else if(command=="on"){
response="switching ON";
}
else{
response="error: unknown command";
}
return response;
}
void setup(){
// initialize serial interface, wifi & tcp-server
Serial.begin(115200);
WiFi.begin("<SSID>","<PASSWORD>");
while (WiFi.status() != WL_CONNECTED){delay(500);}
TCPserver.begin();
}
void loop() {
if(!client.connected()){
client=TCPserver.available();
}else{
struct parsed_query query=parser();
// This prints "error: unkno??*/???*??"
Serial.println(str2char(executor(query.command,query.arguments)));
// here, the client receives "????**?*??*?wn command"
client.write(str2char(executor(query.command,query.arguments))));
}
}
I have two ideas what could be causing this result (even though I don't know where to fix it in my code):
Case 1: Maybe, I meshed up call-by-reference and call-by-value at some point (if yes, where??)
Case 2: My programm is causing a stack overflow (if yes, where??)
Any help highly appreciated as I don't want to spend one more night.
In str2char
you're returning a pointer to a local array, but like every local variable, it doesn't exist anymore after the function has returned. So reading from the returned pointer causes undefined behavior.
Compiling with warnings enabled (which is highly recommended) should output something like:
warning: address of local variable 'as_char' returned