AutoMakeQTYRZ.cs 15 KB

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