Esempio n. 1
0
 static void ExcuteAnalyse(object obj)
 {
     try
     {
         SocketMiddleware socket          = obj as SocketMiddleware;
         MessageBusiness  messageBusiness = new MessageBusiness(socket);
         messageBusiness.ExcuteAnalyse();
     }
     catch (Exception ex)
     {
         LoggerHelper.Error(typeof(Program), ex.Message, ex);
         Console.WriteLine(ex);
     }
 }
Esempio n. 2
0
        /// <summary>
        /// 握手业务
        /// </summary>
        /// <param name="revData"></param>
        /// <returns>握手后状态</returns>
        public SiteModel Handshake(SocketMiddleware socket)
        {
            SiteModel site = null;

            byte[] revData = new byte[15];
Handshake:
            if (!socket.Send(OrderHelper.Handshake))
            {
                return(site);
            }

            //站点反馈的命令
            if (!socket.Receive(revData))
            {
                return(site);
            }

            //判断握手是否正常
            if (revData[1] != 'S' || revData[2] != 'H' || revData[3] != 'O' || revData[4] != 'K')
            {
                return(site);
            }

            //设置站点空闲状态
            if (revData[7] != 1)
            {
                //长时间波形采集中 返回
                if (revData[7] == 4)
                {
                    site = new SiteModel(revData);
                    SetSiteDatabase(site.Sn);
                    _connectLogServer.InsertEntity(new ConnectLog()
                    {
                        ClTime = DateTime.Now, SiteSn = site.Sn
                    });
                    return(site);
                }

                //置空闲失败
                if (!socket.Send(OrderHelper.SetSiteLeisure()))
                {
                    return(null);
                }

                byte[] tempData = new byte[13];
                if (!socket.Receive(tempData))
                {
                    return(null);
                }

                if (tempData[1] != 'P' || tempData[2] != 'P' || tempData[3] != 'O' || tempData[4] != 'K')
                {
                    return(null);
                }

                Console.WriteLine("握手成功,置空闲状态!");
                Thread.Sleep(5000);
                goto Handshake; //重新握手
            }

            site = new SiteModel(revData);
            SetSiteDatabase(site.Sn);
            _connectLogServer.InsertEntity(new ConnectLog()
            {
                ClTime = DateTime.Now, SiteSn = site.Sn
            });
            return(site);
        }
Esempio n. 3
0
        public void GetDataOa(SiteModel site, SocketMiddleware socket)
        {
            Console.WriteLine("开始采集总值数据!");
            _machineStopList = _machineStopService.Query(ms => ms.AreaId == site.AearId);

            try
            {
                //通道OA的数据集合
                List <AutoMeasuredValue> amvList = new List <AutoMeasuredValue>();
                //工况集合
                List <int> workStatuesList = null;
                //获取接收的数据缓存
                byte[] sendData = null;
                #region 准备获取总值

                //PrintHelper.Info("【{0}】发送OA采集命令成功!{1}", _site.GetSN(), sendData);

                /********************************************************************************************************************************
                 * 【1 |	0x??】
                 * 【2,3,4,5 |	P,P,O,K  ASCII码等于(80,80,79,75)】
                 * 【6,7 | 仪器序列号(1~65536)(0填充)】
                 * 【8,9,10,11 |	仪器报警状态100:正常;1~17:不同报警】
                 * 【12,13,14,15 |	(int数据)振动总值参数检测的次数AutoRun_Num(用于在结构体里面提取有效振动总值参数的个数)】
                 * 【16,17,18,19 |	(int数据)一个测点的振动总值参数占用字节的位数84*AutoRun_Num(运行的次数) + 20】
                 * 【20,21,22,23 |	(int数据)当前运行的测点组号Num为0:准备好非0:等待Num*10后再发此命令查询】
                 * 【24 | 校验】
                 *******************************************************************************************************************************/
                #endregion

                #region 总值获取

                //循环获取每个通道下的数据
                foreach (ChannelStruct channel in site.ChannelStructList)
                {
                    workStatuesList = channel.StateStatus.Where(s => s != -1).ToList();
                    sendData        = OrderHelper.GetDataOaByChannelNum(channel.ChannelID, false);
                    if (socket.Send(sendData))
                    {
                        byte[] dataTemp = new byte[13];
                        if (socket.Receive(dataTemp))
                        {
                            int count = BitConverter.ToInt32(dataTemp, 5);
                            if (count > 0)
                            {
                                if (socket.Send(OrderHelper.GetDataOaByChannelNum(channel.ChannelID, true)))
                                {
                                    int    length  = 28 + count * 84;
                                    byte[] revData = new byte[length];
                                    if (socket.Receive(revData))
                                    {
                                        //获取数据进行结构化转换
                                        AutoMeasuredValue amv = GetAutoMeasuredValue(revData);
                                        //工况筛选
                                        IEnumerable <MeasuredValue> measuredValueList = amv.MeasuredList.Where(m => workStatuesList.Exists(w => w == m.WorkStatus));
                                        amv.MeasuredList = measuredValueList == null ? new List <MeasuredValue>() : measuredValueList.ToList();
                                        amvList.Add(amv);
                                    }
                                }
                            }
                        }
                    }
                }
                //通道采集完成后,告诉下位机继续自动运行
                sendData = OrderHelper.GetDataOaByChannelNum(-1, false);
                if (socket.Send(sendData))
                {
                    byte[] revData = new byte[13];
                    if (socket.Receive(revData))
                    {
                        if (OrderHelper.CheckCode(revData, 0) == revData[revData.Length - 1] &&
                            revData[1] == (byte)'P' && revData[2] == (byte)'P')
                        {
                            if (revData[3] == (byte)'O' && revData[4] == (byte)'K')
                            {
                                //PrintHelper.Info("将站点置为自动运行模式!");
                            }
                        }
                    }
                }
                #endregion

                #region 总值存储  同时修改报警状态
                //存储总值
                if (amvList.Count > 0)
                {
                    foreach (AutoMeasuredValue amv in amvList)
                    {
                        if (amv == null)
                        {
                            continue;
                        }
                        Console.WriteLine("【区域:{0},机器:{1},测点:{2},方向:{3}一共有{4}笔数据】", amv.areaId, amv.machineId, amv.monitorId, amv.position_HVA, amv.MeasuredList.Count);
                        InserDataOaList(amv);
                    }
                }
                #endregion

                Console.WriteLine("采集总值数据完成!");
            }
            catch (Exception ex)
            {
                Program.LoggerHelper.Error(typeof(DataOaModule), ex.Message, ex);
                Console.WriteLine(string.Format("采集总值数据出现异常!{0}", ex));
            }
        }
