using Rs.Framework; using Rs.MotionPlat.Flow; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO.Ports; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace Rs.MotionPlat.AuxiliaryEquipment { /// /// 镭射头 /// public class LaserEquipment { List bufferList = new List(); SerialPort serialPort; const string regStr = @"[+-]\d{5}"; public LaserEquipment() { serialPort = new SerialPort(); serialPort.PortName = "COM1"; serialPort.Parity = Parity.None; serialPort.StopBits = StopBits.One; serialPort.DataBits = 8; serialPort.BaudRate = 38400; } /// /// 是否已经连接上设备 /// public bool IsConnected { get; set; } public bool Open() { try { if (serialPort != null && serialPort.IsOpen) { serialPort.Close(); } IsConnected = true; serialPort.Open(); MessageQueue.Instance.Insert("测高仪链接成功"); return true; } catch (Exception ex) { MessageQueue.Instance.Warn("测高仪链接失败"); IsConnected = false; return false; } } public double Read() { bool readOk = false; if (IsConnected) { serialPort.Write("%01#RMD**\r"); Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); while (!readOk && stopwatch.ElapsedMilliseconds<3000) { int datalen = serialPort.BytesToRead; if (datalen>0) { byte[] buffer=new byte[datalen]; serialPort.Read(buffer, 0, datalen); foreach (byte b in buffer) { if(b!=13) { bufferList.Add(b); } else { bufferList.Add((byte)b); readOk = true; return ParseValue(); } } } } } return AlarmConstID.NG; } double ParseValue() { string val = Encoding.ASCII.GetString(bufferList.ToArray()); bufferList.Clear(); Regex reg = new Regex("[+-][^*]*"); if(reg.IsMatch(val)) { string v1 = reg.Match(val).Value; double v2 = double.Parse(v1)/10000; return v2; } return AlarmConstID.NG; } } }