AutoMakeQTY.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  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. using System.Linq.Expressions;
  13. using System.Linq;
  14. namespace FileWatcher
  15. {
  16. public partial class AutoMakeQTY : Form
  17. {
  18. DataHelper dh;
  19. DataTable dt;
  20. DataTable DB;
  21. /// <summary>
  22. /// 用户编号
  23. /// </summary>
  24. string iusercode;
  25. /// <summary>
  26. /// 岗位资源
  27. /// </summary>
  28. string isource;
  29. Thread InitDB;
  30. /// 当前工序
  31. /// </summary>
  32. string istepcode;
  33. StringBuilder sql = new StringBuilder();
  34. /// <summary>
  35. /// 缓存的文件
  36. /// </summary>
  37. public static string CachePath = Environment.GetEnvironmentVariable("windir").Substring(0, 1) + @":/UAS_MES/XmlAnalysor/Cache.xml";
  38. /// <summary>
  39. /// 缓存的文件夹
  40. /// </summary>
  41. public static string CachePathFolder = Environment.GetEnvironmentVariable("windir").Substring(0, 1) + @":/UAS_MES/XmlAnalysor/";
  42. ftpOperater ftp = new ftpOperater();
  43. public AutoMakeQTY()
  44. {
  45. InitializeComponent();
  46. StartPosition = FormStartPosition.CenterScreen;
  47. }
  48. DataTable Dbfind;
  49. string IPAddress = "";
  50. private void nr_rule_DBChange(object sender, EventArgs e)
  51. {
  52. Dbfind = li_code.ReturnData;
  53. BaseUtil.SetFormValue(this.Controls, Dbfind);
  54. }
  55. private int Val(char Expression)
  56. {
  57. if (Expression >= '1' && Expression <= '9')
  58. {
  59. return unchecked((int)Expression) - 48;
  60. }
  61. return 0;
  62. }
  63. private void Form1_Load(object sender, EventArgs e)
  64. {
  65. byte[] b2 = new byte[4];
  66. float f2;
  67. string tmp_b2 = "43666AEC";
  68. tmp_b2 = tmp_b2.Replace(" ", "");//删除字符串中间的空格
  69. if (tmp_b2.Length != 8)
  70. {
  71. //判断输入字符串的长度是否合适
  72. MessageBox.Show("输入Byte长度错误,为连续8位4个字节,高位为0的补齐0");
  73. }
  74. else
  75. {
  76. //将收到的字符串分成4个字节,这4个字节是字符串的形式
  77. string tmp_char1 = tmp_b2.Substring(0, 2);
  78. string tmp_char2 = tmp_b2.Substring(2, 2);
  79. string tmp_char3 = tmp_b2.Substring(4, 2);
  80. string tmp_char4 = tmp_b2.Substring(6, 2);
  81. //将4字节的字符串格式转换成16进制的byte格式
  82. b2[3] = Convert.ToByte(tmp_char1, 16);
  83. b2[2] = Convert.ToByte(tmp_char2, 16);
  84. b2[1] = Convert.ToByte(tmp_char3, 16);
  85. b2[0] = Convert.ToByte(tmp_char4, 16);
  86. //将16进制byte转换成浮点数格式
  87. f2 = BitConverter.ToSingle(b2, 0);
  88. Console.WriteLine(Convert.ToString(f2)); ;
  89. }
  90. CheckForIllegalCrossThreadCalls = false;
  91. FormBorderStyle = FormBorderStyle.FixedSingle;
  92. serialPort1.DataReceived += SerialPort1_DataReceived;
  93. InitDB = new Thread(ConnectDB);
  94. //添加监控事件
  95. XmlWatcher.Changed += new FileSystemEventHandler(XmlWatcher_Created);
  96. //ATEFile.Changed += new FileSystemEventHandler(XmlWatcher_Created);
  97. SetLoadingWindow stw = new SetLoadingWindow(InitDB, "正在启动程序");
  98. stw.StartPosition = FormStartPosition.CenterScreen;
  99. stw.ShowDialog();
  100. List<string> CacheInf = new List<string>();
  101. IPHostEntry IpEntry = Dns.GetHostEntry(Dns.GetHostName());
  102. for (int i = 0; i < IpEntry.AddressList.Length; i++)
  103. {
  104. if (IpEntry.AddressList[i].AddressFamily == AddressFamily.InterNetwork)
  105. IPAddress = IpEntry.AddressList[i].ToString();
  106. }
  107. //获取缓存信息
  108. try
  109. {
  110. Type.Text = BaseUtil.GetCacheData("Type").ToString();
  111. ComPort.Text = BaseUtil.GetCacheData("ComPort").ToString();
  112. BaudRate.Text = BaseUtil.GetCacheData("BaudRate").ToString();
  113. li_code.Text = BaseUtil.GetCacheData("Line").ToString();
  114. }
  115. catch (Exception ex) { MessageBox.Show(ex.Message); }
  116. }
  117. double lastqty = 0;
  118. private void SerialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
  119. {
  120. int len = serialPort1.BytesToRead;
  121. Byte[] readBuffer = new Byte[len];
  122. serialPort1.Read(readBuffer, 0, len); //将数据读入缓存
  123. string data = BitConverter.ToString(readBuffer, 0, readBuffer.Length).Replace("-", "");
  124. //Convert.ToInt32(data.Substring(6, 8), 16);
  125. //Console.WriteLine(data.Substring(6, 2));
  126. //double Num1 = double.Parse(data.Substring(8, 2)) * 10000;
  127. //Console.WriteLine(data.Substring(8, 2));
  128. //double Num2 = double.Parse(data.Substring(10, 2)) * 1000;
  129. //Console.WriteLine(data.Substring(10, 2));
  130. //double Num3 = double.Parse(data.Substring(12, 2)) * 100;
  131. //Console.WriteLine(data.Substring(12, 2));
  132. //double Num4 = double.Parse(data.Substring(14, 2)) * 10;
  133. //Console.WriteLine(data.Substring(14, 2));
  134. //double Num5 = double.Parse(data.Substring(16, 2));
  135. if (data != "")
  136. {
  137. double qty = Convert.ToInt32(data.Substring(6, 8), 16);
  138. if (lastqty > qty)
  139. {
  140. lastqty = 0;
  141. }
  142. NowQTY.Text = qty.ToString();
  143. if (Type.Text == "投入")
  144. {
  145. string ma_inqty = dh.getFieldDataByCondition("make", "nvl(ma_inqty,0)", "ma_code='" + ma_code.Text + "'").ToString();
  146. dh.ExecuteSql("update make set ma_inqty=nvl(ma_inqty,0)+'" + (qty - lastqty) + "' where ma_code='" + ma_code.Text + "' ", "update");
  147. dh.ExecuteSql("insert into makehourcount(mhc_id,mhc_macode,mhc_indate,mhc_type,mhc_qty,mhc_linecode)" +
  148. "values(makehourcount_seq.nextval,'" + ma_code.Text + "',sysdate,'" + Type.Text + "','" + (qty - lastqty) + "','" + li_code.Text + "')", "insert");
  149. }
  150. else
  151. {
  152. string ma_endqty = dh.getFieldDataByCondition("make", "nvl(ma_endqty,0)", "ma_code='" + ma_code.Text + "'").ToString();
  153. dh.ExecuteSql("update make set ma_endqty=nvl(ma_endqty,0)+'" + (qty - lastqty) + "' where ma_code='" + ma_code.Text + "' ", "update");
  154. dh.ExecuteSql("insert into makehourcount(mhc_id,mhc_macode,mhc_indate,mhc_type,mhc_qty,mhc_linecode)" +
  155. "values(makehourcount_seq.nextval,'" + ma_code.Text + "',sysdate,'" + Type.Text + "','" + (qty - lastqty) + "','" + li_code.Text + "')", "insert");
  156. }
  157. lastqty = qty;
  158. }
  159. }
  160. private void ConnectDB()
  161. {
  162. dh = new DataHelper();
  163. SystemInf.dh = dh;
  164. ma_code.TableName = "make";
  165. ma_code.SelectField = "ma_code # 工单号";
  166. ma_code.FormName = Name;
  167. ma_code.DBTitle = "工单查询";
  168. ma_code.SetValueField = new string[] { "ma_code" };
  169. ma_code.Condition = "";
  170. ma_code.DbChange += nr_rule_DBChange;
  171. li_code.TableName = "line";
  172. li_code.SelectField = "li_code # 线别编号,li_name # 线别名称";
  173. li_code.FormName = Name;
  174. li_code.DBTitle = "线别查询";
  175. li_code.SetValueField = new string[] { "li_code" };
  176. li_code.Condition = "";
  177. li_code.DbChange += nr_rule_DBChange;
  178. }
  179. SerialPort serialPort1 = new SerialPort();
  180. private void StartWatch_Click(object sender, EventArgs e)
  181. {
  182. BaseUtil.SetCacheData("Type", Type.Text);
  183. BaseUtil.SetCacheData("ComPort", ComPort.Text);
  184. BaseUtil.SetCacheData("BaudRate", BaudRate.Text);
  185. BaseUtil.SetCacheData("Line", li_code.Text);
  186. if (!dh.CheckExist("Make", "ma_code='" + ma_code.Text + "'"))
  187. {
  188. OperateResult.AppendText("工单号不能为空\n");
  189. return;
  190. }
  191. if (!dh.CheckExist("line", "li_code='" + li_code.Text + "'"))
  192. {
  193. OperateResult.AppendText("线别不能为空\n");
  194. return;
  195. }
  196. if (Type.Text == "印刷机")
  197. {
  198. Timer.Start();
  199. }
  200. else
  201. {
  202. string ExitConfirm = MessageBox.Show(this, "确认计数器是否置为0?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question).ToString();
  203. if (ExitConfirm != "Yes")
  204. {
  205. return;
  206. }
  207. //设置按钮不可点击
  208. StartWatch.Enabled = false;
  209. ma_code.Enabled = false;
  210. StopWatch.Enabled = true;
  211. try
  212. {
  213. serialPort1.PortName = ComPort.Text;
  214. serialPort1.BaudRate = int.Parse(BaudRate.Text);
  215. serialPort1.Open();
  216. Timer.Start();
  217. }
  218. catch (Exception mes)
  219. {
  220. if (BaudRate.Text == "" || BaudRate.Text == "")
  221. OperateResult.AppendText(">>请先维护波特率和串口\n");
  222. else
  223. OperateResult.AppendText(">>" + mes.Message + "\n");
  224. }
  225. }
  226. OperateResult.AppendText("开始执行监控\n");
  227. }
  228. private void XmlWatcher_Created(object sender, FileSystemEventArgs e)
  229. {
  230. OperateResult.AppendText("文件修改:" + e.FullPath + "\n");
  231. TxtHandleProcess(e.FullPath);
  232. }
  233. string nextLine;
  234. private void TxtHandleProcess(string FileName)
  235. {
  236. List<string> badcode = new List<string>();
  237. List<string> badlocation = new List<string>();
  238. List<string> badprod = new List<string>();
  239. }
  240. private void StopWatch_Click(object sender, EventArgs e)
  241. {
  242. XmlWatcher.EnableRaisingEvents = false;
  243. StartWatch.Enabled = true;
  244. ma_code.Enabled = true;
  245. StopWatch.Enabled = false;
  246. OperateResult.AppendText("停止执行监控\n");
  247. }
  248. private void Clean_Click(object sender, EventArgs e)
  249. {
  250. OperateResult.Clear();
  251. }
  252. private void Form1_FormClosing(object sender, FormClosingEventArgs e)
  253. {
  254. string ExitConfirm = MessageBox.Show(this, "确认退出?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question).ToString();
  255. if (ExitConfirm != "Yes")
  256. {
  257. WindowState = FormWindowState.Minimized;
  258. e.Cancel = true;
  259. }
  260. }
  261. private void Timer_Tick(object sender, EventArgs e)
  262. {
  263. if (Type.Text == "印刷机")
  264. {
  265. DateTime targetDate = new DateTime(2025, 3, 17);
  266. var AllXmls = Directory.GetFiles(FolderPath.Text, "*.*", SearchOption.AllDirectories).Where(s => s.ToUpper().EndsWith(".CSV") || s.ToUpper().EndsWith(".INI"));
  267. foreach (var Xml in AllXmls)
  268. {
  269. //解析当天日志
  270. if (Xml.Contains(DateTime.Now.ToString("yyyy-MM-dd")))
  271. {
  272. var filteredLines = File.ReadLines(Xml).Skip(1) // 跳过标题行
  273. .Where(line =>
  274. {
  275. string[] parts = line.Split(',');
  276. if (parts.Length < 2) return false;
  277. if (DateTime.TryParse(parts[1], out DateTime timestamp))
  278. {
  279. return timestamp > DateTime.Now.AddDays(-10);
  280. }
  281. return false;
  282. });
  283. int pcbcount = int.Parse(dh.getFieldDataByCondition("make left join product on ma_prodcode=pr_code", "nvl(pr_pcbacount,1)", "ma_code='" + ma_code.Text + "'").ToString());
  284. foreach (var line in filteredLines)
  285. {
  286. dh.ExecuteSql("insert into makehourcount(mhc_id,mhc_macode,mhc_indate,mhc_type,mhc_qty,mhc_linecode)" +
  287. "values(makehourcount_seq.nextval,'" + ma_code.Text + "',sysdate,'" + Type.Text + "','" + pcbcount + "','" + li_code.Text + "')", "insert");
  288. }
  289. }
  290. }
  291. }
  292. else
  293. {
  294. if (serialPort1.IsOpen)
  295. {
  296. byte[] data = HexStringToBytes("01 03 00 01 00 06 94 08");
  297. serialPort1.Write(data, 0, data.Length);
  298. }
  299. }
  300. }
  301. private void AutoStart_CheckedChanged(object sender, EventArgs e)
  302. {
  303. SetAutoRun();
  304. }
  305. private void SetAutoRun()
  306. {
  307. if (AutoStart.Checked) //设置开机自启动
  308. {
  309. string path = Application.ExecutablePath;
  310. RegistryKey rk = Registry.LocalMachine;
  311. RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
  312. rk2.SetValue("FileWatcher.exe", path);
  313. rk2.Close();
  314. rk.Close();
  315. }
  316. else //取消开机自启动
  317. {
  318. string path = Application.ExecutablePath;
  319. RegistryKey rk = Registry.LocalMachine;
  320. RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
  321. rk2.DeleteValue("FileWatcher.exe", false);
  322. rk2.Close();
  323. rk.Close();
  324. }
  325. }
  326. private byte[] HexStringToBytes(string hs)//十六进制字符串转byte
  327. {
  328. string a = hs.Replace(" ", "");
  329. int bytelength = 0;
  330. if (a.Length % 2 == 0)
  331. {
  332. bytelength = a.Length / 2;
  333. }
  334. else
  335. {
  336. bytelength = a.Length / 2 + 1;
  337. }
  338. byte[] b = new byte[bytelength];
  339. //逐个字符变为16进制字节数据
  340. for (int i = 0; i < bytelength; i++)
  341. {
  342. if (i == bytelength - 1)
  343. {
  344. b[i] = Convert.ToByte(a.Substring(i * 2), 16);
  345. }
  346. else
  347. {
  348. b[i] = Convert.ToByte(a.Substring(i * 2, 2), 16);
  349. }
  350. }
  351. //按照指定编码将字节数组变为字符串
  352. return b;
  353. }
  354. private void ChooseFolder_Click(object sender, EventArgs e)
  355. {
  356. FolderBrowserDialog folder = new FolderBrowserDialog();
  357. folder.Description = "选择监控文件夹";
  358. DialogResult result = folder.ShowDialog();
  359. if (result == DialogResult.OK)
  360. {
  361. FolderPath.Text = folder.SelectedPath;
  362. }
  363. }
  364. }
  365. }