C#每10秒自动发送命令的方法

时间:2011-10-14 04:11:26

标签: c# methods

我有6台设备连接到转换器RS485 / USB。 发送ID0#命令时:(0#= 01或02或03或04或05或06) 收到一个字符串IDXX  0#,22008,21930,00000, n / a, n / a! 然后用substring()划分字符串,并将片段转换为变量。 应该是每10秒自动发送命令的方法,接收字符串,用substring()拆分并将它们存储在变量中?

我试着这样: 与timer1上的tick相关联,间隔为10000。

 private void button6_Click(object sender, EventArgs e)
    {
        string s_ID = stringOut.Trim().Substring(1,2);
        string ID01 = "id01";
        string id01_02mm = "";
        string id01_07mm = "";
        string id01_10mm = "";
        CommPort com = CommPort.Instance;
        ID01 = ConvertEscapeSequences(ID01);
        com.Send(ID01);            

        if(s_ID=="01")
        {
           string id01_time=DateTime.Now.ToString("HH:mm:ss");
           string id01_ID = "ID01";
           id01_02mm=stringOut.Trim().Substring(4,5);
           id01_07mm=stringOut.Trim().Substring(10,5);
           id01_10mm=stringOut.Trim().Substring(16,5);
        }
    }

谢谢, ocaccy

1 个答案:

答案 0 :(得分:1)

如果你想围绕OOP更多地组织代码,可以创建一个RS485USBDevice类来进行解析和发送。然后创建并命令6个实例。它可能类似于以下内容:

public class RS485USBDevice
{
    public int DeviceId { get; set; }
    public string Id_02mm { get; set; } // need more descriptive name
    public string Id_07mm { get; set; } // need more descriptive name
    public string Id_10mm { get; set; } // need more descriptive name
    public DateTime LastRequestTime { get; set; }

    public RS485USBDevice(int deviceId)
    {
        this.DeviceId = deviceId;
    }

    public void SendRequest()
    {
        // where does CommPort come from? custom class?
        CommPort com = CommPort.Instance;
        string ID = "id0" + this.DeviceId;
        ID = ConvertEscapeSequences(ID);
        com.Send(ID);  // shouldn't this have a return value

        // where does stringOut come from? naughty global variable
        this.Id_02mm = stringOut.Trim().Substring(4,5);
        this.Id_07mm = stringOut.Trim().Substring(10,5);
        this.Id_10mm = stringOut.Trim().Substring(16,5);
        this.LastRequestTime = DateTime.Now;
    }
}

public class MainClass
{
    private List<RS485USBDevice> _devices;

    public MainClass()
    {
        // initialize setup of all 6 devices
        this._devices = new List<RS485USBDevice>();
        for (int i = 1; i <= 6; i++)
        {
            var device = new RS485USBDevice(i);
            this._devices.Add(device);
        }
    }

    // this should be timer tick event on 10 seconds
    private void button6_Click(object sender, EventArgs e)
    {
        // make all devices send
        foreach (var device in this._devices)
            device.SendRequest();

        // do something with response data from device obj
    }
}