Make_WirelessThroughput.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633
  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 instr(mp_stepname, '吞吐量') > 0", "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(200);
  308. WriteStream(_telnetStream, "cp /mnt/tf/usb1_1/iperf3_mstar /var/tmp/ -f");
  309. streamTxt.Append(ReadStream(_telnetStream));
  310. Thread.Sleep(200);
  311. WriteStream(_telnetStream, "chmod a+x /var/tmp/iperf3_mstar");
  312. streamTxt.Append(ReadStream(_telnetStream));
  313. Thread.Sleep(200);
  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. Close();
  325. return $"OK,{upRate}|{downRate}";
  326. }
  327. catch (Exception ex)
  328. {
  329. return $"NG,{ex.Message}";
  330. }
  331. }
  332. private void RunIperfClient(string args, string path, string logPath)
  333. {
  334. var psi = new ProcessStartInfo
  335. {
  336. FileName = path,
  337. Arguments = args,
  338. RedirectStandardOutput = true,
  339. RedirectStandardError = true,
  340. UseShellExecute = false,
  341. CreateNoWindow = true,
  342. WorkingDirectory = Path.GetDirectoryName(path)
  343. };
  344. using (var process = Process.Start(psi))
  345. {
  346. StringBuilder outputBuilder = new StringBuilder();
  347. StringBuilder errorBuilder = new StringBuilder();
  348. process.OutputDataReceived += (sender, e) =>
  349. {
  350. if (!string.IsNullOrEmpty(e.Data))
  351. {
  352. outputBuilder.AppendLine(e.Data);
  353. }
  354. };
  355. process.ErrorDataReceived += (sender, e) =>
  356. {
  357. if (!string.IsNullOrEmpty(e.Data))
  358. {
  359. errorBuilder.AppendLine(e.Data);
  360. }
  361. };
  362. process.BeginOutputReadLine();
  363. process.BeginErrorReadLine();
  364. process.WaitForExit();
  365. File.WriteAllText(logPath, outputBuilder.ToString() + errorBuilder.ToString());
  366. }
  367. }
  368. public string ParseIperfBitrate(string logPath)
  369. {
  370. if (!File.Exists(logPath)) return "0.0";
  371. var lines = File.ReadAllLines(logPath);
  372. List<string> logItem = new List<string> { };
  373. foreach (var line in lines)
  374. {
  375. if (line.Trim().StartsWith("[SUM]"))
  376. {
  377. logItem.Add(line);
  378. }
  379. }
  380. if (logItem.Count > 0 && logItem[logItem.Count - 2].Contains("sender"))
  381. {
  382. var match = Regex.Match(logItem[logItem.Count - 2], @"(\d+\.\d+\s+MBytes).*?(\d+\.\d+\s+Mbits/sec)");
  383. if (match.Success)
  384. {
  385. sVal1 = match.Groups[1].Value;
  386. sVal2 = match.Groups[2].Value;
  387. }
  388. }
  389. if (logItem.Count > 0 && logItem[logItem.Count -1].Contains("receiver"))
  390. {
  391. var match = Regex.Match(logItem[logItem.Count - 1], @"(\d+\.\d+\s+MBytes).*?(\d+\.\d+\s+Mbits/sec)");
  392. if (match.Success)
  393. {
  394. rVal1 = match.Groups[1].Value;
  395. rVal2 = match.Groups[2].Value;
  396. }
  397. }
  398. //double num1 = (double.Parse(sVal1.Split(' ')[0]) + double.Parse(rVal1.Split(' ')[0])) / 2;
  399. //double num2 = (double.Parse(sVal2.Split(' ')[0]) + double.Parse(rVal2.Split(' ')[0])) / 2;
  400. return rVal2;
  401. }
  402. private string WriteStream(NetworkStream stream, string data)
  403. {
  404. try
  405. {
  406. byte[] dataBytes = Encoding.UTF8.GetBytes(data + "\r\n");
  407. stream.Write(dataBytes, 0, dataBytes.Length);
  408. stream.Flush();
  409. return $"OK";
  410. }
  411. catch (Exception ex)
  412. {
  413. Close();
  414. return $"NG,写入数据时发生错误: {ex.Message}";
  415. }
  416. }
  417. private string ReadStream(NetworkStream stream)
  418. {
  419. try
  420. {
  421. StringBuilder response = new StringBuilder();
  422. byte[] buffer = new byte[1024];
  423. int bytesRead;
  424. while (stream.DataAvailable || response.Length == 0)
  425. {
  426. bytesRead = stream.Read(buffer, 0, buffer.Length);
  427. if (bytesRead > 0)
  428. {
  429. response.Append(Encoding.UTF8.GetString(buffer, 0, bytesRead));
  430. }
  431. else
  432. {
  433. break;
  434. }
  435. Thread.Sleep(100);
  436. }
  437. return response.ToString();
  438. }
  439. catch (IOException ioEx) when (ioEx.InnerException is SocketException socketEx && socketEx.SocketErrorCode == SocketError.TimedOut)
  440. {
  441. Close();
  442. return "NG,读取数据超时";
  443. }
  444. catch (Exception ex)
  445. {
  446. Close();
  447. return $"NG,读取数据时发生错误: {ex.Message}";
  448. }
  449. }
  450. private void Close()
  451. {
  452. _telnetClient?.Close();
  453. _telnetStream?.Close();
  454. }
  455. }
  456. private void ShowMsg(int type, string msg)
  457. {
  458. msg = msg.Replace("\r", "").Replace("\n", "");
  459. string msgTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
  460. string showMsg = $"{msgTime}: {msg}\n";
  461. if (type == 0)
  462. {
  463. OperatResult.AppendText(showMsg, Color.Red);
  464. }
  465. else if (type == 1)
  466. {
  467. OperatResult.AppendText(showMsg, Color.Green);
  468. }
  469. }
  470. private void Radio1_Click(object sender, EventArgs e)
  471. {
  472. if (Radio1.Checked)
  473. {
  474. Radio2.Checked = false;
  475. }
  476. }
  477. private void Radio2_Click(object sender, EventArgs e)
  478. {
  479. if (Radio2.Checked)
  480. {
  481. Radio1.Checked = false;
  482. }
  483. }
  484. private void Locat1_Click(object sender, EventArgs e)
  485. {
  486. if (Locat1.Checked)
  487. {
  488. Locat2.Checked = false;
  489. Locat3.Checked = false;
  490. }
  491. }
  492. private void Locat2_Click(object sender, EventArgs e)
  493. {
  494. if (Locat2.Checked)
  495. {
  496. Locat1.Checked = false;
  497. Locat3.Checked = false;
  498. }
  499. }
  500. private void Locat3_Click(object sender, EventArgs e)
  501. {
  502. if (Locat3.Checked)
  503. {
  504. Locat1.Checked = false;
  505. Locat2.Checked = false;
  506. }
  507. }
  508. private void Account_KeyDown(object sender, KeyEventArgs e)
  509. {
  510. if (e.KeyCode != Keys.Enter) return;
  511. Password.Focus();
  512. Password.SelectAll();
  513. }
  514. private void Password_KeyDown(object sender, KeyEventArgs e)
  515. {
  516. if (e.KeyCode != Keys.Enter) return;
  517. TestTime.Focus();
  518. TestTime.SelectAll();
  519. }
  520. private void ExePath_Click(object sender, EventArgs e)
  521. {
  522. using (OpenFileDialog openFileDialog = new OpenFileDialog())
  523. {
  524. openFileDialog.Title = "选择iperf3启动文件";
  525. openFileDialog.Filter = "可执行文件 (*.exe)|*.exe|所有文件 (*.*)|*.*";
  526. openFileDialog.FilterIndex = 1;
  527. openFileDialog.RestoreDirectory = true;
  528. // 设置初始目录(可选)
  529. if (!string.IsNullOrEmpty(ExePath.Text) && System.IO.File.Exists(ExePath.Text))
  530. {
  531. openFileDialog.InitialDirectory = System.IO.Path.GetDirectoryName(ExePath.Text);
  532. }
  533. else
  534. {
  535. openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
  536. }
  537. if (openFileDialog.ShowDialog() == DialogResult.OK)
  538. {
  539. ExePath.Text = openFileDialog.FileName;
  540. ShowMsg(1, $"已成功选择iperf3启动文件");
  541. }
  542. }
  543. }
  544. private void Clear_Click(object sender, EventArgs e)
  545. {
  546. OperatResult.Clear();
  547. }
  548. }
  549. }