Reputation: 33
I have the following code in a loop, reading the contents of a file and transferring it via USB to an external device.
The loop works fine on one device, but if I swap it out for a different device (same device type, different unit) it works fine, but on the last iteration of the loop, somehow the Serial Port gets jammed up or something, not allowing me to perform any Read actions without a Timeout exception being thrown.
I've verified there are bytes available to read in the buffer, yet it just times out.
Now since it's the same code executing again and again (hundreds if not thousands of times, depending on the file size) I don't see why it should act any differently on the last iteration.
I assume I am doing something wrong (even though the code works on another unit) yet this is still mind boggling to me. Any sort of help will be greatly appreciated.
Here's the code:
for(int i = 0; i < fileData.Length; i++)
{
sendBuffer.Add(fileData[i]);
if(sendBuffer.Count == 61)
{
var result = writeI2cWithoutRegister(0x40, sendBuffer.ToArray());
Thread.Sleep(50); // At least 50ms between write actions
sendBuffer.Clear();
}
}
public bool writeI2cWithoutRegister(int deviceAddress, byte[] data)
{
mainPort.WriteLine(""); // This sends a certain command for our external product.
Thread.Sleep(25); // Force at least 25ms between write and read actions.
bool success = false;
do
{
try
{
var msg = mainPort.ReadLine();
Thread.Sleep(50);
if (msg.Contains("Write") || msg.Contains("Error"))
success = false;
if (!bool.TryParse(msg, out success))
success = false;
}
catch
{
success = false;
Console.WriteLine("Read exception, trying again...");
counter++;
}
}
while (success == false);
return success;
}
The do-while was an attempt to perhaps retry again and again until it works, I end up in an infinite loop, it always throws an exception (on the last for loop iteration as mentioned before).
Code above 99.99% of the time works, but not for the last message, not quite sure what's going on here. SerialPort WriteLine function works, but ReadLine times out while there definitely is data in the In Buffer.
Upvotes: 2
Views: 587
Reputation: 33
I've done some digging around and it turns out @MatthewWatson's lead helped me the most, so all credit goes to them.
I've modified my code to use the Base Stream and not using the high-level functions of the SerialPort class, and it seems to have solved my issues.
Hopefully this helps someone in the future.
Upvotes: 1