I am programming an ESP8266 module via Arduino IDE. I basically have to use it as a server that can light up a led when a client sends a request.
This is okay but I have to implement it with a NONCE and AES encryption system to prevent replay attacks. My problem is that my esp server has to send a value to a client but I only saw the ESP as a data receiver and I can't send custom strings.
This is my code but it does not work because I have problems with the serverClients[i].write(randomstr,4);
function
I highlighted the non working part of the code
#include <ESP8266WiFi.h>
#define RANDOM_REG32 ESP8266_DREG(0x20E44)
#define MAX_SRV_CLIENTS 3
const char* ssid = "********";
const char* password = "********";
WiFiServer server(7000);
WiFiClient serverClients[MAX_SRV_CLIENTS];
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
delay(5000);
Serial.print("\nConnecting to "); Serial1.println(ssid);
server.begin();
server.setNoDelay(true);
Serial.print("Ready! Use 'port ");
Serial.print(WiFi.localIP());
Serial.println(" 7000' to connect");
}
void loop(){
uint8_t i;
if (server.hasClient()){
for(i = 0; i < MAX_SRV_CLIENTS; i++){
if (!serverClients[i] || !serverClients[i].connected()){
if(serverClients[i]) serverClients[i].stop();
serverClients[i] = server.available();
continue;
}
}
//no free spot
WiFiClient serverClient = server.available();
serverClient.stop();
}
for(i = 0; i < MAX_SRV_CLIENTS; i++){
if (serverClients[i] && serverClients[i].connected()){
if(serverClients[i].available()){
while(serverClients[i].available()) Serial.write(serverClients[i].read());
//THIS IS THE NON WORKING PART
long randNumber = RANDOM_REG32 % 10000;
Serial.println(randNumber);
String randomstr = String(randNumber);
serverClients[i].write(randomstr,4);
}
}
}
if(Serial.available()){
size_t len = Serial.available();
uint8_t sbuf[len];
Serial.readBytes(sbuf, len);
for(i = 0; i < MAX_SRV_CLIENTS; i++){
if (serverClients[i] && serverClients[i].connected()){
serverClients[i].write(sbuf, len);
delay(1);
}
}
}
}
I guess I have some problems with char arrays, strings, etc... but I can't make it work
while(serverClients[i].available()) Serial.write(serverClients[i].read());
?if(Serial.available()) { ...
work as expected? Are the clients receiving the data read from the serial port?