VStoreCollection.cs 11.5 KB
using log4net;
using Newtonsoft.Json;
using OnlineStore.Common;
using RtTower.WebService.ComTowerApp.Contract;
using RtTower.WebService.SharedService;
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;

namespace DeviceLibrary
{
    public class VStoreCollection
    {
        
        MydataWcfServiceTest.ServiceReference2.TowerAppWSClient towerAppWSClient;
        ServiceHost Host = null;
        public VLog VLog = new VLog();
        public string StoreServerURL;
        public static Dictionary<string, VStore> VStoreList = new Dictionary<string, VStore>();
        public VStoreCollection() {
            
            StoreServerURL = Setting_Init.Device_StoreServerURL;
            service.OnCommand += Service_OnCommand;
            StartService();

            if(!string.IsNullOrEmpty(Setting_Init.Runtime_OutStoreReelInfo))
                OutStoreReelInfo = JsonConvert.DeserializeObject<Dictionary<string, JobInfo>>(Setting_Init.Runtime_OutStoreReelInfo);

            BasicHttpBinding binding = new BasicHttpBinding();
            binding.MaxReceivedMessageSize = 1073741824;
            binding.MaxBufferSize = 1073741824;
            binding.MaxBufferPoolSize = 5242880;
            binding.AllowCookies = false;
            Uri baseAddress = new Uri(StoreServerURL);
            EndpointAddress endpointAddress = new EndpointAddress(baseAddress.ToString());
            towerAppWSClient = new MydataWcfServiceTest.ServiceReference2.TowerAppWSClient(binding, endpointAddress);
            //TowerList.List.Add("123132", new TowerInfo() { TowerID = "13123", TowerName = "asdasd" });
            //TowerList.SaveTowerInfo();
            TowerList.List.Values.ToList().ForEach(s =>
            {
                VLog.Info("加载RT料仓:" + s.TowerID);
                VStore vStore = new VStore(s,this);
                VStoreList[s.TowerID] = vStore;
            });
        }

        private void Service_OnCommand(object sender, string xmlString)
        {
           var cmd= XmlCommandSerializer.DeserializeCommand(xmlString);
            switch (cmd.Command) {
                case "NotifyCarrierLoad":
                    // put in your code here
                    var r = XElement.Parse(cmd.Parameter);
                    var reelid = r.Descendants("Barcode").FirstOrDefault().Value;
                    var towerid = r.Descendants("TowerId").FirstOrDefault().Value;
                    VLog.Info("收到入库完成通知:" + $"ReelID:{reelid},TowerID:{towerid}");
                    if (!VStoreList.ContainsKey(towerid))
                    {
                        VLog.Error("收到入库信息,但没有找到该料仓id");
                    }else
                        VStoreList[towerid].InStoreEnd(reelid);
                    break;
                case "NotifyCarrierUnload":
                    // put in your code here
                    r = XElement.Parse(cmd.Parameter);
                    reelid = r.Descendants("Barcode").FirstOrDefault().Value;
                    towerid = r.Descendants("TowerId").FirstOrDefault().Value;                   
                    VLog.Info("收到出库完成通知:" + $"ReelID:{reelid},TowerID:{towerid}");
                    if (!VStoreList.ContainsKey(towerid)) {
                        VLog.Error("收到出库信息,但没有找到该料仓id");
                    }
                    else
                        VStoreList[towerid].OutStoreEnd(reelid);
                    //VStoreList[towerid].ReelPutOnOutSide(reelid);
                    break;

            }
        }
        Thread td;
        public void Start() {
            td = new Thread(new ThreadStart(Run));
            td.Start();
        }
        bool mstate = false;
        void Run() {
            mstate = true;
            while (mstate) {
                Thread.Sleep(1000);
                VStoreList.Values.ToList().ForEach(vs=>
                {
                    try
                    {
                        MsgService.MSList["RT-" + vs.CID].clear();
                        vs.VTowerProcess();
                    }
                    finally {
                        MsgService.MSList["RT-" + vs.CID].Show();
                    }
                });
            }
            VLog.Info("RT料仓退出主循环");
        }

