using System;
using CRVM.Driver;
using CRVM.Entity;
using System.Threading;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using ICService;
using System.Collections.Generic;
using CRVM.Utility;
using Apache.NMS;
using Apache.NMS.ActiveMQ;
using RestApi;
using Memcached.ClientLibrary;
using System.Timers;
using Newtonsoft.Json;

namespace CRVM.SIDExcuter
{

    public class NormalDistributionGenerator
    {
        private Random random;
        private double[] data = new double[1024];
        private double[] start_1 = new double[5] { 0, 0, 0, 0, 0 };
        //double[] time_list = GenerateArithmeticSequence(0, 0.000195,1024);
        int index = 0;

        private DateTime startTime = DateTime.Now;
        const int timeLenth = 5;//测试 5分钟一卷
        private bool cutFlag = false;
        private bool alarFlag = false;
        public bool faultFlag = false;
        private DateTime alarmStartTime = DateTime.Now;
        private DateTime faultStartTime = DateTime.Now;
        public int alarmTimes = 0;
        public int faultTimes = 0;

        public NormalDistributionGenerator()
        {
            random = new Random();
        }


        // 生成正态分布的随机数
        public double NextGaussian(double mean, double standardDeviation)
        {
            double u1 = 1.0 - random.NextDouble(); // 避免u1 = 0
            double u2 = 1.0 - random.NextDouble(); // 避免u2 = 0
            double z = Math.Sqrt(-2.0 * Math.Log(u1)) * Math.Sin(2.0 * Math.PI * u2);
            return z * standardDeviation + mean;
        }
        public double[] SinSingnal(double A, double f)
        {
            double start_time = start_1[index];
            for (int i = 0; i < 1024; i++)
            {
                data[i] = A * Math.Cos(2 * Math.PI * f * (start_time + i * 0.000195) + 0.00002) + NextGaussian(0.00001, 0.01);
            }
            start_1[index] = start_time + 0.2;
            index++;
            index = index % 5;

            return data;
        }
        public bool cutedFlag()
        {
            if ((DateTime.Now - startTime).TotalMinutes > timeLenth)
            {

                startTime = DateTime.Now;

                cutFlag = true;
            }
            else
            {
                cutFlag = false;
            }

            return cutFlag;

        }

        public bool alarmFlag()
        {
            if ((DateTime.Now - alarmStartTime).TotalMinutes > timeLenth / 5)
            {
                if (alarmTimes > 30)
                {
                    alarmStartTime = DateTime.Now;
                    alarmTimes = 0;
                }
                alarmTimes++;
                alarFlag = true;
            }
            else
            {
                alarFlag = false;
            }
            if ((DateTime.Now - faultStartTime).TotalMinutes > timeLenth / 2)
            {
                if (faultTimes > 30)
                {
                    faultStartTime = DateTime.Now;
                    faultTimes = 0;
                }
                faultTimes++;
                faultFlag = true;
            }
            else
            {
                faultFlag = false;
            }

            return alarFlag;
        }

        //public static List<T> GenerateArithmeticSequence<T>(T start, T difference, int length) where T : struct, IComparable, IFormattable, IConvertible, IComparable<T>, IEquatable<T>
        //{
        //    List<T> sequence = new List<T>();

        //    dynamic current = start; // 使用 dynamic 支持泛型计算
        //    dynamic diff = difference;

        //    for (int i = 0; i < length; i++)
        //    {
        //        sequence.Add(current);
        //        current += diff; // 动态计算下一个值
        //    }

        //    return sequence;
        //}
    }
    public class OrginalCollectDataEventArgs : EventArgs { }

    public delegate void ComeNewDataHandle(OrginalCollectDataEventArgs e);
    public class DataProcessCenter
    {
        public static string BORKER_URL = "tcp://10.171.7.115:61616/";
        public static string TOPIC_NAME = "VIB_DATA";

        //仿真---测试
        NormalDistributionGenerator ndb = new NormalDistributionGenerator();
        double[] Fmean = new double[8] { 0.01, 0.02, 0.01, 0.07, 0.001, 0.001, 0, 0 };
        double[] Fspeed = new double[8] { 190, 349, 538, 820, 1270, 1370, 0, 0 };
        DateTime LastExecTime;//测试

        public event ComeNewDataHandle DataChanged;
        private Machine mac;
        private IDataHelper dataHelper;
        private DaqDriver daqDriver;
        private bool startFlag = false;
        private ZDSate zdState;
        private bool[] zdStateData;//报警状态发送
        private bool cutStateLast = false;
        private double disSignalLast = 0.0;
        private double disSignalFirst = 0.0;
        private int disPeriods = 0;
        private int disflag = 0;
        private int disCount = 0;
        private double dislen_start = 4.0;
        private bool isFirstPeriods = false;
        private bool isFirstDisLen = false;

        private double stripLenLast = 0.0;

        private int calCount = 0;
        private int calFlag = 0;

        private bool isAlarmingNow;
        private bool isAlarmingLast;
        private bool lowRing, midRing, highRing;
        private bool isDefect;
        private bool[,] ringflag = new bool[SysParam.Instance.SpeedChannelCount, 3];//报警范围内使用，记录报警范围内哪个机架哪个频段发生报警
        private bool[,] defectflag = new bool[SysParam.Instance.SpeedChannelCount, 3];//报警范围内使用，记录报警范围内哪个机架哪个频段发生报警
        private double[] alarm_MaxEnergy = new double[SysParam.Instance.SpeedChannelCount];//报警范围内使用，记录五个机架报警范围内产生的最大能量值
        private int[] alarm_Position = new int[SysParam.Instance.SpeedChannelCount];

        private AlarmRing alarmRing;
        public List<string> alarmInfoNow = new List<string>();
        public string[] alarmInfoLast;
        private System.Timers.Timer alarmParamUpdate = new System.Timers.Timer();

       // private double[] lineSpdFactor = { 87.5, 87.5, 87.5, 87.5, 87.5, 87.5 };//max=1400, 1400/16=87.5
        //private double[] lineSpdFactor = { 175, 175, 175, 175, 175, 175 };//max=1400, 1400/8=175
        private double[] lineSpdFactor = { 24.36, 34.87,48.43, 61.26,74.385,89.968 };//max=1400,max/16,[389.77,557.94,774.92,980.22,1190.16,1439.49]
        private double[] lineSpdBias = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };//
        private double lenFactor = 0.0d;
        //private double[] lineSpdFactor = { 93.75, 93.75, 93.75, 93.75, 93.75 };
        //private double lenFactor = 0.0d;
        double firstPeriodsLen = 0d;

        double startLenSignal = 4.0;

        int waitMaxNum = 0;
        int waitNum = 0;
        int cutCounter = 0;
        bool cutFlag = false;
        DateTime lastCutTime;
        DateTime thisCutTime;


        /*private IConnectionFactory factory = null;
        private IConnection connection = null;
        private ISession session = null;
        private IMessageProducer prod = null;
        private bool mqOK = false;*/

        SockIOPool pool = null;
        MemcachedClient mc = null;


        double coilenMax = 0.0d;
        int nextCoilCounter = 0;

        // 页面 刷新的数据 ---2025-01-09 新增
        public BoxData[] roll_mill_data_array { set; get; }

