ServerCommunication.cs 13.3 KB
using OnlineStore.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;

namespace DeviceLibrary
{
    public class ServerCommunication
    { 
       private static string server = Setting_Init.Device_Server_Address;
        public string CID; 
        private System.Timers.Timer serverConnectTimer = new System.Timers.Timer();

        object serverclock = new object();
       
        public ServerCommunication( )
        {
            CID = "line"; 
            serverConnectTimer.Interval =2000;
            serverConnectTimer.AutoReset = true;
            serverConnectTimer.Enabled = false;
            serverConnectTimer.Elapsed += ServerConnectTimer_Elapsed;
            GC.KeepAlive(serverConnectTimer);
            LogUtil.info($"server:{server},cid:{CID}");
            InitModuleMap();
        }
        private void ServerConnectTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                if (!RobotManage.isRunning)
                {
                    return;
                }
                if (!string.IsNullOrEmpty(server))
                {
                    SendLineStatus();
                }
            }
            catch (Exception ex)
            {
                LogUtil.info($"ServerConnectTimer_Elapsed:{ex}");
            }
        }
        public void StartConnectServer() {
            serverConnectTimer.Enabled = true;
        }
        public void StopConnectServer() {
            serverConnectTimer.Enabled = false;
        } 
         
        private static string api_communication = "service/equipment/communication";    //流水线状态通信接口
        public static string GetPostApi(string api)
        {
            var host = server;
            if (!host.StartsWith("http://"))
            {
                host = "http://" + host;
            }
            if (!host.EndsWith("/"))
            {
                host = host + "/";
            }
            if (api.StartsWith("/"))
            {
                api = api.Substring(1);
            }
            return host + api;
        }

        private List<EquipMsg> otherEquipMsg = new List<EquipMsg>();

        public void AddWarnMsg(string errorCode, string moudle,string msg,string type= "WARNING")
        {
            otherEquipMsg.Add(EquipMsg.newMsg(errorCode, moudle,msg,type));
        }


        private List<EquipMsg> alarmMsgList = new List<EquipMsg>();

        public void AddAlarmMsg(string errorCode, string moudle, string msg,string type="ERROR")
        {
            alarmMsgList.Add(EquipMsg.newMsg(errorCode, moudle, msg ,type));
        }
        private Dictionary<string, string> msgMoudleMap =null;

        public void  InitModuleMap()
        {
            if (msgMoudleMap == null)
            {
                msgMoudleMap = new Dictionary<string, string>();
                msgMoudleMap.Add("2000", "line");
                msgMoudleMap.Add("2010", "MU1");
                msgMoudleMap.Add("2011", "MU1_1");
                msgMoudleMap.Add("2012", "MU1_2");
                msgMoudleMap.Add("2020", "MU2");
                msgMoudleMap.Add("2021", "MU2_1");
                msgMoudleMap.Add("2030", "MU3_1");
                msgMoudleMap.Add("2040", "MU4");
                msgMoudleMap.Add("2041", "MU4_1");
                msgMoudleMap.Add("2042", "MU4_2");
                msgMoudleMap.Add("2050", "MU5");
                msgMoudleMap.Add("2051", "MU5_1");
                msgMoudleMap.Add("2052", "MU5_2");
            }
        }

        public void AddMsgList(List<Msg> msgs)
        {
            try
            {
                foreach (Msg msg in msgs)
                {
                    string moudle = "line";
                   

                    if (msg.msgtxt == "")
                    {
                        continue;
                    }
                    string pattern = @"\d+秒";
                    string replacement = "";
                    string msgStr = Regex.Replace(msg.msgtxt, pattern, replacement);
                    string regex = "\\[\\d+\\.\\d+\\]秒";
                      msgStr = Regex.Replace(msgStr, regex, "");

                     regex = "\\[\\d+\\]秒";
                    msgStr = Regex.Replace(msgStr,regex, "");
                    //已存在的不重复发送
                    int count = (from m in alarmMsgList where m.msg.Equals(msgStr) select m).ToList().Count();
                    if (count >=1)
                    {
                        continue;
                    }
                    foreach (string key in msgMoudleMap.Keys)
                    {
                        if (msg.alarmCode.StartsWith(key))
                        {
                            moudle = msgMoudleMap[key];
                        }
                    }
                    if (msg.msgLevel.Equals(MsgLevel.warning))
                    {
                        AddAlarmMsg(msg.alarmCode, moudle, msgStr, "WARNING");
                    }
                    else if (msg.msgLevel.Equals(MsgLevel.info))
                    {
                        AddAlarmMsg(msg.alarmCode, moudle, msgStr, "INFO");
                    }
                    else
                    {
                        AddAlarmMsg(msg.alarmCode, moudle, msgStr);
                    }
                }
            }
            catch (Exception ex)
            {
                LogUtil.error("AddAlarmMsg 出错:" + ex.ToString());
            }
        }

        public void SendLineStatus()
        {
            if (Monitor.TryEnter(serverclock, 10))
            {

                try
                {

                    bool printlog = false;
                    DateTime time = DateTime.Now;
                    //构建发送给服务器的对象
                    EquipStatusBean bean = new EquipStatusBean();
                    bean.cid = CID;
                    bean.seq = ConfigAppSettings.nextSeq();

                    List<EquipMsg> equipMsgs = new List<EquipMsg>();
                    //List<MoveInfo> moves = MoveInfo.allList();
                    //foreach (MoveInfo move in moves)
                    //{

                    //    if (string.IsNullOrEmpty(move.lasterrmsg))
                    //    {
                    //        TimeSpan span = DateTime.Now - move.lastErrmsgTime;
                    //        if (span.TotalSeconds <= 3)
                    //        {
                    //            string pattern = @"\d+秒";
                    //            string replacement = "";
                    //            string output = Regex.Replace(move.lasterrmsg, pattern, replacement);


                    //            //三秒内的就发送
                    //            EquipMsg msg = EquipMsg.newMsg(move.Name, output);
                    //            equipMsgs.Add(msg);
                    //        }
                    //    }

                    //}
                    equipMsgs.AddRange(otherEquipMsg);
                    equipMsgs.AddRange(alarmMsgList);
                    otherEquipMsg = new List<EquipMsg>();
                    alarmMsgList = new List<EquipMsg>();

                    //如果在暂停中,需要设置报警状态
                    List<StatusInfo> list = GetStatuses(equipMsgs);
                    bean.msgList = equipMsgs;
                    bean.statusList = list;
                    EquipStatusBean result = HttpHelper.Post(GetPostApi(api_communication), bean, 1000, printlog);

                    //暂无处理
                }
                catch (Exception e)
                {
                    LogUtil.error("SendLineStatus 出错: " + e.ToString());
                }
                finally
                {
                    Monitor.Exit(serverclock);
                }
            }
        }

        private List<StatusInfo> GetStatuses(List<EquipMsg> msgList)
        {
            List<string> muNames = new List<string>() { "MU1_1", "MU1_2", "MU2_1", "MU3_1", "MU4_1", "MU4_2", "MU5_1", "MU5_2" };
            Dictionary<string, int> sMap = new Dictionary<string, int>();
            try
            {

                //如果是正在暂停中,状态为报警
                //  0=离线,1=正常运行中, 2=急停, 3=故障(气压检测不到等,用msg发送详细故障说明)
                foreach (string name in muNames)
                {
                    List<EquipMsg> msg = (from m in msgList where m.module.Equals(name) select m).ToList();
                    if (msg.Count > 0)
                    {
                        UpdateS(sMap, name, 3);
                    }
                }
                foreach (UMEquipBase mu in RobotManage.UMEquipMap.Values)
                {
                    int s = 1;
                    if (mu.runStatus == RunStatus.Stop)
                    {
                        s = 0;
                    }
                    else if (mu.isInSuddenDown)
                    {
                        s = 2;
                    }
                    if (mu.UMLine1 != null)
                    {
                        bool result1 = UpdateS(sMap, mu.UMLine1.Name, s);
                        if (!result1 && s == 2)
                        {
                            EquipMsg msg = EquipMsg.newMsg(mu.UMLine1.alarmCode + "0006", mu.UMLine1.Name, $"{mu.Name}急停中");
                            msgList.Add(msg);
                        }
                    }
                    if (mu.UMLine2 != null)
                    {
                        bool result2 = UpdateS(sMap, mu.UMLine2.Name, s);
                        if (!result2 && s == 2)
                        {
                            EquipMsg msg = EquipMsg.newMsg(mu.UMLine2.alarmCode + "0006", mu.UMLine2.Name, $"{mu.Name}急停中");
                            msgList.Add(msg);
                        }
                    }
                }
                int mu3s = 1;
                if (RobotManage.uM1Equip.runStatus == RunStatus.Stop)
                {
                    mu3s = 0;
                }
                else if (RobotManage.uM1Equip.isInSuddenDown)
                {
                    mu3s = 2;
                }
                bool result = UpdateS(sMap, "MU3_1", mu3s);
                if (!result && mu3s == 2)
                {
                    EquipMsg msg = EquipMsg.newMsg("20300006", "MU3_1", $"MU3_1急停中");
                    msgList.Add(msg);
                }
                foreach (MoveInfo moveInfo in MoveInfo.allList())
                {
                    if (moveInfo.isAlarmStop)
                    {
                        List<string> muList = getMuNameList(moveInfo.Name);
                        if (muList.Count > 0)
                        {
                            foreach (string n in muList)
                            {
                                if (!UpdateS(sMap, n, 3))
                                {
                                    EquipMsg msg = EquipMsg.newMsg("20" + n.Replace("MU", "").Replace("_", "") + "0005", n, $"{moveInfo.Name} 暂停中");
                                    msgList.Add(msg);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogUtil.error("获取出料口状态出错:" + ex.ToString());
            }
            List<StatusInfo> list = new List<StatusInfo>();
            foreach (string key in sMap.Keys)
            {
                int v = sMap[key];
                list.Add(new StatusInfo() { module = key, status = v });
            }
            return list;
        }

        private List<string> getMuNameList(string mName)
        {
            List<string> result = new List<string>();
            if (mName.StartsWith("MU3"))
            {
                result.Add("MU3");
                return result;
            }

            List<string> muNames = new List<string>() { "MU1_1", "MU1_2", "MU2_1", "MU3_1", "MU4_1", "MU4_2", "MU5_1", "MU5_2" };
            foreach (string muName in muNames)
            {
                if (mName.StartsWith(muName))
                {
                    result.Add(mName);
                    return result;
                }
            }

            foreach (UMEquipBase mu in RobotManage.UMEquipMap.Values)
            {
                if (mName.StartsWith(mu.Name))
                {
                    if (mu.UMLine1 != null)
                    {
                        result.Add(mu.UMLine1.Name);
                    }
                    if (mu.UMLine2 != null)
                    {
                        result.Add(mu.UMLine2.Name);
                    }

                    return result;
                }
            }
            return result;
        }

        private bool UpdateS(Dictionary<string,int> sMap,string name,int s )
        {
           if(sMap.ContainsKey(name))
            {
                if (sMap[name] ==2||s==2) {
                    sMap[name] = 2;
                }else if (sMap[name] < s)
                {
                    sMap[name] = s;
                } 
                sMap[name] = s;
                return true  ;
            }
            else
            {
                sMap.Add(name, s);
                return false ;
            }
        }

    } 
}