| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466 | using System;using System.Collections.Generic;using System.Windows.Forms;using StandardLibrary;using UserSettings;using System.Drawing;using System.Diagnostics;using System.Threading;using static StandardLibrary.UserAccount;using System.IO;using HslCommunication.LogNet;using System.Data;using MainForm.FaForm;using System.Runtime.CompilerServices;using MainForm.ClassFile;using System.Threading.Tasks;using Newtonsoft.Json;using SqlSugar.Extensions;namespace MainForm{    public partial class Form_Main : Form    {        #region 变量        /// <summary>        /// 窗体字典与窗体        /// </summary>        Dictionary<Button, Form> m_dicForm = new Dictionary<Button, Form>();  // 窗体字典        Form m_currentForm = null;             // 当前窗体        public static Form_Home formHome;        private Form_Order formOrder;          // 订单维护窗体        public static Form_DevAlarm formDevAlarm;  // 设备运行情况窗体        private Form_Alarm formAlarm;          // 数据及报警查询窗体        public static Form_PLCDB formPLCDB;    // PLC点位维护窗体        private Form_Other formOther;          // 测试窗体        private Form_SystemSet formSystemSet;  // 设置页窗体        /// <summary>        /// 记录用户正在触发的按钮        /// </summary>        Button m_currentButton = null;        /// <summary>        /// 当前用户信息        /// </summary>        private UserAccount userAccount = new UserAccount();        /// <summary>        /// 当前用户角色        /// </summary>        string currentRole = "SuperAdmin";        /// <summary>        /// 是否可正常上传数据到MES(有2小时前的数据未上传则为2;正常为1)        /// </summary>        public static int IsNormal_MESServer = 0;        /// <summary>        /// 用于记录"运行日志"        /// </summary>        ILogNet logNet = new LogNetDateTime(GlobalContext.WorkLogDir, GenerateMode.ByEveryHour);        #endregion 变量        #region 窗体基础事件        public Form_Main()        {            InitializeComponent();            // 需要权限的按钮绑定权限控制事件            this.btnOrder.Click += new System.EventHandler(this.SwitchWnd);            this.Btn_DevAlarm.Click += new System.EventHandler(this.SwitchWnd);            this.button_Alarm.Click += new System.EventHandler(this.SwitchWnd);            this.btnPLCDB.Click += new System.EventHandler(this.SwitchWnd);            this.button_SystemSet.Click += new System.EventHandler(this.SwitchWnd);            this.button_Other.Click += new System.EventHandler(this.SwitchWnd);            this.button_Home.Click += new System.EventHandler(this.SwitchWnd);            //this.button_Other.Click += new System.EventHandler(this.SwitchWnd);        }        /// <summary>        /// 窗体加载事件        /// </summary>        /// <param name="sender"></param>        /// <param name="e"></param>        private void Form_Main_Load(object sender, EventArgs e)        {            try            {                #region 尝试关联启动“气密设备软件”(进程名QIMITest.exe)与“电测设备软件”(进程名MainForm.exe)。                Task.Run(() =>                {                    try                    {                        if (!ProcessHelper.CheckProcessActivityByProcessName("QIMITest"))  // 进程名QIMITest.exe                        {                            string pathStr1 = @"D:\MES\QIMIAPP\QIMITest.exe";                            if (FileIOHelper.ISExists_File(pathStr1))                                ProcessHelper.StartProcess(pathStr1);                        }                    }                    catch { }                    try                    {                        if (!ProcessHelper.CheckProcessActivityByProcessName("MainForm"))  // 进程名MainForm.exe                        {                            // 电测使用 ProcessHelper.StartProcess启动时页面UI异常,所以使用bat启动                            string pathStr2 = Application.StartupPath + @"\启动电测.bat";                            string pathStr3 = @"D:\MES\DianCeAPP\MainForm.exe";                            if (FileIOHelper.ISExists_File(pathStr2) && FileIOHelper.ISExists_File(pathStr3))                                ProcessHelper.StartProcess(pathStr2);                        }                    }                    catch { }                });                #endregion 尝试关联启动“气密设备软件”与“电测设备软件”                //初始化目录                if (!Directory.Exists(GlobalContext.DBDir)) Directory.CreateDirectory(GlobalContext.DBDir);    // 判断路径是否存在,不存在则创建路径                 if (!Directory.Exists(GlobalContext.ProcessDataDir)) Directory.CreateDirectory(GlobalContext.ProcessDataDir);    // 判断路径是否存在,不存在则创建路径                 if (!Directory.Exists(GlobalContext.OneCheckDataDir)) Directory.CreateDirectory(GlobalContext.OneCheckDataDir);  // 判断路径是否存在,不存在则创建路径                GlobalContext.UpdateData();                //创建窗体及事件                formOrder = new Form_Order();          // 订单维护窗体                formDevAlarm = new Form_DevAlarm();    // 设备运行情况窗体                formAlarm = new Form_Alarm();          // 数据及报警查询窗体                formPLCDB = new Form_PLCDB();          // PLC点位维护窗体                formOther = new Form_Other();          // 测试窗体                formSystemSet = new Form_SystemSet();  // 设置页窗体                formHome = new Form_Home();            // 首页窗体                userAccount.UserChangedEvent += new UserChangedHandler(ForUserChangeToUpdate);                // 改变用户时更新页面信息                userAccount.UserChangedEvent += new UserChangedHandler(formOrder.ForUserChangeToUpdate);      // 改变用户时更新页面信息                userAccount.UserChangedEvent += new UserChangedHandler(formPLCDB.ForUserChangeToUpdate);      // 改变用户时更新页面信息                userAccount.UserChangedEvent += new UserChangedHandler(formSystemSet.ForUserChangeToUpdate);  // 改变用户时更新页面信息                formHome.MessageEvent += new HomeMessageHandler(WriteWorkLog);            // 写入工作日志                formOrder.MessageEvent += new OrderMessageHandler(WriteWorkLog);          // 写入工作日志                formSystemSet.MessageEvent += new SystemSetMessageHandler(WriteWorkLog);  // 写入工作日志                formDevAlarm.MessageEvent += new AlarmMessageHandler(formHome.AddMessage);                formAlarm.MessageEvent += new AlarmMessageHandler(formHome.AddMessage);                formPLCDB.MessageEvent += new AlarmMessageHandler(formHome.AddMessage);                //formAlarm.SaveProcessDataEvent += new HomeSaveProcessDataHandler(formHome.SaveProcessDataByDB);     // 保存加工数据的事件                //formAlarm.SaveOneCheckDataEvent += new HomeSaveOneCheckDataHandler(formHome.SaveOneCheckDataByDB);  // 保存点检数据的事件                //formAlarm.SaveAlarmDataEvent += new HomeSaveAlarmDataHandler(formHome.SaveAlarmDataByDB);           // 保存报警数据的事件                this.Text += " - V" + Application.ProductVersion;  // 显示版本信息                // Btn_DevAlarm                m_dicForm.Add(btnOrder, formOrder);              // 将按钮与事件存到字典中                m_dicForm.Add(Btn_DevAlarm, formDevAlarm);       // 将按钮与事件存到字典中                m_dicForm.Add(button_Alarm, formAlarm);          // 将按钮与事件存到字典中                m_dicForm.Add(btnPLCDB, formPLCDB);              // 将按钮与事件存到字典中                m_dicForm.Add(button_SystemSet, formSystemSet);  // 将按钮与事件存到字典中                m_dicForm.Add(button_Home, formHome);            // 将按钮与事件存到字典中                m_dicForm.Add(button_Other, formOther);          // 将按钮与事件存到字典中                foreach (KeyValuePair<Button, Form> kp in m_dicForm)  // 设置窗体属性(无边框、嵌套、停靠)                {                    kp.Value.TopLevel = false;                    kp.Value.FormBorderStyle = FormBorderStyle.None;                    kp.Value.Parent = this.panelMain;                    kp.Value.Dock = DockStyle.Fill;                }                GlobalContext.UpdateData();                SQLHelper.DBInitWork();             // 初始化数据库                SQLHelper.CreateDataBase_DBMain();  // 初始化主数据库                button_Home.PerformClick();  // 模拟点击button_Home按钮                currentRole = "";            // 重置当前用户的角色                OnModeChanged();             // 模式更改事件                #region 定时任务                //timer1.Interval = 60000;  // 间隔一分钟                timer1.Interval = 1800000;  // 间隔半小时                timer1.Enabled = true;      // 开启                #endregion 定时任务            }            catch (Exception ex)            {                string str = ex.StackTrace;                logNet.WriteError("主窗体初始化出错!异常位置:" + str.Substring(str.LastIndexOf("\\") + 1, str.Length - str.LastIndexOf("\\") - 1) + ";异常信息:" + ex.Message.ToString());                MessageBox.Show("主窗体初始化出错!异常信息:" + ex.Message.ToString());            }        }        /// <summary>        /// 窗体关闭事件        /// </summary>        private void Form_Main_FormClosing(object sender, FormClosingEventArgs e)        {            formHome.Closed2();            if (GlobalContext.Save != null)                GlobalContext.Save();        }        /// <summary>        /// 定时任务        /// </summary>        private void timer1_Tick(object sender, EventArgs e)        {            try            {                DateTime dtNow = DateTime.Now;                #region 检测2h前是否有漏传的数据,有就报警                // 检测2h前是否有漏传的数据,有就报警                ProcessData processData0 = new ProcessData();                string QuerySQL0 = processData0.ToStringQueryCount(dtNow.AddHours(-2).ToString("yyyy-MM-dd HH:mm:ss"), "未上传");                DataSet ds1 = SQLHelper_New.Query(QuerySQL0, null);                if (ds1 != null && ds1.Tables.Count > 0 && ds1.Tables[0].Rows.Count > 0)                {                    int count = ds1.Tables[0].Rows[0][0].ObjToInt();                    IsNormal_MESServer = count < 1 ? 1 : 2;                }                #endregion 检测2h前是否有漏传的数据,有就报警                #region 检查48h内(正常就2h内的数据)是否有漏传的数据,有就重新上传                // 检查MES地址是否可以ping通                bool mesret = HttpUitls.PingIP(GlobalContext.ServerHost);                if (!mesret)                {                    return;                }                // 查询所有未上传的值-6h                ProcessData processData = new ProcessData();                string QuerySQL = processData.ToStringQuery2(dtNow.AddHours(-48).ToString("yyyy-MM-dd HH:mm:ss"), dtNow.ToString("yyyy-MM-dd HH:mm:ss"), "未上传");                DataSet ds = SQLHelper_New.Query(QuerySQL, null);                if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)                {                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)                    {                        var idStr = ds.Tables[0].Rows[i][0].ToString().Trim();                        // 上传                        var processData1 = new List<ProcessData>(){                             new ProcessData()                            {                                Equipment_code = ds.Tables[0].Rows[i][1].ToString().Trim(),                                Workorder_code = ds.Tables[0].Rows[i][2].ToString().Trim(),                                Batch_number = ds.Tables[0].Rows[i][3].ToString().Trim(),                                Sn = ds.Tables[0].Rows[i][4].ToString().Trim(),                                Testitem = ds.Tables[0].Rows[i][5].ToString().Trim(),                                Parameter_values = JsonConvert.DeserializeObject<List<TestItem>>(ds.Tables[0].Rows[i][6].ToString().Trim()),                                Write_user = ds.Tables[0].Rows[i][7].ToString().Trim(),                                Test_time = ds.Tables[0].Rows[i][8].ToString().Trim(),                            }                        };                        var jsonstr = JsonConvert.SerializeObject(processData1);                        if (GlobalContext.IsSendProcessData)  // 上传mes                        {                            string url = @"HTTP://" + GlobalContext.ServerHost + ":" + @"/api/ProductionLine/ProcessData";                            string mesRet = HttpUitls.SubmitDataToMES(url, jsonstr);                            int upload = 0;                            //本地数据                            if (mesRet == "成功")                            {                                upload = 1;                                SQLHelper_New.ExecuteSQL(ProcessData.ToStringUpdateStatusByID(upload, idStr), null);                            }                            else                            {                                upload = 0;                            }                            logNet.WriteInfo("定时任务上传加工数据【Id:" + idStr + "】到MES服务器---" + mesRet);                        }                        // 定时任务运行超过30分钟,则停止运行                        var dtLong = (DateTime.Now - dtNow).TotalMinutes;                        if (dtLong > 30)                        {                            break;                        }                    }                }                #endregion 检查48h内是否有流传的数据,有就重新上传            }            catch (Exception ex)            {                string str = ex.StackTrace;                logNet.WriteError("定时检查加工数据漏传的任务执行出错!异常位置:" + str.Substring(str.LastIndexOf("\\") + 1, str.Length - str.LastIndexOf("\\") - 1) + ";异常信息:" + ex.Message.ToString());            }        }        #endregion 窗体基础事件        #region 菜单栏按钮        /// <summary>        /// 登录按钮事件        /// </summary>        private void button_Login_Click(object sender, EventArgs e)        {            Form formOpen = Application.OpenForms["Form_UserLogin"];   //查找是否打开过窗体              if ((formOpen == null) || (formOpen.IsDisposed))           //如果没有打开过            {                Form_UserLogin form = new Form_UserLogin(userAccount);                form.ShowDialog();   //打开窗体            }            else            {                formOpen.Activate(); //如果已经打开过就让窗体获得焦点                  formOpen.WindowState = FormWindowState.Normal;//使恢复正常窗体大小            }        }        /// <summary>        /// 订单按钮        /// </summary>        private void btnOrder_Click(object sender, EventArgs e)        {        }        /// <summary>        /// 查看数据记录        /// </summary>        private void button_Alarm_Click(object sender, EventArgs e)        {        }        /// <summary>        /// 查看日志文件        /// </summary>        private void button1_Click(object sender, EventArgs e)        {            Process.Start(GlobalContext.MainDir);        }        /// <summary>        /// 设置按钮        /// </summary>        private void button_vision_Click(object sender, EventArgs e)        {        }        #endregion 菜单栏按钮        /// <summary>        /// 带有权限的窗体访问管理        /// </summary>        public void SwitchWnd(object sender, EventArgs e)        {            Button btn = sender as Button;            if (m_currentButton != btn)            {                if (currentRole == "Admin" || currentRole == "SuperAdmin")                {                    if (m_currentButton != null)                        m_currentButton.ImageIndex--;                    m_currentButton = btn;                    m_currentButton.ImageIndex++;                    if (m_currentForm != null)                        m_currentForm.Hide();                    if (m_currentForm != m_dicForm[btn])                    {                        m_currentForm = m_dicForm[btn];                        m_currentForm.Show();                        if (btn.Name != "button_SystemSet")  // 当没有点击“设置”按钮时,降级到操作员级别                        {                            userAccount.UserSet(User.Operator);                        }                        else if (btn.Name != "btnOrder")                        {                            userAccount.UserSet(User.Operator);                        }                        else if (btn.Name != "btnPLCDB")                        {                            userAccount.UserSet(User.Operator);                        }                    }                }                else                {                    if (btn.Name == "button_SystemSet" || btn.Name == "btnOrder" || btn.Name == "btnPLCDB")                    {                        MessageBox.Show("您无权限进行此操作,请先登录!");                    }                    else                    {                        if (m_currentButton != null)                            m_currentButton.ImageIndex--;                        m_currentButton = btn;                        m_currentButton.ImageIndex++;                        if (m_currentForm != null)                            m_currentForm.Hide();                        if (m_currentForm != m_dicForm[btn])                        {                            m_currentForm = m_dicForm[btn];                            m_currentForm.Show();                        }                    }                }            }        }        /// <summary>        /// 改变用户时更新页面UI        /// </summary>        /// <param name="user"></param>        private void ForUserChangeToUpdate(User user)        {            currentRole = user.ToString();            switch (currentRole)            {                case "Operator":                    toolStripStatusLabel_user.Text = "操作员";                    break;                case "Admin":                    toolStripStatusLabel_user.Text = "管理员";                    break;                case "SuperAdmin":                    toolStripStatusLabel_user.Text = "超级管理员";                    break;                default:                    toolStripStatusLabel_user.Text = "未登录";                    break;            }        }        /// <summary>        /// 模式更改事件        /// </summary>        private void OnModeChanged()        {        }        /// <summary>        /// 记录日志的方法        /// </summary>        /// <param name="logType">日志类型</param>        /// <param name="logValue">日志的值</param>        private void WriteWorkLog(LogType logType, string logValue)        {            switch ((int)logType)            {                case 0:                    logNet.WriteDebug(logValue);                    break;                case 1:                    logNet.WriteInfo(logValue);                    break;                case 2:                    logNet.WriteWarn(logValue);                    break;                case 3:                    logNet.WriteError(logValue);                    break;                default:                    logNet.WriteFatal(logValue);                    break;            }        }    }    public enum LogType    {        Debug,        Info,        Warning,        Error    }}
 |