using Mesnac.DoUtils.enumInfo; using System; using System.Collections.Generic; using System.IO.Ports; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; namespace Mesnac.DoUtils { /// /// 报警灯控制类 /// public sealed class DoControl { public SerialPort serialPort = new SerialPort("COM5"); private static readonly Lazy lazy = new Lazy(() => new DoControl()); public static DoControl Instance { get { return lazy.Value; } } private DoControl() { serialPort.BaudRate = 115200; serialPort.DataBits = 8; serialPort.StopBits = StopBits.One; serialPort.Parity = Parity.None; } /// /// 串口启动 /// public void ComOn() { try { if (!serialPort.IsOpen) { serialPort.Open(); ICSharpCode.Core.LoggingService.Debug($"打开报警器串口成功,串口:{serialPort.PortName};波特率:{serialPort.BaudRate}"); } }catch (Exception ex) { ICSharpCode.Core.LoggingService.Error($"报警器串口打开异常,串口:{serialPort.PortName};波特率:{serialPort.BaudRate};异常信息:{ex.Message}"); } } /// /// 串口关闭 /// public void ComOff() { if (serialPort.IsOpen) { serialPort.Close(); } } /// /// DO1设备启动(红灯) /// public void redLightOn() { DOControl(DOName.Red, DOOnOff.On); } /// /// DO2设备启动(绿灯) /// public void greenLightOn() { DOControl(DOName.Green, DOOnOff.On); } /// /// DO3设备启动(蜂鸣器) /// public void buzzerOn() { DOControl(DOName.Buzzer, DOOnOff.On); } /// /// DO1设备关闭(红灯) /// public void redLightOff() { DOControl(DOName.Red, DOOnOff.Off); } /// /// DO2设备关闭(绿灯) /// public void greenLightOff() { DOControl(DOName.Green, DOOnOff.Off); } /// /// DO3设备关闭(蜂鸣器) /// public void buzzerOff() { DOControl(DOName.Buzzer, DOOnOff.On); } /// /// 重置串口和DO状态 /// public void Reset() { SetOff(); ComOff(); } /// /// 重置DO状态 /// public void SetOff() { foreach (DOName dOName in Enum.GetValues(typeof(DOName))) { DOControl(dOName, DOOnOff.Off); } } /// /// DO启停控制 /// /// DegitalOut接口名称 /// 启停状态 public void DOControl(DOName dOName, DOOnOff dOOnOff) { if (serialPort.IsOpen) { serialPort.Write(new byte[] { 0xE3, 0x01, 0x09, (byte)dOName, (byte)dOOnOff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, 0, 12); } else { ComOn(); } } /// /// 文本框传输数据控制COM5串口 /// public void DOTestSend(string str) { //ComOn(); string[] strArray = str.Split(' '); byte[] bytes = new byte[strArray.Length]; for (int i = 0; i < bytes.Length; i++) { bytes[i] = Convert.ToByte(strArray[i], 16); } serialPort.Write(bytes, 0, bytes.Length); } } }