TheMachine.cs 18.0 KB
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 using System;
using System.Collections.Generic;
using System.Threading;
using System.Windows.Forms;
using log4net;
using System.Reflection;
namespace MachineDll
{
    public class TheMachine
    {
        enum MachineType { 
        IO,PLC
        }
        //接受到的数据
        private int _ReadCount;
       
        private MachineControllor _ItsControllor;
        //private Thread readThread;
        public SerialPortSetting _ItsSerialPort;
        private readonly List<IReceiveData> itsClietns = new List<IReceiveData>();
        public static readonly ILog LOGGER = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        MachineType machineType= MachineType.IO;
        public bool IsDebug = false;
        //防止该类被外部引用实例化
        //唯一访问的入口点是单一实例,以防不测
        public TheMachine() { 
        }
        public TheMachine(string port,string type = "IO")
        {
            if (("PLC").Equals(type))
            {
                machineType = MachineType.PLC;
            }
            LOGGER.Info($"port={port},machineType={machineType}");
            SerialPortSetting.PortName = port;
        }

        public SerialPortSetting ItsSerialPort
        {
            get
            {
                return _ItsSerialPort;
            }
        }
        public List<IReceiveData> ItsClietns
        {
            get
            {
                return itsClietns;
            }
        }
        public void AddClients(IReceiveData client)
        {
            itsClietns.Add(client);
        }

        public void RemoveClients(IReceiveData waitRemovedClient)
        {
            //LOGGER.Debug("11");
            itsClietns.Remove(waitRemovedClient);
        }

        public string TestConnection()
        {
            _ItsSerialPort = new SerialPortSetting();
            string portName = _ItsSerialPort.TestConnection();
            return portName;
        }

        public bool StartConnection()
        {
            if (IsDebug)
            {
                _ItsControllor = new MachineControllor(_ItsSerialPort, IsDebug);
                return true;
            }

            bool isConnection = false;
            _ItsControllor = new MachineControllor(_ItsSerialPort);
            if (_ItsSerialPort == null)
            {
                //LOGGER.Debug("_ItsSerialPort is null");
                try
                {
                    _ItsSerialPort = new SerialPortSetting();
                    _ItsControllor = new MachineControllor(_ItsSerialPort);
                    isConnection = _ItsSerialPort.StartConnection();
                    
                }
                catch (Exception ex)
                {
                    LOGGER.Error(ex.ToString());
                }
                //LOGGER.Debug("new one _ItsSerialPort object");
            }
            else
            {
                if (!_ItsSerialPort.PortIsOpen())
                {
                    isConnection = _ItsSerialPort.StartConnection();
                }
                else
                {
                    isConnection = true;
                }
            }
            return isConnection;
        }

        public void CloseConnection()
        {
            if (_ItsSerialPort != null)
            {
                _ItsSerialPort.CloseConnection();
            }
        }

        private System.Timers.Timer readTimer = new System.Timers.Timer();

        public bool StartReading()
        {

            if (_ItsSerialPort == null && !IsDebug)
            {
                MessageBox.Show("串口未连接,请先连接串口");
            }
            LOGGER.Debug("Start Reading From PLC");
            readTimer.Stop();
            readTimer = new System.Timers.Timer();
            readTimer.Interval = 1000;
            readTimer.AutoReset = true;
            readTimer.Elapsed += StartReadFromBuffer;
            readTimer.Start();
            return true;
        }

        /// <summary>
        /// 不要随意终止该读取的线程,当有2个以上客户端时,如果仅仅是本线程不需要读取,调用RemoveClients方法将自己移除
        /// </summary>
        public void StopReading()
        {
            readTimer.Stop();
            LOGGER.Info("StopReading");
            if (_ItsSerialPort != null && _ItsSerialPort.PortIsOpen())
            {
                _ItsSerialPort.ReadExisting();
            }
            //LOGGER.Debug("9");
        }

        public MachineControllor GetControllor
        {
            get
            {
                if (_ItsControllor == null)
                {
                    MessageBox.Show("请确认端口已经连接,否则无法对清洗机操作!");
                }
                return _ItsControllor;
            }
        }
        private Byte[] reciveValue;
        private void StartReadFromBuffer(object sender, EventArgs e)
        {
            try
            {
                if (_ItsSerialPort != null && _ItsSerialPort.PortIsOpen())
                {
                        Byte[] byte1 = new Byte[1];
                        byte1[0] = 0x80;
                        _ItsSerialPort.SendByteNew(byte1);//BuffType.ADDRESS.ToString());
                        System.Threading.Thread.Sleep(200);

                        Byte[] flag = _ItsSerialPort.ReadByte();
                        if (flag.Length == 0)
                        {
                            return;
                        }
                        if ((int)flag[0] == 6)//握手成功
                        {
                            byte1 = new Byte[1];
                            byte1[0] = 0x0;
                            _ItsSerialPort.SendByteNew(byte1);//BuffType.COMMAND1.ToString());
                            System.Threading.Thread.Sleep(200);

                            reciveValue = _ItsSerialPort.ReadByte();
                            RealDataRead();
                        }
                }
            }
            catch (Exception ex)
            {

            }
            
        }

