AutoMakeQTYRZ.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. using Microsoft.Win32;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Data;
  5. using System.IO;
  6. using System.Threading;
  7. using System.Windows.Forms;
  8. using System.Xml;
  9. using System.Text;
  10. using System.Net;
  11. using System.Net.Sockets;
  12. using System.Text.RegularExpressions;
  13. using System.IO.Ports;
  14. using static System.Windows.Forms.VisualStyles.VisualStyleElement;
  15. using System.Windows.Media.Media3D;
  16. using System.Runtime.InteropServices;
  17. namespace FileWatcher
  18. {
  19. public partial class AutoMakeQTYRZ : Form
  20. {
  21. DataHelper dh;
  22. DataTable dt;
  23. DataTable DB;
  24. /// <summary>
  25. /// 用户编号
  26. /// </summary>
  27. string iusercode;
  28. /// <summary>
  29. /// 岗位资源
  30. /// </summary>
  31. string isource;
  32. Thread InitDB;
  33. /// 当前工序
  34. /// </summary>
  35. string istepcode;
  36. StringBuilder sql = new StringBuilder();
  37. /// <summary>
  38. /// 缓存的文件
  39. /// </summary>
  40. public static string CachePath = Environment.GetEnvironmentVariable("windir").Substring(0, 1) + @":/UAS_MES/XmlAnalysor/Cache.xml";
  41. /// <summary>
  42. /// 缓存的文件夹
  43. /// </summary>
  44. public static string CachePathFolder = Environment.GetEnvironmentVariable("windir").Substring(0, 1) + @":/UAS_MES/XmlAnalysor/";
  45. ftpOperater ftp = new ftpOperater();
  46. private bool waitingForStableData = false;
  47. private DateTime lastCurrentReadingTime;
  48. public AutoMakeQTYRZ()
  49. {
  50. InitializeComponent();
  51. StartPosition = FormStartPosition.CenterScreen;
  52. }
  53. DataTable Dbfind;
  54. string IPAddress = "";
  55. bool writedata = true;
  56. private void nr_rule_DBChange(object sender, EventArgs e)
  57. {
  58. Dbfind = li_code.ReturnData;
  59. BaseUtil.SetFormValue(this.Controls, Dbfind);
  60. }
  61. private void Form1_Load(object sender, EventArgs e)
  62. {
  63. CheckForIllegalCrossThreadCalls = false;
  64. InitDB = new Thread(ConnectDB);
  65. SetLoadingWindow stw = new SetLoadingWindow(InitDB, "正在启动程序");
  66. stw.StartPosition = FormStartPosition.CenterScreen;
  67. stw.ShowDialog();
  68. //string[] str = new string[] { "AA001097796643D67FE43D4185C74185EB47429A63783F64",
  69. // "AA001097796643D67FE43D4185C74185EB47429A63783F64",
  70. // "AA001097796643D67FE43D4185C74185EB47429A63783F64",
  71. // "AA001097796643D67FE43D4185C74185EB47429A63783F64",
  72. // "AA0010685B664300000000BE2BC74185EB47423655783F1E",
  73. // "AA001097796643D67FE43D4185C74185EB47429A63783F64",
  74. // "AA001097796643D67FE43D4185C74185EB47429A63783F64"};
  75. //for (int i = 0; i < str.Length; i++)
  76. //{
  77. // float 电压数据 = getdata(str[i].Substring(6, 8));
  78. // float 电流数据 = getdata(str[i].Substring(14, 8));
  79. // float 功率数据 = getdata(str[i].Substring(22, 8));
  80. // float 频率数据 = getdata(str[i].Substring(30, 8));
  81. // float 功率因素 = getdata(str[i].Substring(38, 8));
  82. // OperateResult.AppendText(str[i]);
  83. // OperateResult.AppendText(电压数据.ToString() + "\n");
  84. // OperateResult.AppendText(电流数据.ToString() + "\n");
  85. // OperateResult.AppendText(功率数据.ToString() + "\n");
  86. // OperateResult.AppendText(频率数据.ToString() + "\n");
  87. // OperateResult.AppendText(功率因素.ToString() + "\n");
  88. // //如果电流是0,则下次重新获取数据
  89. // if (电流数据 == 0)
  90. // {
  91. // writedata = false;
  92. // if (电流数据 == 0 && !writedata) {
  93. // writedata = true;
  94. // }
  95. // }
  96. // if (writedata)
  97. // {
  98. // if (电流数据 != 0) {
  99. // dh.ExecuteSql("insert into currenttest(CT_ID, CT_MAKECODE, CT_VOLTAGE, CT_CURRENT, CT_POWER, CT_FREQUENCY, CT_POWER1)" +
  100. // "VALUES(currenttest_SEQ.NEXTVAL,'" + ma_code.Text + "','" + 电压数据 + "','" + 电流数据 + "','" + 功率数据 + "','" + 频率数据 + "','" + 功率因素 + "')", "insert");
  101. // writedata = false;
  102. // }
  103. // }
  104. //}
  105. FormBorderStyle = FormBorderStyle.FixedSingle;
  106. serialPort1.DataReceived += SerialPort1_DataReceived;
  107. //添加监控事件
  108. XmlWatcher.Changed += new FileSystemEventHandler(XmlWatcher_Created);
  109. //ATEFile.Changed += new FileSystemEventHandler(XmlWatcher_Created);
  110. List<string> CacheInf = new List<string>();
  111. IPHostEntry IpEntry = Dns.GetHostEntry(Dns.GetHostName());
  112. for (int i = 0; i < IpEntry.AddressList.Length; i++)
  113. {
  114. if (IpEntry.AddressList[i].AddressFamily == AddressFamily.InterNetwork)
  115. IPAddress = IpEntry.AddressList[i].ToString();
  116. }
  117. //获取缓存信息
  118. try
  119. {
  120. Type.Text = BaseUtil.GetCacheData("Type").ToString();
  121. ComPort.Text = BaseUtil.GetCacheData("ComPort").ToString();
  122. BaudRate.Text = BaseUtil.GetCacheData("BaudRate").ToString();
  123. li_code.Text = BaseUtil.GetCacheData("Line").ToString();
  124. }
  125. catch (Exception ex) { MessageBox.Show(ex.Message); }
  126. }
  127. private float getdata(string tmp_b2)
  128. {
  129. byte[] b2 = new byte[4];
  130. float f2 = 0;
  131. tmp_b2 = tmp_b2.Replace(" ", "");//删除字符串中间的空格
  132. if (tmp_b2.Length != 8)
  133. {
  134. //判断输入字符串的长度是否合适
  135. MessageBox.Show("输入Byte长度错误,为连续8位4个字节,高位为0的补齐0");
  136. }
  137. else
  138. {
  139. //将收到的字符串分成4个字节,这4个字节是字符串的形式
  140. string tmp_char1 = tmp_b2.Substring(6, 2);
  141. string tmp_char2 = tmp_b2.Substring(4, 2);
  142. string tmp_char3 = tmp_b2.Substring(2, 2);
  143. string tmp_char4 = tmp_b2.Substring(0, 2);
  144. //将4字节的字符串格式转换成16进制的byte格式
  145. b2[3] = Convert.ToByte(tmp_char1, 16);
  146. b2[2] = Convert.ToByte(tmp_char2, 16);
  147. b2[1] = Convert.ToByte(tmp_char3, 16);
  148. b2[0] = Convert.ToByte(tmp_char4, 16);
  149. //将16进制byte转换成浮点数格式
  150. f2 = BitConverter.ToSingle(b2, 0);
  151. }
  152. return f2;
  153. }
  154. string data = "";
  155. bool realwritedata = false;
  156. private bool canRecordData = true; // 初始为true,允许第一次记录
  157. private bool currentWasZero = true; // 初始状态假设电流为0
  158. private bool isWaitingForStableData = false;
  159. private DateTime currentDetectionTime;
  160. private string pendingData = "";
  161. private void SerialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
  162. {
  163. try
  164. {
  165. int len = serialPort1.BytesToRead;
  166. Byte[] readBuffer = new Byte[len];
  167. serialPort1.Read(readBuffer, 0, len);
  168. string rawData = BitConverter.ToString(readBuffer, 0, readBuffer.Length).Replace("-", "");
  169. // 保存原始数据用于后续处理
  170. pendingData = rawData.Length > 48 ? rawData.Substring(0, 48) : rawData;
  171. if (pendingData.Length == 48)
  172. {
  173. float 电流数据 = getdata(pendingData.Substring(14, 8));
  174. // 如果检测到有电流且不在等待状态
  175. if (电流数据 != 0 && !isWaitingForStableData)
  176. {
  177. OperateResult.AppendText($"检测到电流({电流数据}A),等待2秒稳定...\n");
  178. isWaitingForStableData = true;
  179. currentDetectionTime = DateTime.Now;
  180. // 启动定时器检查是否已等待足够时间
  181. System.Windows.Forms.Timer delayTimer = new System.Windows.Forms.Timer();
  182. delayTimer.Interval = 2000; // 2秒
  183. delayTimer.Tick += (s, args) =>
  184. {
  185. delayTimer.Stop();
  186. ProcessStableData();
  187. };
  188. delayTimer.Start();
  189. }
  190. else if (电流数据 == 0)
  191. {
  192. isWaitingForStableData = false;
  193. }
  194. }
  195. }
  196. catch (Exception ex)
  197. {
  198. OperateResult.AppendText($"处理数据时出错: {ex.Message}\n");
  199. }
  200. }
  201. private void ProcessStableData()
  202. {
  203. try
  204. {
  205. if (pendingData.Length == 48)
  206. {
  207. float 电压数据 = getdata(pendingData.Substring(6, 8));
  208. float 电流数据 = getdata(pendingData.Substring(14, 8));
  209. float 功率数据 = getdata(pendingData.Substring(22, 8));
  210. float 频率数据 = getdata(pendingData.Substring(30, 8));
  211. float 功率因素 = getdata(pendingData.Substring(38, 8));
  212. if (电流数据 != 0) // 再次确认电流仍然存在
  213. {
  214. double num, num1;
  215. if (double.TryParse(FunctionNum.Text, out num) &&
  216. double.TryParse(FunctionNum1.Text, out num1))
  217. {
  218. if (功率数据 > num && 功率数据 < num1)
  219. {
  220. OperateResult.AppendText($"数据稳定,记录: 电压={电压数据}V, 电流={电流数据}A, 功率={功率数据}W\n");
  221. dh.ExecuteSql("insert into currenttest(CT_ID,ct_linecode, CT_MAKECODE, CT_VOLTAGE, CT_CURRENT, CT_POWER, CT_FREQUENCY, CT_POWER1) " +
  222. "VALUES(currenttest_SEQ.NEXTVAL,'" + li_code.Text + "','" + ma_code.Text + "','" + 电压数据 + "','" + 电流数据 + "','" + 功率数据 + "','" + 频率数据 + "','" + 功率因素 + "')", "insert");
  223. NowQTY.Text = dh.getRowCount("currenttest", "ct_makecode='" + ma_code.Text + "'").ToString();
  224. }
  225. else
  226. {
  227. OperateResult.AppendText($"功率数据异常: {功率数据}W (应在{num}-{num1}W之间)\n");
  228. }
  229. }
  230. else
  231. {
  232. OperateResult.AppendText("请正确设置功率标准值\n");
  233. }
  234. }
  235. else
  236. {
  237. OperateResult.AppendText("电流已消失,取消记录\n");
  238. }
  239. }
  240. isWaitingForStableData = false;
  241. }
  242. catch (Exception ex)
  243. {
  244. OperateResult.AppendText($"处理稳定数据时出错: {ex.Message}\n");
  245. isWaitingForStableData = false;
  246. }
  247. }
  248. private void ConnectDB()
  249. {
  250. dh = new DataHelper();
  251. SystemInf.dh = dh;
  252. ma_code.TableName = "make";
  253. ma_code.SelectField = "ma_code # 工单号";
  254. ma_code.FormName = Name;
  255. ma_code.DBTitle = "工单查询";
  256. ma_code.SetValueField = new string[] { "ma_code" };
  257. ma_code.Condition = "";
  258. ma_code.DbChange += nr_rule_DBChange;
  259. li_code.TableName = "line";
  260. li_code.SelectField = "li_code # 线别编号,li_name # 线别名称";
  261. li_code.FormName = Name;
  262. li_code.DBTitle = "线别查询";
  263. li_code.SetValueField = new string[] { "li_code" };
  264. li_code.Condition = "";
  265. li_code.DbChange += nr_rule_DBChange;
  266. }
  267. SerialPort serialPort1 = new SerialPort();
  268. private void StartWatch_Click(object sender, EventArgs e)
  269. {
  270. BaseUtil.SetCacheData("Type", Type.Text);
  271. BaseUtil.SetCacheData("ComPort", ComPort.Text);
  272. BaseUtil.SetCacheData("BaudRate", BaudRate.Text);
  273. BaseUtil.SetCacheData("Line", li_code.Text);
  274. if (!dh.CheckExist("Make", "ma_code='" + ma_code.Text + "'"))
  275. {
  276. OperateResult.AppendText("工单号不能为空\n");
  277. return;
  278. }
  279. //if (!dh.CheckExist("line", "li_code='" + li_code.Text + "'"))
  280. //{
  281. // OperateResult.AppendText("线别不能为空\n");
  282. // return;
  283. //}
  284. //string ExitConfirm = MessageBox.Show(this, "确认计数器是否置为0?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question).ToString();
  285. //if (ExitConfirm != "Yes")
  286. //{
  287. // return;
  288. //}
  289. //设置按钮不可点击
  290. StartWatch.Enabled = false;
  291. ma_code.Enabled = false;
  292. StopWatch.Enabled = true;
  293. try
  294. {
  295. serialPort1.PortName = ComPort.Text;
  296. serialPort1.BaudRate = int.Parse(BaudRate.Text);
  297. serialPort1.Open();
  298. Timer.Start();
  299. }
  300. catch (Exception mes)
  301. {
  302. if (BaudRate.Text == "" || BaudRate.Text == "")
  303. OperateResult.AppendText(">>请先维护波特率和串口\n");
  304. else
  305. OperateResult.AppendText(">>" + mes.Message + "\n");
  306. }
  307. OperateResult.AppendText("开始执行监控\n");
  308. }
  309. private void XmlWatcher_Created(object sender, FileSystemEventArgs e)
  310. {
  311. OperateResult.AppendText("文件修改:" + e.FullPath + "\n");
  312. TxtHandleProcess(e.FullPath);
  313. }
  314. string nextLine;
  315. private void TxtHandleProcess(string FileName)
  316. {
  317. List<string> badcode = new List<string>();
  318. List<string> badlocation = new List<string>();
  319. List<string> badprod = new List<string>();
  320. }
  321. private void StopWatch_Click(object sender, EventArgs e)
  322. {
  323. XmlWatcher.EnableRaisingEvents = false;
  324. StartWatch.Enabled = true;
  325. ma_code.Enabled = true;
  326. StopWatch.Enabled = false;
  327. OperateResult.AppendText("停止执行监控\n");
  328. }
  329. private void Clean_Click(object sender, EventArgs e)
  330. {
  331. OperateResult.Clear();
  332. }
  333. private void Form1_FormClosing(object sender, FormClosingEventArgs e)
  334. {
  335. string ExitConfirm = MessageBox.Show(this, "确认退出?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question).ToString();
  336. if (ExitConfirm != "Yes")
  337. {
  338. WindowState = FormWindowState.Minimized;
  339. e.Cancel = true;
  340. }
  341. }
  342. private void Timer_Tick(object sender, EventArgs e)
  343. {
  344. if (serialPort1.IsOpen)
  345. {
  346. if (!realwritedata)
  347. {
  348. byte[] data = HexStringToBytes("55 00 10 65");
  349. serialPort1.Write(data, 0, data.Length);
  350. }
  351. }
  352. }
  353. private void AutoStart_CheckedChanged(object sender, EventArgs e)
  354. {
  355. SetAutoRun();
  356. }
  357. private void SetAutoRun()
  358. {
  359. if (AutoStart.Checked) //设置开机自启动
  360. {
  361. string path = Application.ExecutablePath;
  362. RegistryKey rk = Registry.LocalMachine;
  363. RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
  364. rk2.SetValue("FileWatcher.exe", path);
  365. rk2.Close();
  366. rk.Close();
  367. }
  368. else //取消开机自启动
  369. {
  370. string path = Application.ExecutablePath;
  371. RegistryKey rk = Registry.LocalMachine;
  372. RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
  373. rk2.DeleteValue("FileWatcher.exe", false);
  374. rk2.Close();
  375. rk.Close();
  376. }
  377. }
  378. private byte[] HexStringToBytes(string hs)//十六进制字符串转byte
  379. {
  380. string a = hs.Replace(" ", "");
  381. int bytelength = 0;
  382. if (a.Length % 2 == 0)
  383. {
  384. bytelength = a.Length / 2;
  385. }
  386. else
  387. {
  388. bytelength = a.Length / 2 + 1;
  389. }
  390. byte[] b = new byte[bytelength];
  391. //逐个字符变为16进制字节数据
  392. for (int i = 0; i < bytelength; i++)
  393. {
  394. if (i == bytelength - 1)
  395. {
  396. b[i] = Convert.ToByte(a.Substring(i * 2), 16);
  397. }
  398. else
  399. {
  400. b[i] = Convert.ToByte(a.Substring(i * 2, 2), 16);
  401. }
  402. }
  403. //按照指定编码将字节数组变为字符串
  404. return b;
  405. }
  406. private void GetData_Click(object sender, EventArgs e)
  407. {
  408. }
  409. }
  410. }