        public RollMillData rollMillData { set; get; }
        public StandRMVibData standRmVibData { set; get; }
        public AlarmInfo alarmInfo { set; get; }
        //public CZState cZState { set; get; }
        private bool[,] standAlarmStateP=new bool[6,3];//[(1~6机架)，(中，低，高)]
        public RollMillEnergyTrend rollMillET { set; get; }
        public DataProcessCenter(Machine mac)
        {
            LastExecTime = DateTime.Now;
            this.mac = mac;
            dataHelper = new IDataHelper(mac);
            alarmRing = new AlarmRing();
            daqDriver = new DaqDriver();
            daqDriver.DaqDataChangEvent += new DaqDriver.DriverCollectDataHandle(DaqDataChangHandler);
            zdState = new ZDSate();
            zdStateData = new bool[zdState.linesCount];//向L1发送报警状态
            mac.startTime = DateTime.Now;
            //lenFactor = (6000.0 / 16.0);
            lenFactor = (200.0 / 8);//12~20mA 200m 锯齿波
            waitMaxNum = 90 * SysParam.Instance.sampleFre / SysParam.Instance.samplePoint;//L1剪切时三秒内的信号不稳定，过滤掉

            startFlag = true;

            /*try
            {
                //Create the Connection Factory   
                factory = new ConnectionFactory(BORKER_URL);
                connection = factory.CreateConnection();

                //Create the Session   
                session = connection.CreateSession();
                //Create the Producer for the topic/queue   
                prod = session.CreateProducer(new Apache.NMS.ActiveMQ.Commands.ActiveMQTopic(TOPIC_NAME));

                mqOK = true;
            }
            catch (Exception e)
            {
                DevelopLog.DeBug.WriteLogFile("ActiveMQ", e.ToString());
            }*/

            lastCutTime = DateTime.Now;
            thisCutTime = DateTime.Now;

            //try
            //{
            //    //分布Memcachedf服务IP 端口
            //    string[] servers = { "10.171.7.100:11211" };

            //    //初始化池
            //    pool = SockIOPool.GetInstance();
            //    pool.SetServers(servers);
            //    pool.InitConnections = 3;
            //    pool.MinConnections = 3;
            //    pool.MaxConnections = 5;
            //    pool.SocketConnectTimeout = 1000;
            //    pool.SocketTimeout = 3000;
            //    pool.MaintenanceSleep = 30;
            //    pool.Failover = true;
            //    pool.Nagle = false;
            //    pool.Initialize();
            //    //客户端实例
            //    mc = new Memcached.ClientLibrary.MemcachedClient();
            //    mc.EnableCompression = false;
            //}
            //catch (Exception e)
            //{
            //    DevelopLog.DeBug.WriteLogFile("Memcached", e.ToString());
            //}

            coilenMax = 0.0d;

            // 页面 刷新的数据 ---2025-01-09 新增
            roll_mill_data_array = new BoxData[6];
            alarmInfo = new AlarmInfo();
            RollMillGetService dh = new RollMillGetService();
            rollMillET = new RollMillEnergyTrend();
            for (int i = 0; i < 6; i++)
            {
                this.roll_mill_data_array[i] = dh.Roll_mill_data.F1.copy();
            }
            alarmInfo = new AlarmInfo();
       
            /* ---------------------定时从数据库更新报警参数任务--------------------*/
            alarmParamUpdate.Interval = 5 * 60 * 1000; //执行间隔时间,单位为毫秒; 
            alarmParamUpdate.Elapsed += new System.Timers.ElapsedEventHandler(AlarmParamUpdate);
            alarmParamUpdate.Enabled = true;
            alarmParamUpdate.Start();


        }

        int testCount = 0;


