I have a WPF application which connect to a weighbridge to get the weights.
spWeigh = new SerialPort("COM1", 9600, Parity.Even, 7, StopBits.One);
spWeigh.RtsEnable = false;
spWeigh.DtrEnable = false;
spWeigh.Handshake = Handshake.None;
spWeigh.ReadTimeout = 10000;
spWeigh.DataReceived += spWeigh_DataReceived;
spWeigh.Write(((char)5).ToString());
void spWeigh_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
strResponseWeigh = spWeigh.ReadLine();
if (strResponseWeigh.Length == 0)
{
MessageBoxWrapper.Show("Error in communication with weighbridge", "Error");
return;
}
string wt = strResponseWeigh.Substring(15, 6);
}
I need to use the same application with a different weighbridge. Then I need to change the code for the weighbridge as below:
spWeigh = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);
spWeigh.RtsEnable = false;
spWeigh.DtrEnable = false;
spWeigh.Handshake = Handshake.None;
spWeigh.ReadTimeout = 10000;
spWeigh.DataReceived += spWeigh_DataReceived;
void spWeigh_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
try
{
strResponseWeigh = spWeigh.ReadLine();
if (strResponseWeigh=="")
{
MessageBoxWrapper.Show("Error communicating with the weighbridge", "Error");
return;
}
//Some more checking are to be done here depending on the response(different from the first weighbridge type)
string wt = strResponseWeigh.Substring(2, 7);
}
Is it possible to make the weighbridge section generic? All that we do is send a character(or characters) to weighbridge, get the response, check whether the response is valid and read the weights.
Is it possible to do a config file so that we change some values in this file depending on the weighbridge without changing the actual code?
The most elegant way to manage this would be to encapsulate the SerialPort object in a class with properties that configures this object.
To store values in a configuration file, you can set values in the config.app file and access values with the ConfigurationManager class