        private void RealDataRead()
        {
            //_FirstBuff = _ItsSerialPort.ReadByte();
            //_SecondBuff = _ItsSerialPort.ReadByte();
            _ReadCount++;
            TellClients();
        }

        private void TellClients()
        {
            foreach (IReceiveData data in itsClietns)
            {
                if (reciveValue.Length > 0)
                {
                    data.NewReceiveData(_ReadCount, reciveValue);
                }
            }
        }

        public bool StartReadingIO()
        {
            if (_ItsSerialPort == null && !IsDebug)
            {
                MessageBox.Show("串口未连接,请先连接串口");
            }
            LOGGER.Debug("Start Reading From IO");
            //再开之前先关闭一下
            readTimer.Stop();
            System.Threading.Thread.Sleep(500);

            //这个可能是每秒读一次的地方,可能是
            readTimer = new System.Timers.Timer();
            readTimer.Interval = 1000;
            readTimer.AutoReset = true;
            readTimer.Elapsed += StartReadIOFromBuffer;
            readTimer.Start();
            return true;
        }
        private void StartReadIOFromBuffer(object sender, EventArgs e)
        {
            if (IsDebug || _ItsSerialPort != null && _ItsSerialPort.PortIsOpen())
            {
                double receiveIOValue = this.GetControllor.SendAIString();
                IOTellClients(receiveIOValue);
            }
        }
        private void IOTellClients(double receiveIOValue)
        {
            foreach (IReceiveData data in itsClietns)
            {
                if (receiveIOValue >= 0)
                {
                    data.NewReceiveIOData(receiveIOValue);
                }
            }
        }
        /// <summary>
        /// 打开过滤
        /// </summary>
        public void OpenFilter() {
            if (machineType == MachineType.PLC)
            {
                _ItsControllor.CloseY0();
                System.Threading.Thread.Sleep(1000);
                _ItsControllor.OpenY1();
                System.Threading.Thread.Sleep(500);
                _ItsControllor.OpenY1();
                System.Threading.Thread.Sleep(1000);
                _ItsControllor.OpenY2();
                System.Threading.Thread.Sleep(500);
                _ItsControllor.OpenY2();
                System.Threading.Thread.Sleep(1000);
            }
            else
                _ItsControllor.OpenY1Y2();
        }
        /// <summary>
        /// 打开清洗
        /// </summary>
        public void OpenWash() {
            if (machineType == MachineType.PLC)
            {
                _ItsControllor.OpenY0();
                System.Threading.Thread.Sleep(500);
                _ItsControllor.OpenY0();
                System.Threading.Thread.Sleep(1000);
                _ItsControllor.OpenY2();
                System.Threading.Thread.Sleep(500);
                _ItsControllor.OpenY2();
                System.Threading.Thread.Sleep(1000);
            }
            else
                _ItsControllor.OpenY0Y2();
        }
        /// <summary>
        /// 关闭
        /// </summary>
        public void Close() {
            if (machineType == MachineType.PLC)
            {
                _ItsControllor.CloseY2();
                System.Threading.Thread.Sleep(1000);
                _ItsControllor.CloseY1();
            }
            else
                _ItsControllor.CloseAll();
        }

        public double GetData()
        {
            if (machineType == MachineType.PLC)
            {
                double returnValue = -1;
                byte[] byte1 = new byte[1];
                byte1[0] = 0x80;
                _ItsSerialPort.SendByteNew(byte1);//BuffType.ADDRESS.ToString());
                System.Threading.Thread.Sleep(200);
                byte[] flag = _ItsSerialPort.ReadByte();
                if (flag.Length == 0)
                {
                    return returnValue;
                }
                if ((int)flag[0] == 6)//握手成功
                {
                    byte1 = new byte[1];
                    byte1[0] = 0x0;
                    _ItsSerialPort.SendByteNew(byte1);//BuffType.COMMAND1.ToString());
                    System.Threading.Thread.Sleep(200);

                    var reciveValue = _ItsSerialPort.ReadByte();
                    string temp = "";

                    for (int i = 1; i < reciveValue.Length; i++)//0~5
                    {
                        if (Convert.ToChar(reciveValue[i]).ToString() == "+")
                        {
                            break;
                        }
                        temp = temp + Convert.ToChar(reciveValue[i]);
                    }
                    
                    double.TryParse(temp, out returnValue);
                }

                return returnValue;
            }
            else
            {
               return _ItsControllor.SendAIString();
            }
        }
    }

}