        private void AlarmParamUpdate(object source, ElapsedEventArgs e)
        {
            DbHelper.GetInstance("").autoUpdateAlarmParam();
        }
        //数据采集完成触发事件
        private void DaqDataChangHandler(Daqdata data)
        {
            DateTime t1 = DateTime.Now;
            /////////////////////////////////////数据采集预处理开始////////////////////////////////////////////
            //每个机架的振动信号
            double cutData = 0d;
            double lenData = 0d;
            //每个机架的振动信号 采集卡1（1，2，3机架），采集卡2（4，5，6机架）
            for (int i = 0; i < SysParam.Instance.samplePoint; i++)
            {

                mac.Stand[0].vib[i] = data.vibData1[0, i];
                mac.Stand[1].vib[i] = data.vibData1[1, i];
                mac.Stand[2].vib[i] = data.vibData1[2, i];
                mac.Stand[3].vib[i] = data.vibData2[0, i];
                mac.Stand[4].vib[i] = data.vibData2[1, i];
                mac.Stand[5].vib[i] = data.vibData2[2, i];
                mac.Stand[6].vib[i] = data.vibData1[3, i];
                mac.Stand[7].vib[i] = data.vibData2[3, i];

            }

            //模拟测试
            //for (int k = 0; k < 5; k++)
            //{
            //    var datak = ndb.SinSingnal(Fmean[k] * 0.7, 124);
            //    if (ndb.alarmFlag())
            //    {
            //        datak = ndb.SinSingnal(Fmean[k] * 1.1, 124);
            //    }
            //    if (ndb.faultFlag)
            //    {
            //        datak = ndb.SinSingnal(Fmean[k] * (3 + ndb.faultTimes % 3), 124);
            //    }

            //    for (int i = 0; i < SysParam.Instance.samplePoint; i++)
            //    {
            //        mac.Stand[k].vib[i] = datak[i];
            //        if (k == 4)
            //        {
            //            mac.Stand[k + 1].vib[i] = datak[i];

            //        }

            //    }

            //}
            //Utility.VibSimulation.UpdateOnlineData();
            //for (int i = 0; i < SysParam.Instance.samplePoint; i++)
            //{
               // mac.Stand[0].vib[i] = Utility.VibSimulation._onlineData.vibData[0, i];
                //mac.Stand[1].vib[i] = Utility.VibSimulation._onlineData.vibData[1, i];
               // mac.Stand[2].vib[i] = Utility.VibSimulation._onlineData.vibData[2, i];
                //mac.Stand[3].vib[i] = Utility.VibSimulation._onlineData.vibData[3, i];
                //mac.Stand[4].vib[i] = Utility.VibSimulation._onlineData.vibData[4, i];
                //mac.Stand[5].vib[i] = Utility.VibSimulation._onlineData.vibData[5, i];
           // }


            //每个机架的线速度 1 2 3 4 5 6
            for (int i = 0; i < SysParam.Instance.SpeedChannelCount; i++)
            {
                double tempSum = 0d;
                double tempAve = 0d;
                for (int j = 0; j < SysParam.Instance.samplePoint; j++)
                {
                    tempSum += data.speedData[i, j];//0 1 2 3 4 5 华美
                }
                tempAve = tempSum / SysParam.Instance.samplePoint;
                mac.Stand[i].speed = (tempAve * 1000 - 4.0) * lineSpdFactor[i] + lineSpdBias[i];//A->mA*速度转换系数 12 -20mA  速度0~1950mpm
               // Console.WriteLine("std:" + i + 1 + ",speed :" + tempAve * 1000 + "mA" + ",speed:" + mac.Stand[i].speed+" mpm");
                //mac.Stand[i].speed = ndb.NextGaussian(Fspeed[i], 1);//模拟测试
               // mac.Stand[i].speed = Utility.VibSimulation._onlineData.speed[i];//模拟测试
            }

            //if (mac.Stand[3].speed > mac.Stand[4].speed)//出现4机架速度比5机架速度大时，手动调节
            //{
            //    mac.Stand[3].speed = mac.Stand[4].speed - 0.1;
            //}

           
            for (int i = 0; i < SysParam.Instance.samplePoint; i++)
            {
                //轧制距离信号求平均 7
               lenData += data.speedData[6, i];
               //剪刀信号求平均  8
               cutData += data.speedData[7, i];
            }
            lenData = lenData / SysParam.Instance.samplePoint;
            cutData = cutData / SysParam.Instance.samplePoint;
           // Console.WriteLine("轧制距离:" + lenData * 1000 + "mA");
            //Console.WriteLine("剪切信号:" + cutData * 1000 + "mA");
            //DevelopLog.DeBug.WriteLogFile("lenData", lenData.ToString());
            //出口速度
            mac.lengthSpeed = mac.Stand[5].speed;

            //剪刀信号求平均  8
           // for (int i = 0; i < SysParam.Instance.samplePoint; i++)
           // {
              // cutData += data.speedData[7, i];
            //}
          // cutData = cutData / SysParam.Instance.samplePoint;

            //剪切信号
            if (waitNum > 0)
            {
                if (waitNum < waitMaxNum)
                {
                    waitNum++;
                    cutData = 0.004;
                    //lenData = 0.004;
                }
                else
                {
                    waitNum = 0;
                }
            }

            if (cutData * 1000 > 12)//电流值大于12mA时，收到剪切信号 L1剪切信号20mA会保持3秒，只取一次剪切信号
            {
                if (cutStateLast == false)
                {
                    mac.cutted = true;
                    cutStateLast = true;
                    waitNum++;
                }
                else
                {
                    mac.cutted = false;
                }
            }
            else
            {
                mac.cutted = false;
                cutStateLast = false;
            }


            //剪切信号
            //if (data.cutData[1] > 0.4)//检查上升沿,出现就是剪切信号
            //{
            //    if (cutStateLast == false)
            //    {
            //        mac.cutted = true;
            //        cutStateLast = true;
            //        //waitNum++;
            //        DevelopLog.DeBug.WriteLogFile("mac.cutted", String.Format("mac.cutted:{0}， 收到剪切信号", mac.cutted));
            //    }
            //    else
            //    {
            //        mac.cutted = false;
            //    }
            //    disPeriods = 0;//剪切信号期间，锯齿波次数归零
            //}

            //else
            //{
            //    mac.cutted = false;
            //    cutStateLast = false;
            //}
  

            //轧制距离
            double disSignalNow = lenData * 1000;

            //DevelopLog.DeBug.WriteLogFile("disSignalNow", disSignalNow.ToString());
            if (disSignalNow < 12)//12 ~20mA 
            {
                disSignalNow = 12;
            }
            //DevelopLog.DeBug.WriteLogFile("mac.stripLength", mac.stripLength.ToString());
            if (disSignalLast - 3 > disSignalNow && calCount == 0)
            {
                calCount++;
                disPeriods++;

                //DevelopLog.DeBug.WriteLogFile("disPeriods++", disPeriods.ToString());
            }

            if (calCount >= 1)
            {
                calFlag++;
            }

            if (calFlag == 5)
            {
                calCount = 0;
                calFlag = 0;
            }

            //mac.stripLength = disPeriods * 200 + lenFactor * (disSignalNow - 12.0);//(4~20mA/0~200m)
            mac.stripLength = 1750 * (lenData * 1000 - 4.0);//(4~20mA/0~200m)
           // mac.stripLength = Utility.VibSimulation._onlineData.length;//模拟测试
            ////mac.stripLength = 4000;///模拟测试
            ////mac.cutted = false;///模拟测试
            //mac.cutted = ndb.cutedFlag();///模拟测试
            //mac.cutted = Utility.VibSimulation._onlineData.isCuted;
            Console.WriteLine("lenData:" + mac.stripLength + " m");
            Console.WriteLine("cutted:" + mac.cutted.ToString());
            //mac.cutted = false;//测试
            if (mac.stripLength + 1 < stripLenLast)
            {
                mac.stripLength = disPeriods * 200;
            }
            ////DevelopLog.DeBug.WriteLogFile("mac.stripLength", mac.stripLength.ToString());

            disSignalFirst = disSignalLast;

            disSignalLast = disSignalNow;

            stripLenLast = mac.stripLength;

            alarmInfo.outLetStripLenth = mac.stripLength;
            //nextCoilCounter++;
            //采集数字钢卷长度信号
            //if (mc.KeyExists("TCM2280_TR"))
            //{
            //    object trLength = mc.Get("TCM2280_TR", null, true);
            //    if (trLength != null)
            //    {
            //        double trLength_d = 0.0;
            //        if (double.TryParse(trLength.ToString(), out trLength_d))
            //        {
            //            mac.stripLength = trLength_d;
            //            if (coilenMax <= mac.stripLength && nextCoilCounter > 20)
            //            {
            //                coilenMax = mac.stripLength;
            //            }

            //            //DevelopLog.DeBug.WriteLogFile("TCM2280_TR/coilenMax/nextCoilCounter", trLength_d.ToString() + "/" + coilenMax.ToString() + "/" + nextCoilCounter.ToString());
            //        }
            //        else
            //        {
            //            DevelopLog.DeBug.WriteLogFile("TCM2280_TR", "格式不对trLength = [" + trLength.ToString() + "]");
            //        }
            //    }
            //}

            /*if (mac.stripLength + 1 < stripLenLast)
            {
                mac.stripLength = disPeriods * 200;
            }*/

            //disSignalFirst = disSignalLast;

            //disSignalLast = disSignalNow;

            /*if (mac.cutted == false && stripLenLast > mac.stripLength)
            {
                mac.stripLength = stripLenLast;
            }*/

            //stripLenLast = mac.stripLength;
            if (mac.cutted == true)
            {
                disPeriods = 0;
                startFlag = true;
                startLenSignal = disSignalNow;

                stripLenLast = 0.0d;
                //DevelopLog.DeBug.WriteLogFile("CUTTTING", "CUTTING");
                //报警参数重置
                for (int i = 0; i < SysParam.Instance.SpeedChannelCount; i++)
                {
                    mac.Stand[i].alarm_L_Times_ck = SysParam.Instance.channel[i].alarmTimes_l;
                    mac.Stand[i].alarm_M_Times_ck = SysParam.Instance.channel[i].alarmTimes_m;
                    mac.Stand[i].alarm_H_Times_ck = SysParam.Instance.channel[i].alarmTimes_h;
                    mac.Stand[i].SetAlarmFred(SysParam.Instance.channel[i].alarmConfig);
                }
            }

            //屏蔽向L1发送报警状态，一直发送false
            for (int i = 0; i < zdStateData.Length; i++)
            {
                zdStateData[i] = false;
            }
            //zdState.WriteData(zdStateData);
            /////////////////////////////////////数据采集预处理结束////////////////////////////////////////////
            //DevelopLog.DeBug.WriteLogFile("PushDataStart", "");
            PushData();
            //DevelopLog.DeBug.WriteLogFile("PushDataEnd", "");
            DataProcess();
            //DevelopLog.DeBug.WriteLogFile("DataProcessEnd", "");
            startFlag = false;

            standRmVibData.flag = testCount;
            //DateTime nt1= DateTime.Now;
            //rollMillData.nowTime = nt1;
            //standRmVibData.nowTime = nt1;
            long nt1 = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;
            Utility.RedisDB.dBStringSet("nowTime", nt1);
            Utility.RedisDB.dBStringSet("RollMill", JsonConvert.SerializeObject(rollMillData));
            Utility.RedisDB.dBStringSet("rmVibData", JsonConvert.SerializeObject(standRmVibData));
            
            //stripLenLast = mac.stripLength;

            /*if (mqOK)
            {
                PushData2DSC();
            }*/

            //PushData2DSC();

            //测试---数据处理时间
            DateTime t2 = DateTime.Now;
            //Console.WriteLine(String.Format("now:{0},interval time:{1} ms", t2.ToString("yyyy-MM-dd hh:mm:ss.FFF"), (t2 - LastExecTime).TotalMilliseconds.ToString()));
            LastExecTime = t2;
           // Console.WriteLine(String.Format("now:{0},DaqDataChangHandler cost time:{1} ms", t2.ToString("yyyy-MM-dd hh:mm:ss.FFF"), (t2 - t1).TotalMilliseconds.ToString()));
        }

