TheMachine.cs 14.8 KB
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 using System;
using System.Collections.Generic;
using System.Threading;
using System.Windows.Forms;
using log4net;
using System.Reflection;
namespace MachineDll
{
    public class TheMachine
    {
        //接受到的数据
        private int _FirstBuff;
        private int _SecondBuff;
        private BuffType _ItsBuffType;
        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);
        //防止该类被外部引用实例化
        //唯一访问的入口点是单一实例,以防不测
        internal TheMachine()
        {
        }

        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()
        {
            bool isConnection = false;
            if (_ItsSerialPort == null)
            {
                //LOGGER.Debug("_ItsSerialPort is null");
                try
                {
                    _ItsSerialPort = new SerialPortSetting();
                    isConnection = _ItsSerialPort.StartConnection();
                    _ItsControllor = new MachineControllor(_ItsSerialPort);
                }
                catch (Exception ex)
                {
                    //LOGGER.Warn(ex.StackTrace);
                }
                //LOGGER.Debug("new one _ItsSerialPort object");
            }
            else
            {
                if (!_ItsSerialPort.PortIsOpen())
                {
                    isConnection = _ItsSerialPort.StartConnection();
                }
                else
                {
                    isConnection = true;
                }
            }
            return isConnection;
        }

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

        public bool StartReading()
        {
            if (_ItsSerialPort == null)
            {
                MessageBox.Show("串口未连接,请先连接串口");
            }
            if (readThread == null || !readThread.IsAlive)
            {
                readThread = new Thread(StartReadFromBuffer);
                readThread.IsBackground = true;
                readThread.Start();
                return true;
            }
            return false;
        }

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

            //LOGGER.Debug("9");
        }

        public MachineControllor GetControllor
        {
            get
            {
                if (_ItsControllor == null)
                {
                    MessageBox.Show("请确认端口已经连接,否则无法对清洗机操作!");
                }
                return _ItsControllor;
            }
        }
        private Byte[] reciveValue;
        private void StartReadFromBuffer()
        {
            if (_ItsSerialPort != null && _ItsSerialPort.PortIsOpen())
            {
                while (true)
                {
                    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();
                    }

                    Thread.Sleep(600);
                }
            }
        }

        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()
        {
            //LOGGER.Debug("3");
            if (_ItsSerialPort == null)
            {
                //LOGGER.Debug("4.1");
                MessageBox.Show("串口未连接,请先连接串口");
            }
            if (readThread == null || !readThread.IsAlive)
            {
                //LOGGER.Debug("into start read io,  new one thread,time is "+DateTime.Now);
                //LOGGER.Debug("4.2");
                readThread = new Thread(StartReadIOFromBuffer);
                readThread.IsBackground = true;
                readThread.Start();
                return true;
            }
            //LOGGER.Debug("5");
            return false;
        }
        System.Timers.Timer timer;
        private void StartReadIOFromBuffer()
        {
            if (_ItsSerialPort != null && _ItsSerialPort.PortIsOpen())
            {
                //LOGGER.Debug("new a timer to read io data,time is "+DateTime.Now +"  current thread ID is "+Thread.CurrentThread.ManagedThreadId);
                timer = new System.Timers.Timer();
                timer.Interval = 1000;
                timer.AutoReset = true;
                timer.Elapsed+=new System.Timers.ElapsedEventHandler(timer_Elapsed);
                timer.Start();
            }
        }
        private void timer_Elapsed(object sender, EventArgs e)
        {
            double receiveIOValue = this.GetControllor.SendAIString();
            IOTellClients(receiveIOValue);
        }
        private void IOTellClients(double receiveIOValue)
        {
            foreach (IReceiveData data in itsClietns)
            {
                if (receiveIOValue >= 0)
                {
                    data.NewReceiveIOData(receiveIOValue);
                }
            }
        }
    }
}