Make_WirelessThroughput.cs 22 KB

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