        /*private void PushData2DSC()
        {
            //Send Messages
            ITextMessage msg = prod.CreateTextMessage();

            //组织内容
            //1号机架中频能量值#1号机架中频报警值#2号机架中频能量值#2号机架中频报警值#3号机架中频能量值#3号机架中频报警值#4号机架中频能量值#4号机架中频报警值#5号机架中频能量值#5号机架中频报警值#
            string msgTxt = "";
            for (int i = 0; i < 5; i++)
            {
                msgTxt += string.Format("{0:F6}", mac.Stand[i].energy_M);
                msgTxt += "#";
                msgTxt += string.Format("{0:F6}", mac.Stand[i].alarm_M_Value_ck);
                msgTxt += "#";
            }

            msg.Text = msgTxt;
            prod.Send(msg, Apache.NMS.MsgDeliveryMode.NonPersistent, Apache.NMS.MsgPriority.Normal, TimeSpan.MinValue);

            //DevelopLog.DeBug.WriteLogFile("ActiveMQ", msgTxt);
        }*/

        private void PushData2DSC()
        {
            //组织内容
            //1号机架中频能量值#1号机架中频报警值#2号机架中频能量值#2号机架中频报警值#3号机架中频能量值#3号机架中频报警值#4号机架中频能量值#4号机架中频报警值#5号机架中频能量值#5号机架中频报警值#
            /*string msgTxt = "";
            for (int i = 0; i < 5; i++)
            {
                msgTxt += string.Format("{0:F6}", mac.Stand[i].energy_M);
                msgTxt += "#";
                msgTxt += string.Format("{0:F6}", mac.Stand[i].alarm_M_Value_ck);
                msgTxt += "#";
            }*/

            string msgTxt = "";//报警等级：0：正常 1：接近报警线(共振) 2：严重警告(共振) 3：设备异常
            string status1 = "0";
            string status2 = "0";
            string status3 = "0";
            string status4 = "0";
            string status5 = "0";

            if (SysParam.Instance.alarming1)
            {
                status1 = "3";
            }
            else
            {
                status1 = "0";
            }

            if (SysParam.Instance.alarming2)
            {
                status2 = "3";
            }
            else
            {
                status2 = "0";
            }

            if (SysParam.Instance.alarming5 && SysParam.Instance.alarming4)//(共振)
            {
                status5 = "2";
                status4 = "2";
                if (SysParam.Instance.alarming3)
                {
                    status3 = "2";
                }
                else
                {
                    if (SysParam.Instance.alarmingS3)
                    {
                        status3 = "1";
                    }
                    else
                    {
                        status3 = "0";
                    }
                }
            }
            else
            {
                if (SysParam.Instance.alarming3)
                {
                    status3 = "3";
                }
                else
                {
                    status3 = "0";
                }

                if (SysParam.Instance.alarming4 && (SysParam.Instance.alarming5 == false))
                {
                    if (SysParam.Instance.alarmingS5)
                    {
                        status4 = "1";
                        status5 = "1";
                    }
                    else
                    {
                        status4 = "3";
                        status5 = "0";
                    }
                }
                if (SysParam.Instance.alarming5 && (SysParam.Instance.alarming4 == false))
                {
                    if (SysParam.Instance.alarmingS4)
                    {
                        status4 = "1";
                        status5 = "1";
                    }
                    else
                    {
                        status5 = "3";
                        status4 = "0";
                    }
                }

                if ((SysParam.Instance.alarming4 == false) && (SysParam.Instance.alarming5 == false))
                {
                    if (SysParam.Instance.alarmingS4 && SysParam.Instance.alarmingS5)
                    {
                        status4 = "1";
                        status5 = "1";
                    }
                    else
                    {
                        status4 = "0";
                        status5 = "0";
                    }
                }
            }

            msgTxt = status1 + "#" + status2 + "#" + status3 + "#" + status4 + "#" + status5;
            //DevelopLog.DeBug.WriteLogFile("AlarmDsc", msgTxt);
            mc.Set("VIB_DATA", msgTxt);
        }

        private void PushData()   //给客户端发送数据
        {
            try
            {
                AllData alldata = new AllData();
                double[] sendVibData = new double[SysParam.Instance.channelCount * SysParam.Instance.samplePoint];
                for (int i = 0; i < SysParam.Instance.channelCount; i++)
                {
                    for (int j = 0; j < SysParam.Instance.samplePoint; j++)
                    {
                        sendVibData[i * SysParam.Instance.samplePoint + j] = mac.Stand[i].vib[j];
                    }
                }
                alldata.vibData = sendVibData;
                alldata.standSpeed = new double[SysParam.Instance.SpeedChannelCount];
                for (int i = 0; i < SysParam.Instance.SpeedChannelCount; i++)
                {
                    alldata.standSpeed[i] = mac.Stand[i].speed;
                }
                alldata.lenthSpeed = mac.lengthSpeed;
                alldata.cutState = mac.cutted;
                alldata.stripLength = mac.stripLength;
                PushMessage.SendMsg(alldata);
            }
            catch (Exception ex)
            {
                DevelopLog.DeBug.WriteLogFile("PushData", ex.ToString());
            }

        }

