usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;namespaceDotNet.ElecScales
{usingSystem.IO.Ports;usingSystem.Text;usingSystem.Threading;///
///针对XK3168E///厂家:杭州福达电子设置厂///设置成 波特率9600, 8位无校验,连续模式///编写:Wdfrog/// http://www.cnblogs.com/wdfrog/archive/2012/10/25/2738257.html
///
public classElecScalesReader
{#region 属性d定义
///
///属性部分///
private List _BufferList = new List(1024 * 10);private byte C_STX = 0x02; //开始位标志
private byte C_END = 0x0D; //结束位标志
private int C_MaxQueueElem = 30;//队列里存放的最多元素个数
private int C_FrameLength = 17;private bool Enabled = false;private Thread WorkThread { get; set; }//公开属性
public Queue DataQueue { get; private set; }public SerialPort COMPort { get; private set; }public Exception LastError { get; set; }#endregion
///
///构造///
publicElecScalesReader()
{
DataQueue= new Queue();
}private voidEnsureCOMPortOpen()
{if (COMPort == null)
{//配置COMPort
COMPort = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);
COMPort.Encoding=Encoding.ASCII;//COMPort.DtrEnable = true;
}if (!COMPort.IsOpen)
{
COMPort.Open();
}
}///
///格式-> 状态,读数,原始数据16进制表示,备注///状态-> 1:成功,0:无数据,4:错误///
///
public stringGetValue()
{string valueTmp = "{0},{1},{2},{3}";//状态{1成功,0无数据,4错误},读数,原始数据16进制表示,备注
try{if (WorkThread == null || WorkThread.IsAlive!=true)
{
Launch();
Thread.Sleep(100);
}
}catch(Exception ex)
{
LastError=ex;return string.Format(valueTmp, "4", "", "", ex.Message);
}
GatherDataInfo data= new GatherDataInfo() { Status = 0, AddTime = DateTime.Now, Bytes = null, StrValue = Thread.CurrentThread.ManagedThreadId.ToString() + ":" + this.GetHashCode().ToString(), };lock(DataQueue)
{if (DataQueue.Count > 0)
{
data=DataQueue.Last();
}
}return string.Format(valueTmp, data.Status, data.StrValue, data.Bytes == null ? "" : BitConverter.ToString(data.Bytes.ToArray()), "");
}///
///关闭COM///
public voidClose()
{this.Enabled = false;while (COMPort != null && COMPort.IsOpen) Thread.Sleep(10);
}///
///启动///
private voidLaunch()
{
EnsureCOMPortOpen();
Enabled= true;
WorkThread= newThread(DoReceive);
WorkThread.IsBackground= true;
WorkThread.Priority=ThreadPriority.Highest;
WorkThread.Start();
}private voidDoReceive()
{
Console.WriteLine(Thread.CurrentThread.ManagedThreadId.ToString());#region
try{byte[] buffer = new byte[COMPort.ReadBufferSize];while(Enabled)
{
Thread.Sleep(15);if (COMPort.BytesToRead <= 0) continue;var readLen = COMPort.Read(buffer, 0, COMPort.BytesToRead);
Array.Resize(refbuffer, readLen);
_BufferList.AddRange(buffer);
Array.Resize(refbuffer, COMPort.ReadBufferSize);#region 数据解析
if (_BufferList.Count <= 0) return;var stxIndex =_BufferList.IndexOf(C_STX);if (stxIndex >= 0)
{var endIndex = stxIndex + C_FrameLength - 1; //一个包17个字节
if (_BufferList.Count >endIndex)
{byte[] frameBytes = new byte[C_FrameLength];
_BufferList.CopyTo(stxIndex, frameBytes,0, C_FrameLength);//清空该帧以及该帧前面的全部数据
_BufferList.RemoveRange(0, endIndex);//验证有效性
if (frameBytes[frameBytes.Length - 1] ==C_END)
{var str = Encoding.ASCII.GetString(frameBytes, 4, 6);var val = (str.Substring(0, 5) + "." + str.Substring(5, 1)).Trim();//将数据入队列
var data = new GatherDataInfo() { Status = 1, AddTime = DateTime.Now, Bytes = new List(frameBytes), StrValue =val };lock(DataQueue)
{
DataQueue.Enqueue(data);if (DataQueue.Count >C_MaxQueueElem)
{
DataQueue.Dequeue();
}
}
}else{
Console.WriteLine("无效帧,结尾不是CR符号!");
}
Console.WriteLine(BitConverter.ToString(frameBytes));
}
}//已经收到17个字节但是还没有找到开始标志的//则放弃缓存中的数据
if (_BufferList.Count > C_FrameLength && stxIndex < 0)
{
_BufferList.RemoveRange(0, _BufferList.Count);
}#endregion}
}catch(Exception ex)
{
LastError=ex;throw;
}finally{if (COMPort != null &&COMPort.IsOpen)
{
COMPort.Close();
}
}#endregion}
}///
///获取的有效桢信息///
public classGatherDataInfo
{public DateTime? AddTime { get; set; }///
///字节信息///
public List Bytes { get; set; }///
///转化后的信息///
public string StrValue { get; set; }///
///1,有效果///0,无效///
public int Status { get; set; }
}public classElecScalesHelper
{private staticElecScalesReader _Reader;public staticElecScalesReader Reader
{get{if (_Reader == null)
{
_Reader= newElecScalesReader();
}return_Reader;
}
}///
///格式-> 状态,读数,原始数据16进制表示,备注///状态-> 1:成功,0:无数据,4:错误///
///
public static stringGetValue()
{lock (typeof(ElecScalesHelper))
{returnReader.GetValue();
}
}///
///关闭COM///
public static stringClose()
{lock (typeof(ElecScalesHelper))
{
Reader.Close();
_Reader= null;
}return "";
}
}
}