Browse Source

串口数据对接开发

callm 11 months ago
parent
commit
11b6694e62
3 changed files with 55 additions and 146 deletions
  1. 13 15
      FileWatcher/AutoMakeQTY.Designer.cs
  2. 41 130
      FileWatcher/AutoMakeQTY.cs
  3. 1 1
      FileWatcher/Program.cs

+ 13 - 15
FileWatcher/AutoMakeQTY.Designer.cs

@@ -42,10 +42,10 @@
             this.Type = new System.Windows.Forms.ComboBox();
             this.label1 = new System.Windows.Forms.Label();
             this.AutoStart = new System.Windows.Forms.CheckBox();
-            this.ComPort = new FileWatcher.SerialPortCombox();
             this.label2 = new System.Windows.Forms.Label();
             this.label3 = new System.Windows.Forms.Label();
             this.BaudRate = new System.Windows.Forms.TextBox();
+            this.ComPort = new FileWatcher.SerialPortCombox();
             ((System.ComponentModel.ISupportInitialize)(this.XmlWatcher)).BeginInit();
             ((System.ComponentModel.ISupportInitialize)(this.ATEFile)).BeginInit();
             this.SuspendLayout();
@@ -112,7 +112,6 @@
             this.MakeCode_lable.Size = new System.Drawing.Size(104, 38);
             this.MakeCode_lable.TabIndex = 12;
             this.MakeCode_lable.Text = "工单号";
-            this.MakeCode_lable.Visible = false;
             // 
             // ma_code
             // 
@@ -121,11 +120,11 @@
             this.ma_code.Name = "ma_code";
             this.ma_code.Size = new System.Drawing.Size(436, 35);
             this.ma_code.TabIndex = 17;
-            this.ma_code.Visible = false;
             // 
             // Timer
             // 
-            this.Timer.Interval = 60000;
+            this.Timer.Interval = 5000;
+            this.Timer.Tick += new System.EventHandler(this.Timer_Tick);
             // 
             // ATEFile
             // 
@@ -155,11 +154,12 @@
             this.label1.Size = new System.Drawing.Size(75, 38);
             this.label1.TabIndex = 19;
             this.label1.Text = "类型";
-            this.label1.Visible = false;
             // 
             // AutoStart
             // 
             this.AutoStart.AutoSize = true;
+            this.AutoStart.Checked = true;
+            this.AutoStart.CheckState = System.Windows.Forms.CheckState.Checked;
             this.AutoStart.Location = new System.Drawing.Point(678, 227);
             this.AutoStart.Name = "AutoStart";
             this.AutoStart.Size = new System.Drawing.Size(186, 28);
@@ -167,14 +167,6 @@
             this.AutoStart.Text = "开机自动启动";
             this.AutoStart.UseVisualStyleBackColor = true;
             // 
-            // ComPort
-            // 
-            this.ComPort.Location = new System.Drawing.Point(204, 120);
-            this.ComPort.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
-            this.ComPort.Name = "ComPort";
-            this.ComPort.Size = new System.Drawing.Size(176, 40);
-            this.ComPort.TabIndex = 21;
-            // 
             // label2
             // 
             this.label2.AutoSize = true;
@@ -197,7 +189,6 @@
             this.label3.Size = new System.Drawing.Size(104, 38);
             this.label3.TabIndex = 23;
             this.label3.Text = "波特率";
-            this.label3.Visible = false;
             // 
             // BaudRate
             // 
@@ -206,7 +197,14 @@
             this.BaudRate.Name = "BaudRate";
             this.BaudRate.Size = new System.Drawing.Size(146, 35);
             this.BaudRate.TabIndex = 24;
-            this.BaudRate.Visible = false;
+            // 
+            // ComPort
+            // 
+            this.ComPort.Location = new System.Drawing.Point(204, 120);
+            this.ComPort.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
+            this.ComPort.Name = "ComPort";
+            this.ComPort.Size = new System.Drawing.Size(176, 40);
+            this.ComPort.TabIndex = 21;
             // 
             // AutoMakeQTY
             // 

+ 41 - 130
FileWatcher/AutoMakeQTY.cs

