#define CMD_HEAD1 0x5A
#define CMD_HEAD2 0xA5
#define CMD_WRITE 0x82
#define CMD_READ 0x83
#define MIN_ASCII 32
#define MAX_ASCII 255
#define CMD_READ_TIMEOUT 50
#define READ_TIMEOUT 100
bool _isSoft; // Is serial interface software
long _baud; // DWIN HMI Baud rate
bool _echo = false; // Response Command Show
bool _isConnected; // Flag set on successful communication
bool _noACK = false; // No ack used with no response kernel
bool _retWord = false; // return word from rx event when true
bool cbfunc_valid;
String checkHex(byte currentNo)
{
if (currentNo < 0x10)
{
return "0" + String(currentNo, HEX);
}
return String(currentNo, HEX);
}
void listenerCallback(String address, int lastBytes, String message, String response)
{
Serial.println("");
Serial.print("addr: " + address + " ");
Serial.print("lastBytes: " + String(lastBytes) + " ");
Serial.print("message: " + message + " ");
Serial.println("response: " + response + " ");
}
String handle()
{
int lastBytes;
int previousByte;
String response;
String address;
String message;
bool isSubstr = false;
bool messageEnd = false;
bool isFirstByte = false;
unsigned long startTime = millis();
while ((millis() - startTime < READ_TIMEOUT))
{
while (Serial.available() > 0)
{
delay(10);
// Serial.println("");
int inhex = Serial.read();
Serial.write(inhex);
if (inhex == 90 || inhex == 165)
{ // 5A A5
isFirstByte = true;
message = "";
address = "";
response.concat(checkHex(inhex) + " ");
continue;
}
for (int i = 1; i <= inhex; i++)
{
int inByte = Serial.read();
Serial.write(inByte);
if (i == 1)response.concat(checkHex(inhex) + " ");
if (i == (inhex-1))previousByte=inByte;
response.concat(checkHex(inByte) + " ");
if (i <= 3)
{
if ((i == 2) || (i == 3))
{
address.concat(checkHex(inByte));
}
continue;
}
else
{
if (messageEnd == false )
{
if (isSubstr && inByte != MAX_ASCII && inByte >= MIN_ASCII)
{
message += char(inByte);
}
else
{
if (inByte == MAX_ASCII)
{
messageEnd = true;
}
isSubstr = true;
}
}
}
lastBytes = inByte;
}
}
}
if (isFirstByte)
{
if (_retWord) lastBytes = (previousByte << 8) + lastBytes;
listenerCallback(address, lastBytes, message, response);
}
if (isFirstByte && _echo)
{
Serial.println("Address :0x" + address + " | Data :0x" + String(lastBytes, HEX) + " | Message : " + message + " | Response " + response);
}
return response;
}
void setup() {
// put your setup code here, to run once:
Serial2.begin(115200,SERIAL_8N1, 47,21);
Serial.begin(115200);
delay(1000);
}
void loop() {
// put your main code here, to run repeatedly:
// delay(10); // this speeds up the simulation
// Serial.println("Hello, ESP32-S3!");
// handle();
while(Serial2.available())
{
Serial.write(Serial2.read());
}
while(Serial.available())
{
Serial2.write(Serial.read());
}
}