For the purposes of this question I'm including a class of mine in its entirety:
public class SerialPortConnection
{
private SerialPort serialPort;
private string ping;
double failOut;
bool isReceiving;
public SerialPortConnection(string comPort = "Com1", int baud = 9600, System.IO.Ports.Parity parity = System.IO.Ports.Parity.None, int dataBits = 8, System.IO.Ports.StopBits stopBits = System.IO.Ports.StopBits.One, string ping = "*IDN?", double failOut = 2)
{
this.ping = ping;
this.failOut = failOut * 1000;
try
{
serialPort = new SerialPort(comPort, baud, parity, dataBits, stopBits);
}
catch (Exception e)
{
throw e;
}
}
//Open Serial Connection. Returns False If Unable To Open.
public bool OpenSerialConnection()
{
//Opens Initial Connection:
try
{
serialPort.Open();
serialPort.Write("REMOTE\r");
}
catch (Exception e)
{
throw e;
}
serialPort.Write(ping + "\r");
var testReceived = "";
isReceiving = true;
Timer StopWatch = new Timer(failOut);
StopWatch.Elapsed += new ElapsedEventHandler(OnTimedEvent);
StopWatch.Interval = failOut;
StopWatch.Enabled = true;
while (isReceiving == true)
{
try
{
testReceived += serialPort.ReadExisting();
}
catch (Exception e)
{
throw e;
}
}
StopWatch.Dispose();
if (testReceived.Contains('>'))
{
return true;
}
else
{
return false;
}
}
public string WriteSerialConnection(string SerialCommand)
{
try
{
serialPort.Write(String.Format(SerialCommand + "\r"));
var received = "";
bool isReceiving = true;
Timer StopWatch = new Timer(failOut);
StopWatch.Elapsed += new ElapsedEventHandler(OnTimedEvent);
StopWatch.Interval = failOut;
StopWatch.Enabled = true;
while (isReceiving == true)
{
try
{
received += serialPort.ReadExisting();
}
catch (Exception e)
{
throw e;
}
}
if (received.Contains('>'))
{
return received;
}
else
{
received = "Error: No Data Received From Device";
return received;
}
StopWatch.Dispose();
}
catch (Exception e)
{
throw e;
}
}
//Closes Serial Connection. Returns False If Unable To Close.
public bool CloseSerialConnection()
{
try
{
serialPort.Write("LOCAL\r");
serialPort.Close();
return true;
}
catch (Exception e)
{
throw e;
}
}
private void OnTimedEvent(object source, ElapsedEventArgs e)
{
isReceiving = false;
}
}
What I'm attempting to do here is keep a loop running for a set amount of time (two seconds in this case) because the device connected to the serial port I'm working with is unpredictable. I don't know what data I will receive from it and I don't know how long it will take. That can't be fixed and is something I have to work with. My best option, currently, is to wait a set amount of time and check the data I've received for an end token (">"). I've tried wiring up a timer even in the class like so:
Timer StopWatch = new Timer(failOut * 1000);
StopWatch.Elapsed += new ElapsedEventHandler(OnTimedEvent);
StopWatch.Interval = failOut;
StopWatch.Enabled = true;
But it doesn't appear to work. The event itself looks like so:
private void OnTimedEvent(object source, ElapsedEventArgs e)
{
isReceiving = false;
}
My objective is to cut the loop isReceiving is tied to:
(while isReceiving == true)
{
//Do Something
}
But it doesn't appear to work. I assume I've completely misunderstood the function of the timer but I've had suggestions before to implement it. What am I doing wrong? If I'm just completely misusing it, what can I use instead of a timer? As I've said, I've no choice but to wait a set amount of time and check what I've received. That can't be avoided or handled in any way other than waiting and hoping I get something.
EDIT:
Maybe it's best I clarify this. The OnTimedEvent event is firing and the variable is set to false but it doesn't cut the loop as isReceiving isn't getting set to false.
EDIT 2:
Mr. Passant's answer works beautifully barring a strange error I'm encountering. As I don't believe it's a problem within his answer, it's more likely that it's a hardware flaw, or something else strange and obscure along those lines, I'm leaving his answer marked as accepted. I recommend anyone that chooses to implement his answer also view the question I have submitted here:
Apparent IO.Ports.SerialPort Flaw in C# or Possible Hardware Flaw
You are making it too difficult on yourself. Simply change the SerialPort.NewLine property to ">". And use SerialPort.ReadLine() to read the response. You can still use a timeout if you need it, assign the SerialPort.ReadTimeout property and be prepared to catch the TimeoutException.
Related
I'm receiving in my serial port the message "Hello World!CRLF" (no quotes) at every 1 second, and I'm using ReadExisting() to read the message, but I can't understand why I'm receiving lots of "\0" before every character.
PuTTy seems to handle the messages just fine, so my code must be the problem. Could someone please help me to figure this out?
Part of my code:
void button1_Click(object sender, EventArgs e)
{
try
{
_serialPort = new SerialPort(cbPort.Text);
_serialPort.BaudRate = Int32.Parse(cbBaudrate.SelectedItem.ToString());
_serialPort.Parity = Parity.None;
_serialPort.StopBits = StopBits.One;
_serialPort.DataBits = 8;
_serialPort.ReadTimeout = 500;
_serialPort.Open();
if (_serialPort.IsOpen)
{
try
{
ReadSerialData();
}
catch (TimeoutException) { }
}
}
catch (Exception er){}
}
private void ReadSerialData()
{
try
{
ReadSerialDataThread = new Thread(ReadSerial);
ReadSerialDataThread.Start();
}
catch (Exception e){}
}
private void ReadSerial()
{
try
{
while (_serialPort.BytesToRead >= 0)
{
readserialvalue = _serialPort.ReadExisting();
ShowSerialData(readserialvalue);
Thread.Sleep(1);
}
}
catch (Exception e){}
}
public delegate void ShowSerialDatadelegate(string r);
private void ShowSerialData(string s)
{
if (rtb_msg.InvokeRequired)
{
ShowSerialDatadelegate SSDD = ShowSerialData;
Invoke(SSDD, s);
}
else
{
rtb_msg.AppendText(readserialvalue);
}
}
As sugested by #Hans Passant changing the encoding to BigEndian solved the main issue.
Still getting lots of invalid unicode chars, but I think is best to open another thread. Thank you all for the support.
_serialPort.Encoding = System.Text.Encoding.BigEndianUnicode;
Are you sure that you want to read from the serial port even if there are 0 bytes to be read? If not, you might want to try changing:
while (_serialPort.BytesToRead >= 0)
to
while (_serialPort.BytesToRead > 0)
I suspect you may be reading from the serial port with 0 bytes to be read, which could return a null (\0) value
In my application I'm using a 9600 baud rate serial connection and I want to use a 115200 baud rate connection for data transfer.
I've disconnected from the old connection and set it to be null value, and set my serial connection to new connection with different baud rate.
The connection is unstable and I sometimes get a System.ObjectDisposedException - what did I miss?
The connection code
public string startConnection()
{
if (serial != null)
{
serial.Dispose();
}
foreach (string portname in SerialPort.GetPortNames())
{
serial = new SerialPort(portname, 9600, Parity.None, 8, StopBits.One);
serial.ReadTimeout = 5000;
serial.WriteTimeout = 5000;
serial.Handshake = System.IO.Ports.Handshake.None;
serial.NewLine = "\n";
string received = "";
try
{
serial.Open();
serial.DiscardInBuffer();
serial.Write(":09;BATTERY;");
Thread.Sleep(500);
received = serial.ReadLine();
if (received.Contains(";BATTERY;V="))
{
status = SERIAL_CONNECTED;
return portname;
}
}
catch (Exception err)
{
try
{
serial.Close();
status = DISCONNECTED;
}
catch (Exception)
{
// throw;
}
}
}
throw new Exception("couldn't connect to coms");
//return "couldn't connect to coms";
//this.Close();
}
Disconnect function:
public void disconnect ()
{
if (serial == null || serial.IsOpen==false ||status == DISCONNECTED)
return;
status = DISCONNECTED;
serial.Close();
serial = null;
}
The main program is:
private async void BurnOFP_click(object sender, RoutedEventArgs e)
{
startConnection();
some actions.............
disconnect();
var t = new Task(() =>
{
try
{
myUswm.startModemConnection(); // same but with different baud rate
}
catch (Exception e2) { MessageBox.Show(e2.Message); }
});
t.Start();
t.Wait();
modem = new XMODEM_FullDotNET(myUswm.getSerialPort(), XMODEM_FullDotNET.Variants.XModemCRC);
buff = File.ReadAllBytes(softwareFilePath_Text.Text);
if (buff.Length < 1)
{
MessageBox.Show("ERROR : wrong OFP file");
return;
}
if (myUswm.prepareOFPBurning()) // sends u to start transfer
{
if (isBurning == false)
{
isBurning = true;
modem._ProgressSent = 0;
myProgBar = new myProgressBar(modem);
myProgBar.StartTransfer(modem, buff.Length);
myProgBar.Show(); // show window
// got the Exception here!!!!!!!!!!
var t3 = new Task(() =>
{
modem.Send(buff);
});
............
}
else
MessageBox.Show("burning in progress..");
}
}
catch (Exception e1)
{
MessageBox.Show(e1.Message);
}
}
Thanks for any help
RESOLVED
my problem was A bad timing caused by closing and reopen the same port.
I've found the information in MSDN Serial class:
The best practice for any application is to wait for some amount of time after calling the Close method before attempting to call the Open method, as the port may not be closed instantly.
my solution was keeping the connection alive and change the baud rate and update the connection status in my application manually.
I am currently working on C# application which requires to read serial port. In UI, there is a ON/OFF button which enables user click on it to start and stop reading data from serial port. If I continuously click on the button on and off. It threw an exception - Access to COM3 is denied or even said "The device is not connected". Can anyone suggest a better way to implement the serial port function which is able to resolve the situation as described above? Here is the code I use:
**// Start reading data from serial port**
public override void StartReading(string portname)
{
try
{
int k = int.Parse(portname.Replace("COM", ""));
if (startThread != null)
{
startThread.Abort();
startThread = null;
}
startThread = new Thread(new ThreadStart(delegate
{
isActive = true;
try
{
using (SerialPort sp = new SerialPort(portname))
{
if (!isActive)
{
DisposeBT(sp);
return;
}
sp.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);
if (!isActive)
{
DisposeBT(sp);
return;
}
if (!isActive)
{
DisposeBT(sp);
return;
}
else
{
Thread.Sleep(6500);
try
{
if (sp != null && !sp.IsOpen)
{
sp.Open();
}
}
catch (Exception ex)
{
Logger.Warn("Failed to open the serial port for HRM once. Try it again.");
Logger.Error(ex);
////////////////////// new added below
if(sp !=null && sp.IsOpen)
{
sp.Dispose();
}
Thread.Sleep(6500);
if (IsPortAvailable(k))
{
try
{
if (sp != null && !sp.IsOpen)
{
sp.Open();
}
}
catch (Exception ex1)
{
////////////////////// new added below
if (sp != null && sp.IsOpen)
{
sp.Dispose();
}
Logger.Warn("Failed to open the serial for HRM twice.");
Logger.Error(ex1);
// return;
}
}
}
}
while (true)
{
if (!isActive)
{
DisposeBT(sp);
break;
}
}
if (!isActive)
{
DisposeBT(sp);
return;
}
DisposeBT(sp);
}
}
catch (Exception ex)
{
Logger.Warn("Exception thrown for HRM.");
Logger.Error(ex);
}
}));
startThread.IsBackground = true;
startThread.Priority = ThreadPriority.Highest;
startThread.Start();
}
catch (Exception ex)
{
Logger.Warn("Failed to start reading for HRM02I3A1 bluetooth device.");
Logger.Error(ex);
}
}
// Stop reading data from serial port
public override void StopReading()
{
try
{
isActive = false;
}
catch { }
}
// event handler for the serial port to read data from sp.
void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
if (isActive)// && startThread.IsAlive
{
SerialPort sp1 = (SerialPort)sender;
try
{
sp1.Read(data, 0, 8);
decoder.Decode(data);
}
catch(Exception ex)
{
Logger.Warn("------data received from Serial Port error for HRM-------");
Logger.Error(ex);
};
}
}
first make background worker thread that accept the cancel event.
in the DoWork method you can write something like that
void DoWork{
// init com port
while(no body cancelled the background worker){
// if there any waiting data receive and process it. do not use event handlers
}
// close the serial port so you can open it again later.
}
Also if you want to cancel the background work it would be a piece of cake
// send cancel command.
// wait till it is canceled.
Try adding startThread.Join() directly after the call to startThread.Abort().
Take a look at the msdn documentation on Thread.Abort and perhaps you also should check what join does.
I have an serial port read running on a background thread, but everytime I try to close it, I get an exception. Usually an IO-exception.
It is as if the read continues on eventhough I close the thread.
This is my current code:
EDIT: I changed the code, removed the checks on threatstate.
public bool Connect(string portName)
{
try
{
sp = new SerialPort(portName, BaudRate);
sp.Open();
sp.DtrEnable = true;
cf = SingletonFormProvider.GetInstance<ConnectionForm>(null);
_continue = true;
readThread = new Thread(Read);
readThread.Start();
return true;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
public void Disconnect()
{
if (IsConnectionOpen)
{
_continue = false;
readThread.Abort();
while (readThread.ThreadState == ThreadState.AbortRequested)
{ }
sp.Close();
readThread.Join();
}
}
private void Read()
{
while (_continue)
{
try
{
string message = sp.ReadLine();
cf.WriteLog(message);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
_continue = false;
readThread.Join();
sp.Close();
}
}
}
You do know that what thread.Abort() does is throw a ThreadAbortException in the thread in question, right? In the thread you catch all exceptions that inherited from Exception. I believe that includes the abort exception. If you really must call Abort, you may want to close the serial port first since I believe that will cause any pending calls to return.
Join your read thread before you close the serial port:
public void Disconnect()
{
if (IsConnectionOpen)
{
_continue = false;
readThread.Join();
sp.Close();
}
}
I got the code below from a website,and this way of serial port reading is my only option because DataReceived event often doesn't work.but this code has a problem,if I close the application while transfering the application hangs forever,but I can't see why?neither freezing nor aborting the thread work.actually aborting the thread causes the program to crash.
public class CommPort
{
SerialPort _serialPort;
Thread _readThread;
bool _keepReading;
//begin Singleton pattern
static readonly CommPort instance = new CommPort();
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static CommPort()
{
}
CommPort()
{
_serialPort = new SerialPort();
_readThread = null;
_keepReading = false;
}
public static CommPort Instance
{
get
{
return instance;
}
}
//end Singleton pattern
//begin Observer pattern
public delegate void EventHandler(string param);
public EventHandler StatusChanged;
public EventHandler DataReceived;
private void StartReading()
{
if (!_keepReading)
{
_keepReading = true;
_readThread = new Thread(new ThreadStart(ReadPort));
_readThread.Start();
}
}
private void StopReading()
{
if (_keepReading)
{
_keepReading = false;
_serialPort.Close();
//_readThread.Join(); //block until exits
_readThread.Abort();
//_readThread = null;
}
}
private void ReadPort()
{
while (_keepReading)
{
if (_serialPort.IsOpen)
{
byte[] readBuffer = new byte[_serialPort.ReadBufferSize + 1];
try
{
// If there are bytes available on the serial port,
// Read returns up to "count" bytes, but will not block (wait)
// for the remaining bytes. If there are no bytes available
// on the serial port, Read will block until at least one byte
// is available on the port, up until the ReadTimeout milliseconds
// have elapsed, at which time a TimeoutException will be thrown.
int count = _serialPort.Read(readBuffer, 0, _serialPort.ReadBufferSize);
String SerialIn = System.Text.Encoding.ASCII.GetString(readBuffer, 0, count);
DataReceived(SerialIn);
}
catch (TimeoutException)
{
}
}
else
{
TimeSpan waitTime = new TimeSpan(0, 0, 0, 0, 50);
Thread.Sleep(waitTime);
}
}
}
/// <summary> Open the serial port with current settings. </summary>
public void Open()
{
Close();
try
{
_serialPort.PortName = Properties.Settings.Default.COMPort;
_serialPort.BaudRate = Properties.Settings.Default.BPS;
_serialPort.Parity = Properties.Settings.Default.Parity;
_serialPort.DataBits = Properties.Settings.Default.DataBit;
_serialPort.StopBits = Properties.Settings.Default.StopBit;
_serialPort.Handshake = Properties.Settings.Default.HandShake;
// Set the read/write timeouts
_serialPort.ReadTimeout = 50;
_serialPort.WriteTimeout = 50;
_serialPort.Open();
StartReading();
}
catch (IOException)
{
StatusChanged(String.Format("{0} does not exist", Properties.Settings.Default.COMPort));
}
catch (UnauthorizedAccessException)
{
StatusChanged(String.Format("{0} already in use", Properties.Settings.Default.COMPort));
}
catch (Exception ex)
{
StatusChanged(String.Format("{0}", ex.ToString()));
}
// Update the status
if (_serialPort.IsOpen)
{
string p = _serialPort.Parity.ToString().Substring(0, 1); //First char
string h = _serialPort.Handshake.ToString();
if (_serialPort.Handshake == Handshake.None)
h = "no handshake"; // more descriptive than "None"
StatusChanged(String.Format("{0}: {1} bps, {2}{3}{4}, {5}",
_serialPort.PortName, _serialPort.BaudRate,
_serialPort.DataBits, p, (int)_serialPort.StopBits, h));
}
else
{
StatusChanged(String.Format("{0} already in use", Properties.Settings.Default.COMPort));
}
}
/// <summary> Close the serial port. </summary>
public void Close()
{
StopReading();
StatusChanged("connection closed");
}
public bool IsOpen
{
get
{
return _serialPort.IsOpen;
}
}
}
When you close the Port in StopReading() it will cause an Exception in _serialPort.Read(...).
Not sure which one exactly but it's not a TimeOut. Your current code lets that escape and that's when your thread and your App are killed.
So add a catch(Exceptiopn ex) around the while loop in ReadPort().
Two issues at first glance.
First off, you have created a singleton class that exposes an event subscription. That's dangerous, because you should keep track of any of the subscribers. Otherwise they may be never released. That's probably what's going on in your case.
Secondly, when you manage something "IDisposable", you should take care about it. So, the SerialPort should be disposed inside a IDisposable implementation within your class. However, that won't make any sense in a singleton class.
The singleton pattern should be used only for centralized passive resources, and never to host "active" objects, events, etc.
Hope this helps.