Esempio n. 4
0
        public void GetDataTw(SiteModel site, SocketMiddleware socket)
        {
            Dictionary <string, bool> stopDic = RedisHelper.Get <Dictionary <string, bool> >($"{CallContext.GetData<ClientInfo>("clientInfo").Database}IsStop");

            Console.WriteLine("开始采集波形数据!");
            //存储集合
            List <int> workStatuesList     = null;
            List <MeterageSamplerate> list = null;

            int type, frequency, line;

            byte[] cmd     = null;
            byte[] recData = new byte[20];
            for (int i = 0; i < site.ChannelStructList.Count; i++)
            {
                //是否停机状态
                string key = $"A{site.ChannelStructList[i].AreaID}M{site.ChannelStructList[i].MachineID}";
                if (stopDic.GetValueOrDefault(key))
                {
                    continue;
                }

                list = _meterageSamplerateService.Query(s =>
                                                        s.AreaId == site.ChannelStructList[i].AreaID &&
                                                        s.McId == site.ChannelStructList[i].MachineID &&
                                                        s.ParId == site.ChannelStructList[i].MonitorID &&
                                                        s.DirId == site.ChannelStructList[i].Position_HVA &&
                                                        s.IsSamplerate == 1);

                workStatuesList = site.ChannelStructList[i].StateStatus.Where(w => w != -1).ToList();
                foreach (MeterageSamplerate item in list)
                {
                    line      = item.MsrLine;
                    frequency = item.MsrRateMax;
                    type      = item.MsrParameter.ToLower().Contains("env") ? 2 : 0;
                    char typeName = item.MsrName.ToUpper()[0];                                                            //类型的首字母  如:Disp 'D'
                    cmd = OrderHelper.TwDataByChannel(site.ChannelStructList[i].ChannelID, typeName, frequency, line, 0); //获取每个通道取数据命令
                    if (socket.Send(cmd))
                    {
                        if (!socket.Receive(recData))    //接收失败
                        {
                            continue;
                        }

                        int len = BitConverter.ToInt32(recData, 15); //获取要接收的数据长度
                        if (len <= 0)                                //是否有数据
                        {
                            continue;
                        }

                        //获取波形数据
                        cmd = OrderHelper.TwDataByChannel(site.ChannelStructList[i].ChannelID, typeName, frequency, line, 1);
                        if (!socket.Send(cmd))
                        {
                            continue;
                        }

                        byte[] data = new byte[len];
                        if (!socket.Receive(data)) //接收波形数据,最后4个字节是工况
                        {
                            Console.WriteLine(string.Format("{0}站点{1}通道号接收波形异常!", site.Sn, i));
                            continue;
                        }

                        DataTw tw = new DataTw()  //数据转化波形对象
                        {
                            AreaId         = item.AreaId,
                            McId           = item.McId,
                            ParId          = item.ParId,
                            DirId          = item.DirId,
                            DataLines      = GetLineByType(item.MsrLine, type),
                            DataPoints     = (int)(GetLineByType(item.MsrLine, type) * 2.56),
                            DataHz         = (int)(GetFrequencyByType(item.MsrRateMax, type) * 2.56),
                            DataIsFFT      = 0,
                            DataType       = type + 1,
                            DataFormat     = 2,
                            Data           = new byte[len - 7 * 4],
                            DataWorkStatus = Convert.ToInt32(BitConverter.ToSingle(data, 24)),
                            Time           = ConvertTime(data)
                        };

                        //是否是要取的工况
                        if (!workStatuesList.Exists(w => w == tw.DataWorkStatus))
                        {
                            continue;
                        }

                        Array.Copy(data, 7 * 4, tw.Data, 0, len - 7 * 4); //把波形数据copy到 tw.data中

                        if (item.MsrParameter.ToLower().Contains("env"))  //包络,直接存
                        {
                            tw.DataIsFFT = 1;
                            tw.Data      = SplitMinFFT(tw.Data, item);                                      //截取最小Fmin
                            _dataTwService.InsertDataTw(tw, string.Format("tb_data_tw_{0}", item.MsrName)); //存入数据库
                        }
                        else if (item.MsrParameter.ToLower().Contains("acc"))
                        {
                            //存储波形
                            _dataTwService.InsertDataTw(tw, string.Format("tb_data_tw_{0}", item.MsrName));

                            //频谱存储
                            float[] accSpectrum = GetAccSpectrum(ToFloatArray(tw.Data), tw.DataLines);
                            for (int z = 0; z < accSpectrum.Length; z++)
                            {
                                accSpectrum[z] = accSpectrum[z] / 1.414f;//峰值转有效值
                            }
                            tw.Data      = ToByteArray(accSpectrum);
                            tw.DataIsFFT = 1;
                            tw.Data      = SplitMinFFT(tw.Data, item); //截取最小Fmin
                            _dataTwService.InsertDataTw(tw, string.Format("tb_data_tw_{0}", item.MsrName));
                        }
                        else if (item.MsrParameter.ToLower().Contains("disp"))
                        {
                            float[] accSpectrum = GetAccSpectrum(ToFloatArray(tw.Data) /*原始波形*/, tw.DataLines);

                            //位移频谱
                            float[] dispSpectrum = GetDispSpectrum(accSpectrum, tw.DataHz, tw.DataPoints);
                            for (int k = 0; k < dispSpectrum.Length; k++)
                            {
                                //位移有效值
                                dispSpectrum[k] = dispSpectrum[k] * 9800 * 1000 / 1.414f;
                            }

                            //位移波形
                            float[] dispTw = new float[tw.DataPoints];
                            FFTHelper.IntegrateFromSpectrum(ToFloatArray(tw.Data) /*原始波形*/, tw.DataHz, tw.DataPoints, item.MsrRateMin, GetFrequencyByType(item.MsrRateMax, type), 2, ref dispTw);
                            for (int k = 0; k < dispTw.Length; k++)
                            {
                                dispTw[k] = dispTw[k] * 9800 * 1000;
                            }

                            //存储波形
                            //tw.data = ToByteArray(dispTw);
                            _dataTwService.InsertDataTw(tw, string.Format("tb_data_tw_{0}", item.MsrName));

                            //频谱存储
                            tw.DataIsFFT = 1;
                            tw.Data      = ToByteArray(dispSpectrum);
                            tw.Data      = SplitMinFFT(tw.Data, item); //截取最小Fmin
                            _dataTwService.InsertDataTw(tw, string.Format("tb_data_tw_{0}", item.MsrName));
                        }
                        else if (item.MsrParameter.ToLower().Contains("vel"))
                        {
                            float[] accSpectrum = GetAccSpectrum(ToFloatArray(tw.Data) /*原始波形*/, tw.DataLines);

                            //速度波形
                            float[] velTw = new float[tw.DataPoints];
                            FFTHelper.IntegrateFromSpectrum(ToFloatArray(tw.Data) /*原始波形*/, tw.DataHz, tw.DataPoints, item.MsrRateMin, GetFrequencyByType(item.MsrRateMax, type), 1, ref velTw);
                            for (int k = 0; k < velTw.Length; k++)
                            {
                                velTw[k] = velTw[k] * 9800;
                            }

                            //速度频谱
                            float[] velSpectrum = GetVelSpectrum(accSpectrum, tw.DataHz, tw.DataPoints);
                            for (int k = 0; k < velSpectrum.Length; k++)
                            {
                                velSpectrum[k] = velSpectrum[k] * 9800 / 1.414f;
                            }

                            //波形存储
                            //tw.data = ToByteArray(velTw);
                            _dataTwService.InsertDataTw(tw, string.Format("tb_data_tw_{0}", item.MsrName));

                            //频谱存储
                            tw.DataIsFFT = 1;
                            tw.Data      = ToByteArray(velSpectrum);   //获取频谱
                            tw.Data      = SplitMinFFT(tw.Data, item); //截取最小Fmin
                            _dataTwService.InsertDataTw(tw, string.Format("tb_data_tw_{0}", item.MsrName));
                        }
                    }
                }
            }

            Console.WriteLine("波形数据采集完成!");
        }