        public void DataProcess()    //数据处理
        {
            isAlarmingNow = false;//初始化报警状态

            lowRing = false;
            midRing = false;
            highRing = false;

            for (int i = 0; i < SysParam.Instance.channelCount; i++)//全部通道
            {
                //消除直流偏置
                DCBias(mac.Stand[i].vib);
                //根据当前速度设定各机架报警系数
                GetAlarmParam(mac.Stand[i].speed, mac.Stand[i]);
                //分频滤波
                mac.Stand[i].vibLow = SysParam.Instance.filterAlgor(mac.Stand[i].vib, mac.Stand[i].band_Fre_L1, mac.Stand[i].band_Fre_L2, SysParam.Instance.samplePoint, 100, SysParam.Instance.sampleFre);
                mac.Stand[i].vibMid = SysParam.Instance.filterAlgor(mac.Stand[i].vib, mac.Stand[i].band_Fre_M1, mac.Stand[i].band_Fre_M2, SysParam.Instance.samplePoint, 100, SysParam.Instance.sampleFre);
                mac.Stand[i].vibHig = SysParam.Instance.filterAlgor(mac.Stand[i].vib, mac.Stand[i].band_Fre_H1, mac.Stand[i].band_Fre_H2, SysParam.Instance.samplePoint, 100, SysParam.Instance.sampleFre);
                //mac.Stand[i].vib2 = SysParam.Instance.filterAlgor(mac.Stand[i].vib, 0, 1000, SysParam.Instance.samplePoint, 100, SysParam.Instance.sampleFre);

                //各通道、各频段能量值计算
                mac.Stand[i].energy_All = GetRMS(mac.Stand[i].vib);
                mac.Stand[i].energy_L = GetRMS(mac.Stand[i].vibLow);
                mac.Stand[i].energy_M = GetRMS(mac.Stand[i].vibMid);
                mac.Stand[i].energy_H = GetRMS(mac.Stand[i].vibHig);
            }

            isDefect = false;///页面用---2025-03-20
            for (int i = 0; i < SysParam.Instance.SpeedChannelCount; i++)//仅针对有速度的通道进行报警判断
            {
                //alarmInfo.stdIsAlarm[i] = false;//报警状态重置
                //轧机振动报警判断
                AlarmJudge(mac.Stand[i], i);
            }
            //alarmingProcess();//20240314

            //alarmInfo.isAlarm = (SysParam.Instance.alarmingType == 2);//共振报警
            for (int i = 0; i < zdStateData.Length; i++)
            {
                zdStateData[i] = isAlarmingNow;
            }
            zdState.WriteData(zdStateData);
            alarmInfo.isAlarm = isAlarmingNow;
            alarmInfo.standAlarmState.update(standAlarmStateP);
            //播放报警铃声        
            //alarmRing.Ring(lowRing, midRing, highRing);
            ////如报警结束，播放语音报告报警机架
            //if (isAlarmingLast && !isAlarmingNow)
            //{
            //    bool[,] tempAlarmFlag = (bool[,])ringflag.Clone();
            //    ringflag.Initialize();
            //    if (isDefect)
            //    {
            //        isDefect = false;
            //        bool[,] tempDefectFlag = (bool[,])defectflag.Clone();
            //        defectflag.Initialize();
            //        alarmRing.DefectVoice(tempDefectFlag, tempAlarmFlag);
            //    }
            //    else
            //    {
            //        alarmRing.AlarmVoice(tempAlarmFlag);
            //    }
            //}

            nextCoilCounter++;
            if (coilenMax <= mac.stripLength && nextCoilCounter > 20)
            {
                coilenMax = mac.stripLength;
            }

            //存储数据        
            if (!SysParam.Instance.fileCreated)
            {
                dataHelper.CreateFileHead();
            }
            dataHelper.writeNew(SysParam.Instance.samplePoint);
            //更新报警信息
            if (isAlarmingNow)
            {
                for (int k = 0; k < SysParam.Instance.SpeedChannelCount; k++)
                {
                    UpdateAlarmInfo(mac.Stand[k], k); ;//更新报警信息   
                }
            }

            //int dislen = Convert.ToInt32(mac.stripLength);
            int dislen = Convert.ToInt32(coilenMax);
            //来了剪切信号
            if (mac.cutted)
            {
                dataHelper.CloseFile(1, alarmInfoNow, dislen);
                stateRefresh();

                mac.stripLength = 0;
                coilenMax = 0.0d;
                nextCoilCounter = 0;
                // 页面 刷新的数据 ---2025-01-09 新增
                alarmInfo.reset();
                isDefect = false;
            }
            //累计采集时间超过半小时，文件强制关闭
            if ((DateTime.Now - mac.startTime).TotalMinutes > 30)
            {
                mac.cutted = true;
                dataHelper.CloseFile(0, alarmInfoNow, dislen);
                stateRefresh();
                // 页面 刷新的数据 ---2025-01-09 新增
                alarmInfo.reset();
                isDefect = false;
            }
            //Console.WriteLine(DateTime.Now.ToString("HH:mm:ss fff") + "  8 FileStore");
            double temptime = DateTime.Now.ToOADate();
            //更新绘图所需数据
            for (int i = 0; i < SysParam.Instance.channelCount; i++)
            {
                ArrayMove(mac.Stand[i].tVib, mac.Stand[i].vib);


                mac.Stand[i].list_Energy_All.Add(mac.Stand[i].energy_All);
                mac.Stand[i].list_Energy_L.Add(mac.Stand[i].energy_L);
                mac.Stand[i].list_Energy_M.Add(mac.Stand[i].energy_M);
                mac.Stand[i].list_Energy_H.Add(mac.Stand[i].energy_H);

                mac.Stand[i].list_Alarm_L.Add(mac.Stand[i].alarm_L_Value_ck);
                mac.Stand[i].list_Alarm_M.Add(mac.Stand[i].alarm_M_Value_ck);
                mac.Stand[i].list_Alarm_H.Add(mac.Stand[i].alarm_H_Value_ck);

                mac.Stand[i].list_Defect_L.Add(mac.Stand[i].defect_L_Value_ck);
                mac.Stand[i].list_Defect_M.Add(mac.Stand[i].defect_M_Value_ck);
                mac.Stand[i].list_Defect_H.Add(mac.Stand[i].defect_H_Value_ck);

                mac.Stand[i].list_Energy_Speed.Add(mac.Stand[i].speed);


                //更新页面数据--2025-01-09 更新
                mac.Stand[i].VibRms[0] = mac.Stand[i].energy_M;
                mac.Stand[i].VibRms[1] = mac.Stand[i].energy_H;
                mac.Stand[i].VibRms[2] = mac.Stand[i].energy_L;
                mac.Stand[i].AlarmRms[0] = mac.Stand[i].alarm_M_Value_ck;
                mac.Stand[i].AlarmRms[1] = mac.Stand[i].alarm_H_Value_ck;
                mac.Stand[i].AlarmRms[2] = mac.Stand[i].alarm_L_Value_ck;
                mac.Stand[i].DefectRms[0] = mac.Stand[i].defect_M_Value_ck;
                mac.Stand[i].DefectRms[1] = mac.Stand[i].defect_H_Value_ck;
                mac.Stand[i].DefectRms[2] = mac.Stand[i].defect_L_Value_ck;
                if (roll_mill_data_array != null && i < SysParam.Instance.SpeedChannelCount)
                {
                    roll_mill_data_array[i].update_data(mac.Stand[i].VibRms, mac.Stand[i].AlarmRms, mac.Stand[i].DefectRms);
                    roll_mill_data_array[i].values[3] = mac.Stand[i].speed;
                    //DevelopLog.DeBug.WriteLogFile("roll_mill_data_array:", roll_mill_data_array[i].values[0].ToString() + "," + roll_mill_data_array[i].values[1].ToString() + "," + roll_mill_data_array[2].values[0].ToString());
                }

            }

            //CZState update 采集箱通电状态
            //if (cZState.values[0] == true && daqDriver.CZconnected[0] == false)
           // {
                //DevelopLog.DeBug.WriteLogFile("DataProcess()", "CZ02 off");
            //}
           // cZState.values[0] = daqDriver.CZconnected[0];
            //if (cZState.values[1] == true && daqDriver.CZconnected[1] == false)
           // {
            //    DevelopLog.DeBug.WriteLogFile("DataProcess()", "CZ03 off");
            //}
           // cZState.values[1] = daqDriver.CZconnected[1];



            mac.xAxisEnergy.Add(temptime);
            mac.distance_Running.Add(mac.stripLength);
            if (mac.cutted)
            {
                mac.list_CutTime.Add(temptime);
            }
            if (mac.list_CutTime.Count > 0 && mac.list_CutTime[0] < mac.xAxisEnergy.Head)
            {
                mac.list_CutTime.RemoveAt(0);
            }

            //剪切信号复位
            mac.cutted = false;
            //帧数据结束
            isAlarmingLast = isAlarmingNow;
            SysParam.Instance.isDatahandlered = true;//此次采集的数据全部处理结束标记
            //DevelopLog.DeBug.WriteLogFile("isDatahandlered = true", "");
        }

