AutoMakeQTY.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  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 AutoMakeQTY : 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. /// <summary>
  34. /// 线别
  35. /// </summary>
  36. string ilinecode;
  37. /// <summary>
  38. /// 不良代码组
  39. /// </summary>
  40. string ibadgroup;
  41. /// <summary>
  42. /// 当前工序
  43. /// </summary>
  44. string istepcode;
  45. StringBuilder sql = new StringBuilder();
  46. /// <summary>
  47. /// 缓存的文件
  48. /// </summary>
  49. public static string CachePath = Environment.GetEnvironmentVariable("windir").Substring(0, 1) + @":/UAS_MES/XmlAnalysor/Cache.xml";
  50. /// <summary>
  51. /// 缓存的文件夹
  52. /// </summary>
  53. public static string CachePathFolder = Environment.GetEnvironmentVariable("windir").Substring(0, 1) + @":/UAS_MES/XmlAnalysor/";
  54. /// <summary>
  55. /// 需要解析的文件名
  56. /// </summary>
  57. List<string> _FileName = new List<string>();
  58. string master = "HUAG";
  59. ftpOperater ftp = new ftpOperater();
  60. public AutoMakeQTY()
  61. {
  62. InitializeComponent();
  63. StartPosition = FormStartPosition.CenterScreen;
  64. }
  65. string IPAddress = "";
  66. private void Form1_Load(object sender, EventArgs e)
  67. {
  68. CheckForIllegalCrossThreadCalls = false;
  69. FormBorderStyle = FormBorderStyle.FixedSingle;
  70. InitDB = new Thread(ConnectDB);
  71. //添加监控事件
  72. XmlWatcher.Changed += new FileSystemEventHandler(XmlWatcher_Created);
  73. //ATEFile.Changed += new FileSystemEventHandler(XmlWatcher_Created);
  74. SetLoadingWindow stw = new SetLoadingWindow(InitDB, "正在启动程序");
  75. stw.StartPosition = FormStartPosition.CenterScreen;
  76. stw.ShowDialog();
  77. List<string> CacheInf = new List<string>();
  78. IPHostEntry IpEntry = Dns.GetHostEntry(Dns.GetHostName());
  79. for (int i = 0; i < IpEntry.AddressList.Length; i++)
  80. {
  81. if (IpEntry.AddressList[i].AddressFamily == AddressFamily.InterNetwork)
  82. IPAddress = IpEntry.AddressList[i].ToString();
  83. }
  84. //获取缓存信息
  85. try
  86. {
  87. Type.Text = BaseUtil.GetCacheData("Type").ToString();
  88. ComPort.Text = BaseUtil.GetCacheData("ComPort").ToString();
  89. BaudRate.Text = BaseUtil.GetCacheData("BaudRate").ToString();
  90. }
  91. catch (Exception ex) { MessageBox.Show(ex.Message); }
  92. //获取岗位资源相关信息
  93. DataTable dt = (DataTable)dh.ExecuteSql("select sc_linecode,sc_stepcode,st_badgroupcode from source left join step on sc_stepcode=st_code where sc_code='" + isource + "'", "select");
  94. if (dt.Rows.Count > 0)
  95. {
  96. ilinecode = dt.Rows[0]["sc_linecode"].ToString();
  97. istepcode = dt.Rows[0]["sc_stepcode"].ToString();
  98. ibadgroup = dt.Rows[0]["st_badgroupcode"].ToString();
  99. }
  100. StartWatch.PerformClick();
  101. }
  102. private void ConnectDB()
  103. {
  104. dh = new DataHelper();
  105. }
  106. SerialPort serialPort1 = new SerialPort();
  107. bool GetData = true;
  108. private void getSerialData()
  109. {
  110. if (serialPort1.IsOpen)
  111. {
  112. try
  113. {
  114. while (GetData)
  115. {
  116. try
  117. {
  118. int len = serialPort1.BytesToRead;
  119. Byte[] readBuffer = new Byte[len];
  120. serialPort1.Read(readBuffer, 0, len); //将数据读入缓存
  121. string weigh = Encoding.Default.GetString(readBuffer);
  122. if (weigh != "")
  123. {
  124. OperateResult.AppendText(weigh + "\n");
  125. }
  126. }
  127. catch (Exception)
  128. {
  129. GetData = false;
  130. }
  131. }
  132. }
  133. catch (IOException ex) { MessageBox.Show(ex.Message); }
  134. }
  135. else OperateResult.AppendText(">>端口已被占用,请关闭其他窗口\n");
  136. }
  137. Thread thread;
  138. private void StartWatch_Click(object sender, EventArgs e)
  139. {
  140. BaseUtil.SetCacheData("Type", Type.Text);
  141. BaseUtil.SetCacheData("ComPort", ComPort.Text);
  142. BaseUtil.SetCacheData("BaudRate", BaudRate.Text);
  143. Timer.Interval = 1000 * 60;
  144. Timer.Start();
  145. //设置按钮不可点击
  146. StartWatch.Enabled = false;
  147. ma_code.Enabled = false;
  148. StopWatch.Enabled = true;
  149. thread = new Thread(getSerialData);
  150. try
  151. {
  152. serialPort1.PortName = BaudRate.Text;
  153. serialPort1.BaudRate = int.Parse(BaudRate.Text);
  154. serialPort1.Open();
  155. GetData = true;
  156. thread.Start();
  157. }
  158. catch (Exception mes)
  159. {
  160. if (BaudRate.Text == "" || BaudRate.Text == "")
  161. OperateResult.AppendText(">>请先维护波特率和串口\n");
  162. else
  163. OperateResult.AppendText(">>" + mes.Message + "\n");
  164. }
  165. OperateResult.AppendText("开始执行监控\n");
  166. }
  167. private void XmlWatcher_Created(object sender, FileSystemEventArgs e)
  168. {
  169. OperateResult.AppendText("文件修改:" + e.FullPath + "\n");
  170. TxtHandleProcess(e.FullPath);
  171. }
  172. string nextLine;
  173. private void TxtHandleProcess(string FileName)
  174. {
  175. List<string> badcode = new List<string>();
  176. List<string> badlocation = new List<string>();
  177. List<string> badprod = new List<string>();
  178. }
  179. private void StopWatch_Click(object sender, EventArgs e)
  180. {
  181. XmlWatcher.EnableRaisingEvents = false;
  182. StartWatch.Enabled = true;
  183. ma_code.Enabled = true;
  184. StopWatch.Enabled = false;
  185. OperateResult.AppendText("停止执行监控\n");
  186. }
  187. private void Clean_Click(object sender, EventArgs e)
  188. {
  189. OperateResult.Clear();
  190. }
  191. private void Form1_FormClosing(object sender, FormClosingEventArgs e)
  192. {
  193. string ExitConfirm = MessageBox.Show(this, "确认退出?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question).ToString();
  194. if (ExitConfirm != "Yes")
  195. {
  196. WindowState = FormWindowState.Minimized;
  197. e.Cancel = true;
  198. }
  199. }
  200. private void AutoStart_CheckedChanged(object sender, EventArgs e)
  201. {
  202. SetAutoRun();
  203. }
  204. private void SetAutoRun()
  205. {
  206. if (AutoStart.Checked) //设置开机自启动
  207. {
  208. string path = Application.ExecutablePath;
  209. RegistryKey rk = Registry.LocalMachine;
  210. RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
  211. rk2.SetValue("FileWatcher.exe", path);
  212. rk2.Close();
  213. rk.Close();
  214. }
  215. else //取消开机自启动
  216. {
  217. string path = Application.ExecutablePath;
  218. RegistryKey rk = Registry.LocalMachine;
  219. RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
  220. rk2.DeleteValue("FileWatcher.exe", false);
  221. rk2.Close();
  222. rk.Close();
  223. }
  224. }
  225. /// <summary>
  226. /// 请求上传图片到阿里云
  227. /// </summary>
  228. /// <param name="url">上传地址</param>
  229. /// <param name="filepath">本地文件路径</param>
  230. /// <param name="dic">上传的数据信息</param>
  231. /// <returns></returns>
  232. public string UploadFilesToRemoteUrl(string url1, string filepath, Dictionary<string, object> dic, out string fp_path, out string fp_id)
  233. {
  234. fp_id = "";
  235. fp_path = "";
  236. try
  237. {
  238. ServicePointManager.DefaultConnectionLimit = 50;
  239. string boundary = DateTime.Now.Ticks.ToString("x");
  240. byte[] boundarybytes = System.Text.Encoding.UTF8.GetBytes("--" + boundary + "\r\n");
  241. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url1);
  242. request.Method = "POST";
  243. request.Timeout = 10 * 10000;
  244. request.ContentType = "multipart/form-data; boundary=" + boundary;
  245. Stream rs = request.GetRequestStream();
  246. var endBoundaryBytes = Encoding.UTF8.GetBytes("--" + boundary + "--\r\n");
  247. string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n" + "\r\n" + "{1}" + "\r\n";
  248. if (dic != null)
  249. {
  250. foreach (string key in dic.Keys)
  251. {
  252. rs.Write(boundarybytes, 0, boundarybytes.Length);
  253. string formitem = string.Format(formdataTemplate, key, dic[key]);
  254. byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
  255. rs.Write(formitembytes, 0, formitembytes.Length);
  256. }
  257. }
  258. string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n\r\n";
  259. {
  260. rs.Write(boundarybytes, 0, boundarybytes.Length);
  261. var header = string.Format(headerTemplate, "file", Path.GetFileName(filepath));
  262. var headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
  263. rs.Write(headerbytes, 0, headerbytes.Length);
  264. using (var fileStream = new FileStream(filepath, FileMode.Open, FileAccess.Read))
  265. {
  266. var buffer = new byte[1024];
  267. var bytesRead = 0;
  268. while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
  269. {
  270. rs.Write(buffer, 0, bytesRead);
  271. }
  272. }
  273. var cr = Encoding.UTF8.GetBytes("\r\n");
  274. rs.Write(cr, 0, cr.Length);
  275. }
  276. rs.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
  277. var response = request.GetResponse() as HttpWebResponse;
  278. StreamReader newReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
  279. string Content = newReader.ReadToEnd();
  280. Dictionary<string, object> dic1 = new Dictionary<string, object>();
  281. List<Dictionary<string, object>> dic2 = null;
  282. dic1 = BaseUtil.ToDictionary(Content);
  283. dic2 = dic1["data"] as List<Dictionary<string, object>>;
  284. if (dic2[0]["filepath"] != null)
  285. {
  286. fp_id = dic2[0]["filepath"].ToString();
  287. fp_path = dic2[0]["path"].ToString();
  288. }
  289. if (response.StatusCode == HttpStatusCode.OK)
  290. {
  291. Console.WriteLine(fp_id);
  292. return fp_id;
  293. }
  294. }
  295. catch (Exception e)
  296. {
  297. Console.WriteLine(e.Message + e.StackTrace);
  298. }
  299. return "";
  300. }
  301. }
  302. }