using DevExpress.Utils.Drawing.Helpers; using DevExpress.XtraReports; using NPOI.SS.Formula.Functions; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Drawing; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Web.Services.Description; using System.Web.UI.WebControls.WebParts; using System.Windows.Forms; using UAS_MES_NEW.DataOperate; using UAS_MES_NEW.Entity; using UAS_MES_NEW.PublicMethod; namespace UAS_MES_NEW.Make { public partial class Make_WirelessThroughput : Form { public Make_WirelessThroughput() { InitializeComponent(); } StringBuilder SQL = new StringBuilder(); DataTable dt; DataHelper dh; string telnetPort; private void Make_WirelessThroughput_Load(object sender, EventArgs e) { dh = SystemInf.dh; try { string hostName = Dns.GetHostName(); IPHostEntry hostEntry = Dns.GetHostEntry(hostName); foreach (IPAddress ip in hostEntry.AddressList) { if (ip.AddressFamily == AddressFamily.InterNetwork) { IPList.Text = ip.ToString(); } } } catch (Exception ex) { ShowMsg(0, $"获取iperf服务器地址失败,{ex.Message}"); } if (!IPList.Text.Contains(":")) { IPList.Text = IPList.Text + ":5021"; } telnetPort = "23"; //if (!ProductList.Text.Contains(":")) //{ // ProductList.Text = ProductList.Text + ":23"; //} Locat1.Visible = false; Locat2.Visible = false; Locat3.Visible = false; Radio1.Visible = false; Radio2.Visible = false; } private void SN_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode != Keys.Enter) return; if (IPList.Text.IndexOf(':') > 0) IPList.Text = IPList.Text.Replace(":", ":"); else IPList.Text = IPList.Text.Trim(); SN.Text = SN.Text.Trim().Replace(";", ";"); string sn = SN.Text.Trim(); SQL.Clear(); //SQL.Append($"SELECT pr_test_account,pr_test_password FROM makeserial,product WHERE ms_sncode = '{sn}' AND ms_prodcode = pr_code"); SQL.Append($"SELECT * FROM (SELECT pr_test_account,pr_test_password FROM makeserial,product WHERE ms_sncode = '{sn}' AND ms_prodcode = pr_code ORDER BY ms_indate DESC) WHERE ROWNUM = 1"); dt = (DataTable)dh.ExecuteSql(SQL.ToString(), "select"); if (dt.Rows.Count == 0) { ShowMsg(0, $"序列号:{sn}未维护吞吐量测试账户密码"); } else { Account.Text = dt.Rows[0]["pr_test_account"].ToString(); Password.Text = dt.Rows[0]["pr_test_password"].ToString(); } if (IsCheckSet()) return; UpdateSN("L", SN.Text.Trim()); ShowMsg(1, $"开始测试"); int iSPort = Convert.ToInt32(IPList.Text.Trim().Split(':')[1]); var tester = new CameraIperfTester( timeOut: TestTime.Text.Trim(), cameraIp: ProductList.Text.Trim().Split(':')[0], cameraPort: Convert.ToInt32(telnetPort), username: Account.Text.Trim(), password: Password.Text.Trim(), iperfServerIp: IPList.Text.Trim().Split(':')[0], iperfServerPort: iSPort ); string parentPath = Path.GetDirectoryName(ExePath.Text.Trim()); string logsPath = Path.Combine(parentPath, "iperf_logs"); if (!Directory.Exists(logsPath)) { Directory.CreateDirectory(logsPath); } string Msg = tester.TestStart(SN.Text.Trim(), ExePath.Text.Trim(), logsPath, comboBox1.SelectedIndex.ToString()); if (Msg.StartsWith("NG")) { ShowMsg(0, Msg); return; } string upRate = Msg.Split('|')[0].Split(',')[1]; string downRate = Msg.Split('|')[1]; ShowMsg(1, $"OK,上行速率: {upRate},下行速率: {downRate}"); ResMax.Text = upRate; ResMin.Text = downRate; string tDetail = $"upRate/{upRate};downRate/{downRate}"; CheckPassStation(SN.Text, "PASS", tDetail); } private void CheckPassStation(string sn, string testRes, string testDetail) { List param = new List() { }; string outMsg = ""; param.Add(workOrder.Text); param.Add(sn); param.Add(User.UserSourceCode); param.Add(testRes); param.Add(""); param.Add(""); param.Add("Thruput"); param.Add(testDetail); param.Add(outMsg); string[] paramList = param.ToArray(); dh.CallProcedure("cs_insert_testrejects", ref paramList); if (paramList[8].Substring(0, 2) == "OK") { ShowMsg(1, $"序列号{sn}采集成功:测试结果为{testRes}"); LogicHandler.DoCommandLog(Tag.ToString(), User.UserCode, workOrder.Text, User.UserLineCode, User.UserSourceCode, "无线吞吐量", "无线吞吐量过站成功", sn, ""); } dt = (DataTable)dh.ExecuteSql($"SELECT mp_id FROM makeprocess WHERE mp_sncode = '{sn}' AND instr(mp_stepname, '吞吐量') > 0", "select"); if (dt.Rows.Count > 0) { ShowMsg(1, $"序列号:{sn}已经过站记录"); return; } string oWO, oWOId, oErrMsg = ""; if (LogicHandler.CheckStepSNAndMacode(workOrder.Text, User.UserSourceCode, sn, User.UserCode, out oWO, out oWOId, out oErrMsg)) { if (LogicHandler.SetStepResult(oWO, User.UserSourceCode, sn, "无线吞吐量", "OK", User.UserCode, out oErrMsg)) { ShowMsg(1, $"序列号{sn},过站记录成功"); } else { ShowMsg(0, $"序列号{sn},处理过站NG:{oErrMsg}"); } } else { ShowMsg(0, $"序列号{sn},过站核对NG:{oErrMsg}"); } } private bool IsCheckSet() { if (string.IsNullOrEmpty(IPList.Text)) { ShowMsg(0, "请选择本地iperf 服务IP地址"); return true; } if (string.IsNullOrEmpty(ProductList.Text)) { ShowMsg(0, "请选择产品固定IP地址"); return true; } if (string.IsNullOrEmpty(Account.Text)) { ShowMsg(0, "请输入Telnet登录账号"); return true; } if (string.IsNullOrEmpty(Password.Text)) { ShowMsg(0, "请输入Telnet登录密码"); return true; } if (string.IsNullOrEmpty(ExePath.Text)) { ShowMsg(0, "请输入启动iperf3文件"); return true; } if (!File.Exists(ExePath.Text)) { Console.WriteLine("iperf3启动文件不存在"); } if (string.IsNullOrEmpty(TestTime.Text)) { ShowMsg(0, "请输入测试时长"); return true; } if (comboBox1.SelectedIndex == -1) { ShowMsg(0, "请选择指令模式"); return true; } //if (Locat1.Checked == false || Locat2.Checked == false || Locat3.Checked == false) //{ // ShowMsg(0, "请选择固件位置"); // return true; //} //if (Radio1.Checked == false || Radio1.Checked == false ) //{ // ShowMsg(0, "请选择测试类型"); // return true; //} return false; } private void UpdateSN(string type, string sn) { if (type == "C") { serialNumber.Text = ""; workOrder.Text = ""; productCode.Text = ""; productName.Text = ""; } else if (type == "L") { SQL.Clear(); SQL.Append($@"SELECT ms_sncode,ma_code,pr_code,pr_spec FROM makeserial,make,product WHERE ms_sncode = '{sn}' AND ms_makecode = ma_code AND ms_prodcode = pr_code"); dt = (DataTable)dh.ExecuteSql(SQL.ToString(), "select"); if (dt.Rows.Count > 0) { serialNumber.Text = dt.Rows[0]["ms_sncode"].ToString(); workOrder.Text = dt.Rows[0]["ma_code"].ToString(); productCode.Text = dt.Rows[0]["pr_code"].ToString(); productName.Text = dt.Rows[0]["pr_spec"].ToString(); } else { UpdateSN("C", sn); } } } public class CameraIperfTester { int timeOut; string cameraIp, iperfServerIp, username, password; int cameraPort, iperfServerPort; string SN, iperfPath, logDirectory; private TcpClient _telnetClient; private NetworkStream _telnetStream; string sVal1, sVal2, rVal1, rVal2; public CameraIperfTester(string timeOut, string cameraIp, int cameraPort, string username, string password, string iperfServerIp, int iperfServerPort) { this.timeOut = Convert.ToInt32(timeOut) * 1000; this.cameraIp = cameraIp; this.cameraPort = cameraPort; this.username = username; this.password = password; this.iperfServerIp = iperfServerIp; this.iperfServerPort = iperfServerPort; } public string TestStart(string sn, string iP, string lD,string cmdType) { StringBuilder Msg = new StringBuilder(); Msg.Append(TelnetConnect()); if (Msg.ToString().StartsWith("NG")) return Msg.ToString(); SN = sn; iperfPath = iP; logDirectory = lD; Msg.Clear(); Msg.Append(StartIperfTest(cmdType)); return Msg.ToString(); } public string TelnetConnect() { try { _telnetClient = new TcpClient(); IAsyncResult connectResult = _telnetClient.BeginConnect(cameraIp, cameraPort, null, null); bool connected = connectResult.AsyncWaitHandle.WaitOne(TimeSpan.FromMilliseconds(timeOut)); if (!connected) { _telnetClient.Close(); return "NG,连接超时"; } try { _telnetClient.EndConnect(connectResult); } catch (SocketException ex) { return $"NG,连接失败: {ex.Message}"; } _telnetStream = _telnetClient.GetStream(); _telnetStream.ReadTimeout = timeOut; StringBuilder fullResponse = new StringBuilder(); string welcomeResponse = ReadStream(_telnetStream); if (welcomeResponse.StartsWith("NG")) return welcomeResponse; fullResponse.Append(welcomeResponse); WriteStream(_telnetStream, username); string usernameResponse = ReadStream(_telnetStream); if (usernameResponse.StartsWith("NG")) return usernameResponse; fullResponse.Append(usernameResponse); WriteStream(_telnetStream, password); string loginResponse = ReadStream(_telnetStream); if (loginResponse.StartsWith("NG")) return loginResponse; fullResponse.Append(loginResponse); return $"OK,{fullResponse.ToString()}"; } catch (Exception ex) { Close(); return $"NG,{ex.Message}"; } } public string StartIperfTest(string cmdType) { try { StringBuilder streamTxt = new StringBuilder(); string upRate, downRate, cmdLog, upLog, downLog; if (cmdType == "0") { WriteStream(_telnetStream, "killall iperf3"); streamTxt.Append(ReadStream(_telnetStream)); Thread.Sleep(500); WriteStream(_telnetStream, $"iperf3 -s -p {iperfServerPort} -i 1&"); streamTxt.Append(ReadStream(_telnetStream)); Thread.Sleep(500); cmdLog = Path.Combine(logDirectory, $"{SN}_CMD.log"); File.WriteAllText(cmdLog, streamTxt.ToString()); upLog = Path.Combine(logDirectory, $"{SN}_up.log"); downLog = Path.Combine(logDirectory, $"{SN}_down.log"); RunIperfClient($"-c {cameraIp} -p {iperfServerPort} -t 10 -w 1M -i 1 -P 8 -R", iperfPath, upLog); RunIperfClient($"-c {cameraIp} -p {iperfServerPort} -t 10 -w 1M -i 1 -P 8", iperfPath, downLog); upRate = ParseIperfBitrate(upLog); downRate = ParseIperfBitrate(downLog); Close(); if(string.IsNullOrEmpty(upRate) || string.IsNullOrEmpty(downRate)) { return $"NG,指令一无法获测试结果,请核对指令或使用吞吐量日志解析"; } return $"OK,{upRate}|{downRate}"; } else { WriteStream(_telnetStream, "killall iperf3_mstar"); streamTxt.Append(ReadStream(_telnetStream)); Thread.Sleep(500); WriteStream(_telnetStream, "cp /mnt/tf/usb1_1/iperf3_mstar /var/tmp/ -f"); streamTxt.Append(ReadStream(_telnetStream)); Thread.Sleep(500); WriteStream(_telnetStream, "chmod a+x /var/tmp/iperf3_mstar"); streamTxt.Append(ReadStream(_telnetStream)); Thread.Sleep(500); WriteStream(_telnetStream, $"/var/tmp/iperf3_mstar -s -p {iperfServerPort} -i 1 &"); streamTxt.Append(ReadStream(_telnetStream)); cmdLog = Path.Combine(logDirectory, $"{SN}_CMD.log"); File.WriteAllText(cmdLog, streamTxt.ToString()); upLog = Path.Combine(logDirectory, $"{SN}_up.log"); downLog = Path.Combine(logDirectory, $"{SN}_down.log"); RunIperfClient($"/var/tmp/iperf3 -c {cameraIp} -p {iperfServerPort} -t 6 -w 1M -i 1 -l 1518 -P 8 -R", iperfPath, upLog); RunIperfClient($"/var/tmp/iperf3 -c {cameraIp} -p {iperfServerPort} -t 6 -w 1M -i 1 -l 1518 -P 8", iperfPath, downLog); upRate = ParseIperfBitrate(upLog); downRate = ParseIperfBitrate(downLog); Close(); if (string.IsNullOrEmpty(upRate) || string.IsNullOrEmpty(downRate)) { return $"NG,指令二获取测试结果,请核对指令或使用吞吐量日志解析"; } return $"OK,{upRate}|{downRate}"; } } catch (Exception ex) { return $"NG,{ex.Message}"; } } private void RunIperfClient(string args, string path, string logPath) { var psi = new ProcessStartInfo { FileName = path, Arguments = args, RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, CreateNoWindow = true, WorkingDirectory = Path.GetDirectoryName(path) }; using (var process = Process.Start(psi)) { StringBuilder outputBuilder = new StringBuilder(); StringBuilder errorBuilder = new StringBuilder(); process.OutputDataReceived += (sender, e) => { if (!string.IsNullOrEmpty(e.Data)) { outputBuilder.AppendLine(e.Data); } }; process.ErrorDataReceived += (sender, e) => { if (!string.IsNullOrEmpty(e.Data)) { errorBuilder.AppendLine(e.Data); } }; process.BeginOutputReadLine(); process.BeginErrorReadLine(); process.WaitForExit(); File.WriteAllText(logPath, outputBuilder.ToString() + errorBuilder.ToString()); } } public string ParseIperfBitrate(string logPath) { if (!File.Exists(logPath)) return "0.0"; var lines = File.ReadAllLines(logPath); List logItem = new List { }; foreach (var line in lines) { if (line.Trim().StartsWith("[SUM]")) { logItem.Add(line); } } if (logItem.Count > 0 && logItem[logItem.Count - 2].Contains("sender")) { var match = Regex.Match(logItem[logItem.Count - 2], @"(\d+\.\d+\s+MBytes).*?(\d+\.\d+\s+Mbits/sec)"); if (match.Success) { sVal1 = match.Groups[1].Value; sVal2 = match.Groups[2].Value; } } if (logItem.Count > 0 && logItem[logItem.Count - 1].Contains("receiver")) { var match = Regex.Match(logItem[logItem.Count - 1], @"(\d+\.\d+\s+MBytes).*?(\d+\.\d+\s+Mbits/sec)"); if (match.Success) { rVal1 = match.Groups[1].Value; rVal2 = match.Groups[2].Value; } } //double num1 = (double.Parse(sVal1.Split(' ')[0]) + double.Parse(rVal1.Split(' ')[0])) / 2; //double num2 = (double.Parse(sVal2.Split(' ')[0]) + double.Parse(rVal2.Split(' ')[0])) / 2; return rVal2; } private string WriteStream(NetworkStream stream, string data) { try { byte[] dataBytes = Encoding.UTF8.GetBytes(data + "\r\n"); stream.Write(dataBytes, 0, dataBytes.Length); stream.Flush(); return $"OK"; } catch (Exception ex) { Close(); return $"NG,写入数据时发生错误: {ex.Message}"; } } private string ReadStream(NetworkStream stream) { try { StringBuilder response = new StringBuilder(); byte[] buffer = new byte[1024]; int bytesRead; while (stream.DataAvailable || response.Length == 0) { bytesRead = stream.Read(buffer, 0, buffer.Length); if (bytesRead > 0) { response.Append(Encoding.UTF8.GetString(buffer, 0, bytesRead)); } else { break; } Thread.Sleep(100); } return response.ToString(); } catch (IOException ioEx) when (ioEx.InnerException is SocketException socketEx && socketEx.SocketErrorCode == SocketError.TimedOut) { Close(); return "NG,读取数据超时"; } catch (Exception ex) { Close(); return $"NG,读取数据时发生错误: {ex.Message}"; } } private void Close() { _telnetClient?.Close(); _telnetStream?.Close(); } } private void ShowMsg(int type, string msg) { msg = msg.Replace("\r", "").Replace("\n", ""); string msgTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); string showMsg = $"{msgTime}: {msg}\n"; if (type == 0) { OperatResult.AppendText(showMsg, Color.Red); } else if (type == 1) { OperatResult.AppendText(showMsg, Color.Green); } } private void Radio1_Click(object sender, EventArgs e) { if (Radio1.Checked) { Radio2.Checked = false; } } private void Radio2_Click(object sender, EventArgs e) { if (Radio2.Checked) { Radio1.Checked = false; } } private void Locat1_Click(object sender, EventArgs e) { if (Locat1.Checked) { Locat2.Checked = false; Locat3.Checked = false; } } private void Locat2_Click(object sender, EventArgs e) { if (Locat2.Checked) { Locat1.Checked = false; Locat3.Checked = false; } } private void Locat3_Click(object sender, EventArgs e) { if (Locat3.Checked) { Locat1.Checked = false; Locat2.Checked = false; } } private void Account_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode != Keys.Enter) return; Password.Focus(); Password.SelectAll(); } private void Password_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode != Keys.Enter) return; TestTime.Focus(); TestTime.SelectAll(); } private void ExePath_Click(object sender, EventArgs e) { using (OpenFileDialog openFileDialog = new OpenFileDialog()) { openFileDialog.Title = "选择iperf3启动文件"; openFileDialog.Filter = "可执行文件 (*.exe)|*.exe|所有文件 (*.*)|*.*"; openFileDialog.FilterIndex = 1; openFileDialog.RestoreDirectory = true; // 设置初始目录(可选) if (!string.IsNullOrEmpty(ExePath.Text) && System.IO.File.Exists(ExePath.Text)) { openFileDialog.InitialDirectory = System.IO.Path.GetDirectoryName(ExePath.Text); } else { openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles); } if (openFileDialog.ShowDialog() == DialogResult.OK) { ExePath.Text = openFileDialog.FileName; ShowMsg(1, $"已成功选择iperf3启动文件"); } } } private void Clear_Click(object sender, EventArgs e) { OperatResult.Clear(); } private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { if (comboBox1.SelectedIndex == -1) return; if (string.IsNullOrEmpty(IPList.Text)) { ShowMsg(0, $"请先选择iperf服务地址"); comboBox1.SelectedIndex = -1; return; } if (string.IsNullOrEmpty(ProductList.Text)) { ShowMsg(0, $"请先选择产品IP地址"); comboBox1.SelectedIndex = -1; return; } string iperfServerPort = IPList.Text.Trim().Split(':')[1]; string cameraIp = ProductList.Text.Trim().Split(':')[0]; if (comboBox1.SelectedIndex == 0) { ShowMsg(1, $"指令一:"); ShowMsg(1, $" killall iperf3"); ShowMsg(1, $" iperf3 -s -p {iperfServerPort} -i 1&"); ShowMsg(1, $" -c {cameraIp} -p {iperfServerPort} -t 10 -w 1M -i 1 -P 8 -R"); ShowMsg(1, $" -c {cameraIp} -p {iperfServerPort} -t 10 -w 1M -i 1 -P 8"); } else if (comboBox1.SelectedIndex == 1) { ShowMsg(1, $"指令二:"); ShowMsg(1, $" killall iperf3_mstar"); ShowMsg(1, $" cp /mnt/tf/usb1_1/iperf3_mstar /var/tmp/ -f"); ShowMsg(1, $" chmod a+x /var/tmp/iperf3_mstar"); ShowMsg(1, $" /var/tmp/iperf3_mstar -s -p {iperfServerPort} -i 1 &"); ShowMsg(1, $" /var/tmp/iperf3 -c {cameraIp} -p {iperfServerPort} -t 6 -w 1M -i 1 -l 1518 -P 8 -R"); ShowMsg(1, $" /var/tmp/iperf3 -c {cameraIp} -p {iperfServerPort} -t 6 -w 1M -i 1 -l 1518 -P 8"); } } } }