        private void alarmingProcess()
        {
            if (SysParam.Instance.alarming1 || SysParam.Instance.alarming2 || SysParam.Instance.alarming3 || SysParam.Instance.alarming4 || SysParam.Instance.alarming5)
            {
                if (SysParam.Instance.alarming5 && SysParam.Instance.alarming4)
                {
                    SysParam.Instance.alarmingType = 2;
                }
                else
                {
                    SysParam.Instance.alarmingType = 1;
                }
            }
            else
            {
                SysParam.Instance.alarmingType = 0;
            }

            if (SysParam.Instance.alarmingType == 2)//现场共振了记录报警信息
            {

                for (int k = 3; k < SysParam.Instance.SpeedChannelCount; k++)//只看4、5机架
                {
                    mac.Stand[k].alarm_M_Times++;
                    if (mac.Stand[k].alarm_M_Times == 1)//第一次报警记录开始位置
                    {
                        mac.Stand[k].tempAlarmMidInfostart = Convert.ToInt32(mac.stripLength);
                        ringflag[k, 1] = true;
                        mac.Stand[k].alarmMidInfo.Add(new Stand.AlarmInfo());
                        mac.Stand[k].indexMid++;
                        mac.Stand[k].alarmMidInfo[mac.Stand[k].indexMid - 1].startPos = mac.Stand[k].tempAlarmMidInfostart;
                        mac.Stand[k].alarmMidInfo[mac.Stand[k].indexMid - 1].endPos = mac.Stand[k].tempAlarmMidInfostart;
                        mac.Stand[k].alarmMidInfo[mac.Stand[k].indexMid - 1].value = mac.Stand[k].energy_M;
                        mac.Stand[k].alarmMidInfo[mac.Stand[k].indexMid - 1].time = DateTime.Now;
                        isAlarmingNow = true;
                    }

                    if (mac.Stand[k].alarm_M_Times > 1)//连续报警时，不断更新结束位置
                    {
                        if (mac.Stand[k].alarmMidInfo[mac.Stand[k].indexMid - 1].value < mac.Stand[k].energy_M)
                        {
                            mac.Stand[k].alarmMidInfo[mac.Stand[k].indexMid - 1].value = mac.Stand[k].energy_M;
                        }
                        mac.Stand[k].alarmMidInfo[mac.Stand[k].indexMid - 1].endPos = Convert.ToInt32(mac.stripLength);
                        isAlarmingNow = true;
                    }
                }
            }
            else
            {
                for (int k = 3; k < SysParam.Instance.SpeedChannelCount; k++)//只看4、5机架
                {
                    mac.Stand[k].alarm_M_Times = 0;
                }
            }
        }

        private void DCBias(double[] temp)////数组先求平均然后数组中的每个值减去这个平均值
        {
            double tempValue = 0;
            int length = temp.Length;
            for (int i = 0; i < length; i++)
            {
                tempValue += temp[i];
            }
            tempValue = tempValue / length;
            for (int i = 0; i < length; i++)
            {
                temp[i] -= tempValue;
            }
        }

        //查表，该机架在当前速度下的报警参数
        private void GetAlarmParam(double speed, Stand std)
        {
            int ias = std.alarm_spd.Length;
            int i_fre = std.fre_l_S1.Length - 1;
            int iIndex = std.alarm_spd[0].alarmSpeed;
            if (speed <= std.alarm_spd[0].alarmSpeed)
            {
                std.band_Fre_L1 = std.fre_l_S1[0];
                std.band_Fre_L2 = std.fre_l_S2[0];
                std.band_Fre_M1 = std.fre_m_S1[0];
                std.band_Fre_M2 = std.fre_m_S2[0];
                std.band_Fre_H1 = std.fre_h_S1[0];
                std.band_Fre_H2 = std.fre_h_S2[0];
                std.alarm_L_Value_ck = std.fre_l_V[0];
                std.alarm_M_Value_ck = std.fre_m_V[0];
                std.alarm_H_Value_ck = std.fre_h_V[0];
                std.defect_L_Value_ck = std.fre_l_D[0];
                std.defect_M_Value_ck = std.fre_m_D[0];
                std.defect_H_Value_ck = std.fre_h_D[0];
            }
            else if (speed >= std.alarm_spd[ias - 1].alarmSpeed)
            {
                std.band_Fre_L1 = std.fre_l_S1[i_fre];
                std.band_Fre_L2 = std.fre_l_S2[i_fre];
                std.band_Fre_M1 = std.fre_m_S1[i_fre];
                std.band_Fre_M2 = std.fre_m_S2[i_fre];
                std.band_Fre_H1 = std.fre_h_S1[i_fre];
                std.band_Fre_H2 = std.fre_h_S2[i_fre];
                std.alarm_L_Value_ck = std.fre_l_V[i_fre];
                std.alarm_M_Value_ck = std.fre_m_V[i_fre];
                std.alarm_H_Value_ck = std.fre_h_V[i_fre];
                std.defect_L_Value_ck = std.fre_l_D[i_fre];
                std.defect_M_Value_ck = std.fre_m_D[i_fre];
                std.defect_H_Value_ck = std.fre_h_D[i_fre];
            }
            else
            {
                std.band_Fre_L1 = std.fre_l_S1[Convert.ToInt32(speed - iIndex)];
                std.band_Fre_L2 = std.fre_l_S2[Convert.ToInt32(speed - iIndex)];
                std.band_Fre_M1 = std.fre_m_S1[Convert.ToInt32(speed - iIndex)];
                std.band_Fre_M2 = std.fre_m_S2[Convert.ToInt32(speed - iIndex)];
                std.band_Fre_H1 = std.fre_h_S1[Convert.ToInt32(speed - iIndex)];
                std.band_Fre_H2 = std.fre_h_S2[Convert.ToInt32(speed - iIndex)];
                std.alarm_L_Value_ck = std.fre_l_V[Convert.ToInt32(speed - iIndex)];
                std.alarm_M_Value_ck = std.fre_m_V[Convert.ToInt32(speed - iIndex)];
                std.alarm_H_Value_ck = std.fre_h_V[Convert.ToInt32(speed - iIndex)];
                std.defect_L_Value_ck = std.fre_l_D[Convert.ToInt32(speed - iIndex)];
                std.defect_M_Value_ck = std.fre_m_D[Convert.ToInt32(speed - iIndex)];
                std.defect_H_Value_ck = std.fre_h_D[Convert.ToInt32(speed - iIndex)];
            }
        }

        private double GetRMS(double[] temp)
        {
            double rms = 0;
            int length = temp.Length;
            for (int i = 0; i < length; i++)
            {
                rms += temp[i] * temp[i];
            }
            rms = Math.Sqrt(rms / length);
            return rms;
        }

        //数据递归画图用
        private void ArrayMove(double[] longArray, double[] shortArray)
        {
            int longlength = longArray.Length;
            int shortlength = shortArray.Length;
            if (longlength > shortlength)
            {
                for (int i = 0; i < longlength - shortlength; i++)
                {
                    longArray[i] = longArray[i + shortlength];
                }
                for (int i = 0; i < shortlength; i++)
                {
                    longArray[i + longlength - shortlength] = shortArray[i];
                }
            }
        }