        public bool SendCommand(string command,bool needlog, out string msg,params string[] arg) {
            string errmsg;
            try
            {
                XmlDocument xd = new XmlDocument();
                command = string.Format(command, arg);
                xd.LoadXml(command);
            }
            catch (Exception ex)
            {
                errmsg = "Command format error:\r\n" + ex.ToString();
                msg = errmsg;
                return false;
            }

            try
            {
                if (needlog)
                    VLog.Info("send: " + command);
                //string command = textBox_sendcommand.Text;
                try
                {
                    var re = towerAppWSClient.XmlAction(command);
                    msg = re.ToString();
                    return true;
                    //errmsg = "Request sent successfully.";

                }
                catch (Exception ex)
                {
                    errmsg = "Failed to send request."+ ex;
                    msg = errmsg;
                    return false;
                }
            }
            catch (Exception ex)
            {
                errmsg = "Error: " + ex.ToString();
                msg = errmsg;
            }
            return false;
        }
        /*
10001 UnknownTower
10002 no Towers to list
10003 no ProductionSite to list
10010 no Articles to list
10011 Article not found
10012 Article aready exists
10013 Article not deleted
10020 no Carriers to list
10021 Carrier not found
10022 Carrier alredy exists
10023 Carrier already in Tower
10041 JobList not found
10042 JobList creation Error
10043 Joblist creation Warning
         */
        public TowerDetailInformation GetTowerDetailInformation(string CID) {
            if (!SendCommand(VCmd.GetTowerInformation,false, out string data, CID))
            {
                VLog.Error(data);
                return null;
            }
            var result = XmlCommandSerializer.DeserializeResult(data);
            if (result.Errorcode != 0) {
                VLog.Error(data);
                return null;
            }
            return XmlCommandSerializer.DeserializeTowerDetailInformation(result.Data);
        }
        public static Dictionary<string, JobInfo> OutStoreReelInfo = new Dictionary<string,JobInfo>();
        public bool BeginOutStore(JobInfo jobInfo, VLog vLog)
        {
            if (!SendCommand(VCmd.GetCarrierInformation, true, out string data, jobInfo.WareNum))
            {
                vLog.Error(data);
                return false;
            }
            var result = XmlCommandSerializer.DeserializeResult(data);
            if (result.Errorcode != 0)
            {
                vLog.Error(data);
                return false;
            }
            var reelinfo = XmlCommandSerializer.DeserializeCarrierInformation(result.Data);
            lock (OutStoreReelInfo) {
                OutStoreReelInfo[jobInfo.WareNum] = new JobInfo(jobInfo.WareNum,"", reelinfo.Diameter, reelinfo.Height);
                Setting_Init.Runtime_OutStoreReelInfo = JsonConvert.SerializeObject(OutStoreReelInfo);
            }
            vLog.Info("出库时获取到料盘数据:"+ OutStoreReelInfo[jobInfo.WareNum].ToStr());
            if (!SendCommand(VCmd.UnloadCarrier,true, out data, jobInfo.WareNum))
            {
                vLog.Error(data);
                return false;
            }
             result = XmlCommandSerializer.DeserializeResult(data);
            if (result.Errorcode != 0)
            {
                vLog.Error(data);
                return false;
            }
            return true;
        }
        public bool BeginInStore(string towerid,JobInfo jobInfo,VLog vLog)
        {
            if (!SendCommand(VCmd.SimulateStartButton, true,out string data, towerid, jobInfo.WareNum))
            {
                vLog.Error(data);
                return false;
            }
            var result = XmlCommandSerializer.DeserializeResult(data);
            if (result.Errorcode != 0)
            {
                vLog.Error(data);
                return false;
            }
            return true;
        }
        RtTowerClientService.Service service = new RtTowerClientService.Service();
        void StartService()
        {
            try
            {
                VLog.Info("start service");
                var uri = new Uri("http://localhost:" + 8686 + "/RtTowerClientService");
                VLog.Info(uri.ToString());
                Host = new ServiceHost(service, uri);
                Host.UnknownMessageReceived += Host_UnknownMessageReceived;
                //绑定
                System.ServiceModel.Channels.Binding httpBinding = new BasicHttpBinding();
                //终结点
                Host.AddServiceEndpoint(typeof(RtTowerClientService.IRtTowerClientService), httpBinding, uri);
                //Host.Open();
                if (Host.Description.Behaviors.Find<System.ServiceModel.Description.ServiceMetadataBehavior>() == null)
                {
                    //行为
                    ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
                    behavior.HttpGetEnabled = true;

                    ////元数据地址
                    //behavior.HttpGetUrl = new Uri("http://localhost:18002/Service");
                    Host.Description.Behaviors.Add(behavior);

                }
                var serviceDebugBehavior = Host.Description.Behaviors.Find<ServiceDebugBehavior>();
                serviceDebugBehavior.HttpHelpPageEnabled = true;
                serviceDebugBehavior.IncludeExceptionDetailInFaults = true;
                //启动
                Host.Open();
                //linkLabel1.Text = uri.ToString();
                VLog.Info("start service success");
                //btn_start.Enabled = false;
                //btn_end.Enabled = true;
                //label_service_state.Text = Host.State.ToString();
            }
            catch (Exception ex)
            {
                VLog.Error(ex.ToString());
                //MessageBox.Show(ex.ToString());
            }
        }

        internal void Stop()
        {
            mstate = false;
        }

        internal void ShutDown()
        {
            StopService();
        }

        private void Host_UnknownMessageReceived(object sender, UnknownMessageReceivedEventArgs e)
        {
            try
            {
                VLog.Info("Host_UnknownMessageReceived:");
                VLog.Info(e.Message.ToString());
                VLog.Info(e.Message.GetReaderAtBodyContents().ToString());
            }
            catch (Exception ex)
            {
                VLog.Error(ex.ToString());
                //MessageBox.Show(ex.ToString());
            }
        }

        void StopService()
        {
            if (Host != null && Host.State == CommunicationState.Opened)
            {
                Host.Close();
                //label_service_state.Text = Host.State.ToString();
                Host = null;
            }
            VLog.Info("stop service success");
        }
        
    }
}