Понятно, что он есть в коде. Я что-то уже запарился. То данные ходят, то нет. Проще говоря - отправляю с модуля на есп ок, на есп при этом отправляется запрос на модуль. Модуль его принимает и отвечает, но вот есп о том, что разобрала респонс не отвечает своим респонсом. Я уже не знаю куда смотреть. Поигрался с задержками - не помогает.
Код который присылает ответ:
Модуль
enum ModuleCommands {
EMPTY_MODULE = 0,
CMD1 = 1
} moduleCommands;
enum EspCommands {
EMPTY_ESP = 0,
CMD_ESP1 = 1
} espCommands;
struct Command {
int cmd;
String data;
};
boolean hasData = false;
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
// Serial.setTimeout(100);
// Serial1.begin(115200);
delay(1000);
}
void loop() {
// if (!hasData) {
sendRequest("test request from module");
//}
if (Serial.available() > 0) {
tryReadRequest();
}
delay(1000);
}
String PATTERN = "CMD | ";
void sendRequest(String request){
// char toSend[6 + request.length() + 1];
// for (int i =0; i < 6 + request.length(); i++) {
// if (i < 6) {
// toSend[i] = PATTERN.charAt(i);
// } else {
// toSend[i] = request.charAt(i-6);
// }
// }
// toSend[6 + request.length()] = '\0';
// Serial.println(toSend);
//Serial.write(toSend);
Serial.println(PATTERN + request);
delay(2);
}
// void sendResponse(){}
struct Command tryReadRequest() {
Command result;
String str = Serial.readString();
delay(2);
Serial.println("received:" + str);
delay(2);
boolean isCommand = str.length() > 7 && str.substring(0, 3) == "CMD";//'CMD | '
// Serial.println(isCommand);
delay(2);
if (isCommand) {
String command = str.substring(6);
int cmd = atoi(str.charAt(6));
result.cmd = cmd;
result.data = "";
} else {
result.cmd = 0;
}
return result;
}
есп
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
Serial.setTimeout(100);
}
int thisByte = 33;
boolean hasData = false;
enum ModuleCommands {
EMPTY_MODULE = 0,
CMD1 = 1
} moduleCommands;
enum EspCommands {
EMPTY_ESP = 0,
CMD_ESP1 = 1
} espCommands;
struct Command {
int cmd;
String data;
};
void loop() {
//if (!hasData) {
sendRequest("test request from esp");
// hasData = true;
//}
delay(1000);
if (Serial.available()) {
Command rr = tryReadRequest();
if (rr.cmd != EMPTY_ESP) {
sendRequest("resent by esp" + rr.data);
}
}
delay(1000);
}
String PATTERN = "CMD | ";
void sendRequest(String request){
// char toSend[6 + request.length() + 1];
// for (int i =0; i < 6 + request.length(); i++) {
// if (i < 6) {
// toSend[i] = PATTERN.charAt(i);
// } else {
// toSend[i] = request.charAt(i-6);
// }
// }
// toSend[6 + request.length()] = '\0';
//Serial.write(toSend);
Serial.println(PATTERN + request);
delay(2);
}
// void sendResponse(){}
struct Command tryReadRequest() {
Command result;
String str = Serial.readString();
delay(2);
boolean isCommand = str.length() > 7 && str.substring(0, 3) == "CMD";//'CMD | '
if (isCommand) {
String command = str.substring(6);
int cmd = str.charAt(6) - 0;
result.cmd = cmd;
result.data = command;
} else {
result.cmd = 0;
}
return result;
}
И вот код, который не присылает:
модуль
#include "GyverOS.h"
GyverOS<7> OS;
void setup() {
Serial.begin(115200);
// Serial1.begin(115200);
delay(300);
OS.attach(5, checkComands, 100);
Serial.println("Setuped");
}
void loop() {
OS.tick();
delay(OS.getLeft());
}
//COMANDS SERIAL
void checkComands() {
if(Serial.available() > 0) {
Command rr = tryReadData();
if (rr.cmd != EMPTY) {
if (rr.type == CMD) {
switch (rr.cmd) {
case CONNECT_DATA_REQUEST:
sendConnectData();
break;
case APPLY_NEW_SETTINGS:
// connectNetwork();
break;
case REQUEST_STATUS:
// connectNetwork();
break;
}
} else if (rr.type == RES) {
// switch (rr.cmd) {
// case SERIAL_RESPONSE:
// serial = rr.data;
// break;
// }
}
}
}
}
void sendConnectData() {
String charArr = " " + String(CONNECT_DATA_RESPONSE) + " " + serialNumber + " " + currentSsid + " " + wifiPassword;
sendResponse(charArr);
}
void sendRequest(String request){
Serial.println(PATTERN_REQ + request);
delay(2);
Serial.println("send request: " + PATTERN_REQ + request);/////
}
void sendResponse(String request){
Serial.println(PATTERN_RES + request);
delay(2);
Serial.println("send response: " + PATTERN_RES + request);/////
}
struct Command tryReadData() {
Command result;
String str = Serial.readString();
delay(2);
Serial.println("received: " + str);/////
delay(2);
boolean isCommand = str.length() > 10 && str.substring(0, 3) == "CMD";//'CMD | C | ' 'CMD | R | 1'
delay(2);
if (isCommand) {
char type = str.charAt(6);
String command = str.substring(12);
int cmd = str.charAt(10) - '0';
result.cmd = cmd;
result.data = command;
result.type = type == 'C' ? CMD : RES;
} else {
result.cmd = 0;
}
return result;
}
есп
#include "ESP8266WiFi.h"
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>
String ssid ="";
String password = "";
String serial = "";
String PATTERN_REQ = "CMD | C |";
String PATTERN_RES = "CMD | R |";
enum DorriCommands{
CONNECT_DATA_REQUEST = 1,
APPLY_NEW_SETTINGS = 2,
REQUEST_STATUS = 3
} dorriComands ;
enum DorriResponse {
CONNECT_DATA_RESPONSE = 1,
} dorriResponse;
enum ModuleCommands{
EMPTY = 0,
LIST_NETWORKS_REQUEST = 1,
CONNECT_NETWORK = 2,
REQUEST_TASKS = 3,
POST_STATUS = 4
} moduleComands ;
enum ModuleResponse{
CONNECT_DATA_APPLYED = 1
} moduleResponse ;
boolean waitForModuleStart = true;
enum CommanType {
CMD = 0,
RES = 1
} commandType;
struct Command {
CommanType type;
int cmd;
String data;
};
uint32_t requestTimeout = 0;
void setup() {
// pinMode(TXD, OUTPUT);
delay(1000);
Serial.begin(115200);
Serial.setTimeout(100);
WiFi.mode(WIFI_STA);
}
void loop() {
if (waitForModuleStart) {
delay(45000);
waitForModuleStart = false;
}
if (hasNotConnectData()) {
requestConnectData();
} else if(WiFi.status() != WL_CONNECTED) {
connectNetwork();
} else {
delay(1000);
// ModuleCommands cmd = EMPTY;
}
delay(1000);
if (Serial.available()) {
Command rr = tryReadData();
Serial.println("received: " + rr.data);//////
if (rr.cmd != EMPTY) {
if (rr.type == CMD) {
switch (rr.cmd) {
case LIST_NETWORKS_REQUEST:
scanNetwork();
break;
case CONNECT_NETWORK:
connectNetwork();
break;
}
} else if (rr.type == RES) {
switch (rr.cmd) {
case CONNECT_DATA_RESPONSE:
parseConnectData(rr.data);
break;
}
}
}
}
delay(1000);
}
void parseConnectData(String data) {
String delimiter = " ";
const int maxParts = 3; // Maximum number of parts
String outputArray[maxParts];
int outputCount = 0;
splitString(data, delimiter, outputArray, outputCount);
serial = outputArray[0];
ssid = outputArray[1];
password = outputArray[2];
delay(100);
sendResponse(" " + String(CONNECT_DATA_APPLYED) + " connect data applyed.");
}
void splitString(String str, String delimiter, String* outputArray, int& outputCount) {
int startIndex = 0;
int endIndex = str.indexOf(delimiter);
outputCount = 0;
while (endIndex != -1) {
outputArray[outputCount++] = str.substring(startIndex, endIndex);
startIndex = endIndex + delimiter.length();
endIndex = str.indexOf(delimiter, startIndex);
}
// Add the last part
outputArray[outputCount++] = str.substring(startIndex);
}
void connectNetwork() {
if (hasNotConnectData()) {
requestConnectData();
}
char ssid_arr[ssid.length()];
char pass_arr[password.length()];
ssid.toCharArray(ssid_arr, ssid.length());
password.toCharArray(pass_arr, password.length());
WiFi.begin(ssid_arr, pass_arr);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
}
}
void scanNetwork() {
WiFi.disconnect();
int n = WiFi.scanNetworks();
Serial.println(n);
for (int i = 0; i < n; i++)
{
Serial.println(WiFi.SSID(i));
}
if (ssid != "") {
char ssid_arr[ssid.length()];
char pass_arr[password.length()];
ssid.toCharArray(ssid_arr, ssid.length());
password.toCharArray(pass_arr, password.length());
WiFi.begin(ssid_arr, pass_arr);
}
}
void requestConnectData() {
if (millis() - requestTimeout > 5000) {// request only throw 5 sec
requestTimeout = millis();
sendRequest(String(" " +String(CONNECT_DATA_REQUEST)));
}
//Serial.println(SERIAL_REQUEST);
//while (!Serial.available()>0){
//
//}
//serial = Serial.readString();
//Serial.println(SSID_NAME_REQUEST);
//while (!Serial.available()>0){
//
//}
//String ssid_pre = Serial.readString();
//if (ssid_pre != "") {
// ssid = ssid_pre;
// while (!Serial.available()>0){
//
//}
// password = Serial.readString();
//}
}
boolean hasNotConnectData(){
boolean notFull = ssid == "" || password == "" ||serial == "" ;
return notFull;
}
void sendRequest(String request){
Serial.println(PATTERN_REQ + request);
delay(2);
}
void sendResponse(String request){
Serial.println(PATTERN_RES + request);
delay(2);
}
struct Command tryReadData() {
Command result;
// if(Serial.available() > 0) {
String str = Serial.readString();
Serial.println("received: " + str);//////
delay(2);
boolean isCommand = str.length() > 10 && str.substring(0, 3) == "CMD";//'CMD | C | ' 'CMD | R | 1'
if (isCommand) {
char type = str.charAt(6);
String command = str.substring(12);
int cmd = str.charAt(10) - '0';
result.cmd = cmd;
result.data = command;
result.type = type == 'C' ? CMD : RES;
} else {
result.cmd = 0;
}
// } else {
// result.cmd = 0;
// }
return result;
}
void postToServer() {
if ((WiFi.status() == WL_CONNECTED)) {
// WiFiClient client;
// HTTPClient http;
//
// Serial.print("[HTTP] begin...\n");
// // configure traged server and url
// http.begin(client, "http://" SERVER_IP "/postplain/"); //HTTP
// http.addHeader("Content-Type", "application/json");
//
// Serial.print("[HTTP] POST...\n");
// // start connection and send HTTP header and body
// int httpCode = http.POST("{\"hello\":\"world\"}");
//
// // httpCode will be negative on error
// if (httpCode > 0) {
// // HTTP header has been send and Server response header has been handled
// Serial.printf("[HTTP] POST... code: %d\n", httpCode);
//
// // file found at server
// if (httpCode == HTTP_CODE_OK) {
// const String& payload = http.getString();
// Serial.println("received payload:\n<<");
// Serial.println(payload);
// Serial.println(">>");
// }
// } else {
// Serial.printf("[HTTP] POST... failed, error: %s\n", http.errorToString(httpCode).c_str());
// }
//
// http.end();
}
}
void getFromServer() {
// WiFiClient client;
//
// HTTPClient http;
//
// Serial.print("[HTTP] begin...\n");
// if (http.begin(client, "http://jigsaw.w3.org/HTTP/connection.html")) { // HTTP
//
//
// Serial.print("[HTTP] GET...\n");
// // start connection and send HTTP header
// int httpCode = http.GET();
//
// // httpCode will be negative on error
// if (httpCode > 0) {
// // HTTP header has been send and Server response header has been handled
// Serial.printf("[HTTP] GET... code: %d\n", httpCode);
//
// // file found at server
// if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) {
// String payload = http.getString();
// Serial.println(payload);
// }
// } else {
// Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
// }
//
// http.end();
// } else {
// Serial.printf("[HTTP} Unable to connect\n");
// }
}
По поводу available() > 0, тоже менял. Ощущение, что не читает ЕСП, хотя когда напрямую проверяю через монитор порта - все читает.