Make_WirelessThroughput.cs 20 KB

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