        private void ListAdd(List<double> tempList, double value)
        {
            tempList.Add(value);
            if (tempList.Count > SysParam.Instance.energyPoints + 1)
            {
                tempList.RemoveAt(0);
            }
        }

        /// <summary>
        /// 振动报警判断
        /// </summary>
        private void AlarmJudge45(Stand std, int standNo)
        {
            bool alarmingFlag = false;
            bool alarmingSFlag = false;

            //低频报警信息
            if (std.energy_L >= std.alarm_L_Value_ck)
            {
                /*std.alarm_L_Times++;
                if (std.alarm_L_Times == 1)
                {
                    std.tempAlarmLowInfostart = Convert.ToInt32(mac.stripLength);
                }
                if (std.alarm_L_Times == std.alarm_L_Times_ck)
                {
                    ringflag[standNo, 0] = true;
                    std.alarmLowInfo.Add(new Stand.AlarmInfo());
                    std.indexLow++;
                    std.alarmLowInfo[std.indexLow - 1].startPos = std.tempAlarmLowInfostart;
                    std.alarmLowInfo[std.indexLow - 1].time = DateTime.Now;
                }
                if (std.alarm_L_Times >= std.alarm_L_Times_ck)
                {
                    if (std.alarmLowInfo[std.indexLow - 1].value < std.energy_L)
                    {
                        std.alarmLowInfo[std.indexLow - 1].value = std.energy_L;
                    }
                    std.alarmLowInfo[std.indexLow - 1].endPos = Convert.ToInt32(mac.stripLength);
                    isAlarmingNow = true;
                    lowRing = true;
                }*/
                if (std.energy_L >= std.defect_L_Value_ck)
                {
                    defectflag[standNo, 0] = true;
                    isDefect = true;
                }
            }
            else
            {
                //std.alarm_L_Times = 0;
            }

            //中频报警位置
            if (std.energy_M >= std.alarm_M_Value_ck)
            {
                alarmingFlag = true;

                /*std.alarm_M_Times++;
                if (std.alarm_M_Times == 1)
                {
                    std.tempAlarmMidInfostart = Convert.ToInt32(mac.stripLength);
                }
                if (std.alarm_M_Times == std.alarm_M_Times_ck)
                {
                    ringflag[standNo, 1] = true;
                    std.alarmMidInfo.Add(new Stand.AlarmInfo());
                    std.indexMid++;
                    std.alarmMidInfo[std.indexMid - 1].startPos = std.tempAlarmMidInfostart;
                    std.alarmMidInfo[std.indexMid - 1].time = DateTime.Now;

                }
                if (std.alarm_M_Times >= std.alarm_M_Times_ck)
                {
                    if (std.alarmMidInfo[std.indexMid - 1].value < std.energy_M)
                    {
                        std.alarmMidInfo[std.indexMid - 1].value = std.energy_M;
                    }
                    std.alarmMidInfo[std.indexMid - 1].endPos = Convert.ToInt32(mac.stripLength);
                    isAlarmingNow = true;
                    midRing = true;
                }*/
                if (std.energy_M >= std.defect_M_Value_ck)
                {
                    defectflag[standNo, 1] = true;
                    isDefect = true;
                }
            }
            else
            {
                //std.alarm_M_Times = 0;
            }

            //高频报警信息
            if (std.energy_H >= std.alarm_H_Value_ck)
            {
                alarmingFlag = true;
                /*std.alarm_H_Times++;
                if (std.alarm_H_Times == 1)
                {
                    std.tempAlarmHighInfostart = Convert.ToInt32(mac.stripLength);
                }
                if (std.alarm_H_Times == std.alarm_H_Times_ck)
                {
                    ringflag[standNo, 2] = true;
                    std.alarmHighInfo.Add(new Stand.AlarmInfo());
                    std.indexHigh++;
                    std.alarmHighInfo[std.indexHigh - 1].startPos = std.tempAlarmHighInfostart;
                    std.alarmHighInfo[std.indexHigh - 1].time = DateTime.Now;

                }
                if (std.alarm_H_Times >= std.alarm_H_Times_ck)
                {
                    if (std.alarmHighInfo[std.indexHigh - 1].value < std.energy_H)
                    {
                        std.alarmHighInfo[std.indexHigh - 1].value = std.energy_H;
                    }
                    std.alarmHighInfo[std.indexHigh - 1].endPos = Convert.ToInt32(mac.stripLength);
                    isAlarmingNow = true;
                    highRing = true;
                }*/
                if (std.energy_H >= std.defect_H_Value_ck)
                {
                    defectflag[standNo, 2] = true;
                    isDefect = true;
                }
            }
            else
            {
                //std.alarm_H_Times = 0;
            }

            if ((std.energy_M >= std.alarm_M_Value_ck * 0.8 && std.energy_M < std.alarm_M_Value_ck)
                || (std.energy_H >= std.alarm_H_Value_ck * 0.8 && std.energy_H < std.alarm_H_Value_ck))//实际值位于报警值80%和100%之间
            {
                alarmingSFlag = true;
            }

            if (standNo == 0)
            {
                SysParam.Instance.alarming1 = alarmingFlag ? true : false;
                SysParam.Instance.alarmingS1 = alarmingSFlag ? true : false;
            }
            if (standNo == 1)
            {
                SysParam.Instance.alarming2 = alarmingFlag ? true : false;
                SysParam.Instance.alarmingS2 = alarmingSFlag ? true : false;
            }
            if (standNo == 2)
            {
                SysParam.Instance.alarming3 = alarmingFlag ? true : false;
                SysParam.Instance.alarmingS3 = alarmingSFlag ? true : false;
            }
            if (standNo == 3)
            {
                SysParam.Instance.alarming4 = alarmingFlag ? true : false;
                SysParam.Instance.alarmingS4 = alarmingSFlag ? true : false;
            }
            if (standNo == 4)
            {
                SysParam.Instance.alarming5 = alarmingFlag ? true : false;
                SysParam.Instance.alarmingS5 = alarmingSFlag ? true : false;
            }
        }


