BOXManager.cs 13.2 KB
using log4net;
using SmartShelf.Common;

using SmartShelf.LoadCSVLibrary;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using System.Windows.Forms;

namespace SmartShelf.DeviceLibrary
{
    /// <summary>
    /// 流水线自动料仓-流水线类
    /// </summary>
    public class BOXManager
    {
        private static readonly ILog LOGGER = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
     
        public static BOX_Config Config = null;
        public static string CID = ""; 
        public static string BoxName = "";
        private static System.Timers.Timer timersTimer; 
        private static System.Timers.Timer serverConTimer = new System.Timers.Timer();
        private static bool isInit = false;
        public static string WarnMsg = "";
        public static Dictionary<string, BoxPosition> PositionMap=null;
        public static int BoxCount = 1;
        /// <summary>
        /// 门状态列表,-1=未知,1=打开,0=关闭
        /// </summary>
        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))
                    {
                        //LEDSingleModule led = new LEDSingleModule(box.DeviceIp);

                        //led.AllLightOn(Light.BlueLight(1));
                        LEDManager.deviceMap.Add(box.DeviceIp, LEDBaseModule.GetModule(box.DeviceIp));

                    }
                    StatusMap.Add(box.PositionNum, -1);
                }

                CID = ConfigAppSettings.GetValue(Setting_Init.Store_CID);
                BoxName = (" 料架_" + CID + " ").ToUpper();
                string filePath = appPath + ConfigAppSettings.GetValue(Setting_Init.Store_ConfigPath);
                Config = (BOX_Config)CSVConfigReader.LoadConfig(1, CID, StoreType.RC_PLC_SM, filePath);
                if (Config == null)
                {
                    return false;
                }
                
                LogUtil.info(LOGGER, "加载料架完成!");
                 
                Init();
                return true;
            } catch (Exception ex)
            {
                LogUtil.error("加载料架配置出错:" + ex.ToString());
            } return false;
        }

        /// <summary>
        /// 初始化
        /// </summary>
        protected static void Init()
        {
            if (!isInit)
            {
                serverConTimer = new System.Timers.Timer();
                serverConTimer.Enabled = false;
                serverConTimer.Interval = 600;
                serverConTimer.Elapsed += server_connect_timer_Tick;
                serverConTimer.AutoReset = true;

                timersTimer = new System.Timers.Timer();
                timersTimer.Enabled = false;
                timersTimer.Interval = 600;
                timersTimer.Elapsed += timersTimer_Elapsed;
                timersTimer.AutoReset = true;
                isInit = true;
            }
        }

        public static bool StartRun()
        { 
            LogUtil.info(LOGGER, BoxName + "启动成功,时间:" + DateTime.Now.ToString() + "!");
            timersTimer.Enabled = true;
            serverConTimer.Enabled = true;
            IsRun = true;
            LEDManager. OpenSGreenLed();
            return true;
        }

        private static void RFID_RW_ReadEvent(string cardNum, string cardValue)
        {
            if (!String.IsNullOrEmpty(cardNum))
            {
                LastCardValue = cardNum + "-" + cardValue;
            }
        }

        public static void StopRun()
        { 
           //关闭串口
            timersTimer.Enabled = false;
            serverConTimer.Enabled = false;
            foreach(LEDBaseModule led in LEDManager.deviceMap.Values)
            {
                led.AllLightOff();
            }
           LEDManager.CloseSLed();
            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.OpenSYellowLed();
                    }
                }
                else
                {
                    if (!LEDManager.CurrLedStatus.Equals(1))
                    {
                        LEDManager.OpenSGreenLed();
                    }
                }
            }
            catch (Exception ex)
            {
                LogUtil.error("timersTimer_Elapsed出错:" + ex.ToString());
            } 
        }

        #region 与服务器通信定时器,每1秒向服务器通知一次状态,同时执行出库操作
         
        private static bool isInProcess = false;
        private static void server_connect_timer_Tick(object sender, EventArgs e)
        {
         
            if (isInProcess)
            {
                return;
            }
            isInProcess = true;
            try
            {
                SendInOutPosId();
            }catch(Exception ex)
            {
                LogUtil.error("server_connect_timer_Tick 出错:" + ex.ToString());
            }
            isInProcess = false;
        }
        private static string LastCardResult = "";
        private static string LastCardValue = "";

        public static string StrMsg = "";

        public static void SendInOutPosId()
        {
            StrMsg = "";
               //构建发送给服务器的对象
               Operation lineOperation = ServerManager.GetLineBoxStatus();
            //获取亮灯的库位
            string posId = "";
            foreach(string key in StatusMap.Keys)
            {
                if (StatusMap[key].Equals(1))
                {
                    posId = posId + key + "|";
                }
            }
            if (String.IsNullOrEmpty(posId).Equals(false))
            {
                lineOperation.data.Add(ParamDefine.posOpened, posId);
                LastCardResult = "";
            }
          
            foreach(string str in lineOperation.data.Keys)
            {
                StrMsg += "[" + str + "=" + lineOperation.data[str] + "]\r\n";
            }
            string server = ConfigAppSettings.GetValue(Setting_Init.http_server);
            Operation resultOperation = HttpHelper.Post(ServerManager.GetPostApi(server), lineOperation, false);

            if (resultOperation == null || resultOperation.data == null)
            {
                //判断服务端是否返回出库操作
                return;
            }

            // 开灯: key为open value为库位信息,如果多个用 | 分割
            //客户端发送
            //当前灯的状态:key为posOpened value为当前亮灯的库位,如果多个用 | 分割
            //卡信息: key为card value为读取到的卡内容,卡号 - 内容
            //写卡:
            //key = writeCard  value为要写的内容
            //  key = cardResult    value = OK表示写成功
            if (resultOperation.data.ContainsKey(ParamDefine.open))
            {
                ProcessOpenDoor(resultOperation.data[ParamDefine.open]);

            }

            if (resultOperation.data.ContainsKey(ParamDefine.close))
            {
                ProcessCloseDoor(resultOperation.data[ParamDefine.close]);
            }

            if (resultOperation.data.ContainsKey(ParamDefine.closeAll))
            {
                ProcessCloseAll();
            }
        }
        public static void 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;
                }
            }
        }
        public static void 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;
                }
            }
        }
        public static void ProcessOpenDoor(string posids, string proMsg = "Revice ")
        {
            LogUtil.info(BoxName + proMsg + " open命令:" + posids);
            string[] posArray = posids.Split('|');
            foreach (string posid in posArray)
            {
                string posName = posid;
                if (posid.Contains("="))
                {
                    posName = posid.Split('=')[0]; 
                }
                if (PositionMap.ContainsKey(posName))
                {
                    BoxPosition position = PositionMap[posName];
                    LEDManager.GetLedModule(position.DeviceIp).LightOn(Light.GetLights(position.DmxId, position.GetLedList()));

                    StatusMap[posName] = 1;
                }
                else
                {
                    LogUtil.error(BoxName + "打开门锁失败,未找到库位号:" + posName);
                }
            }
        }
        public static void ProcessCloseDoor(string posids, string proMsg = "Revice ")
        {
            LogUtil.info(BoxName + proMsg + " close命令:" + posids);
            string[] posArray = posids.Split('|');
            foreach (string posid in posArray)
            {

                string posName = posid;
                if (posid.Contains("="))
                {
                    posName = posid.Split('=')[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);
                }
            }
        }


        #endregion

     
    }
}