BOXManager.cs 14.2 KB
using log4net;
using SmartShelf.Common; 
using SmartShelf.LoadCSVLibrary;
using System;
using System.Collections.Generic; 
using System.Linq; 
using System.Windows.Forms;

namespace SmartShelf.DeviceLibrary
{
    /// <summary>
    /// 流水线自动料仓-流水线类
    /// </summary>
    public class BOXManager
    {
        private static  int ServerPort = ConfigAppSettings.GetIntValue(Setting_Init.ServerPort);
        private static readonly ILog LOGGER = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        public static string BoxName = "单色灯料架"; 
        public static string CID = ""; 
      
        private static System.Timers.Timer timersTimer;  
        private static bool isInit = false;
        public static string WarnMsg = "";
        public static Dictionary<string, BoxPosition> PositionMap=null;
        public static int BoxCount = 1;
   
        public static Dictionary<string, int> StatusMap = new Dictionary<string, int>(); 
        public static bool IsRun = false;
    
        public static bool StartInit()
        {
            try
            { 
                BoxCount = ConfigAppSettings.GetIntValue(Setting_Init.BoxCount);
                string appPath = Application.StartupPath;
                //加载位置
                string positionConfigFile = appPath + ConfigAppSettings.GetValue(Setting_Init.Store_Position_Config);
                if (BoxCount > 1)
                {
                    string fileSub = System.IO.Path.GetExtension(positionConfigFile);
                    for (int i = 1; i <= BoxCount; i++)
                    { 
                        string fileName = positionConfigFile.Substring(0, positionConfigFile.Length - fileSub.Length) + "_" + i + fileSub;
                        CSVPositionReader<BoxPosition>.AddCSVFile(fileName);
                    }
                }
                else
                {
                    CSVPositionReader<BoxPosition>.AddCSVFile(positionConfigFile);
                }
                PositionMap = CSVPositionReader<BoxPosition>.allPositionMap;
                if (PositionMap == null || PositionMap.Count <= 0)
                {
                    return false;
                }
                LEDManager.deviceMap = new Dictionary<string, LEDBaseModule>();
                StatusMap = new Dictionary<string, int>(); 
                foreach (BoxPosition box in PositionMap.Values)
                {
                    if (!LEDManager.deviceMap.ContainsKey(box.DeviceIp))
                    {
                        LEDManager.deviceMap.Add(box.DeviceIp, LEDBaseModule.GetModule(box.DeviceIp));
                    }
                    StatusMap.Add(box.PositionNum, -1); 
                }

                CID = ConfigAppSettings.GetValue(Setting_Init.Store_CID);
                BoxName = (" 单色灯料架_" + CID + " ").ToUpper();
                if (LEDManager.DeviceLedType.Equals(1) || LEDManager.DeviceLedType.Equals(2))
                {
                    BoxName = (" 三色灯料架_" + CID + " ").ToUpper();
                }
                LogUtil.info(BoxName + "加载完成!");

                Init();
                return true;
            }
            catch (Exception ex)
            {
                LogUtil.error(BoxName + "加载配置出错:" + ex.ToString());
            }
            return false;
        } 
        protected static void Init()
        {
            if (!isInit)
            {  
                timersTimer = new System.Timers.Timer();
                timersTimer.Enabled = false;
                timersTimer.Interval = 200;
                timersTimer.Elapsed += timersTimer_Elapsed;
                timersTimer.AutoReset = true;
                isInit = true; 
            }
        }

        public static bool StartRun()
        {
            ServerPort = ConfigAppSettings.GetIntValue(Setting_Init.ServerPort);
            LogUtil.info(LOGGER, BoxName + "开始启动:" + DateTime.Now.ToString() + "!");
            timersTimer.Enabled = true; 
            IsRun = true;
            LEDManager. OpenStatusLights("green");
            HttpServer.Start(ServerOnReceived, ServerPort);
            LogUtil.info("启动服务完成,ServerPort【" + ServerPort + "】");
            return true;
        } 

