VStoreCollection.cs 12.1 KB
using Newtonsoft.Json;
using OnlineStore.Common;
using RemoteSheardObject;
using RtTower.WebService.SharedService;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
using static RemoteSheardObject.TheLine;

namespace DeviceLibrary
{
    public class VStoreCollection
    {


        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);

            //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;
            });
            UploadCarrierInformationData();
        }

        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}");
                    VStoreList[towerid].log("收到入库完成通知:" + $"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}");
                    VStoreList[towerid].log("收到出库完成通知:" + $"ReelID:{reelid},TowerID:{towerid}");
                    if (!VStoreList.ContainsKey(towerid))
                    {
                        VLog.Error("收到出库信息,但没有找到该料仓id");
                    }
                    else
                        VStoreList[towerid].OutStoreEnd(reelid, towerid);
                    //VStoreList[towerid].ReelPutOnOutSide(reelid);
                    break;

            }
        }
        Thread td;
        public void Start()
        {
            td = new Thread(new ThreadStart(Run));
            td.Start();
        }
        bool mstate = false;

        DateTime LastQueryCarrierListTime = DateTime.MinValue;
        void Run()
        {
            mstate = true;
            while (mstate)
            {
                Thread.Sleep(1000);
                VStoreList.Values.ToList().ForEach(vs =>
                {
                    try
                    {
                        MsgService.MSList["RT-" + vs.CID].clear();
                        vs.VTowerProcess();
                    }
                    catch (Exception ex)
                    {
                        VLog.Error("VTowerProcess error:" + ex);
                    }
                    finally
                    {
                        MsgService.MSList["RT-" + vs.CID].Show();
                    }
                });

                if ((DateTime.Now - LastQueryCarrierListTime).TotalHours > 1)
                {
                    LastQueryCarrierListTime = DateTime.Now;
                    Task.Run(() => { GetCarrierList(); });
                }
            }
            VLog.Info("RT料仓退出主循环");
        }

        public static Dictionary<string, JobInfo> OutStoreReelInfo = new Dictionary<string, JobInfo>();

        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.Error("Host_UnknownMessageReceived:");
                VLog.Error(e.Message.ToString());
                //VLog.Error(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");
        }

        public async void GetCarrierList()
        {
            try
            {
                BasicHttpBinding binding = new BasicHttpBinding();
                binding.MaxReceivedMessageSize = 1073741824;
                binding.MaxBufferSize = 1073741824;
                binding.MaxBufferPoolSize = 5242880;
                binding.AllowCookies = false;
                binding.OpenTimeout = TimeSpan.FromMinutes(5);
                binding.CloseTimeout = TimeSpan.FromMinutes(5);
                binding.SendTimeout = TimeSpan.FromMinutes(5);
                binding.ReceiveTimeout = TimeSpan.FromMinutes(10);
                Uri baseAddress = new Uri(Setting_Init.Device_StoreServerURL);
                EndpointAddress endpointAddress = new EndpointAddress(baseAddress.ToString());
                var towerAppWSClient = new MydataWcfServiceTest.ServiceReference3.WSInterfaceClient(binding, endpointAddress);
                VLog.Info("开始查询 CarrierList");
                var result = await towerAppWSClient.XmlActionAsync(VCmd.GetCarrierList);
                VLog.Info("结束查询 CarrierList");
                File.WriteAllText("logs\\CarrierList.xml", result.ToString());
                towerAppWSClient.Close();
                towerAppWSClient = null;
                UploadCarrierInformationData();
            }
            catch (Exception ex)
            {
                VLog.Error("GetCarrierList:" + ex.ToString());
            }
        }
        Dictionary<string, List<string>> SNList;
        Dictionary<string, string> SNFullList;

        public void UploadCarrierInformationData()
        {
            lock (this)
            {
                SNList = new Dictionary<string, List<string>>();
                SNFullList = new Dictionary<string, string>();
                var cril = new List<CarrierInformationData>();
                try
                {
                    XmlDocument xml = new XmlDocument();
                    xml.Load("logs\\CarrierList.xml");
                    var en = xml.SelectSingleNode("/XmlResult/Errorcode");
                    if (en.InnerText != "0")
                        return;
                    var crl = xml.SelectNodes("/XmlResult/Data/ArrayOfCarrierInformation/CarrierInformation");
                    foreach (XmlNode cr in crl)
                    {
                        var ci = new CarrierInformationData();
                        var Depot = cr.SelectSingleNode("Depot");
                        if (Depot == null)
                        {
                            continue;
                        }
                        var carrier = cr.SelectSingleNode("Carrier").InnerText;

                        ci.carrier = AddToSNList(carrier);
                        //ci.partnumber = cr.SelectSingleNode("Carrier").InnerText;
                        ci.depot = cr.SelectSingleNode("Depot").InnerText;
                        ci.ArticleName = cr.SelectSingleNode("ArticleName").InnerText;
                        ci.Stock = int.Parse(cr.SelectSingleNode("Stock").InnerText);
                        ci.diameter = int.Parse(cr.SelectSingleNode("Diameter").InnerText);
                        ci.height = int.Parse(cr.SelectSingleNode("Height").InnerText);

                        SNFullList.Add(ci.carrier, $"P{ci.ArticleName}#S{ci.carrier}#{ci.Stock}#");
                        cril.Add(ci);
                    }
                    TheLine.UploadCarrierInformation(cril);
                    VLog.Info("上传库位信息:" + cril.Count);
                }
                catch (Exception ex)
                {
                    VLog.Error("上传库位信息失败:" + ex);
                }
            }
        }
        public string GetSNFullString(string sn)
        {
            lock (this)
            {
                return SNFullList.ContainsKey(sn) ? SNFullList[sn] : sn;
            }
        }
        string AddToSNList(string carrierstring)
        {
            var carrier = carrierstring;
            var carriers = carrierstring.Split('#');
            if (carriers.Count() >= 2)
            {
                carrier = carriers[1];
            }

            if (SNList.ContainsKey(carrier))
            {
                if (!SNList[carrier].Contains(carrierstring))
                    SNList[carrier].Add(carrierstring);
            }
            else
            {
                SNList.Add(carrier, new List<string>() { carrierstring });
            }
            return carrier;
        }
    }
}