《SerialPort访问接口获取电子称数据》由会员分享,可在线阅读,更多相关《SerialPort访问接口获取电子称数据(5页珍藏版)》请在金锄头文库上搜索。
1、using System;using System.IO.Ports;using System.Text;using System.Threading; / / 封装 COM 口数据/ public class ComInformation string _wdata;string _wunit;string _qdata;string _qunit;string _percentage;/ / 获取或设置重量/ public string WData get return this._wdata; set this._wdata = value; / / 获取或设置重量单位/ public
2、string WUnit get return this._wunit; set this._wunit = value; / / 获取或设置数量/ public string QData get return this._qdata; set this._qdata = value; / / 获取或设置数量单位/ public string QUnit get return this._qunit; set this._qunit = value; / / 获取或设置百分数/ public string Percentage get return this._percentage; set
3、this._percentage = value; / / 电子称数据读取类/ public class WeightReader : IDisposable #region 字段、属性与构造函数SerialPort sp;int _speed = 300;/ / 获取或设置电脑取 COM 数据缓冲时间,单位毫秒/ public int Speedgetreturn this._speed;setif (value / 初始化串口/ / 数据传输端口/ 波特率/ 串口读数缓冲时间/ public bool InitCom(string PortName, int BaudRate,int Sp
4、eed) trysp = new SerialPort(PortName, BaudRate, Parity.None, 8);sp.ReceivedBytesThreshold = 10;sp.Handshake = Handshake.RequestToSend;sp.Parity = Parity.None;sp.ReadTimeout = 600;sp.WriteTimeout = 600;this.Speed = Speed;if (!sp.IsOpen)sp.Open();return true;catch throw new Exception(string.Format(无法初
5、始化串口0!,PortName);#endregion#region 串口数据读取方法public WeightInformation ReadInfo()string src = this.ReadCom();WeightInformation info = new WeightInformation();info.WData = this.DecodeWeightData(src);info.WUnit = this.DecodeWeightUnit(src);info.Percentage = this.DecodePercentage(src);info.QData = this.De
6、codeQualityData(src);info.QUnit = this.DecodeQualityUnit(src);return info;/ / 将 COM 口缓存数据全部读取/ / private string ReadCom()/返回信息 if (this.sp.IsOpen)Thread.Sleep(this._speed);string res = ;/for (int i = 0; i / 从字符串中取值/ / 起始字符串/ 间隔位长度/ 值长度/ 源字符串/ private string DecodeValue(string head, int intervalLen,
7、int valueLen,string src)int index = src.IndexOf(head);return src.Substring(index + intervalLen, valueLen);/ / 取重量/ / 源字符串/ private string DecodeWeightData(string srcString)return this.DecodeValue(GS, 3, 8,srcString);/ / 取重量单位/ / 源字符串/ private string DecodeWeightUnit(string srcString)return this.Deco
8、deValue(GS, 12, 2, srcString);/ / 取百分数/ / 源字符串/ private string DecodePercentage(string srcString)return this.DecodeValue(U.W., 4, 14, srcString);/ / 取数量/ / 源字符串/ private string DecodeQualityData(string srcString)return this.DecodeValue(PCS, 3, 9, srcString); / / 取数量单位/ / 源字符串/ private string DecodeQualityUnit(string srcString)return this.DecodeValue(PCS, 12, 3, srcString); #endregion#region 释放所有资源public void Dispose()if (sp != null & sp.IsOpen)sp.Close();#endregion