tx
10 天以前 e0b138b3e057de6f57021e6c8963868f5c5acc5a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
 
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using TProduct.Link.Shun; 
 
 
//测试AB口(RS485)
namespace TProduct.Link.Debugger
{
    public partial class DebugMsg_LMAG流量计_Ctrl : UserControl, ILinkDebugger
    {
        public SerialPort _serialPort = null;
 
 
        private bool _isDisp0X = true;//是否是显示16进制
 
        //
        public DebugMsg_LMAG流量计_Ctrl()
        {
            InitializeComponent();
             
        }
 
        private void TestRS485Form_Load(object sender, EventArgs e)
        {
            //设置当前电脑有哪个串口可用的Combox控件
            InitialDispContrl(comboBoxCOM);
 
            groupBox1.Enabled = false;
            groupBox3.Enabled = false;
 
            comboBoxbtl.SelectedIndex = 2;
        }
 
 
 
        public static bool InitialDispContrl(System.Windows.Forms.ComboBox ctrl)
        {
            ctrl.Items.AddRange(System.IO.Ports.SerialPort.GetPortNames());
            if (ctrl.Items.Count == 0)
            {
                MessageBox.Show("没有COM端口");
                return false;
            }
            ctrl.SelectedIndex = 0;
            return true;
        }
 
        public void DisposePort()
        {
            if (_serialPort != null)
            {
                if (_serialPort.IsOpen)
                {
                    //清理事件接收
                    this._serialPort.DataReceived -= new System.IO.Ports.SerialDataReceivedEventHandler(this.OnReceiveMessage);
                    //关闭
                    _serialPort.Close();
                }
            }
        }
 
        byte[] commandSend = null;//rs485的发送命令
        //连接设备(下发命令)
        private void btnSendQueryMsg_Click(object sender, EventArgs e)
        {
            if (_serialPort == null)
                return;
            if (!_serialPort.IsOpen)
            {
                MessageBox.Show("端口没有打开!");
                return;
            }
     
            //设备地址
            byte addr10 = 0;
            try
            {
                if (radioButton10.Checked)
                {
                    addr10 = byte.Parse(textEquipAddress.Text);
                }
                else
                {
                    addr10 = Convert.ToByte(textEquipAddress.Text, 16);
                }
            }
            catch (Exception)
            {
                MessageBox.Show("请输入合理的地址");
                return;
            }
            if (addr10 < 0)
            {
                MessageBox.Show("地址请输入0-256");
                return;
            }
 
            //
            TProduct.RS485.Properties.Settings.Default.PortName = comboBoxCOM.Text;
            TProduct.RS485.Properties.Settings.Default.TestRs485addr = textEquipAddress.Text;
            TProduct.RS485.Properties.Settings.Default.TestRs485addr10 = radioButton10.Checked;
            TProduct.RS485.Properties.Settings.Default.Save();
 
            this.rtfTerminal1.AppendText("----------------------------START------------------------------\n");
 
 
 
            Task.Run(() =>
            {
                commandSend = TProduct.Link.Kedi.Msg_爱福士_流量计.BuildQueryMessage(addr10);
 
                OnSendMessageManu();
 
            });
 
 
        }
 
 
 
        //手动发消息
        public void OnSendMessageManu()
        {
            if (null == commandSend)
                return;
 
            try
            {
                //清除
                _serialPort.DiscardOutBuffer();
                _serialPort.DiscardInBuffer();
 
                //发送查询
                _serialPort.Write(commandSend, 0, commandSend.Length);
            }
            catch (Exception ex)
            {
                this.rtfTerminal1.AppendText("Error : 发送失败" + ex.Message);
                return;
            }
 
 
            //查询命令(字符)      
            string strMessage;
            if (_isDisp0X)
                strMessage = BitConverter.ToString(commandSend, 0, commandSend.Length);
            else
                strMessage = Encoding.ASCII.GetString(commandSend.ToArray());
 
            DisplayMessage(string.Format("------{0}: {1} ;\n", "查询消息", strMessage));
        }
 
