TimerBl.cs 8.57 KB
using OS.Spin.Common;
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace OS.Spin.BusinessLayer.SubBusiness
{

    public class TimerBl
    {
        /// <summary>
        /// 接收巨细数据处理
        /// </summary>
        /// <param name="type"></param>
        /// <param name="meter"></param>
        public delegate void TimerRecived(int type, double meter);

        public TimerRecived DoRecived;


        private bool _isClosed = false;

        private string _ip = "192.168.100.2";

        private int _port = 5002;

        private int _localPort = 5001;

        private string _localIp = "192.168.100.1";

        private Socket _client;

        private EndPoint _desPoint;
        private Thread _reciveThread;
        public TimerBl()
        {


        }

        private bool _connect = false;

        private Thread _threadBeat;
        public void OnStart()
        {
            try
            {
                _client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                _client.Bind(new IPEndPoint(IPAddress.Parse(_localIp), _localPort));
                _desPoint = new IPEndPoint(IPAddress.Parse(_ip), _port);

                if (null == _reciveThread)
                {
                    _reciveThread = new Thread(ReciveMsg);
                    _reciveThread.Start();
                }

                _connect = true;

                if (null == _threadBeat)
                {
                    _threadBeat = new Thread(DoBeat);
                    _threadBeat.Start();
                }
            }
            catch (Exception ex)
            {
                LogisTrac.WriteInfoLog(String.Format("[OnStart 失败] =====[{0}]======", ex.Message));
                _connect = false;
            }
        }

        private void DoBeat()
        {
            while (true)
            {
                Thread.Sleep(500);
                if (_connect)
                {
                    continue;
                }

                OnStart();
            }
        }

        public void Stop()
        {
            try
            {
                if (!_connect)
                {
                    return;
                }

                byte[] bits = new byte[7];
                int send_cnt = 0;
                bits[send_cnt++] = 0xFF;
                bits[send_cnt++] = 0xFD;
                bits[send_cnt++] = (byte)7;
                bits[send_cnt++] = 0x11;
                bits[send_cnt++] = 0x01;
                bits[send_cnt++] = 0x01;
                bits[send_cnt++] = 0xAA;

                _client.SendTo(bits, _desPoint);
            }
            catch (Exception ex)
            {
                LogisTrac.WriteLog(string.Format("Stop:{0}", ex.Message));
            }
        }

        public void Start()
        {
            try
            {
                if (!_connect)
                {
                    return;
                }

                byte[] bits = new byte[7];
                int send_cnt = 0;

                bits[send_cnt++] = 0xFF;
                bits[send_cnt++] = 0xFD;
                bits[send_cnt++] = (byte)0;
                bits[send_cnt++] = 0x22;
                bits[send_cnt++] = 0x01;
                bits[send_cnt++] = 0x01;
                bits[send_cnt++] = 0xAA;

                _client.SendTo(bits, _desPoint);
            }
            catch (Exception ex)
            {
                LogisTrac.WriteLog(string.Format("Start:{0}", ex.Message));
            }
        }

        public void Zero()
        {
            try
            {
                if (!_connect)
                {
                    return;
                }

                byte[] bits = new byte[7];
                int send_cnt = 0;

                bits[send_cnt++] = 0xFF;
                bits[send_cnt++] = 0xFD;
                bits[send_cnt++] = (byte)7;
                bits[send_cnt++] = 0x33;
                bits[send_cnt++] = 0x01;
                bits[send_cnt++] = 0x01;
                bits[send_cnt++] = 0xAA;

                _client.SendTo(bits, _desPoint);
            }
            catch (Exception ex)
            {
                LogisTrac.WriteLog(string.Format("Zero:{0}", ex.Message));
            }
        }

        /// <summary>
        /// 接收发送给本机ip对应端口号的数据报
        /// </summary>
        private void ReciveMsg()
        {

            EndPoint point = new IPEndPoint(IPAddress.Any, 0);  //用来保存发送方的ip和端口号
            while (true)
            {
                //EndPoint point = new IPEndPoint(IPAddress.Any, 0);//用来保存发送方的ip和端口号
                try
                {
                    LogisTrac.WriteInfoLog(String.Format("[接收数据] 开始 =============="));
                    byte[] bits = new byte[100];
                    int length = _client.ReceiveFrom(bits, ref point);//接收数据报
                    LogisTrac.WriteInfoLog(String.Format("[接收] =====[{0}]======", length));

                    for (var i = 0; i < length; i++)
                    {
                        LogisTrac.WriteInfoLog(String.Format("[{0}]: {1} ", i, bits[i].ToString("x2")));
                    }

                    if (0 == length)
                    {
                        if (null != _client)
                        {
                            _client.Close();
                            _client.Dispose();
                        }
                        _client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                        _client.Bind(new IPEndPoint(IPAddress.Parse(_localIp), _localPort));
                        continue;
                    }
                    if (null == bits || length <= 8 || !(bits[0] == 0xFF && bits[1] == 0xFE && bits[length - 1] == 0xAA))
                    {
                        continue;
                    }

                    // 切换花纹
                    if (bits[3] == 0x33)
                    {
                        //  切换花纹
                        //OS.Spin.Running.Cache.GetInstance().FigureId = bits[4];
                        continue;
                    }

                    // 过滤非法数据
                    if (!(bits[3] == 0x11) && !(bits[3] == 0x99))
                    {
                        continue;
                    }

                    // 计算当前米数
                    double current_meter = bits[4] * 256 + bits[5] + bits[6] / 100.0;

                    if (bits[3] == 0x99)
                    {
                        // 修改当前米数
                        OS.Spin.Running.Cache.GetInstance().Speed = 0;
                        DoRecived?.Invoke(0, current_meter);
                        continue;
                    }

                    // 修改当前米数
                    OS.Spin.Running.Cache.GetInstance().Speed = (bits[7] * 256 + bits[8]) / 100.0;

                    //if (current_meter <= 2)
                    //{
                    //    //  清空上次数据
                    //    //DoRecived?.Invoke(0, current_meter);
                    //    continue;
                    //}

                    // 软触发相机
                    DoRecived?.Invoke(1, current_meter);
                }
                catch (Exception ex)
                {
                    LogisTrac.WriteLog(ex);
                    if (_isClosed)
                    {
                        return;
                    }
                    if (null != _client)
                    {
                        _client.Close();
                        _client.Dispose();
                    }
                    _client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                    _client.Bind(new IPEndPoint(IPAddress.Parse(_localIp), _localPort));
                    continue;
                }
            }
        }

        public void Dispose()
        {
            try
            {
                _isClosed = true;
                if (null != _reciveThread && _reciveThread.IsAlive)
                {
                    _reciveThread.Abort();
                }
                if (null != _client)
                {
                    _client.Close();
                    _client.Dispose();
                }

                if (null != _threadBeat && _threadBeat.IsAlive)
                {
                    _threadBeat.Abort();
                }
            }
            catch (Exception ex)
            {
                LogisTrac.WriteLog(string.Format("Dispose:{0}", ex.Message));
            }
        }
    }
}