Make_WirelessThroughput.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  1. using DevExpress.Utils.Drawing.Helpers;
  2. using NPOI.SS.Formula.Functions;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.ComponentModel;
  6. using System.Data;
  7. using System.Diagnostics;
  8. using System.Drawing;
  9. using System.IO;
  10. using System.Linq;
  11. using System.Net;
  12. using System.Net.Sockets;
  13. using System.Text;
  14. using System.Text.RegularExpressions;
  15. using System.Threading;
  16. using System.Web.Services.Description;
  17. using System.Web.UI.WebControls.WebParts;
  18. using System.Windows.Forms;
  19. using UAS_MES_NEW.DataOperate;
  20. using UAS_MES_NEW.Entity;
  21. using UAS_MES_NEW.PublicMethod;
  22. namespace UAS_MES_NEW.Make
  23. {
  24. public partial class Make_WirelessThroughput : Form
  25. {
  26. public Make_WirelessThroughput()
  27. {
  28. InitializeComponent();
  29. }
  30. StringBuilder SQL = new StringBuilder();
  31. DataTable dt;
  32. DataHelper dh;
  33. private void Make_WirelessThroughput_Load(object sender, EventArgs e)
  34. {
  35. dh = SystemInf.dh;
  36. try
  37. {
  38. string hostName = Dns.GetHostName();
  39. IPHostEntry hostEntry = Dns.GetHostEntry(hostName);
  40. foreach (IPAddress ip in hostEntry.AddressList)
  41. {
  42. if (ip.AddressFamily == AddressFamily.InterNetwork)
  43. {
  44. IPList.Text = ip.ToString();
  45. }
  46. }
  47. }
  48. catch (Exception ex)
  49. {
  50. ShowMsg(0, $"获取iperf服务器地址失败,{ex.Message}");
  51. }
  52. if (!IPList.Text.Contains(":"))
  53. {
  54. IPList.Text = IPList.Text + ":5001";
  55. }
  56. if (!ProductList.Text.Contains(":"))
  57. {
  58. ProductList.Text = ProductList.Text + ":23";
  59. }
  60. }
  61. private void SN_KeyDown(object sender, KeyEventArgs e)
  62. {
  63. if (e.KeyCode != Keys.Enter) return;
  64. if (IsCheckSet()) return;
  65. string sn = SN.Text.Trim();
  66. if (IPList.Text.IndexOf(':') > 0) IPList.Text = IPList.Text.Replace(":", ":");
  67. else IPList.Text = IPList.Text.Trim();
  68. if (SN.Text.IndexOf(';') > 0) SN.Text = sn.Replace(";", ";");
  69. else SN.Text = sn;
  70. UpdateSN("L", SN.Text.Trim());
  71. ShowMsg(1, $"开始测试");
  72. int cSPort = Convert.ToInt32(ProductList.Text.Trim().Split(':')[1]);
  73. int iSPort = Convert.ToInt32(IPList.Text.Trim().Split(':')[1]);
  74. var tester = new CameraIperfTester(
  75. timeOut: TestTime.Text.Trim(),
  76. cameraIp: ProductList.Text.Trim().Split(':')[0],
  77. cameraPort: cSPort,
  78. username: Account.Text.Trim(),
  79. password: ProductList.Text.Trim(),
  80. iperfServerIp: IPList.Text.Trim().Split(':')[0],
  81. iperfServerPort: iSPort
  82. );
  83. string Msg = tester.TelnetConnect();
  84. if (Msg.Substring(0, 2) != "OK")
  85. {
  86. ShowMsg(0, $"Telnet登录失败,{Msg}");
  87. return;
  88. }
  89. ShowMsg(1, $"Telnet登录成功");
  90. string parentPath = Path.GetDirectoryName(ExePath.Text.Trim());
  91. string logsPath = Path.Combine(parentPath, "iperf_logs");
  92. if (!Directory.Exists(logsPath))
  93. {
  94. Directory.CreateDirectory(logsPath);
  95. }
  96. //string[] comList = new string[] {
  97. // "killall iperf3",
  98. // $"iperf3 -s -p {iSPort} -i 1&"
  99. //};
  100. string[] comList = new string[] {
  101. "cd /tmp/",
  102. "ls iperf3_mstar",
  103. "chmod a+x iperf3_mstar"
  104. };
  105. Msg = tester.StartIperfTest(SN.Text.Trim(), ExePath.Text.Trim(), logsPath, comList);
  106. if (Msg.Substring(0, 2) != "OK")
  107. {
  108. ShowMsg(0, $"iperf3启动失败,{Msg}");
  109. return;
  110. }
  111. string upRate = Msg.Split('|')[0].Split(',')[1];
  112. string downRate = Msg.Split('|')[1];
  113. ShowMsg(1, $"OK,上行速率: {upRate},下行速率: {downRate}");
  114. ResMax.Text = upRate;
  115. ResMin.Text = downRate;
  116. string tDetail = $"upRate/{upRate};downRate/{downRate}";
  117. CheckPassStation(SN.Text, upRate, downRate, "PASS", tDetail);
  118. }
  119. private void CheckPassStation(string sn, string upRate, string downRate, string testRes,string testDetail)
  120. {
  121. string oWO, oWOId, oErrMsg = "";
  122. if (LogicHandler.CheckStepSNAndMacode(workOrder.Text, User.UserSourceCode, sn, User.UserCode, out oWO, out oWOId, out oErrMsg))
  123. {
  124. if (LogicHandler.SetStepResult(oWO, User.UserSourceCode, sn, "无线吞吐量", "OK", User.UserCode, out oErrMsg))
  125. {
  126. List<string> param = new List<string>() { };
  127. string outMsg = "";
  128. param.Add(oWO);
  129. param.Add(sn);
  130. param.Add(User.UserSourceCode);
  131. param.Add(testRes);
  132. param.Add("");
  133. param.Add("");
  134. param.Add("WirelessThroughput");
  135. param.Add(testDetail);
  136. param.Add(outMsg);
  137. string[] paramList = param.ToArray();
  138. dh.CallProcedure("cs_insert_testrejects", ref paramList);
  139. if (paramList[8].Substring(0, 2) == "OK")
  140. {
  141. ShowMsg(1, $"序列号{sn}采集成功:测试结果为{testRes}");
  142. LogicHandler.DoCommandLog(Tag.ToString(), User.UserCode, oWO, User.UserLineCode, User.UserSourceCode, "无线吞吐量", "无线吞吐量过站成功", sn, "");
  143. }
  144. }
  145. else
  146. {
  147. ShowMsg(0, $"序列号{sn},处理过站NG:{oErrMsg}");
  148. }
  149. }
  150. else
  151. {
  152. ShowMsg(0, $"序列号{sn},过站核对NG:{oErrMsg}");
  153. }
  154. }
  155. private bool IsCheckSet()
  156. {
  157. if (string.IsNullOrEmpty(IPList.Text))
  158. {
  159. ShowMsg(0, "请选择本地iperf 服务IP地址");
  160. return true;
  161. }
  162. if (string.IsNullOrEmpty(ProductList.Text))
  163. {
  164. ShowMsg(0, "请选择产品固定IP地址");
  165. return true;
  166. }
  167. if (string.IsNullOrEmpty(Account.Text))
  168. {
  169. ShowMsg(0, "请输入Telnet登录账号");
  170. return true;
  171. }
  172. if (string.IsNullOrEmpty(Password.Text))
  173. {
  174. ShowMsg(0, "请输入Telnet登录密码");
  175. return true;
  176. }
  177. if (string.IsNullOrEmpty(ExePath.Text))
  178. {
  179. ShowMsg(0, "请输入启动iperf3文件");
  180. return true;
  181. }
  182. if (!File.Exists(ExePath.Text))
  183. {
  184. Console.WriteLine("iperf3启动文件不存在");
  185. }
  186. if (string.IsNullOrEmpty(TestTime.Text))
  187. {
  188. ShowMsg(0, "请输入测试时长");
  189. return true;
  190. }
  191. //if (Locat1.Checked == false || Locat2.Checked == false || Locat3.Checked == false)
  192. //{
  193. // ShowMsg(0, "请选择固件位置");
  194. // return true;
  195. //}
  196. //if (Radio1.Checked == false || Radio1.Checked == false )
  197. //{
  198. // ShowMsg(0, "请选择测试类型");
  199. // return true;
  200. //}
  201. return false;
  202. }
  203. private void UpdateSN(string type, string sn)
  204. {
  205. if (type == "C")
  206. {
  207. serialNumber.Text = "";
  208. workOrder.Text = "";
  209. productCode.Text = "";
  210. productName.Text = "";
  211. }
  212. else if (type == "L")
  213. {
  214. SQL.Clear();
  215. SQL.Append($@"SELECT ms_sncode,ma_code,pr_code,pr_spec FROM makeserial,make,product
  216. WHERE ms_sncode = '{sn}' AND ms_makecode = ma_code AND ms_prodcode = pr_code");
  217. dt = (DataTable)dh.ExecuteSql(SQL.ToString(), "select");
  218. if (dt.Rows.Count > 0)
  219. {
  220. serialNumber.Text = dt.Rows[0]["ms_sncode"].ToString();
  221. workOrder.Text = dt.Rows[0]["ma_code"].ToString();
  222. productCode.Text = dt.Rows[0]["pr_code"].ToString();
  223. productName.Text = dt.Rows[0]["pr_spec"].ToString();
  224. }
  225. else
  226. {
  227. UpdateSN("C", sn);
  228. }
  229. }
  230. }
  231. public class CameraIperfTester
  232. {
  233. int timeOut;
  234. string cameraIp;
  235. int cameraPort;
  236. string username;
  237. string password;
  238. string iperfServerIp;
  239. int iperfServerPort;
  240. private TcpClient _telnetClient;
  241. private NetworkStream _telnetStream;
  242. string sVal1, sVal2, rVal1, rVal2;
  243. public CameraIperfTester(string timeOut, string cameraIp, int cameraPort, string username, string password, string iperfServerIp, int iperfServerPort)
  244. {
  245. this.timeOut = Convert.ToInt32(timeOut) * 1000;
  246. this.cameraIp = cameraIp;
  247. this.cameraPort = cameraPort;
  248. this.username = username;
  249. this.password = password;
  250. this.iperfServerIp = iperfServerIp;
  251. this.iperfServerPort = iperfServerPort;
  252. }
  253. public string StartIperfTest(string SN, string iperfPath,string logDirectory, string[] CList)
  254. {
  255. if (_telnetStream == null)
  256. return "NG,未建立连接";
  257. try
  258. {
  259. foreach (var comItem in CList)
  260. {
  261. WriteStream(_telnetStream, comItem);
  262. ReadStream(_telnetStream);
  263. }
  264. Thread.Sleep(1000); // 等服务端启动
  265. string serverStartLog = Path.Combine(logDirectory, $"{SN}_start.log");
  266. RunIperfClient($"./iperf3_mstar -s -p {iperfServerPort} -i l&", iperfPath, serverStartLog);
  267. string upLog = Path.Combine(logDirectory, $"{SN}_up.log");
  268. string downLog = Path.Combine(logDirectory, $"{SN}_down.log");
  269. //RunIperfClient($"-c {cameraIp} -p {iperfServerPort} -t 10 -w 1M -i 1 -P 8 -R", iperfPath, upLog);
  270. //RunIperfClient($"-c {cameraIp} -p {iperfServerPort} -t 10 -w 1M -i 1 -P 8", iperfPath, downLog);
  271. RunIperfClient($"./iperf3_mstar -c {cameraIp} -p {iperfServerPort} -i l -b 100M -t 10 -R", iperfPath, upLog);
  272. RunIperfClient($"./iperf3_mstar -c {cameraIp} -p {iperfServerPort} -i l -b 100M -t 10", iperfPath, downLog);
  273. string upRate = ParseIperfBitrate(upLog);
  274. string downRate = ParseIperfBitrate(downLog);
  275. return $"OK,{upRate}|{downRate}";
  276. }
  277. catch (Exception ex)
  278. {
  279. return $"NG,{ex.Message}";
  280. }
  281. }
  282. public string TelnetConnect()
  283. {
  284. try
  285. {
  286. _telnetClient = new TcpClient();
  287. IAsyncResult connectResult = _telnetClient.BeginConnect(cameraIp, cameraPort, null, null);
  288. bool connected = connectResult.AsyncWaitHandle.WaitOne(TimeSpan.FromMilliseconds(timeOut));
  289. if (!connected)
  290. {
  291. _telnetClient.Close();
  292. return "NG,连接超时";
  293. }
  294. try
  295. {
  296. _telnetClient.EndConnect(connectResult);
  297. }
  298. catch (SocketException ex)
  299. {
  300. return $"NG,连接失败: {ex.Message}";
  301. }
  302. _telnetStream = _telnetClient.GetStream();
  303. _telnetStream.ReadTimeout = 3000; // 3S读取超时
  304. StringBuilder fullResponse = new StringBuilder();
  305. string welcomeResponse = ReadStream(_telnetStream);
  306. fullResponse.Append(welcomeResponse);
  307. WriteStream(_telnetStream, username);
  308. string usernameResponse = ReadStream(_telnetStream);
  309. fullResponse.Append(usernameResponse);
  310. WriteStream(_telnetStream, password);
  311. string loginResponse = ReadStream(_telnetStream);
  312. fullResponse.Append(loginResponse);
  313. return $"OK,{fullResponse.ToString()}";
  314. }
  315. catch (Exception ex)
  316. {
  317. return $"NG,{ex.Message}";
  318. }
  319. }
  320. private void RunIperfClient(string args, string path, string logPath)
  321. {
  322. var psi = new ProcessStartInfo
  323. {
  324. FileName = path,
  325. Arguments = args,
  326. RedirectStandardOutput = true,
  327. RedirectStandardError = true,
  328. UseShellExecute = false,
  329. CreateNoWindow = true,
  330. WorkingDirectory = Path.GetDirectoryName(path)
  331. };
  332. using (var process = Process.Start(psi))
  333. {
  334. StringBuilder outputBuilder = new StringBuilder();
  335. StringBuilder errorBuilder = new StringBuilder();
  336. process.OutputDataReceived += (sender, e) =>
  337. {
  338. if (!string.IsNullOrEmpty(e.Data))
  339. {
  340. outputBuilder.AppendLine(e.Data);
  341. }
  342. };
  343. process.ErrorDataReceived += (sender, e) =>
  344. {
  345. if (!string.IsNullOrEmpty(e.Data))
  346. {
  347. errorBuilder.AppendLine(e.Data);
  348. }
  349. };
  350. process.BeginOutputReadLine();
  351. process.BeginErrorReadLine();
  352. process.WaitForExit();
  353. File.WriteAllText(logPath, outputBuilder.ToString() + errorBuilder.ToString());
  354. }
  355. }
  356. public string ParseIperfBitrate(string logPath)
  357. {
  358. if (!File.Exists(logPath)) return "0.0";
  359. var lines = File.ReadAllLines(logPath);
  360. List<string> logItem = new List<string> { };
  361. foreach (var line in lines)
  362. {
  363. if (line.Trim().StartsWith("[SUM]"))
  364. {
  365. logItem.Add(line);
  366. }
  367. }
  368. if (logItem.Count > 0 && logItem[logItem.Count - 2].Contains("sender"))
  369. {
  370. var match = Regex.Match(logItem[logItem.Count - 2], @"(\d+\.\d+\s+MBytes).*?(\d+\.\d+\s+Mbits/sec)");
  371. if (match.Success)
  372. {
  373. sVal1 = match.Groups[1].Value;
  374. sVal2 = match.Groups[2].Value;
  375. }
  376. }
  377. if (logItem.Count > 0 && logItem[logItem.Count -1].Contains("receiver"))
  378. {
  379. var match = Regex.Match(logItem[logItem.Count - 1], @"(\d+\.\d+\s+MBytes).*?(\d+\.\d+\s+Mbits/sec)");
  380. if (match.Success)
  381. {
  382. rVal1 = match.Groups[1].Value;
  383. rVal2 = match.Groups[2].Value;
  384. }
  385. }
  386. //double num1 = (double.Parse(sVal1.Split(' ')[0]) + double.Parse(rVal1.Split(' ')[0])) / 2;
  387. //double num2 = (double.Parse(sVal2.Split(' ')[0]) + double.Parse(rVal2.Split(' ')[0])) / 2;
  388. return rVal2;
  389. }
  390. private void WriteStream(NetworkStream stream, string text)
  391. {
  392. byte[] data = Encoding.ASCII.GetBytes(text + "\r\n");
  393. stream.Write(data, 0, data.Length);
  394. stream.Flush();
  395. }
  396. private string ReadStream(NetworkStream stream)
  397. {
  398. StringBuilder sb = new StringBuilder();
  399. byte[] buffer = new byte[1024];
  400. int totalBytesRead = 0;
  401. int currentBytesRead = 0;
  402. DateTime lastReadTime = DateTime.UtcNow;
  403. TimeSpan idleTimeout = TimeSpan.FromMilliseconds(800); // 空闲超时
  404. try
  405. {
  406. do
  407. {
  408. currentBytesRead = stream.Read(buffer, 0, buffer.Length);
  409. if (currentBytesRead > 0)
  410. {
  411. sb.Append(Encoding.ASCII.GetString(buffer, 0, currentBytesRead));
  412. totalBytesRead += currentBytesRead;
  413. lastReadTime = DateTime.UtcNow;
  414. }
  415. } while ((DateTime.UtcNow - lastReadTime) < idleTimeout);
  416. }
  417. catch (IOException ioEx)
  418. {
  419. }
  420. catch (ObjectDisposedException)
  421. {
  422. throw;
  423. }
  424. catch (SocketException sockEx)
  425. {
  426. throw new IOException($"NG,网络错误: {sockEx.Message}", sockEx);
  427. }
  428. return sb.ToString();
  429. }
  430. }
  431. private void ShowMsg(int type, string msg)
  432. {
  433. msg = msg.Replace("\r", "").Replace("\n", "");
  434. string msgTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
  435. string showMsg = $"{msgTime}: {msg}\n";
  436. if (type == 0)
  437. {
  438. OperatResult.AppendText(showMsg, Color.Red);
  439. }
  440. else if (type == 1)
  441. {
  442. OperatResult.AppendText(showMsg, Color.Green);
  443. }
  444. }
  445. private void Radio1_Click(object sender, EventArgs e)
  446. {
  447. if (Radio1.Checked)
  448. {
  449. Radio2.Checked = false;
  450. }
  451. }
  452. private void Radio2_Click(object sender, EventArgs e)
  453. {
  454. if (Radio2.Checked)
  455. {
  456. Radio1.Checked = false;
  457. }
  458. }
  459. private void Locat1_Click(object sender, EventArgs e)
  460. {
  461. if (Locat1.Checked)
  462. {
  463. Locat2.Checked = false;
  464. Locat3.Checked = false;
  465. }
  466. }
  467. private void Locat2_Click(object sender, EventArgs e)
  468. {
  469. if (Locat2.Checked)
  470. {
  471. Locat1.Checked = false;
  472. Locat3.Checked = false;
  473. }
  474. }
  475. private void Locat3_Click(object sender, EventArgs e)
  476. {
  477. if (Locat3.Checked)
  478. {
  479. Locat1.Checked = false;
  480. Locat2.Checked = false;
  481. }
  482. }
  483. private void Account_KeyDown(object sender, KeyEventArgs e)
  484. {
  485. if (e.KeyCode != Keys.Enter) return;
  486. Password.Focus();
  487. Password.SelectAll();
  488. }
  489. private void Password_KeyDown(object sender, KeyEventArgs e)
  490. {
  491. if (e.KeyCode != Keys.Enter) return;
  492. TestTime.Focus();
  493. TestTime.SelectAll();
  494. }
  495. private void ExePath_Click(object sender, EventArgs e)
  496. {
  497. using (OpenFileDialog openFileDialog = new OpenFileDialog())
  498. {
  499. openFileDialog.Title = "选择iperf3启动文件";
  500. openFileDialog.Filter = "可执行文件 (*.exe)|*.exe|所有文件 (*.*)|*.*";
  501. openFileDialog.FilterIndex = 1;
  502. openFileDialog.RestoreDirectory = true;
  503. // 设置初始目录(可选)
  504. if (!string.IsNullOrEmpty(ExePath.Text) && System.IO.File.Exists(ExePath.Text))
  505. {
  506. openFileDialog.InitialDirectory = System.IO.Path.GetDirectoryName(ExePath.Text);
  507. }
  508. else
  509. {
  510. openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
  511. }
  512. if (openFileDialog.ShowDialog() == DialogResult.OK)
  513. {
  514. ExePath.Text = openFileDialog.FileName;
  515. ShowMsg(1, $"已成功选择iperf3启动文件");
  516. }
  517. }
  518. }
  519. private void Clear_Click(object sender, EventArgs e)
  520. {
  521. OperatResult.Clear();
  522. }
  523. }
  524. }