        //接收消息(事件)
        private void OnReceiveMessage(object sender, SerialDataReceivedEventArgs e)
        { 
            //等一条完整的命令进入缓冲区 
            Thread.Sleep(200);
 
            //读取串口中的数据
            int count = _serialPort.BytesToRead;
            if (count < 5)
            {
                DisplayMessage(string.Format("Error196 : 可能设备没有连接上,得到的数据长度为: {0}; ", count));
                return;
            }
            byte[] byteMessage = new byte[count];
            try
            {
                _serialPort.Read(byteMessage, 0, byteMessage.Length);
            }
            catch (Exception ex)
            {
                DisplayMessage("Error206 : 数据读取失败 " + ex.Message);
                return;
            }
 
            //显示收到的消息
            string strMessage;
            if (_isDisp0X)
                strMessage = BitConverter.ToString(byteMessage, 0, byteMessage.Length);
            else
                strMessage = Encoding.ASCII.GetString(byteMessage.ToArray());
 
            DisplayMessage(string.Format("######收到的消息:  {0}; ", strMessage));
 
 
            byte[] byteValue = new byte[4];
            Array.Copy(byteMessage, 3 + 0, byteValue, 0, 4);
            var rValve = BitConverter.ToSingle(byteValue.Reverse().ToArray(), 0);//采用了IEEE-754二进制浮点数算术标准
            DisplayMessage(string.Format("######流量数据:   {0}; ", rValve));
        }
 
        //输出到主窗口文本控件
        void DisplayMessage(string strMessage)
        {
            this.rtfTerminal1.Invoke
               (
                       /*表示一个委托,该委托可执行托管代码中声明为 void 且不接受任何参数的任何方法。
                         * 在对控件的 Invoke    方法进行调用时或需要一个简单委托又不想自己定义时可以使用该委托。*/
                       new MethodInvoker
                           (
                               delegate
                               {
                                   /*匿名方法,这是一种允许程序员将一段完整代码区块当成参数传递的程序代码编写技术,
                                    * 通过此种方法可  以直接使用委托来设计事件响应程序以下就是你要在主线程上实现的功能但是有一点要注意,
                                    * 这里不适宜处理过多的方法,因为C#消息机制是消息流水线响应机制,
                                    * 如果这里在主线程上处理语句的时间过长会导致主UI线程阻塞,
                                    * 停止响应或响应不顺畅,这时你的主form界面会延迟或卡死 */
 
                                   //具体的值
                                   this.rtfTerminal1.AppendText(strMessage);
                                   this.rtfTerminal1.AppendText("\n");
                               }
                           )
                );
        }
 
 
 
 
        //打开
        private void btnOpenCom_Click(object sender, EventArgs e)
        {
            try
            {
                if (_serialPort == null)
                {
                    _serialPort = new SerialPort();
                    //使用事件接收
                    //this._serialPort.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(this.OnReceiveMessage);
                }
 
                if (_serialPort.IsOpen)
                {
                    MessageBox.Show("串口已打开,请关闭后再打开");
                    return;
                }
                // 
                _serialPort.BaudRate = Convert.ToInt32(comboBoxbtl.Text);
                _serialPort.PortName = comboBoxCOM.Text;
                _serialPort.DataBits = 8;
                _serialPort.Parity = Parity.None;
                _serialPort.StopBits = StopBits.One;
                _serialPort.ReceivedBytesThreshold = 1;
 
                //打开COM接口
                _serialPort.Open();
                if (!_serialPort.IsOpen)
                    return;
 
 
                //!设置按钮
                groupBox1.Enabled = true;
                groupBox3.Enabled = true;
 
                _isDisp0X = true;//是否是显示16进制
 
 
                //使用事件接收
                this._serialPort.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(this.OnReceiveMessage);
 
 
 
                // watingTime = productRS485.GetMiniReceiveWaitTime() > 0 ? productRS485.GetMiniReceiveWaitTime() : 200;
                // textWaitingTime.Text = watingTime.ToString();
 
 
            }
            catch (Exception ex)
            {
                MessageBox.Show("串口信息提示:" + ex.Message, "信息提示",
                    MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
 
        //关闭
        private void btnCloseCom_Click(object sender, EventArgs e)
        {
            if (_serialPort.IsOpen)
            {
                _serialPort.Close();
 
                this._serialPort.DataReceived -= new System.IO.Ports.SerialDataReceivedEventHandler(this.OnReceiveMessage);
            }
        }
 
        private void btnClearText_Click(object sender, EventArgs e)
        {
            rtfTerminal1.Text = string.Empty;
        }
 
 
 
    }
}