Form_Main.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Windows.Forms;
  4. using StandardLibrary;
  5. using UserSettings;
  6. using System.Drawing;
  7. using System.Diagnostics;
  8. using System.Threading;
  9. using static StandardLibrary.UserAccount;
  10. using System.IO;
  11. using HslCommunication.LogNet;
  12. using System.Data;
  13. using MainForm.FaForm;
  14. using System.Runtime.CompilerServices;
  15. using MainForm.ClassFile;
  16. using System.Threading.Tasks;
  17. using Newtonsoft.Json;
  18. using SqlSugar.Extensions;
  19. namespace MainForm
  20. {
  21. public partial class Form_Main : Form
  22. {
  23. #region 变量
  24. /// <summary>
  25. /// 窗体字典与窗体
  26. /// </summary>
  27. Dictionary<Button, Form> m_dicForm = new Dictionary<Button, Form>(); // 窗体字典
  28. Form m_currentForm = null; // 当前窗体
  29. public static Form_Home formHome;
  30. private Form_Order formOrder; // 订单维护窗体
  31. public static Form_DevAlarm formDevAlarm; // 设备运行情况窗体
  32. private Form_Alarm formAlarm; // 数据及报警查询窗体
  33. public static Form_PLCDB formPLCDB; // PLC点位维护窗体
  34. private Form_Other formOther; // 测试窗体
  35. private Form_SystemSet formSystemSet; // 设置页窗体
  36. /// <summary>
  37. /// 记录用户正在触发的按钮
  38. /// </summary>
  39. Button m_currentButton = null;
  40. /// <summary>
  41. /// 当前用户信息
  42. /// </summary>
  43. private UserAccount userAccount = new UserAccount();
  44. /// <summary>
  45. /// 当前用户角色
  46. /// </summary>
  47. string currentRole = "SuperAdmin";
  48. /// <summary>
  49. /// 是否可正常上传数据到MES(有2小时前的数据未上传则为2;正常为1)
  50. /// </summary>
  51. public static int IsNormal_MESServer = 0;
  52. /// <summary>
  53. /// 用于记录"运行日志"
  54. /// </summary>
  55. ILogNet logNet = new LogNetDateTime(GlobalContext.WorkLogDir, GenerateMode.ByEveryHour);
  56. #endregion 变量
  57. #region 窗体基础事件
  58. public Form_Main()
  59. {
  60. InitializeComponent();
  61. // 需要权限的按钮绑定权限控制事件
  62. this.btnOrder.Click += new System.EventHandler(this.SwitchWnd);
  63. this.Btn_DevAlarm.Click += new System.EventHandler(this.SwitchWnd);
  64. this.button_Alarm.Click += new System.EventHandler(this.SwitchWnd);
  65. this.btnPLCDB.Click += new System.EventHandler(this.SwitchWnd);
  66. this.button_SystemSet.Click += new System.EventHandler(this.SwitchWnd);
  67. this.button_Other.Click += new System.EventHandler(this.SwitchWnd);
  68. this.button_Home.Click += new System.EventHandler(this.SwitchWnd);
  69. //this.button_Other.Click += new System.EventHandler(this.SwitchWnd);
  70. }
  71. /// <summary>
  72. /// 窗体加载事件
  73. /// </summary>
  74. /// <param name="sender"></param>
  75. /// <param name="e"></param>
  76. private void Form_Main_Load(object sender, EventArgs e)
  77. {
  78. try
  79. {
  80. #region 尝试关联启动“气密设备软件”(进程名QIMITest.exe)与“电测设备软件”(进程名MainForm.exe)。
  81. Task.Run(() =>
  82. {
  83. try
  84. {
  85. if (!ProcessHelper.CheckProcessActivityByProcessName("QIMITest")) // 进程名QIMITest.exe
  86. {
  87. string pathStr1 = @"D:\MES\QIMIAPP\QIMITest.exe";
  88. if (FileIOHelper.ISExists_File(pathStr1))
  89. ProcessHelper.StartProcess(pathStr1);
  90. }
  91. }
  92. catch { }
  93. try
  94. {
  95. if (!ProcessHelper.CheckProcessActivityByProcessName("MainForm")) // 进程名MainForm.exe
  96. {
  97. // 电测使用 ProcessHelper.StartProcess启动时页面UI异常,所以使用bat启动
  98. string pathStr2 = Application.StartupPath + @"\启动电测.bat";
  99. string pathStr3 = @"D:\MES\DianCeAPP\MainForm.exe";
  100. if (FileIOHelper.ISExists_File(pathStr2) && FileIOHelper.ISExists_File(pathStr3))
  101. ProcessHelper.StartProcess(pathStr2);
  102. }
  103. }
  104. catch { }
  105. });
  106. #endregion 尝试关联启动“气密设备软件”与“电测设备软件”
  107. //初始化目录
  108. if (!Directory.Exists(GlobalContext.DBDir)) Directory.CreateDirectory(GlobalContext.DBDir); // 判断路径是否存在,不存在则创建路径
  109. if (!Directory.Exists(GlobalContext.ProcessDataDir)) Directory.CreateDirectory(GlobalContext.ProcessDataDir); // 判断路径是否存在,不存在则创建路径
  110. if (!Directory.Exists(GlobalContext.OneCheckDataDir)) Directory.CreateDirectory(GlobalContext.OneCheckDataDir); // 判断路径是否存在,不存在则创建路径
  111. GlobalContext.UpdateData();
  112. //创建窗体及事件
  113. formOrder = new Form_Order(); // 订单维护窗体
  114. formDevAlarm = new Form_DevAlarm(); // 设备运行情况窗体
  115. formAlarm = new Form_Alarm(); // 数据及报警查询窗体
  116. formPLCDB = new Form_PLCDB(); // PLC点位维护窗体
  117. formOther = new Form_Other(); // 测试窗体
  118. formSystemSet = new Form_SystemSet(); // 设置页窗体
  119. formHome = new Form_Home(); // 首页窗体
  120. userAccount.UserChangedEvent += new UserChangedHandler(ForUserChangeToUpdate); // 改变用户时更新页面信息
  121. userAccount.UserChangedEvent += new UserChangedHandler(formOrder.ForUserChangeToUpdate); // 改变用户时更新页面信息
  122. userAccount.UserChangedEvent += new UserChangedHandler(formPLCDB.ForUserChangeToUpdate); // 改变用户时更新页面信息
  123. userAccount.UserChangedEvent += new UserChangedHandler(formSystemSet.ForUserChangeToUpdate); // 改变用户时更新页面信息
  124. formHome.MessageEvent += new HomeMessageHandler(WriteWorkLog); // 写入工作日志
  125. formOrder.MessageEvent += new OrderMessageHandler(WriteWorkLog); // 写入工作日志
  126. formSystemSet.MessageEvent += new SystemSetMessageHandler(WriteWorkLog); // 写入工作日志
  127. formDevAlarm.MessageEvent += new AlarmMessageHandler(formHome.AddMessage);
  128. formAlarm.MessageEvent += new AlarmMessageHandler(formHome.AddMessage);
  129. formPLCDB.MessageEvent += new AlarmMessageHandler(formHome.AddMessage);
  130. //formAlarm.SaveProcessDataEvent += new HomeSaveProcessDataHandler(formHome.SaveProcessDataByDB); // 保存加工数据的事件
  131. //formAlarm.SaveOneCheckDataEvent += new HomeSaveOneCheckDataHandler(formHome.SaveOneCheckDataByDB); // 保存点检数据的事件
  132. //formAlarm.SaveAlarmDataEvent += new HomeSaveAlarmDataHandler(formHome.SaveAlarmDataByDB); // 保存报警数据的事件
  133. this.Text += " - V" + Application.ProductVersion; // 显示版本信息
  134. // Btn_DevAlarm
  135. m_dicForm.Add(btnOrder, formOrder); // 将按钮与事件存到字典中
  136. m_dicForm.Add(Btn_DevAlarm, formDevAlarm); // 将按钮与事件存到字典中
  137. m_dicForm.Add(button_Alarm, formAlarm); // 将按钮与事件存到字典中
  138. m_dicForm.Add(btnPLCDB, formPLCDB); // 将按钮与事件存到字典中
  139. m_dicForm.Add(button_SystemSet, formSystemSet); // 将按钮与事件存到字典中
  140. m_dicForm.Add(button_Home, formHome); // 将按钮与事件存到字典中
  141. m_dicForm.Add(button_Other, formOther); // 将按钮与事件存到字典中
  142. foreach (KeyValuePair<Button, Form> kp in m_dicForm) // 设置窗体属性(无边框、嵌套、停靠)
  143. {
  144. kp.Value.TopLevel = false;
  145. kp.Value.FormBorderStyle = FormBorderStyle.None;
  146. kp.Value.Parent = this.panelMain;
  147. kp.Value.Dock = DockStyle.Fill;
  148. }
  149. GlobalContext.UpdateData();
  150. SQLHelper.DBInitWork(); // 初始化数据库
  151. SQLHelper.CreateDataBase_DBMain(); // 初始化主数据库
  152. button_Home.PerformClick(); // 模拟点击button_Home按钮
  153. currentRole = ""; // 重置当前用户的角色
  154. OnModeChanged(); // 模式更改事件
  155. #region 定时任务
  156. //timer1.Interval = 60000; // 间隔一分钟
  157. timer1.Interval = 1800000; // 间隔半小时
  158. timer1.Enabled = true; // 开启
  159. #endregion 定时任务
  160. }
  161. catch (Exception ex)
  162. {
  163. string str = ex.StackTrace;
  164. logNet.WriteError("主窗体初始化出错!异常位置:" + str.Substring(str.LastIndexOf("\\") + 1, str.Length - str.LastIndexOf("\\") - 1) + ";异常信息:" + ex.Message.ToString());
  165. MessageBox.Show("主窗体初始化出错!异常信息:" + ex.Message.ToString());
  166. }
  167. }
  168. /// <summary>
  169. /// 窗体关闭事件
  170. /// </summary>
  171. private void Form_Main_FormClosing(object sender, FormClosingEventArgs e)
  172. {
  173. formHome.Closed2();
  174. if (GlobalContext.Save != null)
  175. GlobalContext.Save();
  176. }
  177. /// <summary>
  178. /// 定时任务
  179. /// </summary>
  180. private void timer1_Tick(object sender, EventArgs e)
  181. {
  182. try
  183. {
  184. DateTime dtNow = DateTime.Now;
  185. #region 检测2h前是否有漏传的数据,有就报警
  186. // 检测2h前是否有漏传的数据,有就报警
  187. ProcessData processData0 = new ProcessData();
  188. string QuerySQL0 = processData0.ToStringQueryCount(dtNow.AddHours(-2).ToString("yyyy-MM-dd HH:mm:ss"), "未上传");
  189. DataSet ds1 = SQLHelper_New.Query(QuerySQL0, null);
  190. if (ds1 != null && ds1.Tables.Count > 0 && ds1.Tables[0].Rows.Count > 0)
  191. {
  192. int count = ds1.Tables[0].Rows[0][0].ObjToInt();
  193. IsNormal_MESServer = count < 1 ? 1 : 2;
  194. }
  195. #endregion 检测2h前是否有漏传的数据,有就报警
  196. #region 检查48h内(正常就2h内的数据)是否有漏传的数据,有就重新上传
  197. // 检查MES地址是否可以ping通
  198. bool mesret = HttpUitls.PingIP(GlobalContext.ServerHost);
  199. if (!mesret)
  200. {
  201. return;
  202. }
  203. // 查询所有未上传的值-6h
  204. ProcessData processData = new ProcessData();
  205. string QuerySQL = processData.ToStringQuery2(dtNow.AddHours(-48).ToString("yyyy-MM-dd HH:mm:ss"), dtNow.ToString("yyyy-MM-dd HH:mm:ss"), "未上传");
  206. DataSet ds = SQLHelper_New.Query(QuerySQL, null);
  207. if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
  208. {
  209. for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
  210. {
  211. var idStr = ds.Tables[0].Rows[i][0].ToString().Trim();
  212. // 上传
  213. var processData1 = new List<ProcessData>(){
  214. new ProcessData()
  215. {
  216. Equipment_code = ds.Tables[0].Rows[i][1].ToString().Trim(),
  217. Workorder_code = ds.Tables[0].Rows[i][2].ToString().Trim(),
  218. Batch_number = ds.Tables[0].Rows[i][3].ToString().Trim(),
  219. Sn = ds.Tables[0].Rows[i][4].ToString().Trim(),
  220. Testitem = ds.Tables[0].Rows[i][5].ToString().Trim(),
  221. Parameter_values = JsonConvert.DeserializeObject<List<TestItem>>(ds.Tables[0].Rows[i][6].ToString().Trim()),
  222. Write_user = ds.Tables[0].Rows[i][7].ToString().Trim(),
  223. Test_time = ds.Tables[0].Rows[i][8].ToString().Trim(),
  224. }
  225. };
  226. var jsonstr = JsonConvert.SerializeObject(processData1);
  227. if (GlobalContext.IsSendProcessData) // 上传mes
  228. {
  229. string url = @"HTTP://" + GlobalContext.ServerHost + ":" + @"/api/ProductionLine/ProcessData";
  230. string mesRet = HttpUitls.SubmitDataToMES(url, jsonstr);
  231. int upload = 0;
  232. //本地数据
  233. if (mesRet == "成功")
  234. {
  235. upload = 1;
  236. SQLHelper_New.ExecuteSQL(ProcessData.ToStringUpdateStatusByID(upload, idStr), null);
  237. }
  238. else
  239. {
  240. upload = 0;
  241. }
  242. logNet.WriteInfo("定时任务上传加工数据【Id:" + idStr + "】到MES服务器---" + mesRet);
  243. }
  244. // 定时任务运行超过30分钟,则停止运行
  245. var dtLong = (DateTime.Now - dtNow).TotalMinutes;
  246. if (dtLong > 30)
  247. {
  248. break;
  249. }
  250. }
  251. }
  252. #endregion 检查48h内是否有流传的数据,有就重新上传
  253. }
  254. catch (Exception ex)
  255. {
  256. string str = ex.StackTrace;
  257. logNet.WriteError("定时检查加工数据漏传的任务执行出错!异常位置:" + str.Substring(str.LastIndexOf("\\") + 1, str.Length - str.LastIndexOf("\\") - 1) + ";异常信息:" + ex.Message.ToString());
  258. }
  259. }
  260. #endregion 窗体基础事件
  261. #region 菜单栏按钮
  262. /// <summary>
  263. /// 登录按钮事件
  264. /// </summary>
  265. private void button_Login_Click(object sender, EventArgs e)
  266. {
  267. Form formOpen = Application.OpenForms["Form_UserLogin"]; //查找是否打开过窗体
  268. if ((formOpen == null) || (formOpen.IsDisposed)) //如果没有打开过
  269. {
  270. Form_UserLogin form = new Form_UserLogin(userAccount);
  271. form.ShowDialog(); //打开窗体
  272. }
  273. else
  274. {
  275. formOpen.Activate(); //如果已经打开过就让窗体获得焦点
  276. formOpen.WindowState = FormWindowState.Normal;//使恢复正常窗体大小
  277. }
  278. }
  279. /// <summary>
  280. /// 订单按钮
  281. /// </summary>
  282. private void btnOrder_Click(object sender, EventArgs e)
  283. {
  284. }
  285. /// <summary>
  286. /// 查看数据记录
  287. /// </summary>
  288. private void button_Alarm_Click(object sender, EventArgs e)
  289. {
  290. }
  291. /// <summary>
  292. /// 查看日志文件
  293. /// </summary>
  294. private void button1_Click(object sender, EventArgs e)
  295. {
  296. Process.Start(GlobalContext.MainDir);
  297. }
  298. /// <summary>
  299. /// 设置按钮
  300. /// </summary>
  301. private void button_vision_Click(object sender, EventArgs e)
  302. {
  303. }
  304. #endregion 菜单栏按钮
  305. /// <summary>
  306. /// 带有权限的窗体访问管理
  307. /// </summary>
  308. public void SwitchWnd(object sender, EventArgs e)
  309. {
  310. Button btn = sender as Button;
  311. if (m_currentButton != btn)
  312. {
  313. if (currentRole == "Admin" || currentRole == "SuperAdmin")
  314. {
  315. if (m_currentButton != null)
  316. m_currentButton.ImageIndex--;
  317. m_currentButton = btn;
  318. m_currentButton.ImageIndex++;
  319. if (m_currentForm != null)
  320. m_currentForm.Hide();
  321. if (m_currentForm != m_dicForm[btn])
  322. {
  323. m_currentForm = m_dicForm[btn];
  324. m_currentForm.Show();
  325. if (btn.Name != "button_SystemSet") // 当没有点击“设置”按钮时,降级到操作员级别
  326. {
  327. userAccount.UserSet(User.Operator);
  328. }
  329. else if (btn.Name != "btnOrder")
  330. {
  331. userAccount.UserSet(User.Operator);
  332. }
  333. else if (btn.Name != "btnPLCDB")
  334. {
  335. userAccount.UserSet(User.Operator);
  336. }
  337. }
  338. }
  339. else
  340. {
  341. if (btn.Name == "button_SystemSet" || btn.Name == "btnOrder" || btn.Name == "btnPLCDB")
  342. {
  343. MessageBox.Show("您无权限进行此操作,请先登录!");
  344. }
  345. else
  346. {
  347. if (m_currentButton != null)
  348. m_currentButton.ImageIndex--;
  349. m_currentButton = btn;
  350. m_currentButton.ImageIndex++;
  351. if (m_currentForm != null)
  352. m_currentForm.Hide();
  353. if (m_currentForm != m_dicForm[btn])
  354. {
  355. m_currentForm = m_dicForm[btn];
  356. m_currentForm.Show();
  357. }
  358. }
  359. }
  360. }
  361. }
  362. /// <summary>
  363. /// 改变用户时更新页面UI
  364. /// </summary>
  365. /// <param name="user"></param>
  366. private void ForUserChangeToUpdate(User user)
  367. {
  368. currentRole = user.ToString();
  369. switch (currentRole)
  370. {
  371. case "Operator":
  372. toolStripStatusLabel_user.Text = "操作员";
  373. break;
  374. case "Admin":
  375. toolStripStatusLabel_user.Text = "管理员";
  376. break;
  377. case "SuperAdmin":
  378. toolStripStatusLabel_user.Text = "超级管理员";
  379. break;
  380. default:
  381. toolStripStatusLabel_user.Text = "未登录";
  382. break;
  383. }
  384. }
  385. /// <summary>
  386. /// 模式更改事件
  387. /// </summary>
  388. private void OnModeChanged()
  389. {
  390. }
  391. /// <summary>
  392. /// 记录日志的方法
  393. /// </summary>
  394. /// <param name="logType">日志类型</param>
  395. /// <param name="logValue">日志的值</param>
  396. private void WriteWorkLog(LogType logType, string logValue)
  397. {
  398. switch ((int)logType)
  399. {
  400. case 0:
  401. logNet.WriteDebug(logValue);
  402. break;
  403. case 1:
  404. logNet.WriteInfo(logValue);
  405. break;
  406. case 2:
  407. logNet.WriteWarn(logValue);
  408. break;
  409. case 3:
  410. logNet.WriteError(logValue);
  411. break;
  412. default:
  413. logNet.WriteFatal(logValue);
  414. break;
  415. }
  416. }
  417. }
  418. public enum LogType
  419. {
  420. Debug,
  421. Info,
  422. Warning,
  423. Error
  424. }
  425. }