@@ -78,6 +78,7 @@ namespace FileWatcher
         {
             CheckForIllegalCrossThreadCalls = false;
             FormBorderStyle = FormBorderStyle.FixedSingle;
+            serialPort1.DataReceived += SerialPort1_DataReceived;
             InitDB = new Thread(ConnectDB);
             //添加监控事件
             XmlWatcher.Changed += new FileSystemEventHandler(XmlWatcher_Created);
@@ -86,7 +87,6 @@ namespace FileWatcher
             stw.StartPosition = FormStartPosition.CenterScreen;
             stw.ShowDialog();
             List<string> CacheInf = new List<string>();
-
             IPHostEntry IpEntry = Dns.GetHostEntry(Dns.GetHostName());
             for (int i = 0; i < IpEntry.AddressList.Length; i++)
             {
@@ -109,7 +109,15 @@ namespace FileWatcher
                 istepcode = dt.Rows[0]["sc_stepcode"].ToString();
                 ibadgroup = dt.Rows[0]["st_badgroupcode"].ToString();
             }
-            StartWatch.PerformClick();
+            //StartWatch.PerformClick();
+        }
+
+        private void SerialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
+        {
+            int len = serialPort1.BytesToRead;
+            Byte[] readBuffer = new Byte[len];
+            serialPort1.Read(readBuffer, 0, len); //将数据读入缓存
+            OperateResult.AppendText(BitConverter.ToString(readBuffer, 0, readBuffer.Length).Replace("-", " "));
         }
 
         private void ConnectDB()
@@ -117,38 +125,8 @@ namespace FileWatcher
             dh = new DataHelper();
         }
         SerialPort serialPort1 = new SerialPort();
-        bool GetData = true;
-        private void getSerialData()
-        {
-            if (serialPort1.IsOpen)
-            {
-                try
-                {
-                    while (GetData)
-                    {
-                        try
-                        {
-                            int len = serialPort1.BytesToRead;
-                            Byte[] readBuffer = new Byte[len];
-                            serialPort1.Read(readBuffer, 0, len); //将数据读入缓存
-                            string weigh = Encoding.Default.GetString(readBuffer);
-                            if (weigh != "")
-                            {
-                                OperateResult.AppendText(weigh + "\n");
-                            }
-                        }
-                        catch (Exception)
-                        {
-                            GetData = false;
-                        }
-                    }
-                }
-                catch (IOException ex) { MessageBox.Show(ex.Message); }
-            }
-            else OperateResult.AppendText(">>端口已被占用,请关闭其他窗口\n");
-        }
 
-        Thread thread;
+
 
         private void StartWatch_Click(object sender, EventArgs e)
         {
@@ -161,14 +139,11 @@ namespace FileWatcher
             StartWatch.Enabled = false;
             ma_code.Enabled = false;
             StopWatch.Enabled = true;
-            thread = new Thread(getSerialData);
             try
             {
-                serialPort1.PortName = BaudRate.Text;
+                serialPort1.PortName = ComPort.Text;
                 serialPort1.BaudRate = int.Parse(BaudRate.Text);
                 serialPort1.Open();
-                GetData = true;
-                thread.Start();
             }
             catch (Exception mes)
             {
@@ -178,7 +153,7 @@ namespace FileWatcher
                     OperateResult.AppendText(">>" + mes.Message + "\n");
             }
             OperateResult.AppendText("开始执行监控\n");
-
+            Timer.Start();
         }
 
         private void XmlWatcher_Created(object sender, FileSystemEventArgs e)
@@ -211,7 +186,6 @@ namespace FileWatcher
             OperateResult.Clear();
         }
 
-
         private void Form1_FormClosing(object sender, FormClosingEventArgs e)
         {
             string ExitConfirm = MessageBox.Show(this, "确认退出?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question).ToString();
@@ -222,11 +196,17 @@ namespace FileWatcher
             }
         }
 
+
+        private void Timer_Tick(object sender, EventArgs e)
+        {
+            byte[] data = HexStringToBytes("01 03 00 01 00 06 94 08");
+            serialPort1.Write(data, 0, data.Length);
+        }
+
         private void AutoStart_CheckedChanged(object sender, EventArgs e)
         {
             SetAutoRun();
         }
-
         private void SetAutoRun()
         {
             if (AutoStart.Checked) //设置开机自启动  
@@ -249,103 +229,34 @@ namespace FileWatcher
             }
         }
 
