连接串口后先发送"CP "激活电子秤数据发送,收到的数据包是17字节的
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace DotNet.ElecScales { using System.IO.Ports; using System.Text; using System.Threading; /// <summary> /// 针对Defender 3000 - T31P /// 厂家:奥豪斯仪器(常州)有限公司 /// 设置成 波特率9600, 8位无校验,连续模式 /// 编写:Wdfrog /// http://www.cnblogs.com/wdfrog/archive/2012/10/25/2738257.html /// </summary> public class ElecScalesReader { #region 属性d定义 private String ComName; private int C_MaxQueueElem = 30;//队列里存放的最多元素个数 private int C_FrameLength = 17; private bool Enabled = false; private Thread WorkThread { get; set; } //公开属性 public Queue<GatherDataInfo> DataQueue { get; private set; } public SerialPort COMPort { get; private set; } public Exception LastError { get; set; } #endregion /// <summary> /// 构造 /// </summary> public ElecScalesReader(string com) { ComName = com; DataQueue = new Queue<GatherDataInfo>(); } private void EnsureCOMPortOpen() { if (COMPort == null) { //配置COMPort COMPort = new SerialPort(ComName.ToUpper(), 9600, Parity.None, 8, StopBits.One); COMPort.Handshake = Handshake.XOnXOff; COMPort.Encoding = Encoding.ASCII; //COMPort.DtrEnable = true; } if (!COMPort.IsOpen) { COMPort.Open(); } } /// <summary> /// 格式-> 状态,读数,原始数据Ascii字符串,备注 /// 状态-> 1:成功,0:无数据,4:错误 /// </summary> /// <returns></returns> public string GetValue() { string valueTmp = "{0},{1},[{2}],{3}";//状态{1成功,0无数据,4错误},读数,原始数据16进制表示,备注 var data = GetValueInfo(); return string.Format(valueTmp, data.Status, data.StrValue, data.RawStr == null ? "" : data.RawStr, ""); } public GatherDataInfo GetValueInfo() { try { if (WorkThread == null || WorkThread.IsAlive != true) { Launch(); Thread.Sleep(100); } } catch (Exception ex) { LastError = ex; return new GatherDataInfo() { Status = 0 }; } if (DataQueue.Count <= 0) Thread.Sleep(100); GatherDataInfo data = new GatherDataInfo() { Status = 0, AddTime = DateTime.Now, RawStr = null, StrValue = Thread.CurrentThread.ManagedThreadId.ToString() + ":" + this.GetHashCode().ToString(), }; lock (DataQueue) { if (DataQueue.Count > 0) { data = DataQueue.Last(); } } return data; } /// <summary> /// 关闭COM /// </summary> public void Close() { this.Enabled = false; while (COMPort != null && COMPort.IsOpen) Thread.Sleep(10); } /// <summary> /// 启动 /// </summary> private void Launch() { EnsureCOMPortOpen(); Enabled = true; WorkThread = new Thread(DoReceive); WorkThread.IsBackground = true; WorkThread.Priority = ThreadPriority.Highest; WorkThread.Start(); } private void DoReceive() { Console.WriteLine("ThreadId:" + Thread.CurrentThread.ManagedThreadId.ToString()); #region try { byte[] buffer = new byte[COMPort.ReadBufferSize]; while (Enabled) { Thread.Sleep(100); if (COMPort.BytesToRead <= 0) continue; var readLine= COMPort.ReadLine(); if (readLine.Length != 17) continue; var v = readLine.Substring(0, 1).Trim() + readLine.Substring(1, 7).Trim(); COMPort.DiscardInBuffer(); Console.WriteLine(v); //将数据入队列 var data = new GatherDataInfo() { Status = 1, AddTime = DateTime.Now, RawStr = readLine, StrValue = v }; lock (DataQueue) { DataQueue.Enqueue(data); if (DataQueue.Count > C_MaxQueueElem) { DataQueue.Dequeue(); } } } } catch (Exception ex) { LastError = ex; throw; } finally { if (COMPort != null && COMPort.IsOpen) { COMPort.Close(); } } #endregion } } /// <summary> /// 获取的有效桢信息 /// </summary> public class GatherDataInfo { public DateTime? AddTime { get; set; } /// <summary> /// 字节信息 /// </summary> public String RawStr { get; set; } /// <summary> /// 转化后的信息 /// </summary> public string StrValue { get; set; } /// <summary> /// 1,有效果 /// 0,无效 /// </summary> public int Status { get; set; } } public class ElecScalesHelper { private static Dictionary<String, ElecScalesReader> _Readers; public static Dictionary<String, ElecScalesReader> Readers { get { if (_Readers == null) { _Readers = new Dictionary<String,ElecScalesReader>(); } return _Readers; } } /// <summary> /// 格式-> 状态,读数,原始数据16进制表示,备注 /// 状态-> 1:成功,0:无数据,4:错误 /// </summary> /// <returns></returns> public static string GetValue(String comName) { var com=comName.Trim().ToLower(); if (com.IndexOf("com") != 0) return "错误的COM名称"; lock (typeof(ElecScalesHelper)) { ElecScalesReader reader = null; if (!Readers.ContainsKey(com)) { reader = new ElecScalesReader(com); Readers.Add(com, reader); } else { reader = Readers[com]; } return reader.GetValue(); } } /// <summary> /// 关闭COM /// </summary> public static string Close(String comName) { var com = comName.Trim().ToLower(); if (!Readers.ContainsKey(com)) return "字典内不存在该串口"; var reader = Readers[com]; lock (typeof(ElecScalesHelper)) { reader.Close(); reader = null; } return ""; } } }