Make_WirelessThroughput.cs 19 KB

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