        public static void StopRun()
        { 
           //关闭串口
            timersTimer.Enabled = false; 
            foreach(LEDBaseModule led in LEDManager.deviceMap.Values)
            {
                led.AllLightOff();
            }
           LEDManager.CloseStatusLights();
            HttpServer.Stop();
            IsRun = false;
            LogUtil.info(LOGGER, BoxName + "停止运行,时间" + DateTime.Now.ToShortTimeString() + "!");
        }
     
        protected static void timersTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                //判断是否需要亮黄灯
                List<string> openLeds = new List<string>();
                foreach (string key in StatusMap.Keys)
                {
                    if (StatusMap[key].Equals(1))
                    {
                        openLeds.Add(key);
                    }
                }
                if (openLeds.Count > 0)
                {
                    if (!LEDManager.CurrLedStatus.Equals(2))
                    {
                        LEDManager.OpenStatusLights("green");
                    }
                }
                else
                {
                    if (!LEDManager.CurrLedStatus.Equals(1))
                    {
                        LEDManager.OpenStatusLights("yellow");
                    }
                }
                 
            }
            catch (Exception ex)
            {
                LogUtil.error("timersTimer_Elapsed出错:" + ex.ToString());
            } 
        }
        public static string Path_LedOn = "/rest/api/v1/shelf/posOn";
        public static string Path_LedOff = "/rest/api/v1/shelf/posOff";
        public static string Path_ledOnAll = "/rest/api/v1/shelf/allPosOn";
        public static string Path_ledOffAll = "/rest/api/v1/shelf/allPosOff";

        public static string Param_posId = "posId";
        public static char PosId_SpiltChar = ';';
        public static char PosId_Color_SpiltChar = '@';

        // 开灯:http:/localhost:80/rest/api/v1/shelf/posOn?posId=1_3_1@green;1_3_2@green;1_3_7@red
        // 关灯:http:/localhost:80/rest/api/v1/shelf/posOff?posId=1_3_1;1_3_2;1_3_4
        //关闭所有:http:/localhost:80/rest/api/v1/shelf/allPosOn
        //打开所有:http:/localhost:80/rest/api/v1/shelf/allPosOff
        private static  string ServerOnReceived(string reqPath, string paramStr)
        {
            try
            {
                Dictionary<string, string> paramMap = GetParam(paramStr);
                string msg = ": conot find param " + Param_posId ; 
                if (reqPath.Equals(Path_LedOn))
                { 
                    if (paramMap.ContainsKey(Param_posId))
                    {
                        string pos = paramMap[Param_posId];
                        bool result = ProcessOpenLed(pos);
                        return GetResult(result, "posOn");
                    }
                    else
                    {
                        return GetResult(false, "posOn")+ msg;
                    }
                }
                else if (reqPath.Equals(Path_LedOff))
                { 
                    if (paramMap.ContainsKey(Param_posId))
                    {
                        string pos = paramMap[Param_posId];
                        bool result = ProcessCloseLed(pos);
                        return GetResult(result, "posOff");
                    }
                    else
                    {
                        return GetResult(false, "posOff") + msg;
                    }
                }
                else if (reqPath.Equals(Path_ledOnAll))
                {
                    bool result = ProcessOpenAll();
                    return GetResult(result, "allPosOn");
                }
                else if (reqPath.Equals(Path_ledOffAll))
                { 
                    bool result = ProcessCloseAll();
                    return GetResult(result, "allPosOff");
                }
                else
                {
                    LogUtil.info("[" + reqPath + "]没有相关处理");
                    return "[" + reqPath + "]没有相关处理";
                }
                return "OK";
            }
            catch (Exception ex)
            {
                LogUtil.info("[" + reqPath + "][" + paramStr + "]处理错误:" + ex.ToString());
                return "Error";
            }
        }
        private static Dictionary<string, string> GetParam(string paramStr)
        {
            Dictionary<string, string> paramMap = new Dictionary<string, string>();

            try
            {
                string[] paramArray = paramStr.Split('&');
                foreach (string param in paramArray)
                {
                    string[] data = param.Split('=');
                    if (data.Length == 2)
                    {
                        string paramName = data[0];
                        string paramValue = data[1];
                        //LogUtil.info("解析参数【"+paramStr+"】 : ["+paramName+"]["+paramValue+"]");
                        paramMap.Add(paramName, paramValue);
                    }
                }
            }
            catch (Exception ex)
            {
                LogUtil.error("解析参数【" + paramStr + "】出错:" + ex.ToString());
            }
            return paramMap;
        }


        private static string  GetResult(bool result, string op)
        {
            if (result)
            {
                return op + " OK";
            }
            else
            {
                return op + " FAIL";
            }
        }

        public static string StrMsg = "";


        public static bool ProcessOpenAll(string proMsg = "Revice ", string ip = "")
        {
            LogUtil.info(BoxName + proMsg + " closeAll命令:");
            List<string> posIdList = new List<string>(PositionMap.Keys);
            foreach (LEDBaseModule led in LEDManager.deviceMap.Values)
            {
                if (String.IsNullOrEmpty(ip) || led.ModuleIP.Equals(ip))
                {
                    led.AllLightOn();
                }
            }
            foreach (string key in posIdList)
            {
                string pIP = "";
                if (PositionMap.ContainsKey(key))
                {
                    pIP = PositionMap[key].DeviceIp;
                }
                if (String.IsNullOrEmpty(ip) || pIP.Equals(ip))
                {
                    StatusMap[key] = 1;
                }
            }
            return true;
        }
        public static bool ProcessCloseAll(string proMsg= "Revice ", string ip = "")
        {
            LogUtil.info(BoxName + proMsg+ " closeAll命令:" );
            List<string> posIdList = new List<string>(PositionMap.Keys);
            foreach(LEDBaseModule led in LEDManager.deviceMap.Values)
            {
                if (String.IsNullOrEmpty(ip) || led.ModuleIP.Equals(ip))
                {
                    led.AllLightOff();
                }
            }
            foreach (string key in posIdList)
            {
                string pIP = "";
                if (PositionMap.ContainsKey(key))
                {
                    pIP = PositionMap[key].DeviceIp;
                }
                if (String.IsNullOrEmpty(ip) || pIP.Equals(ip))
                {
                    StatusMap[key] = 0;
                }
            }
            return true;
        }
      
        public static bool  ProcessOpenLed(string posids, string proMsg = "Revice ")
        {
            LogUtil.info(BoxName + proMsg + " open命令:" + posids);
            string[] posArray = posids.Split(PosId_SpiltChar);
           
            foreach (string posStr in posArray)
            { 
                string posid = posStr;
                string color = "Green";
                if (posStr.Contains(PosId_Color_SpiltChar))
                {
                    string[] posInfos = posStr.Split(PosId_Color_SpiltChar);
                    posid = posInfos[0];
                    color = posInfos[1]; 
                }
                color = color.ToLower();
                if (PositionMap.ContainsKey(posid))
                { 
                    BoxPosition position = PositionMap[posid];
                    Light[] lights = Light.GetLights(position.DmxId, color, position.GetLedList().ToArray());
                    LEDManager.GetLedModule(position.DeviceIp).LightOn(lights);
                    StatusMap[posid] = 1;
                }
                else
                {
                    if (posid.ToLower().Equals("statuslight"))
                    {
                        LogUtil.info("状态灯指令:" + posid + "=" + color);
                    }
                    else
                    {
                        LogUtil.error(BoxName + "打开灯失败,未找到库位号:" + posid);
                    }
                }
            }
            return true;
        }
         
         
        public static bool  ProcessCloseLed(string posids, string proMsg = "Revice ")
        {
            LogUtil.info(BoxName + proMsg + " close命令:" + posids);
            string[] posArray = posids.Split(PosId_SpiltChar);
            foreach (string posid in posArray)
            {

                string posName = posid;
                if (posid.Contains(PosId_Color_SpiltChar))
                {
                    posName = posid.Split(PosId_Color_SpiltChar)[0];
                }

                if (PositionMap.ContainsKey(posName))
                {
                    BoxPosition position = PositionMap[posName];
                    LEDManager.GetLedModule(position.DeviceIp).LightOff(Light.GetLights(position.DmxId,position.GetLedList(),0) ); 
                    StatusMap[posName] = 0;
                }
                else
                {
                    LogUtil.error(BoxName + "关闭灯败,未找到库位号:" + posName);
                }
            }
            return true;
        }
         
    }
}