-        /// <summary>
-        /// 请求上传图片到阿里云
-        /// </summary>
-        /// <param name="url">上传地址</param>
-        /// <param name="filepath">本地文件路径</param>
-        /// <param name="dic">上传的数据信息</param>
-        /// <returns></returns>
-        public string UploadFilesToRemoteUrl(string url1, string filepath, Dictionary<string, object> dic, out string fp_path, out string fp_id)
+        private byte[] HexStringToBytes(string hs)//十六进制字符串转byte
         {
-            fp_id = "";
-            fp_path = "";
-            try
+            string a = hs.Replace(" ", "");
+            int bytelength = 0;
+            if (a.Length % 2 == 0)
             {
-                ServicePointManager.DefaultConnectionLimit = 50;
-
-                string boundary = DateTime.Now.Ticks.ToString("x");
-
-                byte[] boundarybytes = System.Text.Encoding.UTF8.GetBytes("--" + boundary + "\r\n");
-
-                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url1);
-                request.Method = "POST";
-                request.Timeout = 10 * 10000;
-                request.ContentType = "multipart/form-data; boundary=" + boundary;
-
-                Stream rs = request.GetRequestStream();
-
-                var endBoundaryBytes = Encoding.UTF8.GetBytes("--" + boundary + "--\r\n");
-
-                string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n" + "\r\n" + "{1}" + "\r\n";
-                if (dic != null)
-                {
-                    foreach (string key in dic.Keys)
-                    {
-                        rs.Write(boundarybytes, 0, boundarybytes.Length);
-
-                        string formitem = string.Format(formdataTemplate, key, dic[key]);
-
-                        byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
-
-                        rs.Write(formitembytes, 0, formitembytes.Length);
-                    }
-
-                }
-
-                string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n\r\n";
-                {
-                    rs.Write(boundarybytes, 0, boundarybytes.Length);
-
-                    var header = string.Format(headerTemplate, "file", Path.GetFileName(filepath));
-
-                    var headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
-
-                    rs.Write(headerbytes, 0, headerbytes.Length);
-
-                    using (var fileStream = new FileStream(filepath, FileMode.Open, FileAccess.Read))
-                    {
-                        var buffer = new byte[1024];
-
-                        var bytesRead = 0;
-
-                        while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
-                        {
-                            rs.Write(buffer, 0, bytesRead);
-                        }
-                    }
-                    var cr = Encoding.UTF8.GetBytes("\r\n");
-
-                    rs.Write(cr, 0, cr.Length);
-                }
-
-                rs.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
-
-                var response = request.GetResponse() as HttpWebResponse;
-
-                StreamReader newReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
-                string Content = newReader.ReadToEnd();
-                Dictionary<string, object> dic1 = new Dictionary<string, object>();
-                List<Dictionary<string, object>> dic2 = null;
-                dic1 = BaseUtil.ToDictionary(Content);
-                dic2 = dic1["data"] as List<Dictionary<string, object>>;
-
-                if (dic2[0]["filepath"] != null)
+                bytelength = a.Length / 2;
+            }
+            else
+            {
+                bytelength = a.Length / 2 + 1;
+            }
+            byte[] b = new byte[bytelength];
+            //逐个字符变为16进制字节数据
+            for (int i = 0; i < bytelength; i++)
+            {
+                if (i == bytelength - 1)
                 {
-                    fp_id = dic2[0]["filepath"].ToString();
-                    fp_path = dic2[0]["path"].ToString();
+                    b[i] = Convert.ToByte(a.Substring(i * 2), 16);
                 }
-                if (response.StatusCode == HttpStatusCode.OK)
+                else
                 {
-                    Console.WriteLine(fp_id);
-                    return fp_id;
+                    b[i] = Convert.ToByte(a.Substring(i * 2, 2), 16);
                 }
             }
-            catch (Exception e)
-            {
-                Console.WriteLine(e.Message + e.StackTrace);
-            }
-            return "";
+            //按照指定编码将字节数组变为字符串
+            return b;
         }
+
     }
 }

+ 1 - 1
FileWatcher/Program.cs

@@ -45,7 +45,7 @@ namespace FileWatcher
                 Application.EnableVisualStyles();
                 Application.SetCompatibleTextRenderingDefault(false);
                 if (principal.IsInRole(WindowsBuiltInRole.Administrator))
-                    Application.Run(new Login());
+                    Application.Run(new AutoMakeQTY());
                 else
                 {
                     //创建启动对象