As title says I can not reestablish connection with a serial device without detach / attach the usb cable.
This is how it works in pseudo code :
public class SerialCommunicaiton
{
proteced SerialPort serial_port = null
protected string serial_port_name;
[...]
public SerialCommunication(string _serial_port_name)
{
serial_port_name = _serial_port_name;
}
public virtual bool Open(bool dtr = true)
{
try
{
if ((serial_port == null || !serial_port.IsOpen))
{
serial_port = new SerialPort(serial_port_name)
{
BaudRate = 115200,
DataBits = 8,
StopBits = StopBits.One,
DtrEnable = dtr,
};
serial_port.Open();
}
catch()[...]
}
}
public SubClass : SerialCommunication
{
[...]
public override bool Open()
{
bool isOK = base.Open(false);
if(isOK)
{
serial_port.DataReceived += Serial_port_DataReceived;
return Init();
}
[...]
}
[...]
}
In the Init()
method i simply send some data to the device. The device should always reply with \u002ACK\x0d
or \u002NACK\x0d
even to unknown commands.
First connection works like a charm, but when program crashes or I close it I cannot reconnect to the device through the override bool Open()
method because I do not receive any response from the device. I can send whatever I want through the serial port but I do not receive any data, synchronous or asynchronous mode changes nothing.
The fun thing, however, is that the only way to reestablish connection is to unplug/plug the device or to use a simply python program or a 3rd part software and sending some data to the device which actually replies with the expected strings. After that the overmentioned code works again.
I tried to check the SerialPort serial_port
object in both working and not working status but it has the same exact properties so my best guess is there are some problems at lower level but I can not find what could it possibly be.