一种不同的称重桥应用?

时间:2012-07-02 11:52:15

标签: c# wpf serial-port

我有一个WPF应用程序连接到地磅以获得权重。

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);
}

我需要在不同的地磅上使用相同的应用程序。然后我需要更改地磅的代码如下:

 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);
}

是否可以使地磅部分通用?我们所做的就是将一个或多个字符发送到地磅,获得响应,检查响应是否有效并读取权重。

是否可以执行配置文件,以便我们根据地磅更改此文件中的某些值而不更改实际代码?

3 个答案:

答案 0 :(得分:2)

管理它的最优雅方法是将SerialPort对象封装在一个具有配置此对象的属性的类中。

要在配置文件中存储值,您可以在config.app文件中设置值,并使用ConfigurationManager

访问值

答案 1 :(得分:0)

您可以将所有动态值(例如Timeout,Com-Port-No ...)放入配置文件中,如您所述。您可以将app.config文件用于此格式或您自己的XML格式文件。

另一种方法可能是战略模式实施,请参阅link

您的方法和事件(Connect,Disconnect,DataReceived)将在策略基类中定义,它描述了算法,实现本身包含在派生策略中。

为了获得最大的灵活性,您还可以将配置文件与策略模式结合使用,尤其是当您希望将来支持超过2个称重和不同的称重算法时。 例如。称重A型和B型应采用策略1,称重C型和D型,采用策略2。

答案 2 :(得分:0)

static class diagram

我认为你需要像这个uml中的内容。在WeighMachine类(抽象)中,您可以定义类似于WeighingReceived事件的内容,并保存对另一个抽象WeighMachineConfig的引用。您的应用程序代码仅处理抽象WeighMachine(使用工厂从config中选择并实例化正确的实例)。每台称重机都可以有不同的配置参数以及发送给它的不同命令,因此配置应该封装在WeighMachineConfigX类和WeighMachineX类中的协议/命令中。当具体的称重机器实例接收数据时,它们应该调用抽象WeighMachine类上定义的公共事件。