- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.IO.Ports;
- using System.Threading;
- namespace CommPort
- {
- enum optype
- {
- Continues,
- Orders
- }
-
-
-
- public class CommOp
- {
- private SerialPort commport ;
- List<byte> list = new List<byte>();
-
-
-
- bool sign = false;
-
-
-
-
- public CommOp(SerialPort sp)
- {
- this.commport = sp;
- }
- public CommOp()
- {
- }
-
-
-
-
- public string GetContinueData()
- {
- string strReceive = "";
- if (sign)
- {
- byte firstbyte = Convert.ToByte(commport.ReadByte());
-
- if (firstbyte == 0x02)
- {
-
- int bytesRead = 10;
-
- byte[] bytesData = new byte[bytesRead];
-
- byte byteData;
- for (int i = 0; i <= bytesRead - 1; i++)
- {
- try
- {
- if (commport.IsOpen)
- {
- byteData = Convert.ToByte(commport.ReadByte());
-
- if (byteData == 0x03)
- {
- break;
- }
- bytesData[i] = byteData;
- }
- }
- catch (Exception ex)
- {
- throw new Exception(ex.Message);
- }
- }
-
- strReceive = System.Text.Encoding.Default.GetString(bytesData);
- }
- }
- return GetWeightData(strReceive, optype.Continues);
-
- }
-
-
-
-
- public string GetDataByOrder(byte[] byts)
- {
- string strReceive = "";
- if (sign)
- {
-
- commport.Write(byts, 0, byts.Length);
-
- Thread.Sleep(500);
-
- int int_Len = commport.BytesToRead;
-
- byte[] bytes = new byte[int_Len];
- commport.Read(bytes, 0, int_Len);
-
- if (int_Len >= 12)
- {
- for (int i = 0; i < bytes.Length; i++)
- {
- list.Add(bytes[i]);
- }
- strReceive = System.Text.Encoding.Default.GetString(list.ToArray());
- list.Clear();
- }
- }
- return GetWeightData(strReceive, optype.Orders);
- }
-
-
-
-
-
- private string GetWeightData(string data,optype type)
- {
-
- double d = 0;
- switch (type)
- {
- case optype.Orders:
- d = Convert.ToDouble(data.Substring(4, 6)) / Math.Pow(10, Convert.ToDouble(data.Substring(10, 1)));
- break;
- case optype.Continues:
- d = Convert.ToDouble(data.Substring(1, 6)) / Math.Pow(10, Convert.ToDouble(data.Substring(7, 1)));
- break;
- }
- return d.ToString().PadLeft(7,'0');
- }
-
-
-
- public void Open()
- {
-
- try
- {
- if (!commport.IsOpen)
- {
- commport.Open();
- Thread.Sleep(1500);
- sign = true;
- }
- }
- catch (Exception ex)
- {
- throw new Exception(ex.Message);
- }
- }
-
-
-
- public void Close()
- {
- try
- {
- if (commport.IsOpen)
- {
- sign = false;
- Thread.Sleep(1500);
- commport.DiscardInBuffer();
- commport.Close();
- }
- }
- catch (Exception ex)
- {
- throw new Exception(ex.Message);
- }
- }
- }
- }
这里采用了两种方式进去读取:
1.连续方式:只要磅秤显示有数据,数据就会源源不断的抛入缓冲区,电脑则可以在此时进行读取并分析。通常可以采用serialPort的DataReceived事件处理。
优点:实时性好。
缺点:数据过多,分析效果不太好。
2.指令方式:联机电脑发送读取指令给磅秤,磅秤则发送相应的数据信息到缓冲区(没有其他信息),我们可以获取并分析。
优点:数据单一,分析容易
缺点:需要手动更新获取数据(可以结合Timer组件实现实时更新数据的效果)。
发表于 @
2008年12月15日 18:54:00 | | 编辑|
举报| 收藏