        private void AlarmJudge(Stand std, int standNo)
        {
            bool flag = false;
            standAlarmStateP[standNo,0] = false;//中频
            standAlarmStateP[standNo, 1] = false;//低频
            standAlarmStateP[standNo, 2] = false;//高频

            //低频报警信息
            if (std.energy_L >= std.alarm_L_Value_ck)
            {
                std.alarm_L_Times++;
                if (std.alarm_L_Times == 1)
                {
                    std.tempAlarmLowInfostart = Convert.ToInt32(mac.stripLength);
                }
                if (std.alarm_L_Times == std.alarm_L_Times_ck)
                {
                    ringflag[standNo, 0] = true;
                    std.alarmLowInfo.Add(new Stand.AlarmInfo());
                    std.indexLow++;
                    std.alarmLowInfo[std.indexLow - 1].startPos = std.tempAlarmLowInfostart;
                    std.alarmLowInfo[std.indexLow - 1].time = DateTime.Now;

                    //Console.WriteLine("|AlarmJudge|std.indexLow:" + std.indexLow + ",std.alarmLowInfo.Count:" + std.alarmLowInfo.Count + "|-----0------|");
                }
                //Console.WriteLine("|AlarmJudge|std.indexLow:" + std.indexLow + ",std.alarmLowInfo.Count:" + std.alarmLowInfo.Count + "|-----1------|");
                if (std.alarm_L_Times >= std.alarm_L_Times_ck)
                {
                    //Console.WriteLine("|AlarmJudge|std.alarm_L_Times:" + std.alarm_L_Times + ",std.alarm_L_Times_ck:" + std.alarm_L_Times_ck + "|-----2------|");
                    //Console.WriteLine("|AlarmJudge|std.indexLow:" + std.indexLow + ",std.alarmLowInfo.Count:" + std.alarmLowInfo.Count + "|-----2------|");
                    if (std.alarmLowInfo[std.indexLow - 1].value < std.energy_L)
                    {
                        std.alarmLowInfo[std.indexLow - 1].value = std.energy_L;
                    }
                    std.alarmLowInfo[std.indexLow - 1].endPos = Convert.ToInt32(mac.stripLength);
                    isAlarmingNow = true;
                    lowRing = true;
                    flag = true;
                    standAlarmStateP[standNo,1] = true;
                }
                if (std.energy_L >= std.defect_L_Value_ck)
                {
                    defectflag[standNo, 0] = true;
                    isDefect = true;
                    flag = true;//源代码有 std.speed>300的条件
                }
            }
            else
            {
                std.alarm_L_Times = 0;
            }

            //中频报警位置
            if (std.energy_M >= std.alarm_M_Value_ck)
            {
                std.alarm_M_Times++;
                if (std.alarm_M_Times == 1)
                {
                    std.tempAlarmMidInfostart = Convert.ToInt32(mac.stripLength);
                }
                if (std.alarm_M_Times == std.alarm_M_Times_ck)
                {
                    ringflag[standNo, 1] = true;
                    std.alarmMidInfo.Add(new Stand.AlarmInfo());
                    std.indexMid++;
                    std.alarmMidInfo[std.indexMid - 1].startPos = std.tempAlarmMidInfostart;
                    std.alarmMidInfo[std.indexMid - 1].time = DateTime.Now;

                }
                if (std.alarm_M_Times >= std.alarm_M_Times_ck)
                {
                    if (std.alarmMidInfo[std.indexMid - 1].value < std.energy_M)
                    {
                        std.alarmMidInfo[std.indexMid - 1].value = std.energy_M;
                    }
                    std.alarmMidInfo[std.indexMid - 1].endPos = Convert.ToInt32(mac.stripLength);
                    isAlarmingNow = true;
                    midRing = true;
                    flag = true;
                    standAlarmStateP[standNo, 0] = true;
                }
                if (std.energy_M >= std.defect_M_Value_ck)
                {
                    defectflag[standNo, 1] = true;
                    isDefect = true;
                    flag = true;//源代码有 std.speed>300的条件
                }
            }
            else
            {
                std.alarm_M_Times = 0;
            }

            //高频报警信息
            if (std.energy_H >= std.alarm_H_Value_ck)
            {
                std.alarm_H_Times++;
                if (std.alarm_H_Times == 1)
                {
                    std.tempAlarmHighInfostart = Convert.ToInt32(mac.stripLength);
                }
                if (std.alarm_H_Times == std.alarm_H_Times_ck)
                {
                    ringflag[standNo, 2] = true;
                    std.alarmHighInfo.Add(new Stand.AlarmInfo());
                    std.indexHigh++;
                    std.alarmHighInfo[std.indexHigh - 1].startPos = std.tempAlarmHighInfostart;
                    std.alarmHighInfo[std.indexHigh - 1].time = DateTime.Now;


                }
                if (std.alarm_H_Times >= std.alarm_H_Times_ck)
                {
                    if (std.alarmHighInfo[std.indexHigh - 1].value < std.energy_H)
                    {
                        std.alarmHighInfo[std.indexHigh - 1].value = std.energy_H;
                    }
                    std.alarmHighInfo[std.indexHigh - 1].endPos = Convert.ToInt32(mac.stripLength);
                    isAlarmingNow = true;
                    highRing = true;
                    flag = true;
                    standAlarmStateP[standNo, 2] = true;
                }
                if (std.energy_H >= std.defect_H_Value_ck)
                {
                    defectflag[standNo, 2] = true;
                    isDefect = true;
                    flag = true;//源代码有 std.speed>300的条件

                }
            }
            else
            {
                std.alarm_H_Times = 0;
            }


            //alarmInfo.stdIsAlarm[standNo] = flag;

        }


        private void UpdateAlarmInfo(Stand std, int stdNo)
        {
            if (std.indexLow > 0)
            {
                AlarmInfo2String(std.alarmLowInfo[std.indexLow - 1], stdNo, "低频");
            }
            if (std.indexMid > 0)
            {
                AlarmInfo2String(std.alarmMidInfo[std.indexMid - 1], stdNo, "中频");
            }
            if (std.indexHigh > 0)
            {
                AlarmInfo2String(std.alarmHighInfo[std.indexHigh - 1], stdNo, "高频");
            }
        }

        private void AlarmInfo2String(Stand.AlarmInfo alarminfo, int standNo, string alarmType)
        {
            string temp = alarminfo.time.ToString("MM/dd HH:mm:ss") + "  " + (standNo + 1) + "号机架" + alarmType + "  位置：" + alarminfo.startPos.ToString("00000") + "-" + alarminfo.endPos.ToString("00000") + "m  能量：" + alarminfo.value.ToString("0.000") + "g";
            string temp2 = (standNo + 1) + "号机架（" + alarminfo.time.ToString("yyyy-MM-dd HH:mm:ss") + "）";
            int index = temp.IndexOf("-") - 15;//查重，从报警时间后至位置起始点
            if (alarmInfoNow.Count > 15)
            {
                for (int i = alarmInfoNow.Count - 15; i < alarmInfoNow.Count; i++)
                {
                    if (alarmInfoNow[i].Substring(15, index) == temp.Substring(15, index))
                    {
                        alarmInfoNow.RemoveAt(i);
                    }
                }
            }
            else
            {
                for (int i = 0; i < alarmInfoNow.Count; i++)
                {
                    if (alarmInfoNow[i].Substring(15, index) == temp.Substring(15, index))
                    {
                        alarmInfoNow.RemoveAt(i);
                    }
                }
            }
            alarmInfoNow.Add(temp);
            alarmInfoNowChanged = true;

            // 页面 刷新的数据 ---2025-02-06 新增
            alarmInfo.update(temp2, isDefect);
            //alarmInfo.stdNo = standNo + 1;

        }

        public bool alarmInfoNowChanged { set; get; }
        public bool alarmInfoLastChanged { set; get; }
        private void stateRefresh()
        {
            if (alarmInfoNow.Count > 0)
            {
                alarmInfoLastChanged = true;
                alarmInfoLast = alarmInfoNow.ToArray();
                alarmInfoNowChanged = true;
                alarmInfoNow.Clear();
            }
            mac.startTime = DateTime.Now;
            mac.lenCountStart = mac.lenCountNow;
            //报警参数复位
            for (int i = 0; i < SysParam.Instance.channelCount; i++)
            {
                //报警次数清零
                mac.Stand[i].alarm_L_Times = 0;
                mac.Stand[i].alarm_M_Times = 0;
                mac.Stand[i].alarm_H_Times = 0;
            }
        }

        public void Stop()
        {
            daqDriver.DaqStop();
            Thread.Sleep(500);//等待0.5秒，以免数据未存储完毕            
            if (dataHelper != null)
            {
                dataHelper.CloseFile(2, alarmInfoNow, Convert.ToInt32(mac.stripLength));//0为超时，1为正常剪切，2为主动关闭
            }
            stateRefresh();
            zdState.Stop();
        }

    }
}