Esempio n. 5
0
        static void Main(string[] args)
        {
            var    basePath      = Environment.CurrentDirectory;
            string redisIP       = AppsettingsHelper.GetConfigString("RedisConfig", "IP");
            string redisPassword = AppsettingsHelper.GetConfigString("RedisConfig", "Password");

            LoggerRepository = LogManager.CreateRepository("BPDM.Logger");
            XmlConfigurator.Configure(LoggerRepository, new FileInfo("Log4net.config"));
            RedisHelper.Initialization(new CSRedis.CSRedisClient($"{redisIP},password={redisPassword},defaultDatabase=13,poolsize=50,ssl=false,writeBuffer=10240,prefix=key前辍"));

            IServiceCollection services = new ServiceCollection();

            services.AddAutoMapper();

            services.AddTransient <IHandshakeModule, HandshakeModule>();
            services.AddTransient <ISiteModule, SiteModule>();
            services.AddTransient <IDataOaModule, DataOaModule>();
            services.AddTransient <IDataTwModule, DataTwModule>();
            services.AddTransient <IExtractModule, ExtractModule>();
            services.AddTransient <IConfigModule, ConfigModule>();
            services.AddTransient <IOaAlarmModule, OaAlarmModule>();
            services.AddSingleton <ILoggerHelper, LogHelper>();
            services.AddTransient <IStopModule, StopModule>();

            ContainerBuilder builder = new ContainerBuilder();
            var servicesDllFile      = Path.Combine(basePath, "Vs.Service.dll");
            var assemblysServices    = Assembly.LoadFile(servicesDllFile);

            builder.RegisterAssemblyTypes(assemblysServices)
            .AsImplementedInterfaces()
            .InstancePerDependency();

            var repositoryDllFile   = Path.Combine(basePath, "Vs.Repository.dll");
            var assemblysRepository = Assembly.LoadFile(repositoryDllFile);

            builder.RegisterAssemblyTypes(assemblysRepository).AsImplementedInterfaces().InstancePerDependency();

            builder.Populate(services);
            container    = builder.Build();
            LoggerHelper = container.Resolve <ILoggerHelper>();

            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            using (StreamReader sr = new StreamReader(Path.Combine(basePath, "clientInfo.json"), Encoding.GetEncoding("gb2312")))
            {
                string json = sr.ReadToEnd();
                ClientInfoList = JsonConvert.DeserializeObject <List <ClientInfo> >(json);
            }
            string    address      = AppsettingsHelper.GetConfigString("SocketServer", "Address");
            int       port         = Convert.ToInt32(AppsettingsHelper.GetConfigString("SocketServer", "port"));
            IPAddress ip           = IPAddress.Parse(address);
            Socket    serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            //绑定IP地址:端口
            serverSocket.Bind(new IPEndPoint(ip, port));
            //设定最多10个排队连接请求
            serverSocket.Listen(10);

            //线程池的容量过去设置
            int workerThreads_max         = 0;
            int completionPortThreads_max = 0;
            int workerThreads_min         = 0;
            int completionPortThreads_min = 0;

            //获取当前系统最大、最小线程池容量
            ThreadPool.GetMaxThreads(out workerThreads_max, out completionPortThreads_max);
            ThreadPool.GetMinThreads(out workerThreads_min, out completionPortThreads_min);

            //自定义线程池容量
            workerThreads_max         = 12;                                         // 12;
            completionPortThreads_max = 12;                                         //12;
            workerThreads_min         = 5;                                          // 5;
            completionPortThreads_min = 5;                                          // 5;

            ThreadPool.SetMinThreads(workerThreads_min, completionPortThreads_min); // set min thread to 5
            ThreadPool.SetMaxThreads(workerThreads_max, completionPortThreads_max); // set max thread to 12
            ThreadPool.QueueUserWorkItem(SendEmail);                                //启动发送邮件
            while (true)
            {
                try
                {
                    Socket clientSocket = serverSocket.Accept();
                    Console.WriteLine($"{clientSocket.RemoteEndPoint}连接成功!时间:{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}");
                    SocketMiddleware socket = new SocketMiddleware(clientSocket);
                    ThreadPool.QueueUserWorkItem(ExcuteAnalyse, socket);
                }
                catch (Exception e)
                {
                    LoggerHelper.Error(typeof(Program), e.Message, e);
                    Console.WriteLine(e);
                }
            }
        }
