Please explain from the beginning.
This is the documentation of Stream.readBytes:
https://www.arduino.cc/reference/en/language/functions/communication/stream/streamreadbytes
What do you expect to happen when the value is -1 ?
From the beginning:
I have a project written a long time ago (2 years roughly) in b4r. It is an ESP8266 and uses an RS232 to TTL board to talk to a Solar inverter. It was working fine. Then I updated it recently (latest b4r, arduino, etc) and it broke. it appeared to stop receiving data back from the rs232 connection. I thought I had damaged the rs232 board when tinkering so ordered a new one. In the meantime I noticed this thread with someone else having the same issue so I wondered if it was a software issue.
Now I have new hardware and tested it with a simple arduino sketch in loopback fashion (connecting the rx and tx pins on the d sub connector). It gets a response.
I then created a small project in b4r to test the same. It does not work. _NewData never seems to be called. So I went hunting in the libs to try figure why. I added Serial.print statements to try follow the code flow and discover where it goes wrong.
In the B4RStream lib, when it reads the bytes, the code that follows looks as though it expects the 'number of bytes read' to be stored in the 'i' variable. This is also what the documentation linked above would indicate.
This does not happen though.
On the first read of bytes, 'i' is set to -1 and so the 'total' is never incremented and is returned as 0.
Now, given that this is being used with SoftwareSerial. From the docs for SoftwareSerial->read(). It returns the bytes read, not the number of bytes read. I don't know if this is what could be causing it?
The code in subject is below to save you having to find/open files. This is from B4RStream
UInt B4RStream::ReadBytes(ArrayByte* Buffer, UInt StartOffset, UInt MaxCount) {
::Serial.println("Stream- ReadBytes");
::Serial.println(StartOffset);
UInt total = 0;
while (MaxCount > 0) {
::Serial.println(MaxCount);
::Serial.println("Bytes");
//::Serial.println(wrappedStream->readBytes(((Byte*)Buffer->data + StartOffset + total), MaxCount)); // When uncommented, this prints 4294967295 I commented it though in case it consumed the bytes
Int i = wrappedStream->readBytes(((Byte*)Buffer->data + StartOffset + total), MaxCount);
::Serial.print("i: ");
::Serial.println((String)i); // Logs -1
if (i <= 0) {
::Serial.print("total: ");
::Serial.println(total);
return total; // This retuns total as 0
}
MaxCount -= i;
total += i; // This never runs
}
return total;
}
Lastly, just to reinforce the theory. As mentioned in my last post, when accessing serial stream direct in b4r. The bytes are logged
but the length (len) = zero
Hope this helps and creates a clear enough picture.