I have a serial port waiting for some weight string from an external scale. The problem is that the scale sends multiple readings, about 8 readings per second, all of which are the same weight, for the same product being weighed. I have to print a label once the weight is received, but since I get multiple readings, it printed a a label with every reading received.
I have tried the following solution, and works for the first two products being weighed, and then triggers multiple prints again.
private void SerialReader_Event(object sender, SerialDataReceivedEventArgs e)
{
string dataRead = String.Empty;
try
{
SerialPort port = (SerialPort)sender;
if (port.IsOpen)
{
dataRead = port.ReadExisting();
}
portDataRead = new DataRead(HandlePortReadData);
this.Invoke(portDataRead, new object[] { dataRead });
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Reading Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void HandlePortReadData(string dataRead)
{
int parsedValue;
if (!String.IsNullOrEmpty(dataRead))
{
var stability = dataRead.Substring(1, 1);
var weight = dataRead.Substring(2, 5);
if (stability == "0") //0 is a Stable wieght
{
this.RemoveReceivedEventHandler();
var parsedSuccess = int.TryParse(weight, out parsedValue);
if (parsedSuccess)
{
if (parsedValue > _weightTrigger) //only trigger print if weight is greater than (n) weight
{
if (!this.IsDisposed)
{
AddWeight(parsedValue);
PerformPrint();
}
}
}
}
}
}
private void RemoveReceivedEventHandler()
{
//remove event
sp.DataReceived -= SerialReader_Event;
System.Threading.Thread.Sleep(1000);
sp.DiscardInBuffer();
sp.DiscardOutBuffer();
_timer.Enabled = true;
_timer.Interval = _weighingDelay;
_timer.AutoReset = false;
_timer.Elapsed += new System.Timers.ElapsedEventHandler(_timer_Tick);
_timer.Start();
}
void _timer_Tick(object sender, EventArgs e)
{
this.AddReceivedEventHandler();
}
private void AddReceivedEventHandler()
{
if (sp != null)
{
sp.DataReceived += SerialReader_Event;
sp.DiscardInBuffer();
}
//InitialiseSerialPort();
if (_timer != null)
{
_timer.Stop();
_timer.Enabled = false;
}
}
As can be seen, when I remove the DataReceived event, I start a timer, which after a few seconds, should add the DataReceived event again.
What am I doing wrong here?