AutoMakeQTYRZ.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  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 void SerialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
  159. {
  160. try
  161. {
  162. int len = serialPort1.BytesToRead;
  163. Byte[] readBuffer = new Byte[len];
  164. serialPort1.Read(readBuffer, 0, len);
  165. data = BitConverter.ToString(readBuffer, 0, readBuffer.Length).Replace("-", "");
  166. if (data.Length > 48)
  167. {
  168. data = data.Substring(0, 48);
  169. }
  170. if (data.Length == 48)
  171. {
  172. float 电压数据 = getdata(data.Substring(6, 8));
  173. float 电流数据 = getdata(data.Substring(14, 8));
  174. float 功率数据 = getdata(data.Substring(22, 8));
  175. float 频率数据 = getdata(data.Substring(30, 8));
  176. float 功率因素 = getdata(data.Substring(38, 8));
  177. // 检查电流状态变化
  178. if (电流数据 == 0)
  179. {
  180. currentWasZero = true;
  181. canRecordData = true; // 电流归零后,允许下次记录
  182. OperateResult.AppendText("电流归零,准备下次记录\n");
  183. }
  184. else if (电流数据 != 0 && currentWasZero && canRecordData)
  185. {
  186. // 电流从0变为非0,且允许记录
  187. double num, num1;
  188. if (double.TryParse(FunctionNum.Text, out num) &&
  189. double.TryParse(FunctionNum1.Text, out num1))
  190. {
  191. if (功率数据 > num && 功率数据 < num1)
  192. {
  193. OperateResult.AppendText("检测到有效电流,记录数据,功率[" + 功率数据 + "]\n");
  194. dh.ExecuteSql("insert into currenttest(CT_ID,ct_linecode, CT_MAKECODE, CT_VOLTAGE, CT_CURRENT, CT_POWER, CT_FREQUENCY, CT_POWER1) " +
  195. "VALUES(currenttest_SEQ.NEXTVAL,'" + li_code.Text + "','" + ma_code.Text + "','" + 电压数据 + "','" + 电流数据 + "','" + 功率数据 + "','" + 频率数据 + "','" + 功率因素 + "')", "insert");
  196. NowQTY.Text = dh.getRowCount("currenttest", "ct_makecode='" + ma_code.Text + "'").ToString();
  197. // 记录后禁止再次记录,直到电流归零
  198. canRecordData = false;
  199. currentWasZero = false;
  200. }
  201. else
  202. {
  203. OperateResult.AppendText("功率数据异常\n");
  204. }
  205. }
  206. else
  207. {
  208. OperateResult.AppendText("请填写功率标准值\n");
  209. }
  210. }
  211. }
  212. }
  213. catch (Exception ex)
  214. {
  215. OperateResult.AppendText(ex.Message + data + "\n");
  216. }
  217. }
  218. private void ConnectDB()
  219. {
  220. dh = new DataHelper();
  221. SystemInf.dh = dh;
  222. ma_code.TableName = "make";
  223. ma_code.SelectField = "ma_code # 工单号";
  224. ma_code.FormName = Name;
  225. ma_code.DBTitle = "工单查询";
  226. ma_code.SetValueField = new string[] { "ma_code" };
  227. ma_code.Condition = "";
  228. ma_code.DbChange += nr_rule_DBChange;
  229. li_code.TableName = "line";
  230. li_code.SelectField = "li_code # 线别编号,li_name # 线别名称";
  231. li_code.FormName = Name;
  232. li_code.DBTitle = "线别查询";
  233. li_code.SetValueField = new string[] { "li_code" };
  234. li_code.Condition = "";
  235. li_code.DbChange += nr_rule_DBChange;
  236. }
  237. SerialPort serialPort1 = new SerialPort();
  238. private void StartWatch_Click(object sender, EventArgs e)
  239. {
  240. BaseUtil.SetCacheData("Type", Type.Text);
  241. BaseUtil.SetCacheData("ComPort", ComPort.Text);
  242. BaseUtil.SetCacheData("BaudRate", BaudRate.Text);
  243. BaseUtil.SetCacheData("Line", li_code.Text);
  244. if (!dh.CheckExist("Make", "ma_code='" + ma_code.Text + "'"))
  245. {
  246. OperateResult.AppendText("工单号不能为空\n");
  247. return;
  248. }
  249. //if (!dh.CheckExist("line", "li_code='" + li_code.Text + "'"))
  250. //{
  251. // OperateResult.AppendText("线别不能为空\n");
  252. // return;
  253. //}
  254. //string ExitConfirm = MessageBox.Show(this, "确认计数器是否置为0?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question).ToString();
  255. //if (ExitConfirm != "Yes")
  256. //{
  257. // return;
  258. //}
  259. //设置按钮不可点击
  260. StartWatch.Enabled = false;
  261. ma_code.Enabled = false;
  262. StopWatch.Enabled = true;
  263. try
  264. {
  265. serialPort1.PortName = ComPort.Text;
  266. serialPort1.BaudRate = int.Parse(BaudRate.Text);
  267. serialPort1.Open();
  268. Timer.Start();
  269. }
  270. catch (Exception mes)
  271. {
  272. if (BaudRate.Text == "" || BaudRate.Text == "")
  273. OperateResult.AppendText(">>请先维护波特率和串口\n");
  274. else
  275. OperateResult.AppendText(">>" + mes.Message + "\n");
  276. }
  277. OperateResult.AppendText("开始执行监控\n");
  278. }
  279. private void XmlWatcher_Created(object sender, FileSystemEventArgs e)
  280. {
  281. OperateResult.AppendText("文件修改:" + e.FullPath + "\n");
  282. TxtHandleProcess(e.FullPath);
  283. }
  284. string nextLine;
  285. private void TxtHandleProcess(string FileName)
  286. {
  287. List<string> badcode = new List<string>();
  288. List<string> badlocation = new List<string>();
  289. List<string> badprod = new List<string>();
  290. }
  291. private void StopWatch_Click(object sender, EventArgs e)
  292. {
  293. XmlWatcher.EnableRaisingEvents = false;
  294. StartWatch.Enabled = true;
  295. ma_code.Enabled = true;
  296. StopWatch.Enabled = false;
  297. OperateResult.AppendText("停止执行监控\n");
  298. }
  299. private void Clean_Click(object sender, EventArgs e)
  300. {
  301. OperateResult.Clear();
  302. }
  303. private void Form1_FormClosing(object sender, FormClosingEventArgs e)
  304. {
  305. string ExitConfirm = MessageBox.Show(this, "确认退出?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question).ToString();
  306. if (ExitConfirm != "Yes")
  307. {
  308. WindowState = FormWindowState.Minimized;
  309. e.Cancel = true;
  310. }
  311. }
  312. private void Timer_Tick(object sender, EventArgs e)
  313. {
  314. if (serialPort1.IsOpen)
  315. {
  316. if (!realwritedata)
  317. {
  318. byte[] data = HexStringToBytes("55 00 10 65");
  319. serialPort1.Write(data, 0, data.Length);
  320. }
  321. }
  322. }
  323. private void AutoStart_CheckedChanged(object sender, EventArgs e)
  324. {
  325. SetAutoRun();
  326. }
  327. private void SetAutoRun()
  328. {
  329. if (AutoStart.Checked) //设置开机自启动
  330. {
  331. string path = Application.ExecutablePath;
  332. RegistryKey rk = Registry.LocalMachine;
  333. RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
  334. rk2.SetValue("FileWatcher.exe", path);
  335. rk2.Close();
  336. rk.Close();
  337. }
  338. else //取消开机自启动
  339. {
  340. string path = Application.ExecutablePath;
  341. RegistryKey rk = Registry.LocalMachine;
  342. RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
  343. rk2.DeleteValue("FileWatcher.exe", false);
  344. rk2.Close();
  345. rk.Close();
  346. }
  347. }
  348. private byte[] HexStringToBytes(string hs)//十六进制字符串转byte
  349. {
  350. string a = hs.Replace(" ", "");
  351. int bytelength = 0;
  352. if (a.Length % 2 == 0)
  353. {
  354. bytelength = a.Length / 2;
  355. }
  356. else
  357. {
  358. bytelength = a.Length / 2 + 1;
  359. }
  360. byte[] b = new byte[bytelength];
  361. //逐个字符变为16进制字节数据
  362. for (int i = 0; i < bytelength; i++)
  363. {
  364. if (i == bytelength - 1)
  365. {
  366. b[i] = Convert.ToByte(a.Substring(i * 2), 16);
  367. }
  368. else
  369. {
  370. b[i] = Convert.ToByte(a.Substring(i * 2, 2), 16);
  371. }
  372. }
  373. //按照指定编码将字节数组变为字符串
  374. return b;
  375. }
  376. private void GetData_Click(object sender, EventArgs e)
  377. {
  378. }
  379. }
  380. }