MainWindow.xaml.cs 11.9 KB
using DMSkin.Core;

using HH_WCS_Standard.Service.Comm;

using HslCommunication.LogNet;

using System;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;

namespace HH_WCS_Standard
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow
    {
        private WcsWebApiBuild wcsWebApiBuild = new WcsWebApiBuild();
        private System.Timers.Timer taskTimer = new System.Timers.Timer();
        private bool stop_Tasktimer = true;
        private BaseBll _bll = new BaseBll();
        private SerialPortHelper SerialPort = new SerialPortHelper();
        System.Threading.Mutex mutex;

        public MainWindow()
        {
            InitializeComponent();
        }

        private void DMSkinWindow_Loaded(object sender, RoutedEventArgs e)
        {
            //CreateTable createTable = new CreateTable();
            //createTable.Main();
            //return;
            CheckExe();
            LogExecute.logNet.BeforeSaveToFile += LogNet_BeforeSaveToFile;
            LogExecute.SrmlogNet.BeforeSaveToFile += LogNet_BeforeSaveToFile;
            LogExecute.ApilogNet.BeforeSaveToFile += LogNet_BeforeSaveToFile;
            MessageList.ItemsSource = App.MessageList;
            Frame.Content = new TaskView();

           
            var buildDevice = InitBll.BuildInit();
            if (!buildDevice.Success)
            {
                MessageBox.Show(buildDevice.Msg);
                Environment.Exit(0);
            }
            var buildService = BuildService();
            if (!buildService.Success)
            {
                MessageBox.Show(buildService.Msg);
                Environment.Exit(0);
            }

            #region 称重数据
            //var buildWeight = BuildWeight();
            //if (!buildWeight.Success)
            //{
            //    MessageBox.Show(buildWeight.Msg);
            //    Environment.Exit(0);
            //}
        }
        //private BllResult BuildWeight()
        //{
        //    //获取系统com 口
        //    if (SerialPort.PortNames.Length == 0)
        //    {
        //        LogExecute.logNet.WriteError($"操作系统端口未打开,请检查端口是否可用");
        //        return BllResult.Error("操作系统端口未打开,请检查端口是否可用");
        //    }
        //    SerialPort.serialPort.PortName = SerialPort.PortNames[0];
        //    if (!SerialPort.serialPort.IsOpen)
        //    {
        //        SerialPort.serialPort.Open();
        //    }
        //    //事件委托:将接收数据的的方法与接收事件关联
        //    SerialPort.serialPort.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(this.DataRev);
        //    return BllResult.Sucess();
        //}
        private void DataRev(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            try
            {
                Thread.Sleep(200);
                int Counts = SerialPort.serialPort.BytesToRead;
                Byte[] byteData = new byte[Counts];
                SerialPort.serialPort.Read(byteData, 0, Counts);
                string value = Encoding.Default.GetString(byteData).Replace("S", "").Replace("k", "").Replace("g", "").Replace("D", "").Replace(" ", "").Replace("\r\n", "");
                int index = value.IndexOf(".");
                string WeightValue = value.Substring(0, index + 2);
                App.WeightValue = WeightValue;
                //LogExecute.logNet.WriteDebug($"重量:{WeightValue}");
            }
            catch (Exception ex)
            {
                LogExecute.logNet.WriteError($"接收数据出现异常,异常原因是{ex.Message}");
            }
        }

        #endregion
        private BllResult BuildService()
        {
            //[1]线程启动
            foreach (I_Excute i_Excute in App.i_Excutes)
            {
                Thread thread = new Thread(Build);
                thread.Start(i_Excute);
            }
            //[2]web接口配置启动
            Task task = Task.Run(() => wcsWebApiBuild.Build());
            //[3]启动定时器,处理固定任务
            TaskTimer();
            //[4]推送
            WcsPushBuild.WcsPushBuildInit();
            return BllResult.Sucess();
        }

        private void Build(object obj)
        {
            I_Excute i_Excute = (I_Excute)obj;
            while (true)
            {
                string name = i_Excute.f_service.device.Name;
                try
                {
                    var connect = i_Excute.f_service.i_OpcHelp.OpenConn();
                    if (!connect.Success)
                    {
                        LogExecute.logNet.WriteError($"{name}建立S7连接失败,请检查网络配置");
                        i_Excute.f_service.vM_WriteModel.LatTime = DateTime.Now;
                        continue;
                    }
                    var result = i_Excute.GetAllAddress();
                    if (!result.Success)
                    {
                        LogExecute.logNet.WriteError($"{name}读取地址处理错误:处理停止,请检查网络配置");
                        continue;
                    }
                    i_Excute.Excute();
                    continue;
                }
                catch (Exception ex)
                {
                    LogExecute.logNet.WriteError($"{name}发生错误:处理停止,错误原因是{ex.Message},请检查网络配置");
                }
                finally
                {
                    Thread.Sleep(1000);
                }
            }
        }

        private void TaskTimer()
        {
            //开启一个定时器,定时去执行任务。
            taskTimer.Interval = 5000; //间隔时间
            taskTimer.Elapsed += TaskTimer_Elapsed;
            taskTimer.AutoReset = true;
            taskTimer.Enabled = true;
        }

        private void TaskTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            lock (new object())
            {
                if (stop_Tasktimer)
                {
                    try
                    {
                        stop_Tasktimer = false;
                        //Stopwatch stopwatch = new Stopwatch();
                        //stopwatch.Restart();
                        _bll.FinishTask();
                    }
                    catch (Exception ex)
                    {
                        LogExecute.logNet.WriteError($"程序出现异常,错误原因是{ex.Message}");
                    }
                    finally
                    {
                        stop_Tasktimer = true;
                        Thread.Sleep(5000);
                    }
                }
            }
        }

        private static void LogNet_BeforeSaveToFile(object sender, HslEventArgs e)
        {
            UIExecute.Run(() =>
            {
                DateTime time = e.HslMessage.Time;//获取时间

                string text = e.HslMessage.Text;//日志文本
                if (App.MessageList.Count >= 30)
                {
                    App.MessageList.RemoveAt(0);
                }
                for (int i = App.MessageList.Count - 1; i >= 0; i--)
                {
                    var value = App.MessageList[i].Text;
                    var values = value.Split('|');
                    if (values.Count() > 0)
                    {
                        if (value.Replace(values[0] + "|", "") == text)
                        {
                            App.MessageList.RemoveAt(i);
                        }
                    }
                }
                TextBlock textBlock = new TextBlock();
                if (e.HslMessage.Degree == HslMessageDegree.ERROR)
                {
                    textBlock.Text = "[错误] " + time.ToString() + "|" + text;
                    textBlock.Background = Brushes.Red;
                }
                else if (e.HslMessage.Degree == HslMessageDegree.DEBUG)
                {
                    textBlock.Text = "[日志] " + time.ToString() + "|" + text;
                    textBlock.Background = Brushes.Green;
                }
                else if (e.HslMessage.Degree == HslMessageDegree.WARN)
                {
                    textBlock.Text = "[警告] " + time.ToString() + " | " + text;
                    textBlock.Background = Brushes.Yellow;
                }
                else
                {
                    textBlock.Text = "[未知] " + time.ToString() + " | " + text;
                }

                App.MessageList.Add(textBlock);
            });
        }

        /// <summary>
        /// 鼠标左键拖动事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            base.OnMouseLeftButtonDown(e);
            // 获取鼠标相对标题栏位置
            Point position = e.GetPosition(this);
            // 如果鼠标位置在标题栏内,允许拖动
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                if (position.X >= 0 && position.X < this.ActualWidth && position.Y >= 0 && position.Y < this.ActualHeight)
                {
                    this.DragMove();
                }
            }
        }

        /// <summary>
        /// 主程序窗口关闭提醒
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DMSkinWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (MessageBox.Show("请确认是否退出程序?\n 退出后将无法继续或者全部功能!", "警告", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
            {
                Environment.Exit(0);
            }
            else
            {
                e.Cancel = true;
            }
        }

        /// <summary>
        /// 主界面标签跳转
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RadioButton_Click(object sender, RoutedEventArgs e)
        {
            RadioButton radioButton = sender as RadioButton;
            if (radioButton.CommandParameter.ToString() == "TaskView")
            {
                Frame.Content = new TaskView();
            }
            else if (radioButton.CommandParameter.ToString() == "SrmView")
            {
                Frame.Content = new SrmView();
            }
            else if (radioButton.CommandParameter.ToString() == "StationView")
            {
                Frame.Content = new StationView();
            }
            else if (radioButton.CommandParameter.ToString() == "HandView")
            {
                Frame.Content = new HandView();
            }
            else if (radioButton.CommandParameter.ToString() == "Seeting")
            {
                Frame.Content = new DeviceView();
            }
            else if (radioButton.CommandParameter.ToString() == "TaskFlow")
            {
                Frame.Content = new TaskFlowView();
            }
            else if (radioButton.CommandParameter.ToString() == "PointStateView")
            {
                Frame.Content = new PointStateView();
            }
            else
            {
                Frame.Content = new TaskView();
            }
        }
        private void CheckExe()
        {
            bool ret;
            mutex = new System.Threading.Mutex(true, "ElectronicNeedleTherapySystem", out ret);
            if (!ret)
            {
                MessageBox.Show("已有一个WCS程序实例运行,请勿重新运行");
                Environment.Exit(0);
            }
        }

        private void MItem_ClearLog(object sender, RoutedEventArgs e)
        {
            App.MessageList.Clear();
        }
    }
}