using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using DeviceLib.DeviceSerial; namespace DoAn.Core { public delegate void ComDataEvent(object sender, string value); public delegate void ComRunEvent(object sender, string value); public delegate void ComErrorEvent(object sender, string value); public class ComServer { private static ComServer _comServer = null; /// /// 串口服务器单例对象 /// /// public static ComServer CreateSingleComServer() { if (_comServer != null) return _comServer; else { _comServer = new ComServer(); return _comServer; } } private DeviceServer _ds = null; /// /// 创建设备服务器对象 /// public DeviceServer DServer { get { return _ds; } } // 委托对象 public ComDataEvent comData; public ComRunEvent comRun; public ComErrorEvent comError; /// /// 构造函数 /// private ComServer() { this._ds = new DeviceServer(); this._ds.DataError += MainDataError; this._ds.DataChange += Com_DataUpdated; this._ds.RunInfo += MainRunInfo; } /// /// 添加设备 /// /// /// /// /// /// /// /// public object AddItem(int Id, string Name, int Number, DeviceModul CompanyModul, string Settings, int Station) { _ds.AddItem(Id, Name, Number, CompanyModul, Settings, Station); return null; } // 开启串口 public void Start() { _ds.Start(); } // 释放资源 public void Dispose() { if (_ds != null) _ds.Dispose(); } public void StartScanner(int port) { SerialPortDevice spd = _ds.FindItemByPort(port); if (spd != null) { this._ds.SyncWrite(spd, new byte[] { 0x16, 0x54, 0x0D }); } } public void StopScanner(int port) { SerialPortDevice spd = _ds.FindItemByPort(port); if (spd != null) { this._ds.SyncWrite(spd, new byte[] { 0x16, 0x55, 0x0D }); } } #region (* 串口事件处理函数 *) // 串口数据接收完成 private void Com_DataUpdated(object sender, object value) { if (sender is SerialPortDevice && value is string) { SerialPortDevice sp = (SerialPortDevice)sender; if (comData != null) { string _sender = sender.ToString(); string _value = (string)value; string strResult = _value.Replace("\n", "").Replace(" ", "").Replace("\t", "").Replace("\r", ""); comData(sp.terDevice.Id.ToString(), strResult); } } } #endregion #region (* 串口运行和故障信息 *) // 运行信息 private void MainRunInfo(string rs) { if (comRun != null) { comRun.BeginInvoke(null, rs, null, null); } } // 故障信息 private void MainDataError(Exception ex) { if (comError != null) { string rs = string.Format("错误原因:{0} ", ex.Message); comError.BeginInvoke(null, rs, null, null); } } #endregion } }