Esempio n. 6
0
        /// <summary>
        /// 初始化,处理波形频谱需要的参数信息
        /// </summary>
        /// <param name="site"></param>
        /// <param name="socket"></param>
        public void InitConfig(SiteModel site, SocketMiddleware socket)
        {
            _site               = site;
            _socket             = socket;
            _stopMachineOa      = RedisHelper.Get <Dictionary <string, bool> >($"{CallContext.GetData<ClientInfo>("clientInfo").Database}IsStop");
            _dirverRelationList = _dirverRelationService.Query(dr => dr.AreaId == _site.AearId);

            //获取测量参数组 及转速定义
            List <MeterageSamplerate> meterageSamplerateList = _meterageSamplerateService.Query(ms => ms.AreaId == _site.AearId && ms.IsSamplerate == 1);
            List <TachoDefind>        tachoDefindList        = _tachoDefindService.Query(td => td.AreaId == _site.AearId);

            foreach (TachoDefind tachoDefind in tachoDefindList)
            {
                //没有找到需要的数据源,查找下一个
                MeterageSamplerate ms = meterageSamplerateList.FirstOrDefault(m => m.MsrId == tachoDefind.MsrId);
                if (ms == null)
                {
                    continue;
                }

                //获取频谱数据
                DataTwModel model = GetTwFFTData(ms);
                if (model == null)
                {
                    continue;
                }
                //提取转速
                float rev = ExtractRPM(model.Data, model.DataHz / ((float)model.DataLines), tachoDefind);
                Console.WriteLine($"转速:{rev}");
                //停机转态不提取
                if (rev <= 0)
                {
                    _stopMachine.Add($"A{tachoDefind.AreaId}M{tachoDefind.McId}", true);
                    continue;
                }
                //修改转速
                MachineRev machineRev = _machineRevService.Query(m => m.AreaId == tachoDefind.AreaId && m.McId == tachoDefind.McId).FirstOrDefault();
                if (machineRev != null)
                {
                    machineRev.MrRev  = rev;
                    machineRev.MrTime = DateTime.Now;
                    _machineRevService.UpdateEntity(machineRev);
                }
                else
                {
                    machineRev = new MachineRev()
                    {
                        AreaId  = tachoDefind.AreaId,
                        McId    = tachoDefind.McId,
                        MrTime  = DateTime.Now,
                        MrLevel = 2,
                        MrRev   = rev
                    };
                    _machineRevService.InsertEntity(machineRev);
                }

                ExtractValue(model, ms, (int)rev);
            }

            foreach (MeterageSamplerate ms in meterageSamplerateList)
            {
                if (tachoDefindList.FirstOrDefault(t => t.MsrId == ms.MsrId) != null)
                {
                    continue;
                }
                DataTwModel model = GetTwFFTData(ms);
                if (model == null)
                {
                    continue;
                }

                //停机状态不提取
                if (_stopMachine.ContainsKey($"A{ms.AreaId}M{ms.McId}"))
                {
                    continue;
                }
                ExtractValue(model, ms);
            }

            //更新元件状态
            foreach (DirverRelation dirverRelation in _dirverRelationList)
            {
                _dirverRelationService.UpdateEntity(dirverRelation);
            }
        }
Esempio n. 7
0
 public MessageBusiness(SocketMiddleware socket)
 {
     _socket = socket;
 }